Debian Codegraph @

lib/ansible/module_utils/distro/_distro.py

raw
1 # Copyright 2015-2021 Nir Cohen
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 # A local copy of the license can be found in licenses/Apache-License.txt
16 #
17 # Modifications to this code have been made by Ansible Project
18
19 """
20 The ``distro`` package (``distro`` stands for Linux Distribution) provides
21 information about the Linux distribution it runs on, such as a reliable
22 machine-readable distro ID, or version information.
23
24 It is the recommended replacement for Python's original
25 :py:func:`platform.linux_distribution` function, but it provides much more
26 functionality. An alternative implementation became necessary because Python
27 3.5 deprecated this function, and Python 3.8 removed it altogether. Its
28 predecessor function :py:func:`platform.dist` was already deprecated since
29 Python 2.6 and removed in Python 3.8. Still, there are many cases in which
30 access to OS distribution information is needed. See `Python issue 1322
31 <https://bugs.python.org/issue1322>`_ for more information.
32 """
33 from __future__ import annotations
34
35 import argparse
36 import json
37 import logging
38 import os
39 import re
40 import shlex
41 import subprocess
42 import sys
43 import warnings
44 from typing import (
45 Any,
46 Callable,
47 Dict,
48 Iterable,
49 Optional,
50 Sequence,
51 TextIO,
52 Tuple,
53 Type,
54 )
55
56 try:
57 from typing import TypedDict
58 except ImportError:
59 # Python 3.7
60 TypedDict = dict
61
62 __version__ = "1.9.0"
63
64
65 class VersionDict(TypedDict):
66 major: str
67 minor: str
68 build_number: str
69
70
71 class InfoDict(TypedDict):
72 id: str
73 version: str
74 version_parts: VersionDict
75 like: str
76 codename: str
77
78
79 _UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc")
80 _UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib")
81 _OS_RELEASE_BASENAME = "os-release"
82
83 #: Translation table for normalizing the "ID" attribute defined in os-release
84 #: files, for use by the :func:`distro.id` method.
85 #:
86 #: * Key: Value as defined in the os-release file, translated to lower case,
87 #: with blanks translated to underscores.
88 #:
89 #: * Value: Normalized value.
90 NORMALIZED_OS_ID = {
91 "ol": "oracle", # Oracle Linux
92 "opensuse-leap": "opensuse", # Newer versions of OpenSuSE report as opensuse-leap
93 }
94
95 #: Translation table for normalizing the "Distributor ID" attribute returned by
96 #: the lsb_release command, for use by the :func:`distro.id` method.
97 #:
98 #: * Key: Value as returned by the lsb_release command, translated to lower
99 #: case, with blanks translated to underscores.
100 #:
101 #: * Value: Normalized value.
102 NORMALIZED_LSB_ID = {
103 "enterpriseenterpriseas": "oracle", # Oracle Enterprise Linux 4
104 "enterpriseenterpriseserver": "oracle", # Oracle Linux 5
105 "redhatenterpriseworkstation": "rhel", # RHEL 6, 7 Workstation
106 "redhatenterpriseserver": "rhel", # RHEL 6, 7 Server
107 "redhatenterprisecomputenode": "rhel", # RHEL 6 ComputeNode
108 }
109
110 #: Translation table for normalizing the distro ID derived from the file name
111 #: of distro release files, for use by the :func:`distro.id` method.
112 #:
113 #: * Key: Value as derived from the file name of a distro release file,
114 #: translated to lower case, with blanks translated to underscores.
115 #:
116 #: * Value: Normalized value.
117 NORMALIZED_DISTRO_ID = {
118 "redhat": "rhel", # RHEL 6.x, 7.x
119 }
120
121 # Pattern for content of distro release file (reversed)
122 _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
123 r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)"
124 )
125
126 # Pattern for base file name of distro release file
127 _DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$")
128
129 # Base file names to be looked up for if _UNIXCONFDIR is not readable.
130 _DISTRO_RELEASE_BASENAMES = [
131 "SuSE-release",
132 "altlinux-release",
133 "arch-release",
134 "base-release",
135 "centos-release",
136 "fedora-release",
137 "gentoo-release",
138 "mageia-release",
139 "mandrake-release",
140 "mandriva-release",
141 "mandrivalinux-release",
142 "manjaro-release",
143 "oracle-release",
144 "redhat-release",
145 "rocky-release",
146 "sl-release",
147 "slackware-version",
148 ]
149
150 # Base file names to be ignored when searching for distro release file
151 _DISTRO_RELEASE_IGNORE_BASENAMES = (
152 "debian_version",
153 "lsb-release",
154 "oem-release",
155 _OS_RELEASE_BASENAME,
156 "system-release",
157 "plesk-release",
158 "iredmail-release",
159 "board-release",
160 "ec2_version",
161 )
162
163
164 def linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]:
165 """
166 .. deprecated:: 1.6.0
167
168 :func:`distro.linux_distribution()` is deprecated. It should only be
169 used as a compatibility shim with Python's
170 :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`,
171 :func:`distro.version` and :func:`distro.name` instead.
172
173 Return information about the current OS distribution as a tuple
174 ``(id_name, version, codename)`` with items as follows:
175
176 * ``id_name``: If *full_distribution_name* is false, the result of
177 :func:`distro.id`. Otherwise, the result of :func:`distro.name`.
178
179 * ``version``: The result of :func:`distro.version`.
180
181 * ``codename``: The extra item (usually in parentheses) after the
182 os-release version number, or the result of :func:`distro.codename`.
183
184 The interface of this function is compatible with the original
185 :py:func:`platform.linux_distribution` function, supporting a subset of
186 its parameters.
187
188 The data it returns may not exactly be the same, because it uses more data
189 sources than the original function, and that may lead to different data if
190 the OS distribution is not consistent across multiple data sources it
191 provides (there are indeed such distributions ...).
192
193 Another reason for differences is the fact that the :func:`distro.id`
194 method normalizes the distro ID string to a reliable machine-readable value
195 for a number of popular OS distributions.
196 """
197 warnings.warn(
198 "distro.linux_distribution() is deprecated. It should only be used as a "
199 "compatibility shim with Python's platform.linux_distribution(). Please use "
200 "distro.id(), distro.version() and distro.name() instead.",
201 DeprecationWarning,
202 stacklevel=2,
203 )
204 return _distro.linux_distribution(full_distribution_name)
205
206
207 def id() -> str:
208 """
209 Return the distro ID of the current distribution, as a
210 machine-readable string.
211
212 For a number of OS distributions, the returned distro ID value is
213 *reliable*, in the sense that it is documented and that it does not change
214 across releases of the distribution.
215
216 This package maintains the following reliable distro ID values:
217
218 ============== =========================================
219 Distro ID Distribution
220 ============== =========================================
221 "ubuntu" Ubuntu
222 "debian" Debian
223 "rhel" RedHat Enterprise Linux
224 "centos" CentOS
225 "fedora" Fedora
226 "sles" SUSE Linux Enterprise Server
227 "opensuse" openSUSE
228 "amzn" Amazon Linux
229 "arch" Arch Linux
230 "buildroot" Buildroot
231 "cloudlinux" CloudLinux OS
232 "exherbo" Exherbo Linux
233 "gentoo" GenToo Linux
234 "ibm_powerkvm" IBM PowerKVM
235 "kvmibm" KVM for IBM z Systems
236 "linuxmint" Linux Mint
237 "mageia" Mageia
238 "mandriva" Mandriva Linux
239 "parallels" Parallels
240 "pidora" Pidora
241 "raspbian" Raspbian
242 "oracle" Oracle Linux (and Oracle Enterprise Linux)
243 "scientific" Scientific Linux
244 "slackware" Slackware
245 "xenserver" XenServer
246 "openbsd" OpenBSD
247 "netbsd" NetBSD
248 "freebsd" FreeBSD
249 "midnightbsd" MidnightBSD
250 "rocky" Rocky Linux
251 "aix" AIX
252 "guix" Guix System
253 "altlinux" ALT Linux
254 ============== =========================================
255
256 If you have a need to get distros for reliable IDs added into this set,
257 or if you find that the :func:`distro.id` function returns a different
258 distro ID for one of the listed distros, please create an issue in the
259 `distro issue tracker`_.
260
261 **Lookup hierarchy and transformations:**
262
263 First, the ID is obtained from the following sources, in the specified
264 order. The first available and non-empty value is used:
265
266 * the value of the "ID" attribute of the os-release file,
267
268 * the value of the "Distributor ID" attribute returned by the lsb_release
269 command,
270
271 * the first part of the file name of the distro release file,
272
273 The so determined ID value then passes the following transformations,
274 before it is returned by this method:
275
276 * it is translated to lower case,
277
278 * blanks (which should not be there anyway) are translated to underscores,
279
280 * a normalization of the ID is performed, based upon
281 `normalization tables`_. The purpose of this normalization is to ensure
282 that the ID is as reliable as possible, even across incompatible changes
283 in the OS distributions. A common reason for an incompatible change is
284 the addition of an os-release file, or the addition of the lsb_release
285 command, with ID values that differ from what was previously determined
286 from the distro release file name.
287 """
288 return _distro.id()
289
290
291 def name(pretty: bool = False) -> str:
292 """
293 Return the name of the current OS distribution, as a human-readable
294 string.
295
296 If *pretty* is false, the name is returned without version or codename.
297 (e.g. "CentOS Linux")
298
299 If *pretty* is true, the version and codename are appended.
300 (e.g. "CentOS Linux 7.1.1503 (Core)")
301
302 **Lookup hierarchy:**
303
304 The name is obtained from the following sources, in the specified order.
305 The first available and non-empty value is used:
306
307 * If *pretty* is false:
308
309 - the value of the "NAME" attribute of the os-release file,
310
311 - the value of the "Distributor ID" attribute returned by the lsb_release
312 command,
313
314 - the value of the "<name>" field of the distro release file.
315
316 * If *pretty* is true:
317
318 - the value of the "PRETTY_NAME" attribute of the os-release file,
319
320 - the value of the "Description" attribute returned by the lsb_release
321 command,
322
323 - the value of the "<name>" field of the distro release file, appended
324 with the value of the pretty version ("<version_id>" and "<codename>"
325 fields) of the distro release file, if available.
326 """
327 return _distro.name(pretty)
328
329
330 def version(pretty: bool = False, best: bool = False) -> str:
331 """
332 Return the version of the current OS distribution, as a human-readable
333 string.
334
335 If *pretty* is false, the version is returned without codename (e.g.
336 "7.0").
337
338 If *pretty* is true, the codename in parenthesis is appended, if the
339 codename is non-empty (e.g. "7.0 (Maipo)").
340
341 Some distributions provide version numbers with different precisions in
342 the different sources of distribution information. Examining the different
343 sources in a fixed priority order does not always yield the most precise
344 version (e.g. for Debian 8.2, or CentOS 7.1).
345
346 Some other distributions may not provide this kind of information. In these
347 cases, an empty string would be returned. This behavior can be observed
348 with rolling releases distributions (e.g. Arch Linux).
349
350 The *best* parameter can be used to control the approach for the returned
351 version:
352
353 If *best* is false, the first non-empty version number in priority order of
354 the examined sources is returned.
355
356 If *best* is true, the most precise version number out of all examined
357 sources is returned.
358
359 **Lookup hierarchy:**
360
361 In all cases, the version number is obtained from the following sources.
362 If *best* is false, this order represents the priority order:
363
364 * the value of the "VERSION_ID" attribute of the os-release file,
365 * the value of the "Release" attribute returned by the lsb_release
366 command,
367 * the version number parsed from the "<version_id>" field of the first line
368 of the distro release file,
369 * the version number parsed from the "PRETTY_NAME" attribute of the
370 os-release file, if it follows the format of the distro release files.
371 * the version number parsed from the "Description" attribute returned by
372 the lsb_release command, if it follows the format of the distro release
373 files.
374 """
375 return _distro.version(pretty, best)
376
377
378 def version_parts(best: bool = False) -> Tuple[str, str, str]:
379 """
380 Return the version of the current OS distribution as a tuple
381 ``(major, minor, build_number)`` with items as follows:
382
383 * ``major``: The result of :func:`distro.major_version`.
384
385 * ``minor``: The result of :func:`distro.minor_version`.
386
387 * ``build_number``: The result of :func:`distro.build_number`.
388
389 For a description of the *best* parameter, see the :func:`distro.version`
390 method.
391 """
392 return _distro.version_parts(best)
393
394
395 def major_version(best: bool = False) -> str:
396 """
397 Return the major version of the current OS distribution, as a string,
398 if provided.
399 Otherwise, the empty string is returned. The major version is the first
400 part of the dot-separated version string.
401
402 For a description of the *best* parameter, see the :func:`distro.version`
403 method.
404 """
405 return _distro.major_version(best)
406
407
408 def minor_version(best: bool = False) -> str:
409 """
410 Return the minor version of the current OS distribution, as a string,
411 if provided.
412 Otherwise, the empty string is returned. The minor version is the second
413 part of the dot-separated version string.
414
415 For a description of the *best* parameter, see the :func:`distro.version`
416 method.
417 """
418 return _distro.minor_version(best)
419
420
421 def build_number(best: bool = False) -> str:
422 """
423 Return the build number of the current OS distribution, as a string,
424 if provided.
425 Otherwise, the empty string is returned. The build number is the third part
426 of the dot-separated version string.
427
428 For a description of the *best* parameter, see the :func:`distro.version`
429 method.
430 """
431 return _distro.build_number(best)
432
433
434 def like() -> str:
435 """
436 Return a space-separated list of distro IDs of distributions that are
437 closely related to the current OS distribution in regards to packaging
438 and programming interfaces, for example distributions the current
439 distribution is a derivative from.
440
441 **Lookup hierarchy:**
442
443 This information item is only provided by the os-release file.
444 For details, see the description of the "ID_LIKE" attribute in the
445 `os-release man page
446 <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.
447 """
448 return _distro.like()
449
450
451 def codename() -> str:
452 """
453 Return the codename for the release of the current OS distribution,
454 as a string.
455
456 If the distribution does not have a codename, an empty string is returned.
457
458 Note that the returned codename is not always really a codename. For
459 example, openSUSE returns "x86_64". This function does not handle such
460 cases in any special way and just returns the string it finds, if any.
461
462 **Lookup hierarchy:**
463
464 * the codename within the "VERSION" attribute of the os-release file, if
465 provided,
466
467 * the value of the "Codename" attribute returned by the lsb_release
468 command,
469
470 * the value of the "<codename>" field of the distro release file.
471 """
472 return _distro.codename()
473
474
475 def info(pretty: bool = False, best: bool = False) -> InfoDict:
476 """
477 Return certain machine-readable information items about the current OS
478 distribution in a dictionary, as shown in the following example:
479
480 .. sourcecode:: python
481
482 {
483 'id': 'rhel',
484 'version': '7.0',
485 'version_parts': {
486 'major': '7',
487 'minor': '0',
488 'build_number': ''
489 },
490 'like': 'fedora',
491 'codename': 'Maipo'
492 }
493
494 The dictionary structure and keys are always the same, regardless of which
495 information items are available in the underlying data sources. The values
496 for the various keys are as follows:
497
498 * ``id``: The result of :func:`distro.id`.
499
500 * ``version``: The result of :func:`distro.version`.
501
502 * ``version_parts -> major``: The result of :func:`distro.major_version`.
503
504 * ``version_parts -> minor``: The result of :func:`distro.minor_version`.
505
506 * ``version_parts -> build_number``: The result of
507 :func:`distro.build_number`.
508
509 * ``like``: The result of :func:`distro.like`.
510
511 * ``codename``: The result of :func:`distro.codename`.
512
513 For a description of the *pretty* and *best* parameters, see the
514 :func:`distro.version` method.
515 """
516 return _distro.info(pretty, best)
517
518
519 def os_release_info() -> Dict[str, str]:
520 """
521 Return a dictionary containing key-value pairs for the information items
522 from the os-release file data source of the current OS distribution.
523
524 See `os-release file`_ for details about these information items.
525 """
526 return _distro.os_release_info()
527
528
529 def lsb_release_info() -> Dict[str, str]:
530 """
531 Return a dictionary containing key-value pairs for the information items
532 from the lsb_release command data source of the current OS distribution.
533
534 See `lsb_release command output`_ for details about these information
535 items.
536 """
537 return _distro.lsb_release_info()
538
539
540 def distro_release_info() -> Dict[str, str]:
541 """
542 Return a dictionary containing key-value pairs for the information items
543 from the distro release file data source of the current OS distribution.
544
545 See `distro release file`_ for details about these information items.
546 """
547 return _distro.distro_release_info()
548
549
550 def uname_info() -> Dict[str, str]:
551 """
552 Return a dictionary containing key-value pairs for the information items
553 from the distro release file data source of the current OS distribution.
554 """
555 return _distro.uname_info()
556
557
558 def os_release_attr(attribute: str) -> str:
559 """
560 Return a single named information item from the os-release file data source
561 of the current OS distribution.
562
563 Parameters:
564
565 * ``attribute`` (string): Key of the information item.
566
567 Returns:
568
569 * (string): Value of the information item, if the item exists.
570 The empty string, if the item does not exist.
571
572 See `os-release file`_ for details about these information items.
573 """
574 return _distro.os_release_attr(attribute)
575
576
577 def lsb_release_attr(attribute: str) -> str:
578 """
579 Return a single named information item from the lsb_release command output
580 data source of the current OS distribution.
581
582 Parameters:
583
584 * ``attribute`` (string): Key of the information item.
585
586 Returns:
587
588 * (string): Value of the information item, if the item exists.
589 The empty string, if the item does not exist.
590
591 See `lsb_release command output`_ for details about these information
592 items.
593 """
594 return _distro.lsb_release_attr(attribute)
595
596
597 def distro_release_attr(attribute: str) -> str:
598 """
599 Return a single named information item from the distro release file
600 data source of the current OS distribution.
601
602 Parameters:
603
604 * ``attribute`` (string): Key of the information item.
605
606 Returns:
607
608 * (string): Value of the information item, if the item exists.
609 The empty string, if the item does not exist.
610
611 See `distro release file`_ for details about these information items.
612 """
613 return _distro.distro_release_attr(attribute)
614
615
616 def uname_attr(attribute: str) -> str:
617 """
618 Return a single named information item from the distro release file
619 data source of the current OS distribution.
620
621 Parameters:
622
623 * ``attribute`` (string): Key of the information item.
624
625 Returns:
626
627 * (string): Value of the information item, if the item exists.
628 The empty string, if the item does not exist.
629 """
630 return _distro.uname_attr(attribute)
631
632
633 try:
634 from functools import cached_property
635 except ImportError:
636 # Python < 3.8
637 class cached_property: # type: ignore
638 """A version of @property which caches the value. On access, it calls the
639 underlying function and sets the value in `__dict__` so future accesses
640 will not re-call the property.
641 """
642
643 def __init__(self, f: Callable[[Any], Any]) -> None:
644 self._fname = f.__name__
645 self._f = f
646
647 def __get__(self, obj: Any, owner: Type[Any]) -> Any:
648 assert obj is not None, f"call {self._fname} on an instance"
649 ret = obj.__dict__[self._fname] = self._f(obj)
650 return ret
651
652
653 class LinuxDistribution:
654 """
655 Provides information about a OS distribution.
656
657 This package creates a private module-global instance of this class with
658 default initialization arguments, that is used by the
659 `consolidated accessor functions`_ and `single source accessor functions`_.
660 By using default initialization arguments, that module-global instance
661 returns data about the current OS distribution (i.e. the distro this
662 package runs on).
663
664 Normally, it is not necessary to create additional instances of this class.
665 However, in situations where control is needed over the exact data sources
666 that are used, instances of this class can be created with a specific
667 distro release file, or a specific os-release file, or without invoking the
668 lsb_release command.
669 """
670
671 def __init__(
672 self,
673 include_lsb: Optional[bool] = None,
674 os_release_file: str = "",
675 distro_release_file: str = "",
676 include_uname: Optional[bool] = None,
677 root_dir: Optional[str] = None,
678 include_oslevel: Optional[bool] = None,
679 ) -> None:
680 """
681 The initialization method of this class gathers information from the
682 available data sources, and stores that in private instance attributes.
683 Subsequent access to the information items uses these private instance
684 attributes, so that the data sources are read only once.
685
686 Parameters:
687
688 * ``include_lsb`` (bool): Controls whether the
689 `lsb_release command output`_ is included as a data source.
690
691 If the lsb_release command is not available in the program execution
692 path, the data source for the lsb_release command will be empty.
693
694 * ``os_release_file`` (string): The path name of the
695 `os-release file`_ that is to be used as a data source.
696
697 An empty string (the default) will cause the default path name to
698 be used (see `os-release file`_ for details).
699
700 If the specified or defaulted os-release file does not exist, the
701 data source for the os-release file will be empty.
702
703 * ``distro_release_file`` (string): The path name of the
704 `distro release file`_ that is to be used as a data source.
705
706 An empty string (the default) will cause a default search algorithm
707 to be used (see `distro release file`_ for details).
708
709 If the specified distro release file does not exist, or if no default
710 distro release file can be found, the data source for the distro
711 release file will be empty.
712
713 * ``include_uname`` (bool): Controls whether uname command output is
714 included as a data source. If the uname command is not available in
715 the program execution path the data source for the uname command will
716 be empty.
717
718 * ``root_dir`` (string): The absolute path to the root directory to use
719 to find distro-related information files. Note that ``include_*``
720 parameters must not be enabled in combination with ``root_dir``.
721
722 * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command
723 output is included as a data source. If the oslevel command is not
724 available in the program execution path the data source will be
725 empty.
726
727 Public instance attributes:
728
729 * ``os_release_file`` (string): The path name of the
730 `os-release file`_ that is actually used as a data source. The
731 empty string if no distro release file is used as a data source.
732
733 * ``distro_release_file`` (string): The path name of the
734 `distro release file`_ that is actually used as a data source. The
735 empty string if no distro release file is used as a data source.
736
737 * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.
738 This controls whether the lsb information will be loaded.
739
740 * ``include_uname`` (bool): The result of the ``include_uname``
741 parameter. This controls whether the uname information will
742 be loaded.
743
744 * ``include_oslevel`` (bool): The result of the ``include_oslevel``
745 parameter. This controls whether (AIX) oslevel information will be
746 loaded.
747
748 * ``root_dir`` (string): The result of the ``root_dir`` parameter.
749 The absolute path to the root directory to use to find distro-related
750 information files.
751
752 Raises:
753
754 * :py:exc:`ValueError`: Initialization parameters combination is not
755 supported.
756
757 * :py:exc:`OSError`: Some I/O issue with an os-release file or distro
758 release file.
759
760 * :py:exc:`UnicodeError`: A data source has unexpected characters or
761 uses an unexpected encoding.
762 """
763 self.root_dir = root_dir
764 self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR
765 self.usr_lib_dir = (
766 os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR
767 )
768
769 if os_release_file:
770 self.os_release_file = os_release_file
771 else:
772 etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)
773 usr_lib_os_release_file = os.path.join(
774 self.usr_lib_dir, _OS_RELEASE_BASENAME
775 )
776
777 # NOTE: The idea is to respect order **and** have it set
778 # at all times for API backwards compatibility.
779 if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(
780 usr_lib_os_release_file
781 ):
782 self.os_release_file = etc_dir_os_release_file
783 else:
784 self.os_release_file = usr_lib_os_release_file
785
786 self.distro_release_file = distro_release_file or "" # updated later
787
788 is_root_dir_defined = root_dir is not None
789 if is_root_dir_defined and (include_lsb or include_uname or include_oslevel):
790 raise ValueError(
791 "Including subprocess data sources from specific root_dir is disallowed"
792 " to prevent false information"
793 )
794 self.include_lsb = (
795 include_lsb if include_lsb is not None else not is_root_dir_defined
796 )
797 self.include_uname = (
798 include_uname if include_uname is not None else not is_root_dir_defined
799 )
800 self.include_oslevel = (
801 include_oslevel if include_oslevel is not None else not is_root_dir_defined
802 )
803
804 def __repr__(self) -> str:
805 """Return repr of all info"""
806 return (
807 "LinuxDistribution("
808 "os_release_file={self.os_release_file!r}, "
809 "distro_release_file={self.distro_release_file!r}, "
810 "include_lsb={self.include_lsb!r}, "
811 "include_uname={self.include_uname!r}, "
812 "include_oslevel={self.include_oslevel!r}, "
813 "root_dir={self.root_dir!r}, "
814 "_os_release_info={self._os_release_info!r}, "
815 "_lsb_release_info={self._lsb_release_info!r}, "
816 "_distro_release_info={self._distro_release_info!r}, "
817 "_uname_info={self._uname_info!r}, "
818 "_oslevel_info={self._oslevel_info!r})".format(self=self)
819 )
820
821 def linux_distribution(
822 self, full_distribution_name: bool = True
823 ) -> Tuple[str, str, str]:
824 """
825 Return information about the OS distribution that is compatible
826 with Python's :func:`platform.linux_distribution`, supporting a subset
827 of its parameters.
828
829 For details, see :func:`distro.linux_distribution`.
830 """
831 return (
832 self.name() if full_distribution_name else self.id(),
833 self.version(),
834 self._os_release_info.get("release_codename") or self.codename(),
835 )
836
837 def id(self) -> str:
838 """Return the distro ID of the OS distribution, as a string.
839
840 For details, see :func:`distro.id`.
841 """
842
843 def normalize(distro_id: str, table: Dict[str, str]) -> str:
844 distro_id = distro_id.lower().replace(" ", "_")
845 return table.get(distro_id, distro_id)
846
847 distro_id = self.os_release_attr("id")
848 if distro_id:
849 return normalize(distro_id, NORMALIZED_OS_ID)
850
851 distro_id = self.lsb_release_attr("distributor_id")
852 if distro_id:
853 return normalize(distro_id, NORMALIZED_LSB_ID)
854
855 distro_id = self.distro_release_attr("id")
856 if distro_id:
857 return normalize(distro_id, NORMALIZED_DISTRO_ID)
858
859 distro_id = self.uname_attr("id")
860 if distro_id:
861 return normalize(distro_id, NORMALIZED_DISTRO_ID)
862
863 return ""
864
865 def name(self, pretty: bool = False) -> str:
866 """
867 Return the name of the OS distribution, as a string.
868
869 For details, see :func:`distro.name`.
870 """
871 name = (
872 self.os_release_attr("name")
873 or self.lsb_release_attr("distributor_id")
874 or self.distro_release_attr("name")
875 or self.uname_attr("name")
876 )
877 if pretty:
878 name = self.os_release_attr("pretty_name") or self.lsb_release_attr(
879 "description"
880 )
881 if not name:
882 name = self.distro_release_attr("name") or self.uname_attr("name")
883 version = self.version(pretty=True)
884 if version:
885 name = f"{name} {version}"
886 return name or ""
887
888 def version(self, pretty: bool = False, best: bool = False) -> str:
889 """
890 Return the version of the OS distribution, as a string.
891
892 For details, see :func:`distro.version`.
893 """
894 versions = [
895 self.os_release_attr("version_id"),
896 self.lsb_release_attr("release"),
897 self.distro_release_attr("version_id"),
898 self._parse_distro_release_content(self.os_release_attr("pretty_name")).get(
899 "version_id", ""
900 ),
901 self._parse_distro_release_content(
902 self.lsb_release_attr("description")
903 ).get("version_id", ""),
904 self.uname_attr("release"),
905 ]
906 if self.uname_attr("id").startswith("aix"):
907 # On AIX platforms, prefer oslevel command output.
908 versions.insert(0, self.oslevel_info())
909 elif self.id() == "debian" or "debian" in self.like().split():
910 # On Debian-like, add debian_version file content to candidates list.
911 versions.append(self._debian_version)
912 version = ""
913 if best:
914 # This algorithm uses the last version in priority order that has
915 # the best precision. If the versions are not in conflict, that
916 # does not matter; otherwise, using the last one instead of the
917 # first one might be considered a surprise.
918 for v in versions:
919 if v.count(".") > version.count(".") or version == "":
920 version = v
921 else:
922 for v in versions:
923 if v != "":
924 version = v
925 break
926 if pretty and version and self.codename():
927 version = f"{version} ({self.codename()})"
928 return version
929
930 def version_parts(self, best: bool = False) -> Tuple[str, str, str]:
931 """
932 Return the version of the OS distribution, as a tuple of version
933 numbers.
934
935 For details, see :func:`distro.version_parts`.
936 """
937 version_str = self.version(best=best)
938 if version_str:
939 version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?")
940 matches = version_regex.match(version_str)
941 if matches:
942 major, minor, build_number = matches.groups()
943 return major, minor or "", build_number or ""
944 return "", "", ""
945
946 def major_version(self, best: bool = False) -> str:
947 """
948 Return the major version number of the current distribution.
949
950 For details, see :func:`distro.major_version`.
951 """
952 return self.version_parts(best)[0]
953
954 def minor_version(self, best: bool = False) -> str:
955 """
956 Return the minor version number of the current distribution.
957
958 For details, see :func:`distro.minor_version`.
959 """
960 return self.version_parts(best)[1]
961
962 def build_number(self, best: bool = False) -> str:
963 """
964 Return the build number of the current distribution.
965
966 For details, see :func:`distro.build_number`.
967 """
968 return self.version_parts(best)[2]
969
970 def like(self) -> str:
971 """
972 Return the IDs of distributions that are like the OS distribution.
973
974 For details, see :func:`distro.like`.
975 """
976 return self.os_release_attr("id_like") or ""
977
978 def codename(self) -> str:
979 """
980 Return the codename of the OS distribution.
981
982 For details, see :func:`distro.codename`.
983 """
984 try:
985 # Handle os_release specially since distros might purposefully set
986 # this to empty string to have no codename
987 return self._os_release_info["codename"]
988 except KeyError:
989 return (
990 self.lsb_release_attr("codename")
991 or self.distro_release_attr("codename")
992 or ""
993 )
994
995 def info(self, pretty: bool = False, best: bool = False) -> InfoDict:
996 """
997 Return certain machine-readable information about the OS
998 distribution.
999
1000 For details, see :func:`distro.info`.
1001 """
1002 return InfoDict(
1003 id=self.id(),
1004 version=self.version(pretty, best),
1005 version_parts=VersionDict(
1006 major=self.major_version(best),
1007 minor=self.minor_version(best),
1008 build_number=self.build_number(best),
1009 ),
1010 like=self.like(),
1011 codename=self.codename(),
1012 )
1013
1014 def os_release_info(self) -> Dict[str, str]:
1015 """
1016 Return a dictionary containing key-value pairs for the information
1017 items from the os-release file data source of the OS distribution.
1018
1019 For details, see :func:`distro.os_release_info`.
1020 """
1021 return self._os_release_info
1022
1023 def lsb_release_info(self) -> Dict[str, str]:
1024 """
1025 Return a dictionary containing key-value pairs for the information
1026 items from the lsb_release command data source of the OS
1027 distribution.
1028
1029 For details, see :func:`distro.lsb_release_info`.
1030 """
1031 return self._lsb_release_info
1032
1033 def distro_release_info(self) -> Dict[str, str]:
1034 """
1035 Return a dictionary containing key-value pairs for the information
1036 items from the distro release file data source of the OS
1037 distribution.
1038
1039 For details, see :func:`distro.distro_release_info`.
1040 """
1041 return self._distro_release_info
1042
1043 def uname_info(self) -> Dict[str, str]:
1044 """
1045 Return a dictionary containing key-value pairs for the information
1046 items from the uname command data source of the OS distribution.
1047
1048 For details, see :func:`distro.uname_info`.
1049 """
1050 return self._uname_info
1051
1052 def oslevel_info(self) -> str:
1053 """
1054 Return AIX' oslevel command output.
1055 """
1056 return self._oslevel_info
1057
1058 def os_release_attr(self, attribute: str) -> str:
1059 """
1060 Return a single named information item from the os-release file data
1061 source of the OS distribution.
1062
1063 For details, see :func:`distro.os_release_attr`.
1064 """
1065 return self._os_release_info.get(attribute, "")
1066
1067 def lsb_release_attr(self, attribute: str) -> str:
1068 """
1069 Return a single named information item from the lsb_release command
1070 output data source of the OS distribution.
1071
1072 For details, see :func:`distro.lsb_release_attr`.
1073 """
1074 return self._lsb_release_info.get(attribute, "")
1075
1076 def distro_release_attr(self, attribute: str) -> str:
1077 """
1078 Return a single named information item from the distro release file
1079 data source of the OS distribution.
1080
1081 For details, see :func:`distro.distro_release_attr`.
1082 """
1083 return self._distro_release_info.get(attribute, "")
1084
1085 def uname_attr(self, attribute: str) -> str:
1086 """
1087 Return a single named information item from the uname command
1088 output data source of the OS distribution.
1089
1090 For details, see :func:`distro.uname_attr`.
1091 """
1092 return self._uname_info.get(attribute, "")
1093
1094 @cached_property
1095 def _os_release_info(self) -> Dict[str, str]:
1096 """
1097 Get the information items from the specified os-release file.
1098
1099 Returns:
1100 A dictionary containing all information items.
1101 """
1102 if os.path.isfile(self.os_release_file):
1103 with open(self.os_release_file, encoding="utf-8") as release_file:
1104 return self._parse_os_release_content(release_file)
1105 return {}
1106
1107 @staticmethod
1108 def _parse_os_release_content(lines: TextIO) -> Dict[str, str]:
1109 """
1110 Parse the lines of an os-release file.
1111
1112 Parameters:
1113
1114 * lines: Iterable through the lines in the os-release file.
1115 Each line must be a unicode string or a UTF-8 encoded byte
1116 string.
1117
1118 Returns:
1119 A dictionary containing all information items.
1120 """
1121 props = {}
1122 lexer = shlex.shlex(lines, posix=True)
1123 lexer.whitespace_split = True
1124
1125 tokens = list(lexer)
1126 for token in tokens:
1127 # At this point, all shell-like parsing has been done (i.e.
1128 # comments processed, quotes and backslash escape sequences
1129 # processed, multi-line values assembled, trailing newlines
1130 # stripped, etc.), so the tokens are now either:
1131 # * variable assignments: var=value
1132 # * commands or their arguments (not allowed in os-release)
1133 # Ignore any tokens that are not variable assignments
1134 if "=" in token:
1135 k, v = token.split("=", 1)
1136 props[k.lower()] = v
1137
1138 if "version" in props:
1139 # extract release codename (if any) from version attribute
1140 match = re.search(r"\((\D+)\)|,\s*(\D+)", props["version"])
1141 if match:
1142 release_codename = match.group(1) or match.group(2)
1143 props["codename"] = props["release_codename"] = release_codename
1144
1145 if "version_codename" in props:
1146 # os-release added a version_codename field. Use that in
1147 # preference to anything else Note that some distros purposefully
1148 # do not have code names. They should be setting
1149 # version_codename=""
1150 props["codename"] = props["version_codename"]
1151 elif "ubuntu_codename" in props:
1152 # Same as above but a non-standard field name used on older Ubuntus
1153 props["codename"] = props["ubuntu_codename"]
1154
1155 return props
1156
1157 @cached_property
1158 def _lsb_release_info(self) -> Dict[str, str]:
1159 """
1160 Get the information items from the lsb_release command output.
1161
1162 Returns:
1163 A dictionary containing all information items.
1164 """
1165 if not self.include_lsb:
1166 return {}
1167 try:
1168 cmd = ("lsb_release", "-a")
1169 stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
1170 # Command not found or lsb_release returned error
1171 except (OSError, subprocess.CalledProcessError):
1172 return {}
1173 content = self._to_str(stdout).splitlines()
1174 return self._parse_lsb_release_content(content)
1175
1176 @staticmethod
1177 def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]:
1178 """
1179 Parse the output of the lsb_release command.
1180
1181 Parameters:
1182
1183 * lines: Iterable through the lines of the lsb_release output.
1184 Each line must be a unicode string or a UTF-8 encoded byte
1185 string.
1186
1187 Returns:
1188 A dictionary containing all information items.
1189 """
1190 props = {}
1191 for line in lines:
1192 kv = line.strip("\n").split(":", 1)
1193 if len(kv) != 2:
1194 # Ignore lines without colon.
1195 continue
1196 k, v = kv
1197 props.update({k.replace(" ", "_").lower(): v.strip()})
1198 return props
1199
1200 @cached_property
1201 def _uname_info(self) -> Dict[str, str]:
1202 if not self.include_uname:
1203 return {}
1204 try:
1205 cmd = ("uname", "-rs")
1206 stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
1207 except OSError:
1208 return {}
1209 content = self._to_str(stdout).splitlines()
1210 return self._parse_uname_content(content)
1211
1212 @cached_property
1213 def _oslevel_info(self) -> str:
1214 if not self.include_oslevel:
1215 return ""
1216 try:
1217 stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
1218 except (OSError, subprocess.CalledProcessError):
1219 return ""
1220 return self._to_str(stdout).strip()
1221
1222 @cached_property
1223 def _debian_version(self) -> str:
1224 try:
1225 with open(
1226 os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
1227 ) as fp:
1228 return fp.readline().rstrip()
1229 except FileNotFoundError:
1230 return ""
1231
1232 @staticmethod
1233 def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:
1234 if not lines:
1235 return {}
1236 props = {}
1237 match = re.search(r"^([^\s]+)\s+([\d\.]+)", lines[0].strip())
1238 if match:
1239 name, version = match.groups()
1240
1241 # This is to prevent the Linux kernel version from
1242 # appearing as the 'best' version on otherwise
1243 # identifiable distributions.
1244 if name == "Linux":
1245 return {}
1246 props["id"] = name.lower()
1247 props["name"] = name
1248 props["release"] = version
1249 return props
1250
1251 @staticmethod
1252 def _to_str(bytestring: bytes) -> str:
1253 encoding = sys.getfilesystemencoding()
1254 return bytestring.decode(encoding)
1255
1256 @cached_property
1257 def _distro_release_info(self) -> Dict[str, str]:
1258 """
1259 Get the information items from the specified distro release file.
1260
1261 Returns:
1262 A dictionary containing all information items.
1263 """
1264 if self.distro_release_file:
1265 # If it was specified, we use it and parse what we can, even if
1266 # its file name or content does not match the expected pattern.
1267 distro_info = self._parse_distro_release_file(self.distro_release_file)
1268 basename = os.path.basename(self.distro_release_file)
1269 # The file name pattern for user-specified distro release files
1270 # is somewhat more tolerant (compared to when searching for the
1271 # file), because we want to use what was specified as best as
1272 # possible.
1273 match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
1274 else:
1275 try:
1276 basenames = [
1277 basename
1278 for basename in os.listdir(self.etc_dir)
1279 if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES
1280 and os.path.isfile(os.path.join(self.etc_dir, basename))
1281 ]
1282 # We sort for repeatability in cases where there are multiple
1283 # distro specific files; e.g. CentOS, Oracle, Enterprise all
1284 # containing `redhat-release` on top of their own.
1285 basenames.sort()
1286 except OSError:
1287 # This may occur when /etc is not readable but we can't be
1288 # sure about the *-release files. Check common entries of
1289 # /etc for information. If they turn out to not be there the
1290 # error is handled in `_parse_distro_release_file()`.
1291 basenames = _DISTRO_RELEASE_BASENAMES
1292 for basename in basenames:
1293 match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
1294 if match is None:
1295 continue
1296 filepath = os.path.join(self.etc_dir, basename)
1297 distro_info = self._parse_distro_release_file(filepath)
1298 # The name is always present if the pattern matches.
1299 if "name" not in distro_info:
1300 continue
1301 self.distro_release_file = filepath
1302 break
1303 else: # the loop didn't "break": no candidate.
1304 return {}
1305
1306 if match is not None:
1307 distro_info["id"] = match.group(1)
1308
1309 # CloudLinux < 7: manually enrich info with proper id.
1310 if "cloudlinux" in distro_info.get("name", "").lower():
1311 distro_info["id"] = "cloudlinux"
1312
1313 return distro_info
1314
1315 def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]:
1316 """
1317 Parse a distro release file.
1318
1319 Parameters:
1320
1321 * filepath: Path name of the distro release file.
1322
1323 Returns:
1324 A dictionary containing all information items.
1325 """
1326 try:
1327 with open(filepath, encoding="utf-8") as fp:
1328 # Only parse the first line. For instance, on SLES there
1329 # are multiple lines. We don't want them...
1330 return self._parse_distro_release_content(fp.readline())
1331 except OSError:
1332 # Ignore not being able to read a specific, seemingly version
1333 # related file.
1334 # See https://github.com/python-distro/distro/issues/162
1335 return {}
1336
1337 @staticmethod
1338 def _parse_distro_release_content(line: str) -> Dict[str, str]:
1339 """
1340 Parse a line from a distro release file.
1341
1342 Parameters:
1343 * line: Line from the distro release file. Must be a unicode string
1344 or a UTF-8 encoded byte string.
1345
1346 Returns:
1347 A dictionary containing all information items.
1348 """
1349 matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])
1350 distro_info = {}
1351 if matches:
1352 # regexp ensures non-None
1353 distro_info["name"] = matches.group(3)[::-1]
1354 if matches.group(2):
1355 distro_info["version_id"] = matches.group(2)[::-1]
1356 if matches.group(1):
1357 distro_info["codename"] = matches.group(1)[::-1]
1358 elif line:
1359 distro_info["name"] = line.strip()
1360 return distro_info
1361
1362
1363 _distro = LinuxDistribution()
1364
1365
1366 def main() -> None:
1367 logger = logging.getLogger(__name__)
1368 logger.setLevel(logging.DEBUG)
1369 logger.addHandler(logging.StreamHandler(sys.stdout))
1370
1371 parser = argparse.ArgumentParser(description="OS distro info tool")
1372 parser.add_argument(
1373 "--json", "-j", help="Output in machine readable format", action="store_true"
1374 )
1375
1376 parser.add_argument(
1377 "--root-dir",
1378 "-r",
1379 type=str,
1380 dest="root_dir",
1381 help="Path to the root filesystem directory (defaults to /)",
1382 )
1383
1384 args = parser.parse_args()
1385
1386 if args.root_dir:
1387 dist = LinuxDistribution(
1388 include_lsb=False,
1389 include_uname=False,
1390 include_oslevel=False,
1391 root_dir=args.root_dir,
1392 )
1393 else:
1394 dist = _distro
1395
1396 if args.json:
1397 logger.info(json.dumps(dist.info(), indent=4, sort_keys=True))
1398 else:
1399 logger.info("Name: %s", dist.name(pretty=True))
1400 distribution_version = dist.version(pretty=True)
1401 logger.info("Version: %s", distribution_version)
1402 distribution_codename = dist.codename()
1403 logger.info("Codename: %s", distribution_codename)
1404
1405
1406 if __name__ == "__main__":
1407 main()