HEX
Server: Apache
System: Linux panel.gemzo.net 4.18.0-477.10.1.lve.el8.x86_64 #1 SMP Wed May 17 07:12:55 EDT 2023 x86_64
User: birehlibraryps (1007)
PHP: 8.1.28
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //bin/package_reinstaller.py
#!/opt/alt/python37/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 /etc/cloudlinux/PANEL
# if FILE absent - create
# if FILE empty - do as FILE absent
# read from FILE panel name
# if panel name change = check panel process end and reinstall lvemanager cagefs lve-utils
import argparse

from subprocess import check_output, CalledProcessError

from cldetectlib import getCPName
from clcommon.utils import run_command
from clcommon.const import Feature
from clcommon.cpapi import is_panel_feature_supported
import os
import logging
from logging.handlers import RotatingFileHandler

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:
        f = open(PANEL_FILE)
        old_panel_name = f.read()
        f.close()
        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 file doesn't exist - panel doesn't change
        logging.warning('Panel file %s is not found!, error: %s', PANEL_FILE, str(e))
        return False, panel_name


def write_panel_file(panel_name):
    try:
        os.mkdir(PANEL_FILE_DIR)
    except OSError:
        pass  # directory already exist
    with open(PANEL_FILE, 'w') as f:
        f.write(panel_name)


def is_panel_process_active(panel_name):
    """
    :param panel_name:
    :return: True if panel is already detect but not install yet
    """
    process_active = False
    if panel_name == 'cPanel':
        process_active = True
        cpanel_install_log = '/var/log/cpanel-install.log'
        # find in log file string Thank you for installing cPanel
        try:
            with open(cpanel_install_log, 'rb') as log:
                for line in log:
                    if line.find(b'Thank you for installing cPanel') >= 0:
                        process_active = False
        except (IOError, OSError):
            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':
        da_setup_txt = '/usr/local/directadmin/scripts/setup.txt'
        return not os.path.exists(da_setup_txt)
    return process_active


def packages_to_reinstall():
    packages = ['lvemanager', 'lve-utils', 'alt-python27-cllib']
    if is_panel_feature_supported(Feature.CAGEFS):
        packages.append('cagefs')
    else:
        packages.append("lvemanager-xray")
    return packages


def check():
    """
    Check if control panel name equals to cached one
    and reinstall packages if not so
    :return: None
    """
    (panel_changed, new_panel_name) = is_panel_change()
    if not panel_changed:
        logging.warning('Panel was not changed, skip reinstalling')
        return

    if new_panel_name in ['cPanel', 'Plesk', 'DirectAdmin']:
        if not is_panel_process_active(new_panel_name):
            retcode, std_out, std_err = run_command([
                'yum',
                'reinstall',
                '-y'
            ] + packages_to_reinstall(), return_full_output=True)
            if retcode == 0 or (retcode == 1 and std_err.find('Nothing to do')):
                write_panel_file(new_panel_name)
            logging.info('Packages are reinstalled! '
                         'STDOUT: %s, \n'
                         'STDERR: %s \n', std_out, std_err)
        else:
            logging.warning('Panel is currently installing, skip reinstall packages!')
    else:
        write_panel_file(new_panel_name)


def init():
    """
    Save current control panel name to cache,
    only if it is 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=f"Init panel name cache; "
                     f"works only once and creates {PANEL_FILE} file")
    subparsers.add_parser(
        'check', help=f"Check for control panel change; "
                      f"Reinstall packages if control panel is not same as in cache.")
    args = parser.parse_args()

    if args.subparser == 'init':
        init()
    elif args.subparser == 'check':
        check()
    else:
        print('Command %s is not implemented' % args.subparser)
        exit(1)