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.
This commit is contained in:
parent
0a304f9b6c
commit
bec9ff4d76
|
@ -2,6 +2,7 @@ import importlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
import signal
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import irc.client
|
import irc.client
|
||||||
|
@ -21,6 +22,7 @@ class Bot(irc.client.SimpleIRCClient, Logger):
|
||||||
self.plugins = []
|
self.plugins = []
|
||||||
self.values = {}
|
self.values = {}
|
||||||
self.storage = self.__get_storage()
|
self.storage = self.__get_storage()
|
||||||
|
self.done = False
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def nick(self):
|
def nick(self):
|
||||||
|
@ -111,13 +113,15 @@ class Bot(irc.client.SimpleIRCClient, Logger):
|
||||||
self.load_plugins()
|
self.load_plugins()
|
||||||
self.log_i("Connecting to server.")
|
self.log_i("Connecting to server.")
|
||||||
self.connect(self.config["host"], self.config["port"], self.nick)
|
self.connect(self.config["host"], self.config["port"], self.nick)
|
||||||
|
signal.signal(signal.SIGTERM, self.handle_sigterm)
|
||||||
try:
|
try:
|
||||||
self.start()
|
self.start()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
self.log_i("Caught keyboard interrupt.")
|
self.log_i("Caught keyboard interrupt.")
|
||||||
|
except: # Yes, I know, who are you going to call?
|
||||||
|
self.log_i("Caught unhandled exception.")
|
||||||
finally:
|
finally:
|
||||||
self.log_i("Stopping Edmond.")
|
self.cleanup()
|
||||||
self.__save_storage()
|
|
||||||
|
|
||||||
def load_plugins(self):
|
def load_plugins(self):
|
||||||
"""Load all installed plugins."""
|
"""Load all installed plugins."""
|
||||||
|
@ -171,3 +175,17 @@ class Bot(irc.client.SimpleIRCClient, Logger):
|
||||||
continue
|
continue
|
||||||
if callbacks[etype](event):
|
if callbacks[etype](event):
|
||||||
break
|
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
|
||||||
|
|
Loading…
Reference in a new issue