|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Host Service to handle docker-to-host communication""" |
| 3 | + |
| 4 | +import os |
| 5 | +import os.path |
| 6 | +import glob |
| 7 | +import importlib |
| 8 | +import sys |
| 9 | + |
| 10 | +import dbus |
| 11 | +import dbus.service |
| 12 | +import dbus.mainloop.glib |
| 13 | + |
| 14 | +from gi.repository import GObject |
| 15 | + |
| 16 | +def register_modules(): |
| 17 | + """Register all host modules""" |
| 18 | + mod_path = os.path.join(os.path.dirname(__file__), 'host_modules') |
| 19 | + sys.path.append(mod_path) |
| 20 | + for mod_file in glob.glob(os.path.join(mod_path, '*.py')): |
| 21 | + if os.path.isfile(mod_file) and not mod_file.endswith('__init__.py'): |
| 22 | + mod_name = os.path.basename(mod_file)[:-3] |
| 23 | + module = importlib.import_module(mod_name) |
| 24 | + |
| 25 | + register_cb = getattr(module, 'register', None) |
| 26 | + if not register_cb: |
| 27 | + raise Exception('Missing register function for ' + mod_name) |
| 28 | + |
| 29 | + register_dbus(register_cb) |
| 30 | + |
| 31 | +def register_dbus(register_cb): |
| 32 | + """Register DBus handlers for individual modules""" |
| 33 | + handler_class, mod_name = register_cb() |
| 34 | + handlers[mod_name] = handler_class(mod_name) |
| 35 | + |
| 36 | +# Create a main loop reactor |
| 37 | +GObject.threads_init() |
| 38 | +dbus.mainloop.glib.threads_init() |
| 39 | +dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) |
| 40 | +loop = GObject.MainLoop() |
| 41 | +handlers = {} |
| 42 | + |
| 43 | +class SignalManager(object): |
| 44 | + ''' This is used to manage signals received (e.g. SIGINT). |
| 45 | + When stopping a process (systemctl stop [service]), systemd sends |
| 46 | + a SIGTERM signal. |
| 47 | + ''' |
| 48 | + shutdown = False |
| 49 | + def __init__(self): |
| 50 | + ''' Install signal handlers. |
| 51 | +
|
| 52 | + SIGTERM is invoked when systemd wants to stop the daemon. |
| 53 | + For example, "systemctl stop mydaemon.service" |
| 54 | + or, "systemctl restart mydaemon.service" |
| 55 | +
|
| 56 | + ''' |
| 57 | + import signal |
| 58 | + signal.signal(signal.SIGTERM, self.sigterm_hdlr) |
| 59 | + |
| 60 | + def sigterm_hdlr(self, _signum, _frame): |
| 61 | + self.shutdown = True |
| 62 | + loop.quit() |
| 63 | + |
| 64 | +sigmgr = SignalManager() |
| 65 | +register_modules() |
| 66 | + |
| 67 | +# Only run if we actually have some handlers |
| 68 | +if handlers: |
| 69 | + import systemd.daemon |
| 70 | + systemd.daemon.notify("READY=1") |
| 71 | + |
| 72 | + while not sigmgr.shutdown: |
| 73 | + loop.run() |
| 74 | + if sigmgr.shutdown: |
| 75 | + break |
| 76 | + |
| 77 | + systemd.daemon.notify("STOPPING=1") |
| 78 | +else: |
| 79 | + print("No handlers to register, quitting...") |
0 commit comments