From cb4e3d3e1fd50447c32de1dbc3f494aba8440420 Mon Sep 17 00:00:00 2001 From: Andres Gomez Date: Fri, 8 Apr 2022 22:38:38 +0300 Subject: [PATCH] dhcp: only install signal handlers from the server "Silently" installing signal handlers from a module that may be imported from another project is not the best idea. Instead we move them to the server, which is where we want them here and as an usage example for other PyPXE users. --- pypxe/dhcp.py | 12 +----------- pypxe/server.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/pypxe/dhcp.py b/pypxe/dhcp.py index 0dbaddf..46b5b60 100644 --- a/pypxe/dhcp.py +++ b/pypxe/dhcp.py @@ -8,7 +8,6 @@ import struct import os import logging -import signal import json from collections import defaultdict from time import time @@ -130,12 +129,7 @@ def __init__(self, **server_settings): except ValueError: pass - signal.signal(signal.SIGINT, self.export_leases) - signal.signal(signal.SIGTERM, self.export_leases) - signal.signal(signal.SIGALRM, self.export_leases) - signal.signal(signal.SIGHUP, self.export_leases) - - def export_leases(self, signum, frame): + def export_leases(self): if self.save_leases_file: export_safe = dict() for lease in self.leases: @@ -145,10 +139,6 @@ def export_leases(self, signum, frame): json.dump(export_safe, leases_file) self.logger.info('Exported leases to {0}'.format(self.save_leases_file)) - # if keyboard interrupt, propagate upwards - if signum == signal.SIGINT: - raise KeyboardInterrupt - def get_namespaced_static(self, path, fallback = {}): statics = self.static_config for child in path.split('.'): diff --git a/pypxe/server.py b/pypxe/server.py index 8ff6aa5..a8c927e 100755 --- a/pypxe/server.py +++ b/pypxe/server.py @@ -6,6 +6,7 @@ import json import logging import logging.handlers +import signal try: import argparse @@ -250,6 +251,13 @@ def main(): # configure/start DHCP server if args.USE_DHCP: + def dhcp_export_leases(signum, frame): + dhcp_server.export_leases() + + # if keyboard interrupt, propagate upwards + if signum == signal.SIGINT: + raise KeyboardInterrupt + # setup DHCP logger dhcp_logger = helpers.get_child_logger(sys_logger, 'DHCP') if args.DHCP_MODE_PROXY: @@ -278,6 +286,10 @@ def main(): static_config = loaded_statics, logger = dhcp_logger, saveleases = args.LEASES_FILE) + signal.signal(signal.SIGINT, dhcp_export_leases) + signal.signal(signal.SIGTERM, dhcp_export_leases) + signal.signal(signal.SIGALRM, dhcp_export_leases) + signal.signal(signal.SIGHUP, dhcp_export_leases) dhcpd = threading.Thread(target = dhcp_server.listen) dhcpd.daemon = True dhcpd.start()