ok

Mini Shell

Direktori : /opt/cloudlinux/venv/lib/python3.11/site-packages/xray/reconfiguration/
Upload File :
Current File : //opt/cloudlinux/venv/lib/python3.11/site-packages/xray/reconfiguration/system_id_shift.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/LICENSE.TXT

import logging
import os
import subprocess
from glob import iglob

from xray.internal.constants import request_data_storage, local_tasks_storage
from xray.internal.utils import dbm_storage
from xray.internal.types import Task

logger = logging.getLogger('reconfiguration')


def get_locations() -> tuple:
    """
    Return all possible locations of xray.ini files in glob-like form
    Panel independent
    """
    return (
        '/opt/alt/php*/link/conf',
        '/var/cagefs/*/*/etc/cl.php.d/alt-php*',
        '/opt/cpanel/ea-php*/root/etc/php.d',
        '/opt/plesk/php/*/etc/php.d',
        '/usr/local/php*/lib/php.conf.d',
        '/usr/share/cagefs/.cpanel.multiphp/opt/cpanel/ea-php*/root/etc/php.d',
        '/usr/share/cagefs-skeleton/usr/local/php*/lib/php.conf.d'
    )


def safe_unlink(_fpath):
    """Wrapped unlink"""
    try:
        os.unlink(_fpath)
    except OSError as e:
        logger.warning('%s not removed, reason: %s', _fpath, e)


def find_xray_inis(globpath: str) -> str:
    """
    Find xray.ini files in every directory matching given glob-like path.
    Return full path to xray.ini
    """
    for conf_dir in iglob(globpath):
        for name in os.listdir(conf_dir):
            if 'xray.ini' in name:
                yield os.path.join(conf_dir, name)


def remove_xray_inis() -> None:
    """
    Remove all xray.ini files found in filesystem
    """
    for location in get_locations():
        for xray_ini in find_xray_inis(location):
            logger.info('Removing %s', xray_ini)
            safe_unlink(xray_ini)


def remove_xray_tasks() -> None:
    """
    Remove all xray.tasks files found in filesystem
    """
    for tasks_file in iglob('/usr/share/alt-php-xray-tasks/*/xray.tasks'):
        logger.info('Removing %s', tasks_file)
        safe_unlink(tasks_file)


def clear_dbm_file() -> None:
    """
    Remove all entries from local dbm file with fake_ids mapping
    """
    with dbm_storage(local_tasks_storage) as task_storage:
        for item in task_storage.keys():
            logger.info('Clear task %s', item.decode())
            del task_storage[item]


def remove_req_id_files() -> None:
    """
    Remove all request_id files
    """
    for name in os.listdir(request_data_storage):
        logger.info('Clear request_id for %s', name)
        safe_unlink(os.path.join(request_data_storage, name))


def restart_agent() -> None:
    """
    Restart X Ray Agent
    """
    try:
        subprocess.run(['/sbin/service',
                        'xray-agent',
                        'restart'],
                       capture_output=True, text=True)
        logger.info('X Ray Agent restarted')
    except (OSError, ValueError, subprocess.SubprocessError) as e:
        logger.error('Failed to restart X-Ray Agent',
                     extra={'err': str(e)})


def reconfigure():
    """
    Perform reconfiguration
    """
    logger.info('system_id shift: reconfigure...')
    remove_xray_inis()
    remove_xray_tasks()
    remove_req_id_files()
    clear_dbm_file()
    restart_agent()
    logger.info('reconfiguration for system_id shift case completed')


def _clean_garbage_tasks():
    """
        1. Get all tasks through /usr/share/alt-php-xray-tasks/*/xray.tasks
           ncuser.com:/*:*:e754fbfdea1eb6f75247
        2. Check that fake_id is present in local storage: /usr/share/alt-php-xray/tasks
        3. If it is not -> task is broken/garbage and must be removed
        """
    if not os.path.exists(local_tasks_storage):
        logger.info('Local storage %s is absent, nothing to do', local_tasks_storage)
        return
    with dbm_storage(local_tasks_storage) as task_storage:
        fake_tasks_ids = list(task_storage.keys())
    for task_file in iglob('/usr/share/alt-php-xray-tasks/*/xray.tasks'):
        alive_tasks = []
        tasks = Task.read_file(task_file)
        for task in tasks.split(','):
            # 'quser.com:/*:*:2bf76cc3989e4b63f6c3'
            fake_id = task.split(':')[3]
            if fake_id.encode() in fake_tasks_ids:
                alive_tasks.append(task)
        if alive_tasks:
            logger.info('Writing tasks %s to %s', ','.join(alive_tasks), task_file)
            Task.unified_write(task_file, ','.join(alive_tasks), target_uid=0,
                               target_gid=os.stat(task_file).st_gid, mask=0o137)
        else:
            # all tasks are garbage, no need to leave file
            logger.info('No real tasks in %s, removing file', task_file)
            Task.unified_erase(task_file)


def cleanup_garbage_tasks():
    try:
        _clean_garbage_tasks()
    except Exception:
        logger.exception('Error during cleaning garbage x-ray tasks')

Zerion Mini Shell 1.0