From 2bdba88389e5c3ee83bcbf719bbbaa1da0f81ede Mon Sep 17 00:00:00 2001 From: Pierce Lopez Date: Tue, 19 Jan 2021 12:46:00 -0500 Subject: [PATCH] server: explicit signal handler for SIGINT and SIGTERM (#3595) When running alone as pid 1 in a container, most signals that would cause the process to exit by default, are instead ignored by default. The container runtime will send SIGTERM, wait 10 seconds, then send SIGKILL, which will work, but moto.server can exit much faster if it has an explicit SIGTERM handler. --- moto/server.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/moto/server.py b/moto/server.py index 28e4ce556..0a419c3c4 100644 --- a/moto/server.py +++ b/moto/server.py @@ -4,6 +4,7 @@ import argparse import io import json import re +import signal import sys from threading import Lock @@ -245,6 +246,11 @@ def create_backend_app(service): return backend_app +def signal_handler(signum, frame): + print("Received signal %d" % signum) + sys.exit(0) + + def main(argv=sys.argv[1:]): parser = argparse.ArgumentParser() @@ -284,6 +290,9 @@ def main(argv=sys.argv[1:]): args = parser.parse_args(argv) + signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) + # Wrap the main application main_app = DomainDispatcherApplication(create_backend_app, service=args.service) main_app.debug = True