ok

Mini Shell

Direktori : /opt/cloudlinux/venv/lib/python3.11/site-packages/clwpos/
Upload File :
Current File : //opt/cloudlinux/venv/lib/python3.11/site-packages/clwpos/daemon_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
#

# pylint: disable=no-absolute-import

import logging
import os
import signal
import json
from typing import Tuple

from clcommon.utils import get_process_pid
from clwpos.logsetup import setup_logging, init_wpos_sentry_safely


class WposDaemonBase:
    """
    AccelerateWP daemon base class. Signals, signal handlers, setup daemon logger, pid file operations
    """
    _PID_FILENAME = "/var/run/clwpos_monitoring.pid"
    _DAEMON_LOGFILE_PATH = "/var/log/clwpos/daemon.log"
    _DAEMON_CONFIG_PATH = "/etc/clwpos/daemon_conf.json"
    # Default redis monitoring interval 300 seconds = 5 min
    _DEFAULT_MONITORING_INTERVAL = 300

    def __init__(self):
        self._reload_config_need = False
        self._is_terminate = False
        self._monitoring_interval, self._is_reload_interval_enabled, is_full_logging_mode = \
            self._update_monitoring_interval()
        self._logger = setup_logging(
            caller_name=__name__,
            console_level=logging.DEBUG if is_full_logging_mode else logging.INFO,
            file_level=logging.DEBUG if is_full_logging_mode else logging.INFO,
            logfile_path=self._DAEMON_LOGFILE_PATH
        )
        init_wpos_sentry_safely(self._logger)
        self._logger.info("Cloudlinux AccelerateWP daemon uses monitoring interval: %d seconds", self._monitoring_interval)
        if not self._is_reload_interval_enabled:
            self._logger.info("NOTE: Cloudlinux AccelerateWP daemon check reload interval is OFF by config")
        if is_full_logging_mode:
            self._logger.info("NOTE: Cloudlinux AccelerateWP daemon full logging mode is ON by config")

    def _update_monitoring_interval(self) -> Tuple[int, bool, bool]:
        """
        Read daemon parameters from config /etc/clwpos/daemon_conf.json. Use only for debug/testing.
        :return: tuple (monitoring_interval, is_reload_interval_enabled, is_full_logging_mode)
            monitoring_interval: redises monitoring inteval, seconds
            is_reload_interval_enabled: True - daemon will disable 'reload' command via socket from same user
                                                 more often then 1 minute
                                         False - daemon will not check time between 'reload' command,
                                                  all queries will be processed
            is_full_logging_mode: True - debug messages will be written to log
                                  False - debug messages will not be written to log
        """
        try:
            with open(self._DAEMON_CONFIG_PATH, 'r') as f:
                daemon_config = json.load(f)
                monitoring_interval = daemon_config['monitoring_interval_5secs'] * 5
                is_reload_interval_enabled = daemon_config.get('is_reload_interval_enabled', True)
                is_full_logging_mode = daemon_config.get('is_full_logging_mode', False)
        except (OSError, IOError, json.JSONDecodeError, KeyError):
            # Config read error, stay default
            monitoring_interval = self._DEFAULT_MONITORING_INTERVAL
            is_reload_interval_enabled = True
            is_full_logging_mode = False
        return monitoring_interval, is_reload_interval_enabled, is_full_logging_mode

    def _setup_signals(self):
        """
        Setup daemon signal handlers
        """
        # Setup SIGHUP signal handler for config reload
        signal.signal(signal.SIGHUP, self._sighup_handler)
        # Setup Ctrl-C signal handler. Used for console debug
        signal.signal(signal.SIGINT, self._sigint_handler)
        # Setup SIGTERM signal. Called when daemon stops
        signal.signal(signal.SIGTERM, self._sigterm_handler)

    def run(self):
        """
        Main work daemon function (implement in child class)
        """
        raise NotImplementedError()

    def stop(self, *args, **kwargs):
        """
        Stops a working daemon process (implement in child class)
        """
        raise NotImplementedError()

    def reload(self):
        """
        Reload working daemon process by sending SIGHUP signal to it
        """
        try:
            pid = get_process_pid(self._PID_FILENAME)
            if pid:
                os.kill(pid, signal.SIGHUP)
        except:
            pass

    def _sighup_handler(self, signum, frame):
        """
        SIGHUP signal handler
        """
        # Load new user configuration from config file
        self._reload_config_need = True
        self._logger.info("SIGHUP: Cloudlinux AccelerateWP daemon sheduled for reload")

    def _sigint_handler(self, signum, frame):
        """
        SIGINT (Ctrl-C) signal handler. For console debug
        """
        self._logger.info("Ctrl-C received, exit")
        # Terminate main cycle
        self._is_terminate = True

    def _sigterm_handler(self, signum, frame):
        """
        SIGTERM signal handler. Called when daemon stopping
        """
        # Terminate main cycle
        self._is_terminate = True

Zerion Mini Shell 1.0