コード例 #1
0
class RPCClient:
    def __init__(self,
                 datadir: str,
                 host: str = CROSSBAR_HOST,
                 port: int = CROSSBAR_PORT,
                 realm: str = CROSSBAR_REALM,
                 ssl: bool = True) -> None:

        address = WebSocketAddress(host, port, realm, ssl)
        cert_manager = CertificateManager(
            os.path.join(get_local_datadir(datadir), CROSSBAR_DIR))
        crsb_user = cert_manager.CrossbarUsers.golemcli
        secret = cert_manager.get_secret(crsb_user)
        self.session = Session(
            address,
            crsb_user=crsb_user,
            crsb_user_secret=secret,
        )

    def call(self,
             method,
             *args,
             on_success=lambda: None,
             on_error=None,
             **kwargs):
        def on_connected(_):
            def default_errback(error):
                print("Error: {}".format(error))

            deferred = self.session.call(method, *args, **kwargs)
            deferred.addCallbacks(on_success, on_error or default_errback)
            deferred.addBoth(self.shutdown)

        def connection_error(error):
            sys.stderr.write(
                "Error connecting to Golem instance ({}): {}\n".format(
                    self.session.address, error))

            self.shutdown()

        return self.session.connect(auto_reconnect=False).addCallbacks(
            on_connected, on_error or connection_error)

    def shutdown(self, *_):
        if self.session:
            self.session.disconnect()
コード例 #2
0
class WebSocketCLI(object):

    class NoConnection(object):
        def __getattribute__(self, item):
            raise Exception("Cannot connect to Golem instance")

    def __init__(self, cli, host, port, realm, ssl=False):
        address = WebSocketAddress(host, port, realm, ssl)

        self.cli = cli
        self.session = Session(address)

    def execute(self, *args, **kwargs):
        from twisted.internet import reactor, threads

        def on_connected(_):
            core_client = Client(self.session, CORE_METHOD_MAP)
            self.cli.register_client(core_client)
            threads.deferToThread(self.cli.execute, *args, **kwargs).addBoth(self.shutdown)

        def on_error(_):
            self.cli.register_client(WebSocketCLI.NoConnection())
            self.cli.execute(*args, **kwargs)
            self.shutdown()

        def connect():
            self.session.connect().addCallbacks(on_connected, on_error)

        reactor.callWhenRunning(connect)
        reactor.run()

    def shutdown(self, *_):
        from twisted.internet import reactor
        from twisted.internet.error import ReactorNotRunning

        if self.cli:
            self.cli.shutdown()
        if self.session:
            self.session.disconnect()

        try:
            reactor.stop()
        except ReactorNotRunning:
            pass
コード例 #3
0
ファイル: websockets.py プロジェクト: U0001F3A2/golem
class WebSocketCLI(object):
    class NoConnection(object):
        def __getattribute__(self, item):
            raise Exception("Cannot connect to Golem instance")

    class CLIClient(ClientProxy):
        def _call(self, method_alias, *args, **kwargs):
            from twisted.internet import reactor
            deferred = Deferred()

            super_call = super()._call

            def in_reactor():
                try:
                    parent_deferred = super_call(
                        method_alias,
                        *args,
                        **kwargs,
                    )
                except Exception as exc:  # pylint: disable=broad-except
                    deferred.errback(exc)
                else:
                    parent_deferred.chainDeferred(deferred)

            reactor.callFromThread(in_reactor)
            return deferred

    def __init__(
            self,
            cli,  # pylint: disable=too-many-arguments
            cert_manager: CertificateManager,
            host: str = CROSSBAR_HOST,
            port: int = CROSSBAR_PORT,
            realm: str = CROSSBAR_REALM,
            ssl: bool = True) -> None:

        address = WebSocketAddress(host, port, realm, ssl)

        self.cli = cli

        crsb_user = cert_manager.CrossbarUsers.golemcli
        self.session = Session(
            address,
            crsb_user=crsb_user,
            crsb_user_secret=cert_manager.get_secret(crsb_user))

    def execute(self, *args, **kwargs):
        from twisted.internet import reactor, threads

        def on_ready(_):
            threads.deferToThread(self.cli.execute, *args, **kwargs) \
                .addBoth(self.shutdown)

        def on_connected(_):
            core_client = WebSocketCLI.CLIClient(self.session)
            self.cli.register_client(core_client)
            core_client._ready.addCallback(on_ready)  # noqa pylint: disable=protected-access

        def on_error(error):
            sys.stderr.write(
                "Error connecting to Golem instance ({}): {}\n".format(
                    self.session.address, error))

            self.cli.register_client(WebSocketCLI.NoConnection())
            self.cli.execute(*args, **kwargs)
            self.shutdown()

        def connect():
            self.session.connect(auto_reconnect=False).addCallbacks(
                on_connected, on_error)

        reactor.callWhenRunning(connect)
        reactor.run()

    def shutdown(self, *_):
        from twisted.internet import reactor
        from twisted.internet.error import ReactorNotRunning

        if self.cli:
            self.cli.shutdown()
        if self.session:
            self.session.disconnect()

        try:
            reactor.stop()
        except ReactorNotRunning:
            pass