Example #1
0
    def test_add2(self):
        """
        Test a very basic call where you square root a number. This has one
        arg, no kwargs, and no authorisation.
        """
        session = TestSession(types.ComponentConfig(u'realm1'))
        self.session_factory.add(session, authrole=u"test_role")

        session2 = ApplicationSession(types.ComponentConfig(u'realm1'))
        self.session_factory.add(session2, authrole=u"test_role")
        resource = CallerResource({}, session2)

        with LogCapturer() as l:
            request = yield renderResource(
                resource,
                b"/",
                method=b"POST",
                headers={b"Content-Type": [b"application/json"]},
                body=b'{"procedure": "com.myapp.sqrt", "args": [2]}')

        self.assertEqual(request.code, 200)
        self.assertEqual(json.loads(native_string(request.get_written_data())),
                         {"args": [1.4142135623730951]})

        logs = l.get_category("AR202")
        self.assertEqual(len(logs), 1)
        self.assertEqual(logs[0]["code"], 200)
Example #2
0
    def RegisterWampClient():

        ## start logging to console
        # log.startLogging(sys.stdout)

        # create a WAMP application session factory
        component_config = types.ComponentConfig(
            realm = realm,
            extra = {"ID":ID})
        session_factory = wamp.ApplicationSessionFactory(
            config = component_config)
        session_factory.session = WampSession

        # create a WAMP-over-WebSocket transport client factory
        transport_factory = WampWebSocketClientFactory(
            session_factory,
            url = url,
            serializers = [MsgPackSerializer()],
            debug = False,
            debug_wamp = False)

        # start the client from a Twisted endpoint
        conn = connectWS(transport_factory)
        confnodesroot.logger.write(_("WAMP connecting to URL : %s\n")%url)
        return conn
Example #3
0
    def _test_application_session_internal_error(self):
        """
        simulate an internal error triggering the 'onJoin' error-case from
        _RouterApplicationSession's send() method (from the Hello msg)
        """
        # setup
        the_exception = RuntimeError("sadness")

        class TestSession(ApplicationSession):
            def onJoin(self, *args, **kw):
                raise the_exception

        session = TestSession(types.ComponentConfig(u'realm1'))
        from crossbar.router.session import _RouterApplicationSession

        # execute, first patching-out the logger so we can see that
        # log.failure() was called when our exception triggers.
        with mock.patch.object(_RouterApplicationSession, 'log') as logger:
            # this should call onJoin, triggering our error
            self.session_factory.add(session)

            # check we got the right log.failure() call
            self.assertTrue(len(logger.method_calls) > 0)
            call = logger.method_calls[0]
            # for a MagicMock call-object, 0th thing is the method-name, 1st
            # thing is the arg-tuple, 2nd thing is the kwargs.
            self.assertEqual(call[0], 'failure')
            self.assertTrue('log_failure' in call[2])
            self.assertEqual(call[2]['log_failure'].value, the_exception)
    def test_add_and_subscribe(self):
        """
        Create an application session that subscribes to some
        topic and add it to a router to run embedded.
        """
        d = txaio.create_future()

        class TestSession(ApplicationSession):
            def onJoin(self, details):
                # noinspection PyUnusedLocal
                def on_event(*arg, **kwargs):
                    pass

                d2 = self.subscribe(on_event, u'com.example.topic1')

                def ok(_):
                    txaio.resolve(d, None)

                def error(err):
                    txaio.reject(d, err)

                txaio.add_callbacks(d2, ok, error)

        session = TestSession(types.ComponentConfig(u'realm1'))

        self.session_factory.add(session)

        return d
Example #5
0
    def test_add_and_subscribe(self):
        """
        Create an application session that subscribes to some
        topic and add it to a router to run embedded.
        """
        d = txaio.create_future()

        class TestSession(ApplicationSession):

            def onJoin(self, details):
                d2 = self.subscribe(lambda: None, 'com.example.topic1')

                def ok(_):
                    txaio.resolve(d, None)

                def error(err):
                    txaio.reject(d, err)

                txaio.add_callbacks(d2, ok, error)

        session = TestSession(types.ComponentConfig('realm1'))

        self.session_factory.add(session, self.router, authrole='test_role')

        return d
Example #6
0
    def __init__(self, config=None):
        """
        Constructor.
        """
        BaseSession.__init__(self)
        self.config = config or types.ComponentConfig(realm=u"default")

        self._transport = None
        self._session_id = None
        self._realm = None

        self._goodbye_sent = False
        self._transport_is_closing = False

        # outstanding requests
        self._publish_reqs = {}
        self._subscribe_reqs = {}
        self._unsubscribe_reqs = {}
        self._call_reqs = {}
        self._register_reqs = {}
        self._unregister_reqs = {}

        # subscriptions in place
        self._subscriptions = {}

        # registrations in place
        self._registrations = {}

        # incoming invocations
        self._invocations = {}
Example #7
0
def RegisterWampClient(wampconf):

    WSClientConf = LoadWampClientConf(wampconf)

    # start logging to console
    # log.startLogging(sys.stdout)

    # create a WAMP application session factory
    component_config = types.ComponentConfig(realm=WSClientConf["realm"],
                                             extra={"ID": WSClientConf["ID"]})
    session_factory = wamp.ApplicationSessionFactory(config=component_config)
    session_factory.session = WampSession

    # create a WAMP-over-WebSocket transport client factory
    transport_factory = ReconnectingWampWebSocketClientFactory(
        session_factory,
        url=WSClientConf["url"],
        serializers=[MsgPackSerializer()],
        debug=False,
        debug_wamp=False)

    # start the client from a Twisted endpoint
    conn = connectWS(transport_factory)
    print("WAMP client connecting to :", WSClientConf["url"])
    return conn
Example #8
0
    def _prepare_transport(self):
        ''' Prepare a transport factory '''
        assert self._reactor, \
            'WAMPFrontend: cannot create transport without an IOLoop and a TornadoReactor'

        config = types.ComponentConfig(
            realm = self.config['wampfrontend']['realm'],
            extra = {
                'name': self.config['wampfrontend']['name'],
                'core': self.core,
                'frontend': self })
        session = wamp.ApplicationSessionFactory(config=config)
        session.session = WAMPFrontendComponent

        # Add a reference toe the frontend object (ourself)
        session._frontend = self
        
        # Add a reference the the ApplicationSession created
        # since we are a client, there will be only one session at all
        session._client = None

        # Now also store a reference to the session factory for us
        self._session = session
        
        transport = MyClientFactory(
            session,
            url = self.config['wampfrontend']['router'],
            debug = self.config['wampfrontend']['debug_autobahn'],
            debug_wamp = self.config['wampfrontend']['debug_wamp'])
        return transport
    def test_application_session_internal_error(self):
        """
        simulate an internal error triggering the 'onJoin' error-case from
        _RouterApplicationSession's send() method (from the Hello msg)
        """
        # setup
        the_exception = RuntimeError("sadness")
        errors = []

        class TestSession(ApplicationSession):
            def onJoin(self, *args, **kw):
                raise the_exception

            def onUserError(self, *args, **kw):
                errors.append((args, kw))
        session = TestSession(types.ComponentConfig(u'realm1'))

        # in this test, we are just looking for onUserError to get
        # called so we don't need to patch the logger. this should
        # call onJoin, triggering our error
        self.session_factory.add(session)

        # check we got the right log.failure() call
        self.assertTrue(len(errors) > 0, "expected onUserError call")
        fail = errors[0][0][0]
        self.assertTrue(fail.value == the_exception)
Example #10
0
    def __init__(self, config=types.ComponentConfig(u"anonymous")):
        """
      Constructor.
      """
        BaseSession.__init__(self)
        self.config = config

        self._transport = None
        self._session_id = None
        self._realm = None

        self._session_id = None
        self._goodbye_sent = False
        self._transport_is_closing = False

        ## outstanding requests
        self._publish_reqs = {}
        self._subscribe_reqs = {}
        self._unsubscribe_reqs = {}
        self._call_reqs = {}
        self._register_reqs = {}
        self._unregister_reqs = {}

        ## subscriptions in place
        self._subscriptions = {}

        ## registrations in place
        self._registrations = {}

        ## incoming invocations
        self._invocations = {}

        self.debug_app = False
Example #11
0
    def __init__(self, **kwargs):
        EventEmitter.__init__(self)
        for key, value in kwargs.iteritems():
            setattr(self, key, value)

        component_config = types.ComponentConfig(realm = u"sputnik")
        wamp.ApplicationSessionFactory.__init__(self, config=component_config)
    def _connect(self):
        if self.client:
            self.logger.debug('already connected to broadcaster %s' % self.url)
            return
        broadcaster = self
        self.logger.debug('trying to connect to broadcaster %s' % self.url)

        class BroadcasterComponent(wamp.ApplicationSession):
            def onJoin(self, details):
                broadcaster.client = self
                broadcaster.onSessionOpen()

            def onDisconnect(self):
                broadcaster.logger.debug(
                    "Disconnected from broadcaster at %s, will reconnect" %
                    broadcaster.host)
                broadcaster.client = None

        component_config = types.ComponentConfig(realm="yadt")
        session_factory = wamp.ApplicationSessionFactory(
            config=component_config)
        session_factory.session = BroadcasterComponent
        serializers = [JsonSerializer()]
        transport_factory = websocket.WampWebSocketClientFactory(
            session_factory,
            serializers=serializers,
            url="ws://{0}:{1}/wamp".format(self.host, self.port),
            debug=False,
            debug_wamp=False)
        client = clientFromString(reactor,
                                  "tcp:{0}:{1}".format(self.host, self.port))
        from functools import partial
        client.connect(transport_factory).addErrback(
            partial(broadcaster.logger.warning,
                    "Could not connect to broadcaster at %s"))
Example #13
0
    def test_add_and_subscribe(self):
        """
      Create an application session that subscribes to some
      topic and add it to a router to run embedded.
      """
        d = FutureMixin._create_future()

        class TestSession(ApplicationSession):
            def onJoin(self, details):
                def on_event(*arg, **kwargs):
                    pass

                d2 = self.subscribe(on_event, u'com.example.topic1')

                def ok(_):
                    FutureMixin._resolve_future(d, None)

                def error(err):
                    FutureMixin._reject_future(d, err)

                FutureMixin._add_future_callbacks(d2, ok, error)

        session = TestSession(types.ComponentConfig('realm1'))

        self.session_factory.add(session)

        if USE_ASYNCIO:
            self.loop.run_until_complete(d)
        elif USE_TWISTED:
            return d
        else:
            raise Exception("logic error")
Example #14
0
def RegisterWampClient(wampconf, secretfname):

    WSClientConf = LoadWampClientConf(wampconf)

    if not WSClientConf:
        print(_("WAMP client connection not established!"))
        return

    WampSecret = LoadWampSecret(secretfname)

    if WampSecret is not None:
        WSClientConf["secret"] = WampSecret

    # create a WAMP application session factory
    component_config = types.ComponentConfig(realm=WSClientConf["realm"],
                                             extra=WSClientConf)
    session_factory = wamp.ApplicationSessionFactory(config=component_config)
    session_factory.session = WampSession

    # create a WAMP-over-WebSocket transport client factory
    transport_factory = ReconnectingWampWebSocketClientFactory(
        session_factory,
        url=WSClientConf["url"],
        serializers=[MsgPackSerializer()])

    # start the client from a Twisted endpoint
    conn = connectWS(transport_factory)
    print(_("WAMP client connecting to :"), WSClientConf["url"])
    return conn
Example #15
0
    def __init__(self,
                 address,
                 mapping=None,
                 cert_manager=None,
                 use_ipv6=False,
                 crsb_user=None,
                 crsb_user_secret=None) -> None:
        self.address = address
        if mapping is None:
            mapping = {}
        self.mapping = mapping

        self.ready = Deferred()
        self.connected = False

        self._cert_manager = cert_manager

        self._client = None
        self._reconnect_service = None
        self._use_ipv6 = use_ipv6

        self.config = types.ComponentConfig(realm=address.realm)
        self.crsb_user = crsb_user
        self.crsb_user_secret = crsb_user_secret

        # pylint:disable=bad-super-call
        super(self.__class__, self).__init__(self.config)  # type: ignore
Example #16
0
    def __init__(self, config=None):
        """

        :param config: The default component configuration.
        :type config: instance of :class:`autobahn.wamp.types.ComponentConfig`
        """
        self.config = config or types.ComponentConfig(realm=u"default")
Example #17
0
    def __init__(self, config=types.ComponentConfig(u"anonymous")):
        """
      Ctor.

      :param config: The default component configuration.
      :type config: instance of :class:`autobahn.wamp.types.ComponentConfig`
      """
        self.config = config
Example #18
0
def RegisterWampClient(wampconf=None, wampsecret=None):
    global _WampConf, _WampSecret
    _WampConfDefault = os.path.join(WorkingDir, "wampconf.json")
    _WampSecretDefault = os.path.join(WorkingDir, "wamp.secret")

    # set config file path only if not already set
    if _WampConf is None:
        # default project's wampconf has precedance over commandline given
        if os.path.exists(_WampConfDefault) or wampconf is None:
            _WampConf = _WampConfDefault
        else:
            _WampConf = wampconf

    WampClientConf = GetConfiguration()

    # set secret file path only if not already set
    if _WampSecret is None:
        # default project's wamp secret also
        # has precedance over commandline given
        if os.path.exists(_WampSecretDefault):
            _WampSecret = _WampSecretDefault
        else:
            _WampSecret = wampsecret

    if _WampSecret is not None:
        WampClientConf["secret"] = LoadWampSecret(_WampSecret)
    else:
        print(_("WAMP authentication has no secret configured"))
        _WampSecret = _WampSecretDefault

    if not WampClientConf["active"]:
        print(_("WAMP deactivated in configuration"))
        return

    # create a WAMP application session factory
    component_config = types.ComponentConfig(
        realm=WampClientConf["realm"],
        extra=WampClientConf)
    session_factory = wamp.ApplicationSessionFactory(
        config=component_config)
    session_factory.session = WampSession

    # create a WAMP-over-WebSocket transport client factory
    ReconnectingWampWebSocketClientFactory(
        component_config,
        session_factory,
        url=WampClientConf["url"],
        serializers=[MsgPackSerializer()])

    # start the client from a Twisted endpoint
    if _transportFactory:
        connectWS(_transportFactory)
        print(_("WAMP client connecting to :"), WampClientConf["url"])
        return True
    else:
        print(_("WAMP client can not connect to :"), WampClientConf["url"])
        return False
Example #19
0
    def test_failure(self):
        """
        A failed call returns the error to the client.
        """
        session = TestSession(types.ComponentConfig(u'realm1'))
        self.session_factory.add(session, authrole=u"test_role")

        session2 = ApplicationSession(types.ComponentConfig(u'realm1'))
        self.session_factory.add(session2, authrole=u"test_role")
        resource = CallerResource({}, session2)

        tests = [
            (u"com.myapp.sqrt", (0,),
             {u"error": u"wamp.error.runtime_error", u"args": [u"don't ask foolish questions ;)"], u"kwargs": {}}),
            (u"com.myapp.checkname", ("foo",),
             {u"error": u"com.myapp.error.reserved", u"args": [], u"kwargs": {}}),
            (u"com.myapp.checkname", ("*",),
             {u"error": u"com.myapp.error.invalid_length", u"args": [], u"kwargs": {"min": 3, "max": 10}}),
            (u"com.myapp.checkname", ("hello",),
             {u"error": u"com.myapp.error.mixed_case", u"args": ["hello", "HELLO"], u"kwargs": {}}),
            (u"com.myapp.compare", (1, 10),
             {u"error": u"com.myapp.error1", u"args": [9], u"kwargs": {}}),
        ]

        for procedure, args, err in tests:
            with LogCapturer() as l:
                request = yield renderResource(
                    resource, b"/",
                    method=b"POST",
                    headers={b"Content-Type": [b"application/json"]},
                    body=dump_json({"procedure": procedure, "args": args}).encode('utf8'))

            self.assertEqual(request.code, 200)
            self.assertEqual(json.loads(native_string(request.get_written_data())),
                             err)

            logs = l.get_category("AR458")
            self.assertEqual(len(logs), 1)
            self.assertEqual(logs[0]["code"], 200)

        # We manually logged the errors; we can flush them from the log
        self.flushLoggedErrors()
Example #20
0
    def __init__(self, address, methods=None, events=None):
        self.address = address
        self.methods = methods or []
        self.events = events or []
        self.subs = {}

        self.ready = Deferred()
        self.connected = False

        self.config = types.ComponentConfig(realm=address.realm)
        super(Session, self).__init__(self.config)
Example #21
0
def magic_box(sproto, extra):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    component_config = types.ComponentConfig(realm="realm1", extra=extra)
    session_factory = wamp.ApplicationSessionFactory(config=component_config)
    session_factory.session = sproto
    transport_factory = websocket.WampWebSocketClientFactory(session_factory)
    coro = loop.create_connection(transport_factory, '127.0.0.1', 9002)
    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()
    return
Example #22
0
def start_server(config):
    log.startLogging(sys.stdout)
    router_factory = wamp.RouterFactory()
    session_factory = wamp.RouterSessionFactory(router_factory)
    component_config = types.ComponentConfig(realm=config['realm'])
    component_session = MindwaveComponent(component_config)
    component_session.app_config = config
    session_factory.add(component_session)
    transport_factory = websocket.WampWebSocketServerFactory(session_factory,
                                                             debug=False,
                                                             debug_wamp=False)
    server = serverFromString(reactor, config['server_string'])
    server.listen(transport_factory)
    reactor.run()
Example #23
0
    def test_add(self):
        """
        Create an application session and add it to a router to
        run embedded.
        """
        d = txaio.create_future()

        class TestSession(ApplicationSession):
            def onJoin(self, details):
                txaio.resolve(d, None)

        session = TestSession(types.ComponentConfig('realm1'))

        self.session_factory.add(session, self.router)

        return d
Example #24
0
def get_wamp_service(config):
    debug = config.get("websocket", "debug") == "true"
    client.load_config(config)

    router_factory = wamp.RouterFactory()
    session_factory = wamp.RouterSessionFactory(router_factory)
    component_config = types.ComponentConfig(realm="anonymous")
    session_factory.add(client.DocumentSession(component_config))

    transport_factory = websocket.WampWebSocketServerFactory(session_factory,
                                                             debug=debug,
                                                             debug_wamp=debug)

    server = internet.TCPServer(int(config.get("websocket", "port")),
                                transport_factory,
                                interface=config.get("websocket", "interface"))

    return server
Example #25
0
def wampConnect(wamp_conf):
    """WAMP connection procedure.

    :param wamp_conf: WAMP configuration from settings.json file

    """

    LOG.info("WAMP connection precedures:")

    try:

        component_config = types.ComponentConfig(
            realm=unicode(wamp_conf['realm'])
        )
        session_factory = wamp.ApplicationSessionFactory(
            config=component_config
        )
        session_factory.session = WampFrontend

        transport_factory = WampClientFactory(
            session_factory,
            url=wamp_conf['url']
        )
        transport_factory.autoPingInterval = 5
        transport_factory.autoPingTimeout = 5

        connector = websocket.connectWS(transport_factory)

        try:

            addr = str(connector.getDestination().host)
            socket.inet_pton(socket.AF_INET, addr)
            LOG.info(" - establishing connection to : " + str(addr))

        except socket.error as err:
            LOG.error(" - IP address validation error: " + str(err))
            Bye()

    except Exception as err:
        LOG.error(" - URI validation error: " + str(err))
        Bye()
Example #26
0
    def test_add(self):
        """
      Create an application session and add it to a router to
      run embedded.
      """
        d = FutureMixin._create_future()

        class TestSession(ApplicationSession):
            def onJoin(self, details):
                FutureMixin._resolve_future(d, None)

        session = TestSession(types.ComponentConfig('realm1'))

        self.session_factory.add(session)

        if USE_ASYNCIO:
            self.loop.run_until_complete(d)
        elif USE_TWISTED:
            return d
        else:
            raise Exception("logic error")
Example #27
0
def wampClient(wampAddress, wampClientEndpoint, topic, key):
    """
    Sets up an Autobahn|python WAMPv2 client.
    Code modified from WAMP documentation.
    """
    
    component_config = types.ComponentConfig(realm = "realm1", extra = {'key': unicode(key), 'topic': unicode(topic)})
    session_factory = ApplicationSessionFactory(config = component_config)  
    session_factory._myConnection = []
    session_factory.session = SubpubTileset
    
    ## create a WAMP-over-WebSocket transport client factory    
    #transport_factory = WampWebSocketClientFactory(session_factory, wampAddress, debug = False)
    transport_factory = MyClientFactory(session_factory, wampAddress, debug = False, debug_wamp = False)
    transport_factory.setProtocolOptions(failByDrop = False)
    
    ## start a WebSocket client from an endpoint
    client = clientFromString(reactor, wampClientEndpoint)
    client.connect(transport_factory)
    
    return session_factory._myConnection
Example #28
0
File: server.py Project: zhill/quay
    def _register_component(self, realm, component_klass, **kwargs):
        """ Registers a component with the server. The component_klass must derive from
        BaseComponent. """
        logger.debug("Registering component with realm %s", realm)
        if realm in self._realm_map:
            logger.debug("Component with realm %s already registered", realm)
            return self._realm_map[realm]

        component = component_klass(types.ComponentConfig(realm=realm),
                                    realm=realm,
                                    **kwargs)
        component.server = self
        component.parent_manager = self._lifecycle_manager
        component.build_logs = self._build_logs
        component.user_files = self._user_files
        component.registry_hostname = self._registry_hostname

        self._realm_map[realm] = component
        self._current_components.append(component)
        self._session_factory.add(component)
        return component
Example #29
0
    def test_application_session_internal_error(self):
        """
        simulate an internal error triggering the 'onJoin' error-case from
        RouterApplicationSession's send() method (from the Hello msg)
        """
        # setup
        the_exception = RuntimeError("sadness")
        errors = []

        class TestSession(ApplicationSession):
            def onJoin(self, *args, **kw):
                raise the_exception

            def onUserError(self, fail, msg):
                errors.append((fail, msg))

        session = TestSession(types.ComponentConfig('realm1'))
        from crossbar.router.session import RouterApplicationSession

        # Note to self: original code was logging directly in
        # RouterApplicationSession -- which *may* actually be better?
        # or not...
        with mock.patch.object(RouterApplicationSession, 'log') as logger:
            # this should call onJoin, triggering our error
            self.session_factory.add(session, self.router)

            if True:
                self.assertEqual(1, len(errors), "Didn't see our error")
                self.assertEqual(the_exception, errors[0][0].value)

            else:
                # check we got the right log.failure() call
                self.assertTrue(len(logger.method_calls) > 0)
                call = logger.method_calls[0]
                # for a MagicMock call-object, 0th thing is the method-name, 1st
                # thing is the arg-tuple, 2nd thing is the kwargs.
                self.assertEqual(call[0], 'failure')
                self.assertEqual(call[1][0].value, the_exception)
Example #30
0
        help='WAMP transport type')

    parser.add_argument(
        "--url",
        type=str,
        default=None,
        help='The WebSocket URL to connect to, e.g. ws://127.0.0.1:8080/ws.')

    args = parser.parse_args()

    ## create a WAMP application session factory
    ##
    from autobahn.asyncio.wamp import ApplicationSessionFactory
    from autobahn.wamp import types
    session_factory = ApplicationSessionFactory(
        types.ComponentConfig(realm=args.realm))

    ## dynamically load the application component ..
    ##
    import importlib
    c = args.component.split('.')
    mod, klass = '.'.join(c[:-1]), c[-1]
    app = importlib.import_module(mod)

    ## .. and set the session class on the factory
    ##
    session_factory.session = getattr(app, klass)

    if args.transport == "websocket":

        ## create a WAMP-over-WebSocket transport client factory