changeset 3489:d71a163c0861

bridge (pb): connection can be set to used either UNIX socket or TCP socket: all settings are to be put in `[DEFAULT]` section - `bridge_pb_connection_type` can be set to `unix_socket` or `socket` - for `socket`, `bridge_pb_host` and `bridge_pb_port` can be specified
author Goffi <goffi@goffi.org>
date Sun, 21 Mar 2021 22:00:55 +0100
parents c80a0f864b5d
children 509f7a1c67dc
files sat/bridge/bridge_constructor/constructors/pb/pb_core_template.py sat/bridge/bridge_constructor/constructors/pb/pb_frontend_template.py sat/bridge/pb.py sat_frontends/bridge/pb.py
diffstat 4 files changed, 126 insertions(+), 14 deletions(-) [+]
line wrap: on
line diff
--- a/sat/bridge/bridge_constructor/constructors/pb/pb_core_template.py	Sun Mar 21 18:23:58 2021 +0100
+++ b/sat/bridge/bridge_constructor/constructors/pb/pb_core_template.py	Sun Mar 21 22:00:55 2021 +0100
@@ -19,9 +19,11 @@
 
 
 import dataclasses
-from sat.core.log import getLogger
+from pathlib import Path
 from twisted.spread import jelly, pb
 from twisted.internet import reactor
+from sat.core.log import getLogger
+from sat.tools import config
 
 log = getLogger(__name__)
 
@@ -103,7 +105,31 @@
     def __init__(self):
         log.info("Init Perspective Broker...")
         self.root = PBRoot()
-        reactor.listenTCP(8789, pb.PBServerFactory(self.root))
+        conf = config.parseMainConf()
+        conn_type = config.getConfig(
+            conf,
+            "",
+            "bridge_pb_connection_type",
+            "unix_socket"
+        )
+        if conn_type == "unix_socket":
+            local_dir = Path(config.getConfig(conf, "", "local_dir")).resolve()
+            socket_path = local_dir / "bridge_pb"
+            log.info(f"using UNIX Socket at {socket_path}")
+            reactor.listenUNIX(
+                str(socket_path), pb.PBServerFactory(self.root), mode=0o600
+            )
+        elif conn_type == "socket":
+            port = int(config.getConfig(
+                conf,
+                "",
+                "bridge_pb_port",
+                8789
+            ))
+            log.info(f"using TCP Socket at port {port}")
+            reactor.listenTCP(port, pb.PBServerFactory(self.root))
+        else:
+            raise ValueError(f"Unknown pb connection type: {conn_type!r}")
 
     def sendSignal(self, name, *args, **kwargs):
         self.root.sendSignal(name, args, kwargs)
@@ -117,7 +143,9 @@
         setattr(self.root, "remote_" + name, callback)
         #  self.root.register_method(name, callback)
 
-    def addMethod(self, name, int_suffix, in_sign, out_sign, method, async_=False, doc={}):
+    def addMethod(
+            self, name, int_suffix, in_sign, out_sign, method, async_=False, doc={}
+    ):
         """Dynamically add a method to PB Bridge"""
         # FIXME: doc parameter is kept only temporary, the time to remove it from calls
         log.debug("Adding method {name} to PB bridge".format(name=name))
--- a/sat/bridge/bridge_constructor/constructors/pb/pb_frontend_template.py	Sun Mar 21 18:23:58 2021 +0100
+++ b/sat/bridge/bridge_constructor/constructors/pb/pb_frontend_template.py	Sun Mar 21 22:00:55 2021 +0100
@@ -17,12 +17,14 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 import asyncio
+from logging import getLogger
 from functools import partial
+from pathlib import Path
 from twisted.spread import pb
 from twisted.internet import reactor, defer
-from twisted.internet.error import ConnectionRefusedError
-from logging import getLogger
+from twisted.internet.error import ConnectionRefusedError, ConnectError
 from sat.core import exceptions
+from sat.tools import config
 from sat_frontends.bridge.bridge_frontend import BridgeException
 
 log = getLogger(__name__)
@@ -130,14 +132,40 @@
 
     def getRootObjectEb(self, failure_):
         """Call errback with appropriate bridge error"""
-        if failure_.check(ConnectionRefusedError):
+        if failure_.check(ConnectionRefusedError, ConnectError):
             raise exceptions.BridgeExceptionNoService
         else:
             raise failure_
 
     def bridgeConnect(self, callback, errback):
         factory = pb.PBClientFactory()
-        reactor.connectTCP("localhost", 8789, factory)
+        conf = config.parseMainConf()
+        conn_type = config.getConfig(
+            conf,
+            "",
+            "bridge_pb_connection_type",
+            "unix_socket"
+        )
+        if conn_type == "unix_socket":
+            local_dir = Path(config.getConfig(conf, "", "local_dir")).resolve()
+            socket_path = local_dir / "bridge_pb"
+            reactor.connectUNIX(str(socket_path), factory)
+        elif conn_type == "socket":
+            host = int(config.getConfig(
+                conf,
+                "",
+                "bridge_pb_host",
+                "localhost"
+            ))
+            port = int(config.getConfig(
+                conf,
+                "",
+                "bridge_pb_port",
+                8789
+            ))
+            reactor.connectTCP(host, port, factory)
+        else:
+            raise ValueError(f"Unknown pb connection type: {conn_type!r}")
         d = factory.getRootObject()
         d.addCallback(self._set_root)
         if callback is not None:
--- a/sat/bridge/pb.py	Sun Mar 21 18:23:58 2021 +0100
+++ b/sat/bridge/pb.py	Sun Mar 21 22:00:55 2021 +0100
@@ -19,9 +19,11 @@
 
 
 import dataclasses
-from sat.core.log import getLogger
+from pathlib import Path
 from twisted.spread import jelly, pb
 from twisted.internet import reactor
+from sat.core.log import getLogger
+from sat.tools import config
 
 log = getLogger(__name__)
 
@@ -103,7 +105,31 @@
     def __init__(self):
         log.info("Init Perspective Broker...")
         self.root = PBRoot()
-        reactor.listenTCP(8789, pb.PBServerFactory(self.root))
+        conf = config.parseMainConf()
+        conn_type = config.getConfig(
+            conf,
+            "",
+            "bridge_pb_connection_type",
+            "unix_socket"
+        )
+        if conn_type == "unix_socket":
+            local_dir = Path(config.getConfig(conf, "", "local_dir")).resolve()
+            socket_path = local_dir / "bridge_pb"
+            log.info(f"using UNIX Socket at {socket_path}")
+            reactor.listenUNIX(
+                str(socket_path), pb.PBServerFactory(self.root), mode=0o600
+            )
+        elif conn_type == "socket":
+            port = int(config.getConfig(
+                conf,
+                "",
+                "bridge_pb_port",
+                8789
+            ))
+            log.info(f"using TCP Socket at port {port}")
+            reactor.listenTCP(port, pb.PBServerFactory(self.root))
+        else:
+            raise ValueError(f"Unknown pb connection type: {conn_type!r}")
 
     def sendSignal(self, name, *args, **kwargs):
         self.root.sendSignal(name, args, kwargs)
@@ -117,7 +143,9 @@
         setattr(self.root, "remote_" + name, callback)
         #  self.root.register_method(name, callback)
 
-    def addMethod(self, name, int_suffix, in_sign, out_sign, method, async_=False, doc={}):
+    def addMethod(
+            self, name, int_suffix, in_sign, out_sign, method, async_=False, doc={}
+    ):
         """Dynamically add a method to PB Bridge"""
         # FIXME: doc parameter is kept only temporary, the time to remove it from calls
         log.debug("Adding method {name} to PB bridge".format(name=name))
--- a/sat_frontends/bridge/pb.py	Sun Mar 21 18:23:58 2021 +0100
+++ b/sat_frontends/bridge/pb.py	Sun Mar 21 22:00:55 2021 +0100
@@ -17,12 +17,14 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 import asyncio
+from logging import getLogger
 from functools import partial
+from pathlib import Path
 from twisted.spread import pb
 from twisted.internet import reactor, defer
-from twisted.internet.error import ConnectionRefusedError
-from logging import getLogger
+from twisted.internet.error import ConnectionRefusedError, ConnectError
 from sat.core import exceptions
+from sat.tools import config
 from sat_frontends.bridge.bridge_frontend import BridgeException
 
 log = getLogger(__name__)
@@ -130,14 +132,40 @@
 
     def getRootObjectEb(self, failure_):
         """Call errback with appropriate bridge error"""
-        if failure_.check(ConnectionRefusedError):
+        if failure_.check(ConnectionRefusedError, ConnectError):
             raise exceptions.BridgeExceptionNoService
         else:
             raise failure_
 
     def bridgeConnect(self, callback, errback):
         factory = pb.PBClientFactory()
-        reactor.connectTCP("localhost", 8789, factory)
+        conf = config.parseMainConf()
+        conn_type = config.getConfig(
+            conf,
+            "",
+            "bridge_pb_connection_type",
+            "unix_socket"
+        )
+        if conn_type == "unix_socket":
+            local_dir = Path(config.getConfig(conf, "", "local_dir")).resolve()
+            socket_path = local_dir / "bridge_pb"
+            reactor.connectUNIX(str(socket_path), factory)
+        elif conn_type == "socket":
+            host = int(config.getConfig(
+                conf,
+                "",
+                "bridge_pb_host",
+                "localhost"
+            ))
+            port = int(config.getConfig(
+                conf,
+                "",
+                "bridge_pb_port",
+                8789
+            ))
+            reactor.connectTCP(host, port, factory)
+        else:
+            raise ValueError(f"Unknown pb connection type: {conn_type!r}")
         d = factory.getRootObject()
         d.addCallback(self._set_root)
         if callback is not None: