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

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