Mini Shell
import logging
import signal
import sys
from typing import Union, Iterable, Callable
from ..modules.processor import RequestProcessor
logger = logging.getLogger('tools')
def log_on_receive(signum: int, frame) -> None:
"""
Signal handler to log received signal
"""
logger.info('Received sig: %i (%s)', signum, signum)
def sigterm_received(signum: int, frame) -> None:
"""
Signal handler to dump collected statistics
"""
logger.info('Received sig: %i', signum)
RequestProcessor().dump_collected_stats_to_file()
logger.info('Dumped successfully after %i signal, exiting...', signum)
sys.exit(0)
def register_a_signal(signum: int, sighandler: Callable) -> None:
"""
Register given sighandler for given signum
"""
try:
signal.signal(signum, sighandler)
logger.info('Registered %s', signum)
except (OSError, ValueError) as e:
logger.info('Skipped %s because of %s', signum, e)
def register_sigterm():
"""
Register a dump handler for SIGTERM signal
"""
register_a_signal(signal.SIGTERM, sigterm_received)
def register_signals(signals: Union[int, Iterable] = None,
handler: Callable = log_on_receive) -> None:
"""
Register given handler for given signal or range of signals
If no signals given, add given handler for all available signals
"""
if signals is None:
# register all available signals
for sig in signal.Signals:
register_a_signal(sig, handler)
else:
if isinstance(signals, int):
# register single signal
register_a_signal(signals, handler)
else:
# register range of signals
for sig in signals:
register_a_signal(sig, handler)
Zerion Mini Shell 1.0