\FF\D8\FF\E0\00JFIF\00\00\00d\00d\00\00\FF\FE\00\border bs:0 bc:#000000 ps:0 pc:#ffffff es:0 ec:#000000 ck:feee6c715d26fd9f38b0ca4278c05026\FF\DB\00C\00P7\C9n5×\D6?\BDê\9Ds\EBp\9F[`8m\B7)o\B5\E8\E6I\99\FE3]]A2\BA\8Cw\D6E\93\\DEv\C8\009\F2\F1NI?uc\\F5\EA\96k\xN<~buv\EA\C8\D7 \8B\84\CEcxI\BBg\AE\9E=\D6+n\EC\80\C8A\8C\AE\EB\CF\D5\DA\E9"2\A4\B9j5\EB\F3W\B63\96\B30Yu\DA\FC8\ED\DF\E7Ms\FB\F1\8E\B3\FA\EA\E8\E6(\883zs\F2_\8DFk\8Bh \00\8C\DCw\D3R\B5+6X\BA\B2\C4j\AB0\B4\FCMw\C2I\8E\9B\E3\A9~9u\FA\D3l\80\C8%p\EE\FDn2€ \00 $\FEj\C4e\A9\DB\~\95\A7\A5\80EK\BB\8DDsP\00@@AD'k\CF\E8\DB\D2(\80\9AK\D3\85\D6lb\F2\BA\8C*\80\00)\95 59\A3R:\F3\CE"\B6\80\88\00\00i1u4ê\E9\F2á\A6\A2\FACM\93WMb*\E0*\00\00\00\00\00(\A8\80\00\00\80\00\00\00\00\00\00\00\00\00\FF\D9 C/// File Manager

File Manager

Path: /opt/cloudlinux/venv/lib64/python3.11/site-packages/xray/reconfiguration/

Viewing File: 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, part_delimiter, task_delimiter
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.

    Only callable from CLI entry point (run_manager.py), not from socket handlers.
    """
    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_tasks_file(task_file)
        for task in tasks:
            # 'quser.com:/*:*:2bf76cc3989e4b63f6c3'
            fake_id = task.rsplit(part_delimiter)[3]
            if fake_id.encode() in fake_tasks_ids:
                alive_tasks.append(task)
        if alive_tasks:
            logger.info('Writing tasks %s to %s', task_delimiter.join(alive_tasks), task_file)
            Task.unified_write(task_file, task_delimiter.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')