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

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