diff --git a/src/appengine/__init__.py b/src/appengine/__init__.py index 97bc4c0..847abd1 100644 --- a/src/appengine/__init__.py +++ b/src/appengine/__init__.py @@ -8,6 +8,7 @@ import logging from systemd import journal import inspect from enum import Enum, auto +import signal from importlib import import_module from threading import Thread, Lock @@ -103,6 +104,12 @@ class Commands(Thread): def stop(self): self.stopped = True + def free(self): + """ Virtual method used to clean resources for threaded Commands + when they are stopped. + """ + pass + def list_modules(self): success = True ret = "List of modules:\n" @@ -296,11 +303,21 @@ class CommandsLoader: if v.threaded: v.start() + def stop(self): + for k, v in self.cmods.items(): + if v.threaded: + v.stop() + def join(self): for k, v in self.cmods.items(): if v.threaded: v.join() + def free(self): + for k, v in self.cmods.items(): + if v.threaded: + v.free() + class AppEngine: def __init__( @@ -310,17 +327,22 @@ class AppEngine: log_file: str = "", debug: bool = False, ) -> None: + self.cl = None self.app_name = app_name self.conf = ConfigParser() if conf_file != "": self.parse_config(conf_file) self.def_log(log_file) - + signal.signal(signal.SIGINT, self.signal_handler) if debug: self.log.setLevel(logging.DEBUG) else: self.log.setLevel(logging.WARNING) + def signal_handler(self, sig, frame): + print("\nExiting.") + self.stop() + def parse_config(self, cf: str): if os.path.exists(cf) and os.path.isfile(cf): self.conf.read(cf) @@ -349,6 +371,10 @@ class AppEngine: self.log.addHandler(journal.JournalHandler()) def exec(self, modpath: str = ""): - cl = CommandsLoader(self.conf, self.log, modpath) - cl.start() - cl.join() + self.cl = CommandsLoader(self.conf, self.log, modpath) + self.cl.start() + self.cl.join() + self.cl.free() + + def stop(self): + self.cl.stop() \ No newline at end of file