????
Current Path : /usr/bin/ |
Current File : //usr/bin/package_reinstaller.py |
#!/opt/cloudlinux/venv/bin/python3 -bb # -*- coding: utf-8 -*- # Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved # # Licensed under CLOUD LINUX LICENSE AGREEMENT # http://cloudlinux.com/docs/LICENSE.TXT # check /var/lve/PANEL # if FILE absent - create # if FILE empty - work as if FILE absent # read panel name from FILE # if panel name changed = check panel process end and reinstall lvemanager cagefs lve-utils import argparse import logging import os from logging.handlers import RotatingFileHandler from subprocess import CalledProcessError, check_output from clcommon.const import Feature from clcommon.cpapi import is_panel_feature_supported from clcommon.lib.cledition import is_ubuntu from clcommon.utils import run_command from cldetectlib import getCPName PANEL_FILE_DIR = '/var/lve' PANEL_FILE = os.path.join(PANEL_FILE_DIR, 'PANEL') LOG = '/var/log/package_reinstaller.log' def is_panel_change(): """ :return: True if names are different and new panel name """ panel_name = getCPName() logging.info('Current panel is %s', panel_name) try: with open(PANEL_FILE, encoding="utf-8") as f: old_panel_name = f.read() logging.info('Old panel is %s', old_panel_name) if old_panel_name != panel_name: return True, panel_name else: return False, panel_name except (OSError, IOError) as e: # if the file doesn't exist - panel doesn't change logging.warning('Panel file %s not found!, error: %s', PANEL_FILE, str(e)) return False, panel_name def write_panel_file(panel_name): """ Save the given panel name to /var/lve/PANEL. :param panel_name: The panel name to save. :type panel_name: str """ try: os.mkdir(PANEL_FILE_DIR) except OSError: pass # directory already exists with open(PANEL_FILE, 'w', encoding="utf8") as f: f.write(panel_name) def is_panel_process_active(panel_name): """ :param panel_name: :return: True if panel is already detected but not installed yet """ process_active = False if panel_name == 'cPanel': # Expect installation in progress if installer.lock file present process_active = os.path.isfile('/root/installer.lock') return process_active elif panel_name == 'Plesk': process_active = True not_running_pattern = 'Plesk Installer is not running' plesk_bin = '/usr/sbin/plesk' # Plesk is installing if we detect it and plesk bin doesn't exist if not os.path.exists(plesk_bin): return process_active try: result = check_output( [ plesk_bin, 'installer', '--query-status', ], text=True, ) process_active = not_running_pattern not in result except (CalledProcessError, FileNotFoundError): return process_active elif panel_name == 'DirectAdmin': # Location changed in DirectAdmin 1.659 # https://docs.directadmin.com/changelog/version-1.659.html#migrate-scripts-setup-txt-to-conf-setup-txt new_da_setup_txt = '/usr/local/directadmin/conf/setup.txt' old_da_setup_txt = '/usr/local/directadmin/scripts/setup.txt' is_da_process_active = not os.path.exists(old_da_setup_txt) and not os.path.exists(new_da_setup_txt) return is_da_process_active return process_active def packages_to_reinstall(): """ Gather packages to reinstall depending on the features supported by the panel. :return: List of package names. :rtype: list[str] """ packages = ['lvemanager', 'lve-utils', 'alt-python27-cllib'] if is_panel_feature_supported(Feature.CAGEFS): packages.append('cagefs') if is_panel_feature_supported(Feature.XRAY): packages.append("lvemanager-xray") if is_panel_feature_supported(Feature.WPOS): packages.append("cloudlinux-awp-plugin") return packages def package_reinstall_apt(pkgs): """ Invokes the package reinstallation command with apt. """ cmd_env = os.environ.copy() # For debconf to avoid making any interactive queries. cmd_env['DEBIAN_FRONTEND'] = 'noninteractive' cmd_env['DEBCONF_NONINTERACTIVE_SEEN'] = 'true' return run_command( ['/usr/bin/apt-get', 'install', '--reinstall', '--yes'] + pkgs, env_data=cmd_env, return_full_output=True, ) def package_reinstall_yum(pkgs): """ Invokes the package reinstallation command with yum. """ return run_command( ['/usr/bin/yum', 'reinstall', '-y'] + pkgs, return_full_output=True, ) def perform_package_reinstallation(): """ Perform the actuall package reinstallation, invoking the package manager. Uses apt-get on Ubuntu-based machines, and yum otherwise. :return: Tuple of (return code, stdout, stderr) :rtype: tuple[int, str, str] """ to_reinstall = packages_to_reinstall() if is_ubuntu(): return package_reinstall_apt(to_reinstall) else: return package_reinstall_yum(to_reinstall) def check(): """ Check if control panel name equals to the cached one and reinstall packages if not so :return: None """ (panel_changed, new_panel_name) = is_panel_change() if not panel_changed: logging.warning('The panel was not changed, skipping package reinstallation') return logging.info('The control panel has changed, reinstalling packages') if new_panel_name in ['cPanel', 'Plesk', 'DirectAdmin']: if not is_panel_process_active(new_panel_name): retcode, std_out, std_err = perform_package_reinstallation() if retcode == 0 or (retcode == 1 and std_err.find('Nothing to do')): write_panel_file(new_panel_name) logging.info( 'Packages have been reinstalled!\nSTDOUT: \n%s\nSTDERR: \n%s\n', std_out, std_err, ) else: logging.warning( 'The panel is currently being installed, skipping package reinstallation!' ) else: write_panel_file(new_panel_name) def init(): """ Save the current control panel name to cache if it's not saved yet. :return: None """ if not os.path.exists(PANEL_FILE): write_panel_file(getCPName()) if __name__ == '__main__': logging.basicConfig( handlers=[RotatingFileHandler(LOG, maxBytes=1024 * 1024, backupCount=2)], level=logging.INFO, format='%(asctime)s %(levelname)s:%(name)s:%(message)s', ) parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='subparser') subparsers.add_parser( 'init', help="Init the panel name cache file; " f"works only once and creates the {PANEL_FILE} file", ) subparsers.add_parser( 'check', help="Check for control panel change; " "Reinstall packages if control panel name doesn't match the one in the cache file.", ) args = parser.parse_args() if args.subparser == 'init': init() elif args.subparser == 'check': check() else: parser.print_help() # print(f'Command {args.subparser} is not implemented') exit(1)