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