Debian Codegraph @

lib/ansible/module_utils/facts/system/distribution.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 import os
9 import platform
10 import re
11 import typing as t
12
13 from ansible.module_utils.common.sys_info import get_distribution, get_distribution_version, \
14 get_distribution_codename, get_distribution_cpe_name
15 from ansible.module_utils.facts.utils import get_file_content, get_file_lines
16 from ansible.module_utils.facts.collector import BaseFactCollector
17
18
19 def get_uname(module, flags=('-v')):
20 if isinstance(flags, str):
21 flags = flags.split()
22 command = ['uname']
23 command.extend(flags)
24 rc, out, err = module.run_command(command)
25 if rc == 0:
26 return out
27 return None
28
29
30 def _file_exists(path, allow_empty=False):
31 # not finding the file, exit early
32 if not os.path.isfile(path):
33 return False
34
35 # if just the path needs to exists (ie, it can be empty) we are done
36 if allow_empty:
37 return True
38
39 # file exists but is empty and we dont allow_empty
40 if os.path.getsize(path) == 0:
41 return False
42
43 # file exists with some content
44 return True
45
46
47 class DistributionFiles:
48 """has-a various distro file parsers (os-release, etc) and logic for finding the right one."""
49 # every distribution name mentioned here, must have one of
50 # - allowempty == True
51 # - be listed in SEARCH_STRING
52 # - have a function get_distribution_DISTNAME implemented
53 # keep names in sync with Conditionals page of docs
54 OSDIST_LIST = (
55 {'path': '/etc/altlinux-release', 'name': 'Altlinux'},
56 {'path': '/etc/oracle-release', 'name': 'OracleLinux'},
57 {'path': '/etc/slackware-version', 'name': 'Slackware'},
58 {'path': '/etc/centos-release', 'name': 'CentOS'},
59 # Must precede RedHat: A-version UOS Server symlinks redhat-release to uos-release.
60 {'path': '/etc/redhat-release', 'name': 'UnionTech'},
61 {'path': '/etc/redhat-release', 'name': 'RedHat'},
62 {'path': '/etc/vmware-release', 'name': 'VMwareESX', 'allowempty': True},
63 {'path': '/etc/openwrt_release', 'name': 'OpenWrt'},
64 {'path': '/etc/os-release', 'name': 'Amazon'},
65 {'path': '/etc/system-release', 'name': 'Amazon'},
66 {'path': '/etc/alpine-release', 'name': 'Alpine'},
67 {'path': '/etc/arch-release', 'name': 'Archlinux', 'allowempty': True},
68 {'path': '/etc/os-release', 'name': 'Archlinux'},
69 {'path': '/etc/os-release', 'name': 'SUSE'},
70 {'path': '/etc/SuSE-release', 'name': 'SUSE'},
71 {'path': '/etc/gentoo-release', 'name': 'Gentoo'},
72 {'path': '/etc/os-release', 'name': 'UnionTech'},
73 {'path': '/etc/os-release', 'name': 'Debian'},
74 {'path': '/etc/lsb-release', 'name': 'Debian'},
75 {'path': '/etc/lsb-release', 'name': 'Mandriva'},
76 {'path': '/etc/sourcemage-release', 'name': 'SMGL'},
77 {'path': '/usr/lib/os-release', 'name': 'ClearLinux'},
78 {'path': '/etc/coreos/update.conf', 'name': 'Coreos'},
79 {'path': '/etc/os-release', 'name': 'Flatcar'},
80 {'path': '/etc/os-release', 'name': 'NA'},
81 )
82
83 SEARCH_STRING = {
84 'OracleLinux': 'Oracle Linux',
85 'RedHat': 'Red Hat',
86 'Altlinux': 'ALT',
87 'SMGL': 'Source Mage GNU/Linux',
88 }
89
90 # We can't include this in SEARCH_STRING because a name match on its keys
91 # causes a fallback to using the first whitespace separated item from the file content
92 # as the name. For os-release, that is in form 'NAME=Arch'
93 OS_RELEASE_ALIAS = {
94 'Archlinux': 'Arch Linux'
95 }
96
97 STRIP_QUOTES = r'\'\"\\'
98
99 def __init__(self, module):
100 self.module = module
101
102 def _get_file_content(self, path):
103 return get_file_content(path)
104
105 def _get_dist_file_content(self, path, allow_empty=False):
106 # can't find that dist file, or it is incorrectly empty
107 if not _file_exists(path, allow_empty=allow_empty):
108 return False, None
109
110 data = self._get_file_content(path)
111 return True, data
112
113 def _parse_dist_file(self, name, dist_file_content, path, collected_facts):
114 dist_file_dict = {}
115 dist_file_content = dist_file_content.strip(DistributionFiles.STRIP_QUOTES)
116 if name in self.SEARCH_STRING:
117 # look for the distribution string in the data and replace according to RELEASE_NAME_MAP
118 # only the distribution name is set, the version is assumed to be correct from distro.linux_distribution()
119 if self.SEARCH_STRING[name] in dist_file_content:
120 # this sets distribution=RedHat if 'Red Hat' shows up in data
121 dist_file_dict['distribution'] = name
122 dist_file_dict['distribution_file_search_string'] = self.SEARCH_STRING[name]
123 else:
124 # this sets distribution to what's in the data, e.g. CentOS, Scientific, ...
125 dist_file_dict['distribution'] = dist_file_content.split()[0]
126
127 return True, dist_file_dict
128
129 if name in self.OS_RELEASE_ALIAS:
130 if self.OS_RELEASE_ALIAS[name] in dist_file_content:
131 dist_file_dict['distribution'] = name
132 return True, dist_file_dict
133 return False, dist_file_dict
134
135 # call a dedicated function for parsing the file content
136 # TODO: replace with a map or a class
137 try:
138 # FIXME: most of these dont actually look at the dist file contents, but random other stuff
139 distfunc_name = 'parse_distribution_file_' + name
140 distfunc = getattr(self, distfunc_name)
141 parsed, dist_file_dict = distfunc(name, dist_file_content, path, collected_facts)
142 return parsed, dist_file_dict
143 except AttributeError as exc:
144 self.module.debug('exc: %s' % exc)
145 # this should never happen, but if it does fail quietly and not with a traceback
146 return False, dist_file_dict
147
148 return True, dist_file_dict
149 # to debug multiple matching release files, one can use:
150 # self.facts['distribution_debug'].append({path + ' ' + name:
151 # (parsed,
152 # self.facts['distribution'],
153 # self.facts['distribution_version'],
154 # self.facts['distribution_release'],
155 # )})
156
157 def _guess_distribution(self):
158 # try to find out which linux distribution this is
159 dist = (get_distribution(), get_distribution_version(), get_distribution_codename())
160 distribution_guess = {
161 'distribution': dist[0] or 'NA',
162 'distribution_version': dist[1] or 'NA',
163 # distribution_release can be the empty string
164 'distribution_release': 'NA' if dist[2] is None else dist[2]
165 }
166
167 distribution_guess['distribution_major_version'] = distribution_guess['distribution_version'].split('.')[0] or 'NA'
168 return distribution_guess
169
170 def process_dist_files(self):
171 # Try to handle the exceptions now ...
172 # self.facts['distribution_debug'] = []
173 dist_file_facts = {}
174
175 dist_guess = self._guess_distribution()
176 dist_file_facts.update(dist_guess)
177
178 for ddict in self.OSDIST_LIST:
179 name = ddict['name']
180 path = ddict['path']
181 allow_empty = ddict.get('allowempty', False)
182
183 has_dist_file, dist_file_content = self._get_dist_file_content(path, allow_empty=allow_empty)
184
185 # but we allow_empty. For example, ArchLinux with an empty /etc/arch-release and a
186 # /etc/os-release with a different name
187 if has_dist_file and allow_empty:
188 dist_file_facts['distribution'] = name
189 dist_file_facts['distribution_file_path'] = path
190 dist_file_facts['distribution_file_variety'] = name
191 break
192
193 if not has_dist_file:
194 # keep looking
195 continue
196
197 parsed_dist_file, parsed_dist_file_facts = self._parse_dist_file(name, dist_file_content, path, dist_file_facts)
198
199 # finally found the right os dist file and were able to parse it
200 if parsed_dist_file:
201 dist_file_facts['distribution'] = name
202 dist_file_facts['distribution_file_path'] = path
203 # distribution and file_variety are the same here, but distribution
204 # will be changed/mapped to a more specific name.
205 # ie, dist=Fedora, file_variety=RedHat
206 dist_file_facts['distribution_file_variety'] = name
207 dist_file_facts['distribution_file_parsed'] = parsed_dist_file
208 dist_file_facts.update(parsed_dist_file_facts)
209 break
210
211 return dist_file_facts
212
213 # FIXME: split distro file parsing into its own module or class
214 def parse_distribution_file_Slackware(self, name, data, path, collected_facts):
215 slackware_facts = {}
216 if 'Slackware' not in data:
217 return False, slackware_facts # TODO: remove
218 slackware_facts['distribution'] = name
219 version = re.findall(r'\w+[.]\w+\+?', data)
220 if version:
221 slackware_facts['distribution_version'] = version[0]
222 return True, slackware_facts
223
224 def parse_distribution_file_Amazon(self, name, data, path, collected_facts):
225 amazon_facts = {}
226 if 'Amazon' not in data:
227 return False, amazon_facts
228 amazon_facts['distribution'] = 'Amazon'
229 if path == '/etc/os-release':
230 version = re.search(r"VERSION_ID=\"(.*)\"", data)
231 if version:
232 distribution_version = version.group(1)
233 amazon_facts['distribution_version'] = distribution_version
234 version_data = distribution_version.split(".")
235 if len(version_data) > 1:
236 major, minor = version_data
237 else:
238 major, minor = version_data[0], 'NA'
239
240 amazon_facts['distribution_major_version'] = major
241 amazon_facts['distribution_minor_version'] = minor
242 else:
243 version = [n for n in data.split() if n.isdigit()]
244 version = version[0] if version else 'NA'
245 amazon_facts['distribution_version'] = version
246
247 return True, amazon_facts
248
249 def parse_distribution_file_OpenWrt(self, name, data, path, collected_facts):
250 openwrt_facts = {}
251 if 'OpenWrt' not in data:
252 return False, openwrt_facts # TODO: remove
253 openwrt_facts['distribution'] = name
254 version = re.search('DISTRIB_RELEASE="(.*)"', data)
255 if version:
256 openwrt_facts['distribution_version'] = version.groups()[0]
257 release = re.search('DISTRIB_CODENAME="(.*)"', data)
258 if release:
259 openwrt_facts['distribution_release'] = release.groups()[0]
260 return True, openwrt_facts
261
262 def parse_distribution_file_Alpine(self, name, data, path, collected_facts):
263 alpine_facts = {}
264 alpine_facts['distribution'] = 'Alpine'
265 alpine_facts['distribution_version'] = data
266 return True, alpine_facts
267
268 def parse_distribution_file_SUSE(self, name, data, path, collected_facts):
269 suse_facts = {}
270 if 'suse' not in data.lower():
271 return False, suse_facts # TODO: remove if tested without this
272 if path == '/etc/os-release':
273 for line in data.splitlines():
274 distribution = re.search("^NAME=(.*)", line)
275 if distribution:
276 suse_facts['distribution'] = distribution.group(1).strip('"')
277 # example pattern are 13.04 13.0 13
278 distribution_version = re.search(r'^VERSION_ID="?([0-9]+\.?[0-9]*)"?', line)
279 if distribution_version:
280 suse_facts['distribution_version'] = distribution_version.group(1)
281 suse_facts['distribution_major_version'] = distribution_version.group(1).split('.')[0]
282 if 'open' in data.lower():
283 release = re.search(r'^VERSION_ID="?[0-9]+\.?([0-9]*)"?', line)
284 if release:
285 suse_facts['distribution_release'] = release.groups()[0]
286 elif 'enterprise' in data.lower() and 'VERSION_ID' in line:
287 # SLES doesn't got funny release names
288 release = re.search(r'^VERSION_ID="?[0-9]+\.?([0-9]*)"?', line)
289 if release.group(1):
290 release = release.group(1)
291 else:
292 release = "0" # no minor number, so it is the first release
293 suse_facts['distribution_release'] = release
294 elif path == '/etc/SuSE-release':
295 if 'open' in data.lower():
296 data = data.splitlines()
297 distdata = get_file_content(path).splitlines()[0]
298 suse_facts['distribution'] = distdata.split()[0]
299 for line in data:
300 release = re.search('CODENAME *= *([^\n]+)', line)
301 if release:
302 suse_facts['distribution_release'] = release.groups()[0].strip()
303 elif 'enterprise' in data.lower():
304 lines = data.splitlines()
305 distribution = lines[0].split()[0]
306 if "Server" in data:
307 suse_facts['distribution'] = "SLES"
308 elif "Desktop" in data:
309 suse_facts['distribution'] = "SLED"
310 for line in lines:
311 release = re.search('PATCHLEVEL = ([0-9]+)', line) # SLES doesn't got funny release names
312 if release:
313 suse_facts['distribution_release'] = release.group(1)
314 suse_facts['distribution_version'] = collected_facts['distribution_version'] + '.' + release.group(1)
315
316 # Check VARIANT_ID first for SLES4SAP or SL-Micro
317 variant_id_match = re.search(r'^VARIANT_ID="?([^"\n]*)"?', data, re.MULTILINE)
318 if variant_id_match:
319 variant_id = variant_id_match.group(1)
320 if variant_id in ('server-sap', 'sles-sap'):
321 suse_facts['distribution'] = 'SLES_SAP'
322 elif variant_id == 'transactional':
323 suse_facts['distribution'] = 'SL-Micro'
324 else:
325 # Fallback for older SLES 15 using baseproduct symlink
326 if os.path.islink('/etc/products.d/baseproduct'):
327 resolved = os.path.realpath('/etc/products.d/baseproduct')
328 if resolved.endswith('SLES_SAP.prod'):
329 suse_facts['distribution'] = 'SLES_SAP'
330 elif resolved.endswith('SL-Micro.prod'):
331 suse_facts['distribution'] = 'SL-Micro'
332
333 return True, suse_facts
334
335 def parse_distribution_file_Debian(self, name, data, path, collected_facts):
336 debian_facts = {}
337 if any(distro in data for distro in ('Debian', 'Raspbian')):
338 debian_facts['distribution'] = 'Debian'
339 release = re.search(r"PRETTY_NAME=[^(]+ \(?([^)]+?)\)", data)
340 if release:
341 debian_facts['distribution_release'] = release.groups()[0]
342
343 # Last resort: try to find release from tzdata as either lsb is missing or this is very old debian
344 if collected_facts['distribution_release'] == 'NA' and 'Debian' in data:
345 dpkg_cmd = self.module.get_bin_path('dpkg')
346 if dpkg_cmd:
347 cmd = "%s --status tzdata|grep Provides|cut -f2 -d'-'" % dpkg_cmd
348 rc, out, err = self.module.run_command(cmd)
349 if rc == 0:
350 debian_facts['distribution_release'] = out.strip()
351 debian_version_path = '/etc/debian_version'
352 distdata = get_file_lines(debian_version_path)
353 for line in distdata:
354 m = re.search(r'(\d+)\.(\d+)', line.strip())
355 if m:
356 debian_facts['distribution_minor_version'] = m.groups()[1]
357 elif 'Ubuntu' in data:
358 debian_facts['distribution'] = 'Ubuntu'
359 # nothing else to do, Ubuntu gets correct info from python functions
360 elif 'SteamOS' in data:
361 debian_facts['distribution'] = 'SteamOS'
362 # nothing else to do, SteamOS gets correct info from python functions
363 elif path in ('/etc/lsb-release', '/etc/os-release') and ('Kali' in data or 'Parrot' in data):
364 if 'Kali' in data:
365 # Kali does not provide /etc/lsb-release anymore
366 debian_facts['distribution'] = 'Kali'
367 elif 'Parrot' in data:
368 debian_facts['distribution'] = 'Parrot'
369 release = re.search('DISTRIB_RELEASE=(.*)', data)
370 if release:
371 debian_facts['distribution_release'] = release.groups()[0]
372 elif 'Devuan' in data:
373 debian_facts['distribution'] = 'Devuan'
374 release = re.search(r"PRETTY_NAME=\"?[^(\"]+ \(?([^) \"]+)\)?", data)
375 if release:
376 debian_facts['distribution_release'] = release.groups()[0]
377 version = re.search(r"VERSION_ID=\"(.*)\"", data)
378 if version:
379 debian_facts['distribution_version'] = version.group(1)
380 debian_facts['distribution_major_version'] = version.group(1)
381 elif 'Cumulus' in data:
382 debian_facts['distribution'] = 'Cumulus Linux'
383 version = re.search(r"VERSION_ID=(.*)", data)
384 if version:
385 major, _minor, _dummy_ver = version.group(1).split(".")
386 debian_facts['distribution_version'] = version.group(1)
387 debian_facts['distribution_major_version'] = major
388
389 release = re.search(r'VERSION="(.*)"', data)
390 if release:
391 debian_facts['distribution_release'] = release.groups()[0]
392 elif "Mint" in data:
393 debian_facts['distribution'] = 'Linux Mint'
394 version = re.search(r"VERSION_ID=\"(.*)\"", data)
395 if version:
396 debian_facts['distribution_version'] = version.group(1)
397 debian_facts['distribution_major_version'] = version.group(1).split('.')[0]
398 elif 'UOS' in data or 'Uos' in data or 'uos' in data:
399 # The RHEL-based UnionTech OS Server variants are handled by
400 # parse_distribution_file_UnionTech via the dedicated OSDIST_LIST entry,
401 # so skip them here to avoid mis-classifying them as the Debian-based Uos.
402 if re.search(r'PLATFORM_ID="?platform:uel', data):
403 return False, debian_facts
404 debian_facts['distribution'] = 'Uos'
405 release = re.search(r"VERSION_CODENAME=\"?([^\"]+)\"?", data)
406 if release:
407 debian_facts['distribution_release'] = release.groups()[0]
408 version = re.search(r"VERSION_ID=\"(.*)\"", data)
409 if version:
410 debian_facts['distribution_version'] = version.group(1)
411 debian_facts['distribution_major_version'] = version.group(1).split('.')[0]
412 elif 'Deepin' in data or 'deepin' in data:
413 debian_facts['distribution'] = 'Deepin'
414 release = re.search(r"VERSION_CODENAME=\"?([^\"]+)\"?", data)
415 if release:
416 debian_facts['distribution_release'] = release.groups()[0]
417 version = re.search(r"VERSION_ID=\"(.*)\"", data)
418 if version:
419 debian_facts['distribution_version'] = version.group(1)
420 debian_facts['distribution_major_version'] = version.group(1).split('.')[0]
421 elif 'LMDE' in data:
422 debian_facts['distribution'] = 'Linux Mint Debian Edition'
423 else:
424 return False, debian_facts
425
426 return True, debian_facts
427
428 def parse_distribution_file_Mandriva(self, name, data, path, collected_facts):
429 mandriva_facts = {}
430 if 'Mandriva' in data:
431 mandriva_facts['distribution'] = 'Mandriva'
432 version = re.search('DISTRIB_RELEASE="(.*)"', data)
433 if version:
434 mandriva_facts['distribution_version'] = version.groups()[0]
435 release = re.search('DISTRIB_CODENAME="(.*)"', data)
436 if release:
437 mandriva_facts['distribution_release'] = release.groups()[0]
438 mandriva_facts['distribution'] = name
439 else:
440 return False, mandriva_facts
441
442 return True, mandriva_facts
443
444 def parse_distribution_file_NA(self, name, data, path, collected_facts):
445 na_facts = {}
446 for line in data.splitlines():
447 distribution = re.search("^NAME=(.*)", line)
448 if distribution and name == 'NA':
449 na_facts['distribution'] = distribution.group(1).strip(DistributionFiles.STRIP_QUOTES)
450 version = re.search("^VERSION=(.*)", line)
451 if version and collected_facts['distribution_version'] == 'NA':
452 na_facts['distribution_version'] = version.group(1).strip(DistributionFiles.STRIP_QUOTES)
453 return True, na_facts
454
455 def parse_distribution_file_Coreos(self, name, data, path, collected_facts):
456 coreos_facts = {}
457 # FIXME: pass in ro copy of facts for this kind of thing
458 distro = get_distribution()
459
460 if distro.lower() == 'coreos':
461 if not data:
462 # include fix from #15230, #15228
463 # TODO: verify this is ok for above bugs
464 return False, coreos_facts
465 release = re.search("^GROUP=(.*)", data)
466 if release:
467 coreos_facts['distribution_release'] = release.group(1).strip('"')
468 else:
469 return False, coreos_facts # TODO: remove if tested without this
470
471 return True, coreos_facts
472
473 def parse_distribution_file_Flatcar(self, name, data, path, collected_facts):
474 flatcar_facts = {}
475 distro = get_distribution()
476
477 if distro.lower() != 'flatcar':
478 return False, flatcar_facts
479
480 if not data:
481 return False, flatcar_facts
482
483 version = re.search("VERSION=(.*)", data)
484 if version:
485 flatcar_facts['distribution_major_version'] = version.group(1).strip('"').split('.')[0]
486 flatcar_facts['distribution_version'] = version.group(1).strip('"')
487
488 return True, flatcar_facts
489
490 def parse_distribution_file_ClearLinux(self, name, data, path, collected_facts):
491 clear_facts = {}
492 if "clearlinux" not in name.lower():
493 return False, clear_facts
494
495 pname = re.search('NAME="(.*)"', data)
496 if pname:
497 if 'Clear Linux' not in pname.groups()[0]:
498 return False, clear_facts
499 clear_facts['distribution'] = pname.groups()[0]
500 else:
501 return False, clear_facts
502 version = re.search('VERSION_ID=(.*)', data)
503 if version:
504 clear_facts['distribution_major_version'] = version.groups()[0]
505 clear_facts['distribution_version'] = version.groups()[0]
506 release = re.search('ID=(.*)', data)
507 if release:
508 clear_facts['distribution_release'] = release.groups()[0]
509 return True, clear_facts
510
511 def parse_distribution_file_CentOS(self, name, data, path, collected_facts):
512 centos_facts = {}
513
514 if 'CentOS Stream' in data:
515 centos_facts['distribution_release'] = 'Stream'
516 return True, centos_facts
517
518 if "TencentOS Server" in data:
519 centos_facts['distribution'] = 'TencentOS'
520 return True, centos_facts
521
522 return False, centos_facts
523
524 def parse_distribution_file_UnionTech(self, name, data, path, collected_facts):
525 # UOS Server (RHEL-based) is identified by PLATFORM_ID="platform:uel*" in
526 # /etc/os-release, or "UOS Server release" / "UnionTech OS Server release"
527 # in /etc/redhat-release. UOS Desktop (Debian-based, no PLATFORM_ID) is
528 # left to parse_distribution_file_Debian.
529 uniontech_facts = {}
530 is_uos_release_file = bool(re.search(r'(UnionTech OS Server|UOS Server) release', data))
531 has_uel_platform_id = bool(re.search(r'PLATFORM_ID="?platform:uel', data))
532 if not (is_uos_release_file or has_uel_platform_id):
533 return False, uniontech_facts
534
535 uniontech_facts['distribution'] = 'UnionTech'
536 release = re.search(r'VERSION_CODENAME="?([^"\n]+)"?', data)
537 if release:
538 uniontech_facts['distribution_release'] = release.group(1)
539 else:
540 # /etc/redhat-release style: "UnionTech OS Server release 20 (kongzi)"
541 release = re.search(r'release\s+\S+\s+\(([^)]+)\)', data)
542 if release:
543 uniontech_facts['distribution_release'] = release.group(1)
544 version = re.search(r'VERSION_ID="?([^"\n]+)"?', data)
545 if version:
546 uniontech_facts['distribution_version'] = version.group(1)
547 uniontech_facts['distribution_major_version'] = version.group(1).split('.')[0]
548 else:
549 version = re.search(r'release\s+(\S+)', data)
550 if version:
551 uniontech_facts['distribution_version'] = version.group(1)
552 uniontech_facts['distribution_major_version'] = version.group(1).split('.')[0]
553 return True, uniontech_facts
554
555
556 class Distribution(object):
557 """
558 This subclass of Facts fills the distribution, distribution_version and distribution_release variables
559
560 To do so it checks the existence and content of typical files in /etc containing distribution information
561
562 This is unit tested. Please extend the tests to cover all distributions if you have them available.
563 """
564
565 # keep keys in sync with Conditionals page of docs
566 OS_FAMILY_MAP = {'RedHat': ['RedHat', 'RHEL', 'Fedora', 'CentOS', 'Scientific', 'SLC',
567 'Ascendos', 'CloudLinux', 'PSBM', 'OracleLinux', 'OVS',
568 'OEL', 'Amazon', 'Amzn', 'Virtuozzo', 'XenServer', 'Alibaba',
569 'EulerOS', 'openEuler', 'AlmaLinux', 'Rocky', 'TencentOS',
570 'EuroLinux', 'Kylin Linux Advanced Server', 'MIRACLE',
571 'UnionTech'],
572 'Debian': ['Debian', 'Ubuntu', 'Raspbian', 'Neon', 'KDE neon',
573 'Linux Mint', 'SteamOS', 'Devuan', 'Kali', 'Cumulus Linux',
574 'Pop!_OS', 'Parrot', 'Pardus GNU/Linux', 'Uos', 'Deepin', 'OSMC',
575 'Linux Mint Debian Edition', 'Univention Corporate Server'],
576 'Suse': ['SuSE', 'SLES', 'SLED', 'openSUSE', 'openSUSE Tumbleweed',
577 'SLES_SAP', 'SUSE_LINUX', 'openSUSE Leap', 'ALP-Dolomite', 'SL-Micro',
578 'openSUSE MicroOS'],
579 'Archlinux': ['Archlinux', 'Antergos', 'Manjaro'],
580 'Mandrake': ['Mandrake', 'Mandriva'],
581 'Solaris': ['Solaris', 'Nexenta', 'OmniOS', 'OpenIndiana', 'SmartOS'],
582 'Slackware': ['Slackware'],
583 'Altlinux': ['Altlinux'],
584 'SMGL': ['SMGL'],
585 'Gentoo': ['Gentoo', 'Funtoo'],
586 'Alpine': ['Alpine'],
587 'AIX': ['AIX'],
588 'HP-UX': ['HPUX'],
589 'Darwin': ['MacOSX'],
590 'FreeBSD': ['FreeBSD', 'TrueOS'],
591 'ClearLinux': ['Clear Linux OS', 'Clear Linux Mix'],
592 'DragonFly': ['DragonflyBSD', 'DragonFlyBSD', 'Gentoo/DragonflyBSD', 'Gentoo/DragonFlyBSD'],
593 'NetBSD': ['NetBSD'], }
594
595 OS_FAMILY = {}
596 for family, names in OS_FAMILY_MAP.items():
597 for name in names:
598 OS_FAMILY[name] = family
599
600 def __init__(self, module):
601 self.module = module
602
603 def get_distribution_facts(self):
604 distribution_facts = {}
605
606 # The platform module provides information about the running
607 # system/distribution. Use this as a baseline and fix buggy systems
608 # afterwards
609 system = platform.system()
610 distribution_facts['distribution'] = system
611 distribution_facts['distribution_release'] = platform.release()
612 distribution_facts['distribution_version'] = platform.version()
613
614 systems_implemented = ('AIX', 'HP-UX', 'Darwin', 'FreeBSD', 'OpenBSD', 'SunOS', 'DragonFly', 'NetBSD')
615
616 if system in systems_implemented:
617 cleanedname = system.replace('-', '')
618 distfunc = getattr(self, 'get_distribution_' + cleanedname)
619 dist_func_facts = distfunc()
620 distribution_facts.update(dist_func_facts)
621 elif system == 'Linux':
622
623 distribution_files = DistributionFiles(module=self.module)
624
625 # linux_distribution_facts = LinuxDistribution(module).get_distribution_facts()
626 dist_file_facts = distribution_files.process_dist_files()
627
628 distribution_facts.update(dist_file_facts)
629
630 distro = distribution_facts['distribution']
631 # look for an os family alias for the 'distribution', if there isn't one, use 'distribution'
632 distribution_facts['os_family'] = self.OS_FAMILY.get(distro, None) or distro
633
634 # CPE name as published in the os-release file (when the distro provides one)
635 distribution_facts['distribution_cpe_name'] = get_distribution_cpe_name()
636
637 return distribution_facts
638
639 def get_distribution_AIX(self):
640 aix_facts = {}
641 rc, out, err = self.module.run_command("/usr/bin/oslevel")
642 data = out.split('.')
643 aix_facts['distribution_major_version'] = data[0]
644 if len(data) > 1:
645 aix_facts['distribution_version'] = '%s.%s' % (data[0], data[1])
646 aix_facts['distribution_release'] = data[1]
647 else:
648 aix_facts['distribution_version'] = data[0]
649 return aix_facts
650
651 def get_distribution_HPUX(self):
652 hpux_facts = {}
653 rc, out, err = self.module.run_command(r"/usr/sbin/swlist |egrep 'HPUX.*OE.*[AB].[0-9]+\.[0-9]+'", use_unsafe_shell=True)
654 data = re.search(r'HPUX.*OE.*([AB].[0-9]+\.[0-9]+)\.([0-9]+).*', out)
655 if data:
656 hpux_facts['distribution_version'] = data.groups()[0]
657 hpux_facts['distribution_release'] = data.groups()[1]
658 return hpux_facts
659
660 def get_distribution_Darwin(self):
661 darwin_facts = {}
662 darwin_facts['distribution'] = 'MacOSX'
663 rc, out, err = self.module.run_command("/usr/bin/sw_vers -productVersion")
664 data = out.split()[-1]
665 if data:
666 darwin_facts['distribution_major_version'] = data.split('.')[0]
667 darwin_facts['distribution_version'] = data
668 return darwin_facts
669
670 def get_distribution_FreeBSD(self):
671 freebsd_facts = {}
672 freebsd_facts['distribution_release'] = platform.release()
673 data = re.search(r'(\d+)\.(\d+)-(RELEASE|STABLE|CURRENT|RC|PRERELEASE).*', freebsd_facts['distribution_release'])
674 if 'trueos' in platform.version():
675 freebsd_facts['distribution'] = 'TrueOS'
676 if data:
677 freebsd_facts['distribution_major_version'] = data.group(1)
678 freebsd_facts['distribution_version'] = '%s.%s' % (data.group(1), data.group(2))
679 return freebsd_facts
680
681 def get_distribution_OpenBSD(self):
682 openbsd_facts = {}
683 openbsd_facts['distribution_version'] = platform.release()
684 rc, out, err = self.module.run_command("/sbin/sysctl -n kern.version")
685 match = re.match(r'OpenBSD\s[0-9]+.[0-9]+-(\S+)\s.*', out)
686 if match:
687 openbsd_facts['distribution_release'] = match.groups()[0]
688 else:
689 openbsd_facts['distribution_release'] = 'release'
690 return openbsd_facts
691
692 def get_distribution_DragonFly(self):
693 dragonfly_facts = {
694 'distribution_release': platform.release()
695 }
696 rc, out, dummy = self.module.run_command("/sbin/sysctl -n kern.version")
697 match = re.search(r'v(\d+)\.(\d+)\.(\d+)-(RELEASE|STABLE|CURRENT).*', out)
698 if match:
699 dragonfly_facts['distribution_major_version'] = match.group(1)
700 dragonfly_facts['distribution_version'] = '%s.%s.%s' % match.groups()[:3]
701 return dragonfly_facts
702
703 def get_distribution_NetBSD(self):
704 netbsd_facts = {}
705 platform_release = platform.release()
706 netbsd_facts['distribution_release'] = platform_release
707 rc, out, dummy = self.module.run_command("/sbin/sysctl -n kern.version")
708 match = re.match(r'NetBSD\s(\d+)\.(\d+)\s\((GENERIC)\).*', out)
709 if match:
710 netbsd_facts['distribution_major_version'] = match.group(1)
711 netbsd_facts['distribution_version'] = '%s.%s' % match.groups()[:2]
712 else:
713 netbsd_facts['distribution_major_version'] = platform_release.split('.')[0]
714 netbsd_facts['distribution_version'] = platform_release
715 return netbsd_facts
716
717 def get_distribution_SMGL(self):
718 smgl_facts = {}
719 smgl_facts['distribution'] = 'Source Mage GNU/Linux'
720 return smgl_facts
721
722 def get_distribution_SunOS(self):
723 sunos_facts = {}
724
725 data = get_file_content('/etc/release').splitlines()[0]
726
727 if 'Solaris' in data:
728 # for solaris 10 uname_r will contain 5.10, for solaris 11 it will have 5.11
729 uname_r = get_uname(self.module, flags=['-r'])
730 ora_prefix = ''
731 if 'Oracle Solaris' in data:
732 data = data.replace('Oracle ', '')
733 ora_prefix = 'Oracle '
734 sunos_facts['distribution'] = data.split()[0]
735 sunos_facts['distribution_version'] = data.split()[1]
736 sunos_facts['distribution_release'] = ora_prefix + data
737 sunos_facts['distribution_major_version'] = uname_r.split('.')[1].rstrip()
738 return sunos_facts
739
740 uname_v = get_uname(self.module, flags=['-v'])
741 distribution_version = None
742
743 if 'SmartOS' in data:
744 sunos_facts['distribution'] = 'SmartOS'
745 if _file_exists('/etc/product'):
746 product_data = dict([l.split(': ', 1) for l in get_file_content('/etc/product').splitlines() if ': ' in l])
747 if 'Image' in product_data:
748 distribution_version = product_data.get('Image').split()[-1]
749 elif 'OpenIndiana' in data:
750 sunos_facts['distribution'] = 'OpenIndiana'
751 elif 'OmniOS' in data:
752 sunos_facts['distribution'] = 'OmniOS'
753 distribution_version = data.split()[-1]
754 elif uname_v is not None and 'NexentaOS_' in uname_v:
755 sunos_facts['distribution'] = 'Nexenta'
756 distribution_version = data.split()[-1].lstrip('v')
757
758 if sunos_facts.get('distribution', '') in ('SmartOS', 'OpenIndiana', 'OmniOS', 'Nexenta'):
759 sunos_facts['distribution_release'] = data.strip()
760 if distribution_version is not None:
761 sunos_facts['distribution_version'] = distribution_version
762 elif uname_v is not None:
763 sunos_facts['distribution_version'] = uname_v.splitlines()[0].strip()
764 return sunos_facts
765
766 return sunos_facts
767
768
769 class DistributionFactCollector(BaseFactCollector):
770 name = 'distribution'
771 _fact_ids = set(['distribution_version',
772 'distribution_release',
773 'distribution_major_version',
774 'distribution_cpe_name',
775 'os_family']) # type: t.Set[str]
776
777 def collect(self, module=None, collected_facts=None):
778 collected_facts = collected_facts or {}
779 facts_dict = {}
780 if not module:
781 return facts_dict
782
783 distribution = Distribution(module=module)
784 distro_facts = distribution.get_distribution_facts()
785
786 return distro_facts