From 3e76827d18826bade5760010e9a2a81c2974b8d6 Mon Sep 17 00:00:00 2001 From: NaruZosa Date: Sat, 26 Oct 2024 18:24:15 +1100 Subject: [PATCH] Update s3s.py to allow clean docker exit Process sigterm to allow the docker container to cleanly exit. https://stackoverflow.com/questions/62853875/stopping-python-container-is-slow-sigterm-not-passed-to-python-process "Docker runs your application, per default, in foreground, so, as PID 1, this said, the process with the PID 1 as a special meaning and specific protections in Linux. This is highlighted in docker run documentation: Note A process running as PID 1 inside a container is treated specially by Linux: it ignores any signal with the default action. As a result, the process will not terminate on SIGINT or SIGTERM unless it is coded to do so." --- s3s.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/s3s.py b/s3s.py index ad8dc1b..ba458ad 100755 --- a/s3s.py +++ b/s3s.py @@ -4,7 +4,7 @@ # https://github.com/frozenpandaman/s3s # License: GPLv3 -import argparse, base64, datetime, json, os, shutil, re, sys, time, uuid +import argparse, base64, datetime, json, os, shutil, signal, re, sys, time, types, uuid from concurrent.futures import ThreadPoolExecutor from subprocess import call import requests, msgpack @@ -1801,12 +1801,28 @@ def parse_arguments(): parser.add_argument("--skipprefetch", required=False, action="store_true", help=argparse.SUPPRESS) return parser.parse_args() +def terminate(sigterm: signal.SIGTERM, frame: types.FrameType) -> None: + '''Terminate cleanly. Needed for stopping swiftly when docker sends the command to stop. + + Args: + ---- + sigterm (signal.Signal): The termination signal. + frame: The execution frame. + + ''' + print(f"Termination signal sent: {datetime.datetime.now()}") + sys.exit(0) + + def main(): '''Main process, including I/O and setup.''' print('\033[93m\033[1m' + "s3s" + '\033[0m\033[93m' + f" v{A_VERSION}" + '\033[0m') + signal.signal(signal.SIGTERM, terminate) # Process termination signals, allowing cleanly stopping when run as a docker container + + # argparse setup ################ parser_result = parse_arguments()