doczkal / rpms / abrt

Forked from rpms/abrt 4 years ago
Clone

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

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