xref: /openbmc/openbmc/poky/meta/lib/oe/lsb.py (revision 92b42cb3)
1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: GPL-2.0-only
5#
6
7def get_os_release():
8    """Get all key-value pairs from /etc/os-release as a dict"""
9    from collections import OrderedDict
10
11    data = OrderedDict()
12    if os.path.exists('/etc/os-release'):
13        with open('/etc/os-release') as f:
14            for line in f:
15                try:
16                    key, val = line.rstrip().split('=', 1)
17                except ValueError:
18                    continue
19                data[key.strip()] = val.strip('"')
20    return data
21
22def release_dict_osr():
23    """ Populate a dict with pertinent values from /etc/os-release """
24    data = {}
25    os_release = get_os_release()
26    if 'ID' in os_release:
27        data['DISTRIB_ID'] = os_release['ID']
28    if 'VERSION_ID' in os_release:
29        data['DISTRIB_RELEASE'] = os_release['VERSION_ID']
30
31    return data
32
33def release_dict_lsb():
34    """ Return the output of lsb_release -ir as a dictionary """
35    from subprocess import PIPE
36
37    try:
38        output, err = bb.process.run(['lsb_release', '-ir'], stderr=PIPE)
39    except bb.process.CmdError as exc:
40        return {}
41
42    lsb_map = { 'Distributor ID': 'DISTRIB_ID',
43                'Release': 'DISTRIB_RELEASE'}
44    lsb_keys = lsb_map.keys()
45
46    data = {}
47    for line in output.splitlines():
48        if line.startswith("-e"):
49            line = line[3:]
50        try:
51            key, value = line.split(":\t", 1)
52        except ValueError:
53            continue
54        if key in lsb_keys:
55            data[lsb_map[key]] = value
56
57    if len(data.keys()) != 2:
58        return None
59
60    return data
61
62def release_dict_file():
63    """ Try to gather release information manually when other methods fail """
64    data = {}
65    try:
66        if os.path.exists('/etc/lsb-release'):
67            data = {}
68            with open('/etc/lsb-release') as f:
69                for line in f:
70                    key, value = line.split("=", 1)
71                    data[key] = value.strip()
72        elif os.path.exists('/etc/redhat-release'):
73            data = {}
74            with open('/etc/redhat-release') as f:
75                distro = f.readline().strip()
76            import re
77            match = re.match(r'(.*) release (.*) \((.*)\)', distro)
78            if match:
79                data['DISTRIB_ID'] = match.group(1)
80                data['DISTRIB_RELEASE'] = match.group(2)
81        elif os.path.exists('/etc/SuSE-release'):
82            data = {}
83            data['DISTRIB_ID'] = 'SUSE LINUX'
84            with open('/etc/SuSE-release') as f:
85                for line in f:
86                    if line.startswith('VERSION = '):
87                        data['DISTRIB_RELEASE'] = line[10:].rstrip()
88                        break
89
90    except IOError:
91        return {}
92    return data
93
94def distro_identifier(adjust_hook=None):
95    """Return a distro identifier string based upon lsb_release -ri,
96       with optional adjustment via a hook"""
97
98    import re
99
100    # Try /etc/os-release first, then the output of `lsb_release -ir` and
101    # finally fall back on parsing various release files in order to determine
102    # host distro name and version.
103    distro_data = release_dict_osr()
104    if not distro_data:
105        distro_data = release_dict_lsb()
106    if not distro_data:
107        distro_data = release_dict_file()
108
109    distro_id = distro_data.get('DISTRIB_ID', '')
110    release = distro_data.get('DISTRIB_RELEASE', '')
111
112    if adjust_hook:
113        distro_id, release = adjust_hook(distro_id, release)
114    if not distro_id:
115        return "unknown"
116    # Filter out any non-alphanumerics and convert to lowercase
117    distro_id = re.sub(r'\W', '', distro_id).lower()
118
119    if release:
120        id_str = '{0}-{1}'.format(distro_id, release)
121    else:
122        id_str = distro_id
123    return id_str.replace(' ','-').replace('/','-')
124