Blame SOURCES/0073-a-a-g-machine-id-add-systemd-s-machine-id.patch

06486d
From b7024111fcfe3662e96f5e6ad51d680fa3607b51 Mon Sep 17 00:00:00 2001
06486d
From: Jakub Filak <jfilak@redhat.com>
06486d
Date: Thu, 23 Oct 2014 16:37:14 +0200
06486d
Subject: [ABRT PATCH 73/75] a-a-g-machine-id: add systemd's machine id
06486d
06486d
The dmidecode based algorithm may not work on all architectures.
06486d
06486d
man machine-id
06486d
06486d
Related to rhbz#1139552
06486d
06486d
Signed-off-by: Jakub Filak <jfilak@redhat.com>
06486d
---
06486d
 src/plugins/abrt-action-generate-machine-id | 162 +++++++++++++++++++++++++---
06486d
 1 file changed, 150 insertions(+), 12 deletions(-)
06486d
06486d
diff --git a/src/plugins/abrt-action-generate-machine-id b/src/plugins/abrt-action-generate-machine-id
06486d
index 0aea787..6f43258 100644
06486d
--- a/src/plugins/abrt-action-generate-machine-id
06486d
+++ b/src/plugins/abrt-action-generate-machine-id
06486d
@@ -1,14 +1,47 @@
06486d
 #!/usr/bin/python
06486d
+
06486d
+## Copyright (C) 2014 ABRT team <abrt-devel-list@redhat.com>
06486d
+## Copyright (C) 2014 Red Hat, Inc.
06486d
+
06486d
+## This program is free software; you can redistribute it and/or modify
06486d
+## it under the terms of the GNU General Public License as published by
06486d
+## the Free Software Foundation; either version 2 of the License, or
06486d
+## (at your option) any later version.
06486d
+
06486d
+## This program is distributed in the hope that it will be useful,
06486d
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
06486d
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
06486d
+## GNU General Public License for more details.
06486d
+
06486d
+## You should have received a copy of the GNU General Public License
06486d
+## along with this program; if not, write to the Free Software
06486d
+## Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA  02110-1335  USA
06486d
+
06486d
+"""This module provides algorithms for generating Machine IDs.
06486d
+"""
06486d
+
06486d
+import sys
06486d
 from argparse import ArgumentParser
06486d
+import logging
06486d
 
06486d
-import dmidecode
06486d
 import hashlib
06486d
 
06486d
+def generate_machine_id_dmidecode():
06486d
+    """Generate a machine_id based off dmidecode fields
06486d
 
06486d
-# Generate a machine_id based off dmidecode fields
06486d
-def generate_machine_id():
06486d
-    dmixml = dmidecode.dmidecodeXML()
06486d
+    The function generates the same result as sosreport-uploader
06486d
+
06486d
+    Returns a machine ID as string or throws RuntimeException
06486d
+
06486d
+    """
06486d
 
06486d
+    try:
06486d
+        import dmidecode
06486d
+    except ImportError as ex:
06486d
+        raise RuntimeError("Could not import dmidecode module: {0}"
06486d
+                .format(str(ex)))
06486d
+
06486d
+    dmixml = dmidecode.dmidecodeXML()
06486d
     # Fetch all DMI data into a libxml2.xmlDoc object
06486d
     dmixml.SetResultType(dmidecode.DMIXML_DOC)
06486d
     xmldoc = dmixml.QuerySection('all')
06486d
@@ -38,20 +71,125 @@ def generate_machine_id():
06486d
     return machine_id.hexdigest()
06486d
 
06486d
 
06486d
-if __name__ == "__main__":
06486d
-    CMDARGS = ArgumentParser(description = "Generate a machine_id based off dmidecode fields")
06486d
-    CMDARGS.add_argument('-o', '--output', type=str, help='Output file')
06486d
+def generate_machine_id_systemd():
06486d
+    """Generate a machine_id equals to a one generated by systemd
06486d
+
06486d
+    This function returns contents of /etc/machine-id
06486d
+
06486d
+    Returns a machine ID as string or throws RuntimeException.
06486d
+
06486d
+    """
06486d
+
06486d
+    try:
06486d
+        with open('/etc/machine-id', 'r') as midf:
06486d
+            return "".join((l.strip() for l in midf))
06486d
+    except IOError as ex:
06486d
+        raise RuntimeError("Could not use systemd's machine-id: {0}"
06486d
+                .format(str(ex)))
06486d
+
06486d
+
06486d
+GENERATORS = { 'sosreport_uploader-dmidecode' : generate_machine_id_dmidecode,
06486d
+               'systemd'                      : generate_machine_id_systemd }
06486d
+
06486d
+
06486d
+def generate_machine_id(generators):
06486d
+    """Generates all requested machine id with all required generators
06486d
+
06486d
+    Keyword arguments:
06486d
+    generators -- a list of generator names
06486d
+
06486d
+    Returns a dictionary where keys are generators and associated values are
06486d
+    products of those generators.
06486d
+
06486d
+    """
06486d
+
06486d
+    ids = {}
06486d
+    workers = GENERATORS
06486d
+    for sd in generators:
06486d
+        try:
06486d
+            ids[sd] = workers[sd]()
06486d
+        except RuntimeError as ex:
06486d
+            logging.error("Machine-ID generator '{0}' failed: {1}"
06486d
+                        .format(sd, ex.message))
06486d
+
06486d
+    return ids
06486d
+
06486d
+
06486d
+def print_result(ids, outfile, prefixed):
06486d
+    """Writes a dictionary of machine ids to a file
06486d
+
06486d
+    Each dictionary entry is written on a single line. The function does not
06486d
+    print trailing new-line if the dictionary contains only one item as it is
06486d
+    common format of one-liners placed in a dump directory.
06486d
+
06486d
+    Keyword arguments:
06486d
+    ids -- a dictionary [generator name: machine ids]
06486d
+    outfile -- output file
06486d
+    prefixed -- use 'generator name=' prefix or not
06486d
+    """
06486d
+
06486d
+    fmt = '{0}={1}' if prefixed else '{1}'
06486d
+
06486d
+    if len(ids) > 1:
06486d
+        fmt += '\n'
06486d
+
06486d
+    for sd, mid in ids.iteritems():
06486d
+        outfile.write(fmt.format(sd,mid))
06486d
+
06486d
+
06486d
+def print_generators(outfile=None):
06486d
+    """Prints requested generators
06486d
+
06486d
+    Keyword arguments:
06486d
+    outfile -- output file (default: sys.stdout)
06486d
+
06486d
+    """
06486d
+    if outfile is None:
06486d
+        outfile = sys.stdout
06486d
+
06486d
+    for sd in GENERATORS.iterkeys():
06486d
+        outfile.write("{0}\n".format(sd))
06486d
+
06486d
+
06486d
+if __name__ == '__main__':
06486d
+    CMDARGS = ArgumentParser(description = "Generate a machine_id")
06486d
+    CMDARGS.add_argument('-o', '--output', type=str,
06486d
+            help="Output file")
06486d
+    CMDARGS.add_argument('-g', '--generators', nargs='+', type=str,
06486d
+            help="Use given generators only")
06486d
+    CMDARGS.add_argument('-l', '--list-generators', action='store_true',
06486d
+            default=False, help="Print out a list of usable generators")
06486d
+    CMDARGS.add_argument('-n', '--noprefix', action='store_true',
06486d
+            default=False, help="Do not use generator name as prefix for IDs")
06486d
 
06486d
     OPTIONS = CMDARGS.parse_args()
06486d
     ARGS = vars(OPTIONS)
06486d
 
06486d
-    machineid =  generate_machine_id()
06486d
+    logging.basicConfig(format='%(message)s')
06486d
+
06486d
+    if ARGS['list_generators']:
06486d
+        print_generators()
06486d
+        sys.exit(0)
06486d
+
06486d
+    requested_generators = None
06486d
+    if ARGS['generators']:
06486d
+        requested_generators = ARGS['generators']
06486d
+    else:
06486d
+        requested_generators = GENERATORS.keys()
06486d
+
06486d
+    machineids = generate_machine_id(requested_generators)
06486d
 
06486d
     if ARGS['output']:
06486d
         try:
06486d
-            with open(ARGS['output'], 'w') as outfile:
06486d
-                outfile.write(machineid)
06486d
+            with open(ARGS['output'], 'w') as fout:
06486d
+                print_result(machineids, fout, not ARGS['noprefix'])
06486d
         except IOError as ex:
06486d
-            print ex
06486d
+            logging.error("Could not open output file: {0}".format(str(ex)))
06486d
+            sys.exit(1)
06486d
     else:
06486d
-        print machineid
06486d
+        print_result(machineids, sys.stdout, not ARGS['noprefix'])
06486d
+        # print_results() omits new-line for one-liners
06486d
+        if len(machineids) == 1:
06486d
+            sys.stdout.write('\n')
06486d
+
06486d
+    sys.exit(len(requested_generators) - len(machineids.keys()))
06486d
-- 
06486d
1.8.3.1
06486d