From 03775c2c3c70880175bfecb055f6c9d58023ab19 Mon Sep 17 00:00:00 2001 From: Blake Harnden <32446120+bharnden@users.noreply.github.com> Date: Wed, 12 Oct 2022 14:34:24 -0700 Subject: [PATCH] daemon/grpc: shifted kill signal handling to grpc server who will handle complete shutdown, no longer done by CoreEmu directly --- daemon/core/api/grpc/server.py | 18 ++++++++++++++---- daemon/core/emulator/coreemu.py | 25 ------------------------- 2 files changed, 14 insertions(+), 29 deletions(-) diff --git a/daemon/core/api/grpc/server.py b/daemon/core/api/grpc/server.py index 3815d6c9..47615b29 100644 --- a/daemon/core/api/grpc/server.py +++ b/daemon/core/api/grpc/server.py @@ -1,7 +1,8 @@ -import atexit import logging import os import re +import signal +import sys import tempfile import time from concurrent import futures @@ -120,11 +121,20 @@ class CoreGrpcServer(core_pb2_grpc.CoreApiServicer): self.coreemu: CoreEmu = coreemu self.running: bool = True self.server: Optional[grpc.Server] = None - atexit.register(self._exit_handler) + # catch signals + signal.signal(signal.SIGHUP, self._signal_handler) + signal.signal(signal.SIGINT, self._signal_handler) + signal.signal(signal.SIGTERM, self._signal_handler) + signal.signal(signal.SIGUSR1, self._signal_handler) + signal.signal(signal.SIGUSR2, self._signal_handler) - def _exit_handler(self) -> None: - logger.debug("catching exit, stop running") + def _signal_handler(self, signal_number: int, _) -> None: + logger.info("caught signal: %s", signal_number) + self.coreemu.shutdown() self.running = False + if self.server: + self.server.stop(None) + sys.exit(signal_number) def _is_running(self, context) -> bool: return self.running and context.is_active() diff --git a/daemon/core/emulator/coreemu.py b/daemon/core/emulator/coreemu.py index 3a9c847b..a4b0be6a 100644 --- a/daemon/core/emulator/coreemu.py +++ b/daemon/core/emulator/coreemu.py @@ -1,8 +1,5 @@ -import atexit import logging import os -import signal -import sys from pathlib import Path from typing import Dict, List, Type @@ -18,25 +15,6 @@ logger = logging.getLogger(__name__) DEFAULT_EMANE_PREFIX: str = "/usr" -def signal_handler(signal_number: int, _) -> None: - """ - Handle signals and force an exit with cleanup. - - :param signal_number: signal number - :param _: ignored - :return: nothing - """ - logger.info("caught signal: %s", signal_number) - sys.exit(signal_number) - - -signal.signal(signal.SIGHUP, signal_handler) -signal.signal(signal.SIGINT, signal_handler) -signal.signal(signal.SIGTERM, signal_handler) -signal.signal(signal.SIGUSR1, signal_handler) -signal.signal(signal.SIGUSR2, signal_handler) - - class CoreEmu: """ Provides logic for creating and configuring CORE sessions and the nodes within them. @@ -70,9 +48,6 @@ class CoreEmu: # check executables exist on path self._validate_env() - # catch exit event - atexit.register(self.shutdown) - def _validate_env(self) -> None: """ Validates executables CORE depends on exist on path.