diff libervia/server/server.py @ 1361:626b7bbb7f90

server: mechanism to exit Libervia with an exit code: the new `SysExit` exception can now be used to quit Libervia with a given shell exit code.
author Goffi <goffi@goffi.org>
date Sat, 14 Nov 2020 22:24:58 +0100
parents 389a83eefe62
children 45ebeea1bacd
line wrap: on
line diff
--- a/libervia/server/server.py	Mon Sep 28 21:12:21 2020 +0200
+++ b/libervia/server/server.py	Sat Nov 14 22:24:58 2020 +0100
@@ -75,6 +75,16 @@
                 | inotify.IN_MOVED_TO)
 
 
+class SysExit(Exception):
+
+    def __init__(self, exit_code, message=""):
+        self.exit_code = exit_code
+        self.message = message
+
+    def __str__(self):
+        return f"System Exit({self.exit_code}): {self.message}"
+
+
 class FilesWatcher(object):
     """Class to check files modifications using iNotify"""
     _notifier = None
@@ -1076,18 +1086,12 @@
         self.site = server.Site(wrapped)
         self.site.sessionFactory = LiberviaSession
 
-    def initEb(self, failure):
-        log.error(_("Init error: {msg}").format(msg=failure))
-        reactor.stop()
-        return failure
-
     def _bridgeCb(self):
         self.bridge.getReady(
             lambda: self.initialised.callback(None),
             lambda failure: self.initialised.errback(Exception(failure)),
         )
         self.initialised.addCallback(lambda __: defer.ensureDeferred(self.backendReady()))
-        self.initialised.addErrback(self.initEb)
 
     def _bridgeEb(self, failure_):
         if isinstance(failure_, BridgeExceptionNoService):
@@ -1416,6 +1420,19 @@
         @param **kwargs: list of keyword arguments of the callback"""
         self._cleanup.insert(0, (callback, args, kwargs))
 
+    def initEb(self, failure):
+        from twisted.application import app
+        if failure.check(SysExit):
+            if failure.value.message:
+                log.error(failure.value.message)
+            app._exitCode = failure.value.exit_code
+            reactor.stop()
+        else:
+            log.error(_("Init error: {msg}").format(msg=failure))
+            app._exitCode = C.EXIT_INTERNAL_ERROR
+            reactor.stop()
+            return failure
+
     def startService(self):
         """Connect the profile for Libervia and start the HTTP(S) server(s)"""
         self._init()
@@ -1447,6 +1464,7 @@
                 self._startService()
 
         self.initialised.addCallback(initOk)
+        self.initialised.addErrback(self.initEb)
 
     ## URLs ##