I recently wrote a little data transfer service in python that runs in ECS. When developing it locally it was easy to handle SIGINT: try write a batch, except KeyboardInterrupt, if caught mark the transfer as incomplete and finally commit the change and shut down.
But there’s no exception in python to catch for a SIGTERM, which is what ECS and other service mangers send when it’s time to shut down. So I had to add a signal handler. Would have been neat if SIGTERM could be caught like SIGINT with a “native” exception.
from signal import SIGTERM, raise_signal, signal
import sys # for excepthook
class Terminate(BaseException):
pass
def _excepthook(type, value, traceback):
if not issubclass(type, Terminate):
return _prevhook(type, value, traceback)
# If a Terminate went unhandled, make sure we are killed
# by SIGTERM as far as wait(2) and friends are concerned.
signal(SIGTERM, _prevterm)
raise_signal(SIGTERM)
_prevhook, sys.excepthook = sys.excepthook, _excepthook
def terminate(signo=SIGTERM, frame=None):
signal(SIGTERM, _prevterm)
raise Terminate
_prevterm = signal(SIGTERM, terminate)
But there’s no exception in python to catch for a SIGTERM, which is what ECS and other service mangers send when it’s time to shut down. So I had to add a signal handler. Would have been neat if SIGTERM could be caught like SIGINT with a “native” exception.