From 7a6603b952b5a75c16959f7da02c88d31eb82867 Mon Sep 17 00:00:00 2001 From: Jon Date: Mon, 22 Nov 2021 21:51:32 -0500 Subject: [PATCH] Allow graceful exit when shutting down in docker --- .gitignore | 5 +++++ modules/docker.py | 11 +++++++++++ qbit_manage.py | 15 +++++++++++---- 3 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 modules/docker.py diff --git a/.gitignore b/.gitignore index 028490b..b92a666 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + *.log* *.yml .vscode/* diff --git a/modules/docker.py b/modules/docker.py new file mode 100644 index 0000000..6c0f7f3 --- /dev/null +++ b/modules/docker.py @@ -0,0 +1,11 @@ +import signal + +#Gracefully kill script when docker stops +class GracefulKiller: + kill_now = False + def __init__(self): + signal.signal(signal.SIGINT, self.exit_gracefully) + signal.signal(signal.SIGTERM, self.exit_gracefully) + + def exit_gracefully(self, *args): + self.kill_now = True \ No newline at end of file diff --git a/qbit_manage.py b/qbit_manage.py index deb92fc..8677beb 100644 --- a/qbit_manage.py +++ b/qbit_manage.py @@ -19,10 +19,12 @@ try: from qbittorrentapi import Client import yaml import schedule + from modules.docker import GracefulKiller except ModuleNotFoundError: print("Requirements Error: Requirements are not installed") sys.exit(0) + if sys.version_info[0] != 3 or sys.version_info[1] < 6: print("Version Error: Version: %s.%s.%s incompatible please use Python 3.6+" % (sys.version_info[0], sys.version_info[1], sys.version_info[2])) sys.exit(0) @@ -187,7 +189,6 @@ client = Client(host=host, ############FUNCTIONS############## - #truncate the value of the torrent url to remove sensitive information def trunc_val(s, d, n=3): return d.join(s.split(d, n)[:n]) @@ -839,7 +840,12 @@ def start(): set_tag_nohardlinks() set_empty_recycle() +def end(): + logger.info("Exiting Qbit_manage") + sys.exit(0) + if __name__ == '__main__': + killer = GracefulKiller() logger.info(" _ _ _ ") logger.info(" | | (_) | ") logger.info(" __ _| |__ _| |_ _ __ ___ __ _ _ __ __ _ __ _ ___ ") @@ -857,8 +863,9 @@ if __name__ == '__main__': schedule.every(sch).minutes.do(start) logger.info(f" Scheduled Mode: Running every {sch} minutes.") start() - while True: + while not killer.kill_now: schedule.run_pending() - time.sleep(60) + time.sleep(1) + end() except KeyboardInterrupt: - logger.info("Exiting Qbit_manage") + end() \ No newline at end of file