File: utils.py

package info (click to toggle)
notus-scanner 22.7.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,556 kB
  • sloc: python: 4,229; sh: 36; makefile: 4
file content (136 lines) | stat: -rw-r--r-- 3,883 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# SPDX-FileCopyrightText: 2021-2024 Greenbone AG
#
# SPDX-License-Identifier: AGPL-3.0-or-later

import atexit
import logging
import os
import signal
import sys
from functools import partial
from logging.handlers import SysLogHandler, WatchedFileHandler
from pathlib import Path
from typing import Optional, Union

import psutil

logger = logging.getLogger(__name__)

DEFAULT_SYS_LOG_DEVICE = "/dev/log"


def go_to_background() -> None:
    """Daemonize the running process."""
    try:
        if os.fork():
            sys.exit()
    except OSError as err:
        logger.error("Fork failed: %s", err)
        sys.exit(1)


def create_pid(pid_file: str) -> bool:
    """Check if there is an already running daemon and creates the pid file.
    Otherwise gives an error."""

    pid = os.getpid()
    new_process = psutil.Process(pid)
    new_process_name = new_process.name()

    pid_path = Path(pid_file)

    if pid_path.is_file():
        process_name = None
        current_pid = pid_path.read_text(encoding="utf-8").strip()
        try:
            current_pid = int(current_pid)
        except (TypeError, ValueError):
            current_pid = None

        if current_pid:
            try:
                process = psutil.Process(current_pid)
                process_name = process.name()
            except psutil.NoSuchProcess:
                pass

            if process_name == new_process_name:
                logger.error(
                    "There is an already running process. See %s.",
                    str(pid_path.absolute()),
                )
                return False
            else:
                logger.debug(
                    "There is an existing pid file '%s', but the PID %s belongs"
                    " to the process %s. It seems that %s was abruptly stopped."
                    " Removing the pid file.",
                    str(pid_path.absolute()),
                    current_pid,
                    process_name,
                    new_process_name,
                )

    try:
        pid_path.write_text(str(pid), encoding="utf-8")
    except (FileNotFoundError, PermissionError) as e:
        logger.error(
            "Failed to create pid file %s. %s", str(pid_path.absolute()), e
        )
        return False

    return True


def exit_cleanup(
    pid_file: str,
    _signum=None,
    _frame=None,
) -> None:
    """Removes the pid_file before ending the daemon."""
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    pid_path = Path(pid_file)

    if not pid_path.is_file():
        return

    with pid_path.open(encoding="utf-8") as f:
        if int(f.read()) == os.getpid():
            logger.debug("Finishing daemon process")
            pid_path.unlink()
            sys.exit()


def init_signal_handler(pid_file: str):
    atexit.register(exit_cleanup, pid_file=pid_file)
    signal.signal(signal.SIGTERM, partial(exit_cleanup, pid_file))
    signal.signal(signal.SIGINT, partial(exit_cleanup, pid_file))


def init_logging(
    name: str,
    log_level: Union[int, str],
    *,
    log_file: Optional[str] = None,
    foreground: Optional[bool] = False,
):
    root_logger = logging.getLogger()
    root_logger.setLevel(log_level)

    formatter = logging.Formatter(
        f"%(asctime)s {name}: %(levelname)s: (%(name)s) %(message)s"
    )
    if foreground:
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        root_logger.addHandler(console_handler)
    if log_file:
        log_file_handler = WatchedFileHandler(log_file)
        log_file_handler.setFormatter(formatter)
        root_logger.addHandler(log_file_handler)
    if not foreground and not log_file:
        syslog_handler = SysLogHandler(DEFAULT_SYS_LOG_DEVICE)
        syslog_handler.setFormatter(formatter)
        root_logger.addHandler(syslog_handler)

    return root_logger