Esempio n. 1
0
    def stop_web_transport_service(self, transport_id, path, details=None):
        """
        Stop a service on a Web transport.

        :param transport_id: The ID of the transport to stop the Web transport service on.
        :type transport_id: str

        :param path: The path (absolute URL, eg "/myservice1") of the service to stop.
        :type path: str

        :param details: Call details.
        :type details: :class:`autobahn.wamp.types.CallDetails`
        """
        self.log.info('{func}(transport_id={transport_id}, path="{path}")',
                      func=hltype(self.stop_web_transport_service),
                      transport_id=hlid(transport_id),
                      path=hlval(path))

        transport = self.transports.get(transport_id, None)
        if not transport or \
           not isinstance(transport, self.personality.RouterWebTransport) or \
           transport.state != self.personality.RouterTransport.STATE_STARTED:
            emsg = "Cannot stop service on Web transport: no transport with ID '{}' or transport is not a Web transport".format(
                transport_id)
            self.log.error(emsg)
            raise ApplicationError('crossbar.error.not_running', emsg)

        if path not in transport.root:
            emsg = "Cannot stop service on Web transport {}: no service running on path '{}'".format(
                transport_id, path)
            self.log.error(emsg)
            raise ApplicationError('crossbar.error.not_running', emsg)

        caller = details.caller if details else None
        self.publish(self._uri_prefix + '.on_web_transport_service_stopping',
                     transport_id,
                     path,
                     options=PublishOptions(exclude=caller))

        # now actually remove the web service. note: currently this is NOT async, but direct/sync.
        # FIXME: check that the underlying Twisted Web resource doesn't need any stopping too!
        del transport.root[path]

        on_web_transport_service_stopped = {
            'transport_id': transport_id,
            'path': path,
        }
        caller = details.caller if details else None
        self.publish(self._uri_prefix + '.on_web_transport_service_stopped',
                     transport_id,
                     path,
                     on_web_transport_service_stopped,
                     options=PublishOptions(exclude=caller))

        return on_web_transport_service_stopped
Esempio n. 2
0
 async def publish(self, session, topic, payload):
     if DEBUG_ACK_SEND:
         pub = await session.publish(
             topic, payload, options=PublishOptions(acknowledge=True))
         print("published {}: {}".format(pub.id, payload))
     else:
         session.publish(topic, payload)
Esempio n. 3
0
def publish_gsi(session):
    if wamp_component.state:
        options = PublishOptions(retain=True)
        yield session.publish(f"{SRC_PREFIX}ltri-dota-gsi-health",
                              wamp_component.state.hero.health_as_color() *
                              LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-dota-gsi-health",
                              options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-dota-gsi-health-inv",
                              wamp_component.state.hero.health_as_color_inv() *
                              LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-dota-gsi-health-inv",
                              options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-dota-gsi-mana",
                              wamp_component.state.hero.mana_as_color() *
                              LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-dota-gsi-mana",
                              options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-dota-gsi-mana-inv",
                              wamp_component.state.hero.mana_as_color_inv() *
                              LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-dota-gsi-mana-inv",
                              options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-dota-gsi-money",
                              wamp_component.state.player.money_as_color() *
                              LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-dota-gsi-money",
                              options=options)
        yield session.publish(
            f"{SRC_PREFIX}ltri-dota-gsi-money-inv",
            wamp_component.state.player.money_as_color_inv() *
            LEDS_IN_ARRAY_DEFAULT,
            id="ltri-dota-gsi-money-inv",
            options=options)
    yield None
Esempio n. 4
0
    def test_flask(self, crossbar):
        app = Flask(__name__)
        wamp = FlaskAutobahnSync()

        publish_opt = PublishOptions(exclude_me=False)

        @wamp.register('flask.flask.rpc')
        def rpc():
            self.rpc_called = True

        @wamp.subscribe('flask.flask.event')
        def sub():
            self.sub_called = True

        with pytest.raises(NotRunningError):
            wamp.session.call('flask.flask.rpc')

        with pytest.raises(NotRunningError):
            wamp.session.publish('flask.flask.event', options=publish_opt)

        assert not self.rpc_called
        assert not self.sub_called

        wamp.init_app(app)

        wamp.session.call('flask.flask.rpc')
        wamp.session.publish('flask.flask.event', options=publish_opt)
        sleep(0.1)  # Dirty way to wait for on_event to be called...

        assert self.rpc_called
        assert self.sub_called
Esempio n. 5
0
def publish_gsi(session):
    if wamp_component.state:
        options = PublishOptions(retain=True)
        # yield session.publish(
        #     f"{SRC_PREFIX}ltri-csgo-gsi-de",
        #     []],
        #     id="ltri-csgo-gsi-de",
        #     options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-csgo-gsi-health",
                              wamp_component.state.player.state.health_as_color() * LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-csgo-gsi-health", options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-csgo-gsi-health-inv",
                              wamp_component.state.player.state.health_as_color_inv() * LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-csgo-gsi-health-inv", options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-csgo-gsi-armor",
                              wamp_component.state.player.state.armor_as_color() * LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-csgo-gsi-armor", options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-csgo-gsi-armor-inv",
                              wamp_component.state.player.state.armor_as_color_inv() * LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-csgo-gsi-armor-inv", options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-csgo-gsi-money",
                              wamp_component.state.player.state.money_as_color() * LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-csgo-gsi-money", options=options)
        yield session.publish(f"{SRC_PREFIX}ltri-csgo-gsi-money-inv",
                              wamp_component.state.player.state.money_as_color_inv() * LEDS_IN_ARRAY_DEFAULT,
                              id="ltri-csgo-gsi-money-inv", options=options)
    yield None
Esempio n. 6
0
    def test_api(self, crossbar):
        publish_opt = PublishOptions(exclude_me=False)

        @register('api.api.rpc')
        def rpc():
            self.rpc_called = True

        @subscribe('api.api.event')
        def sub():
            self.sub_called = True

        with pytest.raises(NotRunningError):
            call('api.api.rpc')

        with pytest.raises(NotRunningError):
            publish('api.api.event', options=publish_opt)

        assert not self.rpc_called
        assert not self.sub_called

        run()

        call('api.api.rpc')
        publish('api.api.event', options=publish_opt)
        sleep(0.1)  # Dirty way to wait for on_event to be called...

        assert self.rpc_called
        assert self.sub_called
Esempio n. 7
0
    def publish_heartbeat_rate(self, heartbeat_rate):
        """
        Publish a heartbeat rate topic.

        This topic is retained so that new clients receive the event.
        """
        return self.session.publish(TOPIC_HEARTBEAT_RATE,
                                    heartbeat_rate,
                                    options=PublishOptions(retain=True))
Esempio n. 8
0
 def test_no_publish(self, crossbar):
     wamp = AutobahnSync()
     wamp.run(realm=u'realm_limited')
     wamp.session.subscribe(lambda: None, 'pubsub.no_publish.event')
     publish_opt = PublishOptions(acknowledge=True)
     with pytest.raises(ApplicationError) as exc:
         res = wamp.session.publish(u'pubsub.no_publish.event',
                                    None,
                                    options=publish_opt)
     assert str(
         exc.value.args[0]
     ) == u"session not authorized to publish to topic 'pubsub.no_publish.event'"
Esempio n. 9
0
 async def _invoke(self):
     topic = self._publisher.topic
     try:
         options = PublishOptions(**self._publisher.publish_options_kwargs)
         session = self._publisher.manager.session.application_session
         print(f'Publication to {topic} with name {self.name} starting')
         self._result = session.publish(topic,
                                        *self._args,
                                        options=options,
                                        **self._kwargs)
         if self._result is not None and self._publisher.acknowledge:
             self._result = await self._result
         print(f'Publication to {topic} with name {self.name} succeeded')
     except Exception as e:
         print(f'Publication to {topic} with name {self.name} failed')
         self._exception = e
Esempio n. 10
0
    async def publish(self, session, topic, payload):
        key_id, enc_ser, ciphertext = await self._seller.wrap(
            self._api_id, self._topic, payload)
        if DEBUG_ACK_SEND:
            pub = await session.publish(
                topic,
                key_id,
                enc_ser,
                ciphertext,
                options=PublishOptions(acknowledge=True))
            print("published {}: {}".format(pub.id, payload))
        else:
            session.publish(topic, key_id, enc_ser, ciphertext)

        if DEBUG_ENABLED:
            debug_topic = 'debug.' + topic
            session.publish(debug_topic, payload)
Esempio n. 11
0
def test_on_join():
    monitor = mk_monitor('ws://localhost:8080/ws', 'realm')

    # Fires the join event.
    mock_session = MagicMock()
    yield monitor.fire('join', mock_session, None)

    assert mock_session.subscribe.called_once_with(monitor.on_heartbeat,
                                                   TOPIC_HEARTBEAT)

    assert mock_session.publish.called_with(
        TOPIC_HEARTBEAT_RATE,
        HEARTBEAT_RATE,
        options=PublishOptions(retain=True))

    assert monitor.dead_service_check_loop is not None
    assert monitor.dead_service_check_loop.running
Esempio n. 12
0
    def publish(self, topic, claims=None, context=None, options=None):
        if context is None:
            context = self.default_call_context
        claims = context.get_claims(claims)

        signed_claims = yield super(CommonSession,
                                    self).call(u'mdstudio.auth.endpoint.sign',
                                               claims)

        options = options or PublishOptions(acknowledge=True, exclude_me=False)

        result = yield super(
            CommonSession, self).publish(topic,
                                         signed_claims=signed_claims,
                                         options=options)  # type: Publication

        return_value(result)
Esempio n. 13
0
    def test_on_exception(self, wamp):
        events = []

        class MyException(Exception):
            pass

        @wamp.subscribe(u'pubsub.on_exception.event')
        def on_event(*args, **kwargs):
            events.append((args, kwargs))
            raise MyException('Ooops !')

        publish_opt = PublishOptions(exclude_me=False, acknowledge=True)
        wamp.session.publish('pubsub.on_exception.event',
                             '1',
                             options=publish_opt)
        sleep(0.1)  # Dirty way to wait for on_event to be called...
        assert events == [(('1', ), {})]
Esempio n. 14
0
 def publish_message(self, user_id, message):
     print("will try to send message")
     try:
         print("Okay")
         return_val = self.wamp_client.publish(
             "com.crossbar_test.notification",
             message,
             options=PublishOptions(acknowledge=True,
                                    eligible_authid=user_id))
         return_val.addCallback(callback)
         return_val.addErrback(callback)
         print(
             "ok, event published to topic {}".format(
                 "com.crossbar_test.notification"), return_val)
     except Exception as e:
         print(
             "publication to topic {} failed (this is expected!) {}".format(
                 "com.crossbar_test.notification", e))
Esempio n. 15
0
    def test_use_decorator(self, wamp):
        events = []

        @wamp.subscribe(u'pubsub.use_decorator.event')
        def on_event(*args, **kwargs):
            events.append((args, kwargs))

        publish_opt = PublishOptions(exclude_me=False)
        wamp.session.publish('pubsub.use_decorator.event',
                             '1',
                             options=publish_opt)
        wamp.session.publish('pubsub.use_decorator.event',
                             '2',
                             options=publish_opt)
        wamp.session.publish('pubsub.use_decorator.event',
                             opt=True,
                             options=publish_opt)
        sleep(0.1)  # Dirty way to wait for on_event to be called...
        assert events == [(('1', ), {}), (('2', ), {}), ((), {'opt': True})]
Esempio n. 16
0
def main():
    timestamp = str(datetime.utcnow())
    print('[Worker %s] Serve request on timestamp %s' % (worker_id, timestamp))
    publish_opt = PublishOptions(exclude_me=False)
    app.wamp.session.publish('com.flask_app.page_served',
                             worker_id,
                             timestamp,
                             options=publish_opt)
    serve_history = app.wamp.session.call('com.flask_app.get_request_history',
                                          worker_id)
    txts = [
        "<table>",
        "<thead><th>Worker id</th><th>Request timestamp</th></thead>",
        "<tbody>"
    ]
    txts += [
        "<tr><td>%s</td><td>%s</td></tr>" % (wid, ts)
        for wid, ts in serve_history
    ]
    txts.append("</tbody></table>")
    return ''.join(txts)
Esempio n. 17
0
    def test_decorate_before_run(self, crossbar):
        events = []
        wamp = AutobahnSync()

        @wamp.subscribe(u'pubsub.decorate_before_run.event')
        def on_event(*args, **kwargs):
            events.append((args, kwargs))

        wamp.run()
        publish_opt = PublishOptions(exclude_me=False)
        wamp.session.publish('pubsub.decorate_before_run.event',
                             '1',
                             options=publish_opt)
        wamp.session.publish('pubsub.decorate_before_run.event',
                             '2',
                             options=publish_opt)
        wamp.session.publish('pubsub.decorate_before_run.event',
                             opt=True,
                             options=publish_opt)
        sleep(0.1)  # Dirty way to wait for on_event to be called...
        assert events == [(('1', ), {}), (('2', ), {}), ((), {'opt': True})]
Esempio n. 18
0
    def start_web_transport_service(self,
                                    transport_id,
                                    path,
                                    config,
                                    details=None):
        """
        Start a service on a Web transport.

        :param transport_id: The ID of the transport to start the Web transport service on.
        :type transport_id: str

        :param path: The path (absolute URL, eg "/myservice1") on which to start the service.
        :type path: str

        :param config: The Web service configuration.
        :type config: dict

        :param details: Call details.
        :type details: :class:`autobahn.wamp.types.CallDetails`
        """
        if not isinstance(config, dict) or 'type' not in config:
            raise ApplicationError(
                'crossbar.invalid_argument',
                'config parameter must be dict with type attribute')

        self.log.info(
            'Starting "{service_type}" Web service on path "{path}" of transport "{transport_id}" {func}',
            service_type=hlval(config.get('type', 'unknown')),
            path=hlval(path),
            transport_id=hlid(transport_id),
            func=hltype(self.start_web_transport_service))

        transport = self.transports.get(transport_id, None)
        if not transport:
            emsg = 'Cannot start service on transport: no transport with ID "{}"'.format(
                transport_id)
            self.log.error(emsg)
            raise ApplicationError('crossbar.error.not_running', emsg)

        if not isinstance(transport, self.personality.RouterWebTransport):
            emsg = 'Cannot start service on transport: transport is not a Web transport (transport_type={})'.format(
                hltype(transport.__class__))
            self.log.error(emsg)
            raise ApplicationError('crossbar.error.not_running', emsg)

        if transport.state != self.personality.RouterTransport.STATE_STARTED:
            emsg = 'Cannot start service on Web transport service: transport {} is not running (transport_state={})'.format(
                transport_id,
                self.personality.RouterWebTransport.STATES.get(
                    transport.state, None))
            self.log.error(emsg)
            raise ApplicationError('crossbar.error.not_running', emsg)

        if path in transport.root:
            emsg = 'Cannot start service on Web transport "{}": a service is already running on path "{}"'.format(
                transport_id, path)
            self.log.error(emsg)
            raise ApplicationError('crossbar.error.already_running', emsg)

        caller = details.caller if details else None
        self.publish(self._uri_prefix + '.on_web_transport_service_starting',
                     transport_id,
                     path,
                     options=PublishOptions(exclude=caller))

        # now actually add the web service ..
        # note: currently this is NOT async, but direct/sync.
        webservice_factory = self.personality.WEB_SERVICE_FACTORIES[
            config['type']]

        webservice = yield maybeDeferred(webservice_factory.create, transport,
                                         path, config)
        transport.root[path] = webservice

        on_web_transport_service_started = {
            'transport_id': transport_id,
            'path': path,
            'config': config
        }
        caller = details.caller if details else None
        self.publish(self._uri_prefix + '.on_web_transport_service_started',
                     transport_id,
                     path,
                     on_web_transport_service_started,
                     options=PublishOptions(exclude=caller))

        returnValue(on_web_transport_service_started)
Esempio n. 19
0
import inspect
from autobahn.wamp import PublishOptions
from autobahn.wamp.request import Registration
from twisted.internet.defer import inlineCallbacks

DOC_LISTENER_URI = "com.lambentri.edge.la4.doc"

pub_options = PublishOptions(acknowledge=True, exclude_me=False)


class DocMixin:
    zsubs = None
    regs = None

    def _get_function_handle_from_uri(self, uri):
        return next(
            iter([i for i in self.members if i[1]._wampuris[0]._uri == uri]))

    def _get_doc_from_name_handle(self, handle):
        return getattr(self, handle).__doc__

    def _get_args_and_kwargs_from_name_handle(self, handle):
        """TODO INSPECT RETURN on args"""
        func = getattr(self, handle)
        args = inspect.signature(func)
        # print(args)
        if args and args.parameters:
            if isinstance(list(args.parameters.values())[0], dict):
                x = {
                    k: v.get("annotation", "str")
                    for k, v in args.parameters.items()