Skip to content

Commit

Permalink
Switch to distro package for os recognition.
Browse files Browse the repository at this point in the history
  • Loading branch information
GeorgePantelakis committed Jun 5, 2024
1 parent fc5e710 commit 5469e09
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 48 deletions.
21 changes: 9 additions & 12 deletions SCAutolib/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
from SCAutolib.models import CA, file, user, card, authselect as auth
from SCAutolib.models.file import File, OpensslCnf
from SCAutolib.models.CA import BaseCA
from SCAutolib.enums import (OSVersion, CardType, UserType)
from SCAutolib.enums import (CardType, UserType)
from SCAutolib.utils import (_check_selinux, _gen_private_key,
_get_os_version, _install_packages,
_check_packages, dump_to_json, ca_factory)
_install_packages, _check_packages,
dump_to_json, ca_factory)
from SCAutolib.isDistro import isDistro


class Controller:
Expand Down Expand Up @@ -140,8 +141,6 @@ def setup_system(self, install_missing: bool, gdm: bool, graphical: bool):
:type graphical: bool
:return:
"""
os_version = _get_os_version()

for d in (LIB_DIR, LIB_BACKUP, LIB_DUMP, LIB_DUMP_USERS, LIB_DUMP_CAS,
LIB_DUMP_CARDS):
d.mkdir(exist_ok=True)
Expand All @@ -161,7 +160,7 @@ def setup_system(self, install_missing: bool, gdm: bool, graphical: bool):
packages += ["pcsc-lite-ccid", "pcsc-lite", "virt_cacard",
"vpcd", "softhsm"]
extra_args = ""
if os_version in (OSVersion.RHEL_10, OSVersion.CentOS_10):
if isDistro(['rhel', 'centos'], version='10'):
# TODO: use better approach later
extra_args = " centos-stream-10-x86_64"
run("dnf -y copr enable jjelen/vsmartcard{0}".format(extra_args))
Expand All @@ -181,9 +180,8 @@ def setup_system(self, install_missing: bool, gdm: bool, graphical: bool):
logger.critical(msg)
raise exceptions.SCAutolibException(msg)

print(f"Os version: {os_version}")
if graphical:
if os_version != OSVersion.Fedora:
if not isDistro('fedora'):
run(['dnf', 'groupinstall', 'Server with GUI', '-y',
'--allowerasing'])
run(['pip', 'install', 'python-uinput'])
Expand All @@ -199,7 +197,7 @@ def setup_system(self, install_missing: bool, gdm: bool, graphical: bool):
self.dconf_file.save()
run('dconf update')

if os_version != OSVersion.Fedora:
if not isDistro('fedora'):
run(['dnf', 'groupinstall', "Smart Card Support", '-y',
'--allowerasing'])
logger.debug("Smart Card Support group in installed.")
Expand Down Expand Up @@ -538,13 +536,12 @@ def _general_steps_for_ipa():
:return: name of the IPA client package for current Linux
"""
os_version = _get_os_version()
if os_version in (OSVersion.RHEL_8, OSVersion.CentOS_8):
if isDistro(['rhel', 'centos'], version='8'):
run("dnf module enable -y idm:DL1")
run("dnf install @idm:DL1 -y")
logger.debug("idm:DL1 module is installed")

if os_version == OSVersion.Fedora:
if isDistro('fedora'):
return ["freeipa-client"]
else:
return ["ipa-client"]
Expand Down
50 changes: 50 additions & 0 deletions SCAutolib/isDistro.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""
This module provides a function (isDistro) that helps us identify the os
of the system and configure the system accordingly.
"""

import distro
from typing import Union


def isDistro(oses: Union[str, list], version: str = None) -> bool:
cur_id = distro.id().lower()
cur_name = distro.name().lower()

if isinstance(oses, str):
results = (oses in cur_id) or (oses in cur_name)
else:
results = False
for item in oses:
if not isinstance(item, str):
continue
item = item.lower()
results = results or (item in cur_id) or (item in cur_name)

if results is False:
return False

if version:
cur_major = int(distro.major_version())
cur_minor = int(distro.minor_version()) if distro.minor_version() else 0

if version[0] in ('<', '=', '>'):
if version[1] == '=':
op = version[:2]
version = version[2:]
else:
op = version[0] if version[0] != '=' else '=='
version = version[1:]
else:
op = '=='

parts = version.split('.')
major = int(parts[0])
minor = int(parts[1]) if len(parts) > 1 else None

if major == cur_major and minor:
return eval("{0} {1} {2}".format(cur_minor, op, minor))
else:
return eval("{0} {1} {2}".format(cur_major, op, major))

return True
7 changes: 3 additions & 4 deletions SCAutolib/models/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

from SCAutolib import logger, TEMPLATES_DIR, LIB_BACKUP, LIB_DUMP_CONFS, run
from SCAutolib.exceptions import SCAutolibException
from SCAutolib.isDistro import isDistro


class File:
Expand Down Expand Up @@ -297,10 +298,8 @@ def __init__(self):
return
self.__initialized = True

with open('/etc/redhat-release', "r") as f:
release = f.read()

if "release 8" in release or "release 9" in release:
if isDistro(['rhel', 'centos'], version='<=9') \
or isDistro(['fedora'], version='<39'):
self._template = TEMPLATES_DIR.joinpath("sssd.conf-8or9")
else:
self._template = TEMPLATES_DIR.joinpath("sssd.conf-10")
Expand Down
6 changes: 2 additions & 4 deletions SCAutolib/models/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
import logging

from SCAutolib import run, logger
from SCAutolib.enums import OSVersion
from SCAutolib.utils import _get_os_version
from SCAutolib.isDistro import isDistro


class HTMLFileHandler(logging.FileHandler):
Expand Down Expand Up @@ -487,8 +486,7 @@ def check_home_screen(self, polarity: bool = True):
else:
func_str = 'assert_no_text'

os_version = _get_os_version()
if os_version == OSVersion.Fedora:
if isDistro('fedora'):
check_str = 'tosearch'
else:
check_str = 'Activities'
Expand Down
28 changes: 0 additions & 28 deletions SCAutolib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from SCAutolib import (run, logger, TEMPLATES_DIR, LIB_DUMP_USERS, LIB_DUMP_CAS,
LIB_DUMP_CARDS)
from SCAutolib.enums import OSVersion
from SCAutolib.exceptions import SCAutolibException
from SCAutolib.models.CA import LocalCA, BaseCA, CustomCA, IPAServerCA
from SCAutolib.models.card import Card
Expand Down Expand Up @@ -58,33 +57,6 @@ def _gen_private_key(key_path: Path):
encryption_algorithm=serialization.NoEncryption()))


def _get_os_version():
"""
Find Linux version. Available version: RHEL 8, RHEL 9, RHEL 10, Fedora.
:return: Enum with OS version
"""
with open('/etc/redhat-release', "r") as f:
cnt = f.read()

os_version = None

if "Fedora" in cnt:
return OSVersion.Fedora
elif "Red Hat Enterprise Linux" in cnt:
os_version = OSVersion.RHEL_8
elif "CentOS Stream" in cnt:
os_version = OSVersion.CentOS_8
else:
raise SCAutolibException("OS is not detected.")

if "release 9" in cnt:
os_version += 1
elif "release 10" in cnt:
os_version += 2

return os_version


def _install_packages(packages):
"""
Install given packages and log package version
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ pytest>=7
schema>=0.7
python_freeipa>=1.0
pexpect>=4
distro>=1.5.0

0 comments on commit 5469e09

Please sign in to comment.