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