Hacked By AnonymousFox

Current Path : /opt/cloudlinux/venv/lib/python3.11/site-packages/clwizard/modules/
Upload File :
Current File : //opt/cloudlinux/venv/lib/python3.11/site-packages/clwizard/modules/base.py

# coding=utf-8
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2021 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENCE.TXT
#

from __future__ import absolute_import

import os
from abc import abstractmethod
from typing import Dict, List, Optional  # NOQA

from clcommon import cpapi
from clcommon.group_info_reader import GroupInfoReader
from clcommon.lib.cledition import is_ubuntu
from clcommon.utils import (
    ExternalProgramFailed,
    get_cl_version,
    get_package_db_errors,
    get_passenger_package_name,
    is_ea4,
    is_package_installed,
    run_command,
)
from clwizard.exceptions import InstallationFailedException
from clwizard.utils import convert_package_version, setup_logger


class WizardInstaller(object):
    """
    General interface for modules installers
    """

    LOG_FILE = ""

    _REQUIRED_CL_COMPONENT_SUPPORT = None

    def __init__(self):
        self.app_logger = setup_logger('wizard.' + self.__class__.__name__, self.LOG_FILE)

    def _run_command(self, cmd, cmd_env=None):
        # type: (List[str]) -> str
        """Run external tool and log results"""
        self.app_logger.info('~' * 60)
        self.app_logger.info("Executing command %s...", ' '.join(cmd))
        try:
            output = run_command(cmd, env_data=cmd_env)
        except ExternalProgramFailed as err:
            self.app_logger.info(
                "...external command failed, see the following lines for tracebacks, errors, etc."
            )
            self.app_logger.error(str(err))
            raise
        else:
            self.app_logger.info("...external command successfully ended with output:")
            self.app_logger.info(output)
        self.app_logger.info('-' * 60)
        return output

    def _is_package_installed(self, package_name):
        # type: (str) -> bool
        """Check if package exists on server"""
        error_message = get_package_db_errors()
        if error_message:
            # DB corrupted
            log_message = f"Can't check package {package_name} presence. Errors:\n{error_message}"
            self.app_logger.error(log_message)
            raise InstallationFailedException()
        return is_package_installed(package_name)

    def _install_package(self, *packages):
        # type: (str) -> Optional[str]
        """Install a package and log results"""
        if is_ubuntu():
            return self._install_apt_package(*packages)
        else:
            return self._install_yum_package(*packages)

    def _install_apt_package(self, *packages):
        # type: (str) -> Optional[str]
        """Install an apt package and log results"""

        apt_env = {}
        # For debconf to avoid making any interactive queries.
        apt_env['DEBIAN_FRONTEND'] = 'noninteractive'
        apt_env['DEBCONF_NONINTERACTIVE_SEEN'] = 'true'

        if packages:
            return self._run_command(['apt-get', 'install', '-y'] + list(packages), cmd_env=apt_env)
        return None

    def _install_yum_package(self, *packages):
        # type: (str) -> Optional[str]
        """Install a yum package and log results"""
        if packages:
            return self._run_command(['yum', 'install', '-y'] + list(packages))
        return None

    def _install_groups(self, *groups):
        # type: (str) -> Optional[str]
        """
        Install a package group.
        At the moment, DEB metapackages are not supported, and
        provided names are simply installed as normal packages.
        This will change in the future.
        """
        if is_ubuntu():
            return self._install_apt_package(*groups)
        else:
            return self._install_yum_groups(*groups)

    def _install_yum_groups(self, *groups):
        # type: (str) -> Optional[str]
        """Install package group with yum and log results"""
        if groups:
            return self._run_command(['yum', 'groupinstall', '-y'] + list(groups))
        return None

    def _ensure_cl_ea4_repo_exists(self):
        """
        Check whether cloudlinux-ea4.repo is present and install it if not.
        It's required only on EA4 to install proper Passenger package
        """
        # LU-3364: should also be made compatible with Ubuntu, once Python/Node/Ruby selector
        # support comes into play.
        cl_ea4_repofile = "/etc/yum.repos.d/cloudlinux-ea4.repo"
        if os.path.exists(cl_ea4_repofile):
            return

        dist = get_cl_version() or 'Unknown'
        if '7' in dist:
            dist_maj_ver = '7'
        elif '6' in dist:
            dist_maj_ver = '6'
        else:
            raise InstallationFailedException("Failed to get the distribution's major version")

        package_url = (
            "https://repo.cloudlinux.com/cloudlinux/EA4/"
            f"cloudlinux-ea4-release-latest-{dist_maj_ver}.noarch.rpm"
        )
        self.app_logger.info(
            "Unable to find cloudlinux-ea4 repo. Trying to install it using url: %s", package_url
        )
        self._install_yum_package(package_url)

    def _install_passenger(self):
        """
        Install proper passenger package for Selectors if it's not yet
        installed
        """
        # LU-3364: should also be made compatible with Ubuntu, once Python/Node/Ruby selector
        # support comes into play.
        if is_ea4():
            self._ensure_cl_ea4_repo_exists()
        passenger = get_passenger_package_name()
        self.app_logger.info("Trying to install Passenger package: %s", passenger)
        try:
            self._install_yum_package(passenger)
        except ExternalProgramFailed as extern_failed:
            raise InstallationFailedException() from extern_failed

    @staticmethod
    def _get_available_versions(group):
        # type: (str) -> List
        """
        Get a list of available Python, NodeJS, PHP or Ruby module versions.
        :param group: - group name, e.g: python
        :return: list of available versions
        """
        available_groups_info = GroupInfoReader.get_group_info(group)
        versions = []
        # we need to format version:
        # python: 2.3.3 -> 2.3
        # ruby: 2.1.1 -> 2.1
        # php: 7.2.0 -> 7.2
        # nodejs: 8.1.0 -> 8
        ver_size = 1 if group == 'nodejs' else 2
        for group_data in available_groups_info.values():
            versions.append(convert_package_version(group_data['version'], version_size=ver_size))
        return versions

    @abstractmethod
    def run_installation(self, options):
        # type: (Dict) -> None
        raise NotImplementedError()

    @classmethod
    def supported_options(cls):
        return set()

    @abstractmethod
    def initial_status(self):
        # type: () -> Dict
        """
        Method that returns dictionary with two required keys:
        {installed: True|False and options: {...}]
        This will be used by lvemanager to properly display wizard.
        """
        raise NotImplementedError()

    @classmethod
    def is_supported_by_control_panel(cls):
        """
        Checks whether we must
        :return:
        """
        if cls._REQUIRED_CL_COMPONENT_SUPPORT is None:
            return True
        return cpapi.is_panel_feature_supported(cls._REQUIRED_CL_COMPONENT_SUPPORT)

Hacked By AnonymousFox1.0, Coded By AnonymousFox