From bec9ff4d76468c46ca5afaff2c0c119eff61a3c8 Mon Sep 17 00:00:00 2001 From: dece Date: Tue, 26 Apr 2022 21:33:43 +0200 Subject: [PATCH] bot: drastically catch exceptions For whatever reason systemd stop signals are not caught anymore by the "except KeyboardInterrupt", so the storage file is lost on what should be a graceful shutdown. --- edmond/bot.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/edmond/bot.py b/edmond/bot.py index 52d3653..294fdc6 100644 --- a/edmond/bot.py +++ b/edmond/bot.py @@ -2,6 +2,7 @@ import importlib import json import os import time +import signal from pathlib import Path import irc.client @@ -21,6 +22,7 @@ class Bot(irc.client.SimpleIRCClient, Logger): self.plugins = [] self.values = {} self.storage = self.__get_storage() + self.done = False @property def nick(self): @@ -111,13 +113,15 @@ class Bot(irc.client.SimpleIRCClient, Logger): self.load_plugins() self.log_i("Connecting to server.") self.connect(self.config["host"], self.config["port"], self.nick) + signal.signal(signal.SIGTERM, self.handle_sigterm) try: self.start() except KeyboardInterrupt: self.log_i("Caught keyboard interrupt.") + except: # Yes, I know, who are you going to call? + self.log_i("Caught unhandled exception.") finally: - self.log_i("Stopping Edmond.") - self.__save_storage() + self.cleanup() def load_plugins(self): """Load all installed plugins.""" @@ -171,3 +175,17 @@ class Bot(irc.client.SimpleIRCClient, Logger): continue if callbacks[etype](event): break + + def handle_sigterm(self, *args): + """Handle SIGTERM (keyboard interrupt, systemd stop, etc).""" + self.cleanup() + + def cleanup(self): + """Save the storage file and close the connection. Run only once.""" + if self.done: + return + self.log_i("Stopping Edmond.") + self.__save_storage() + if self.connection.is_connected(): + self.connection.close() + self.done = True