Пример #1
0
class WampServer:

    def __init__(self, debug = '0'):

        self.debug = debug

        log.startLogging(sys.stdout)

        ## we use an Autobahn utility to install the "best" available Twisted reactor
        ##
        from autobahn.twisted.choosereactor import install_reactor
        self.reactor = install_reactor()
        print("Running on reactor {}".format(self.reactor))


        ## create a WAMP router factory
        ##
        from autobahn.twisted.wamp import RouterFactory
        self.router_factory = RouterFactory()


        ## create a WAMP router session factory
        ##
        from autobahn.twisted.wamp import RouterSessionFactory
        self.session_factory = RouterSessionFactory(self.router_factory)


        ## Add embedded WAMP application sessions to the router
        ##
        from core.rpc import MyBackendComponent
        component_config = types.ComponentConfig(realm = "realm1")
        component_session = MyBackendComponent(component_config)
        self.session_factory.add(component_session)

        ## create a WAMP-over-WebSocket transport server factory
        ##
        from autobahn.twisted.websocket import WampWebSocketServerFactory
        self.transport_factory = WampWebSocketServerFactory(self.session_factory, debug = self.debug)
        self.transport_factory.setProtocolOptions(failByDrop = False)


    def run(self, config):
        ## start the server from an endpoint
        ##
        enpoint = 'tcp:' + config.PORT
        print enpoint
        self.server = serverFromString(self.reactor, enpoint)
        self.server.listen(self.transport_factory)

        ## now enter the Twisted reactor loop
        ##
        self.reactor.run()
Пример #2
0
      def test_minimal(self):

         embedded_components, client_components = [], [Case2_Backend, Case2_Frontend]

         ## create a WAMP router factory
         ##
         router_factory = RouterFactory()


         ## create a WAMP router session factory
         ##
         session_factory = RouterSessionFactory(router_factory)



         ## .. and create and add an WAMP application session to
         ## run next to the router
         ##
         config = types.ComponentConfig(realm = self.realm,
            extra = {
               'caselog': 'case1.log'
            }
         )
         try:
            log = io.open('caselog.log', 'w')
         except Exception as e:
            print(e)
            return
   #      log = io.open(config.extra['caselog'], 'w')
         config.log = log
         config.dlog = []
         config.components = []

         config.all_done = []

         for C in embedded_components:
            one_done = Deferred()
            config.all_done.append(one_done)
            c = C(config, one_done)
            config.components.append(c)
            session_factory.add(c)

         if self.transport == "websocket":

            ## create a WAMP-over-WebSocket transport server factory
            ##
            transport_factory = WampWebSocketServerFactory(session_factory, debug_wamp = self.debug)
            transport_factory.setProtocolOptions(failByDrop = False, openHandshakeTimeout = 0, closeHandshakeTimeout = 0)

         elif self.transport in ['rawsocket-json', 'rawsocket-msgpack']:

            ## create a WAMP-over-RawSocket transport server factory
            ##
            if self.transport == 'rawsocket-msgpack':
               serializer = MsgPackSerializer()
            elif self.transport == 'rawsocket-json':
               serializer = JsonSerializer()
            else:
               raise Exception("should not arrive here")

            transport_factory = WampRawSocketServerFactory(session_factory, serializer, debug = self.debug)

         else:
            raise Exception("should not arrive here")


         ## start the server from an endpoint
         ##
         from twisted.internet import reactor
         server = serverFromString(reactor, self.server)
         d = server.listen(transport_factory)

         def onlisten(port):
            config.port = port

         d.addCallback(onlisten)

         clients = []
         clients_d = []
         for C in client_components:
            ## create a WAMP application session factory
            ##
            session_factory = ApplicationSessionFactory(config)

            one_done = Deferred()
            config.all_done.append(one_done)

            def make_make(Klass, done):
               def make(config):
                  c = Klass(config, done)
                  config.components.append(c)
                  return c
               return make

            ## .. and set the session class on the factory
            ##
            session_factory.session = make_make(C, one_done)

            if self.transport == "websocket":

               serializers = [JsonSerializer()]

               ## create a WAMP-over-WebSocket transport client factory
               ##
               transport_factory = WampWebSocketClientFactory(session_factory, serializers = serializers, url = self.url, debug_wamp = self.debug)

               if True:
                  def maker(Klass):
                     class TestClientProtocol(WampWebSocketClientProtocol):
                        def onOpen(self):
                           self.txcnt = 0
                           self.rxcnt = 0
                           WampWebSocketClientProtocol.onOpen(self)

                        def sendMessage(self, payload, isBinary):
                           self.txcnt += 1
                           print("> : {0:>3} : {1:<20} : {3}".format(self.txcnt, Klass.__name__, payload))
                           WampWebSocketClientProtocol.sendMessage(self, payload, isBinary)

                        def onMessage(self, payload, isBinary):
                           self.rxcnt += 1
                           print("< : {0:>3} : {1:<20} : {2}".format(self.rxcnt, Klass.__name__, payload))
                           WampWebSocketClientProtocol.onMessage(self, payload, isBinary)
                     return TestClientProtocol

                  transport_factory.protocol = maker(C)
               else:
                  transport_factory.protocol = WampWebSocketClientProtocol

               transport_factory.setProtocolOptions(failByDrop = False, openHandshakeTimeout = 0, closeHandshakeTimeout = 0)

            elif self.transport in ['rawsocket-json', 'rawsocket-msgpack']:

               ## create a WAMP-over-RawSocket transport client factory
               ##
               if self.transport == 'rawsocket-msgpack':
                  serializer = MsgPackSerializer()
               elif self.transport == 'rawsocket-json':
                  serializer = JsonSerializer()
               else:
                  raise Exception("should not arrive here")

               transport_factory = WampRawSocketClientFactory(session_factory, serializer, debug = self.debug)


            ## start the client from an endpoint
            ##
            cl = clientFromString(reactor, self.client)
            clients_d.append(cl.connect(transport_factory))

            clients.append(cl)

         config.connected_clients = None

         def client_connected(res):
            config.connected_clients = [proto for success, proto in res if success]

         DeferredList(clients_d).addCallback(client_connected)


         d = DeferredList(config.all_done, consumeErrors = True)
         #d = config.components[1]._done

         def done(_):
            log.flush()
            log.close()
            if config.port:
               config.port.stopListening()
            if config.connected_clients:
               for proto in config.connected_clients:
                  proto.transport.abortConnection()
            print("Log length: {0}".format(len(config.dlog)))
            print(config.dlog)
            #from twisted.internet import reactor
            #reactor.callLater(1, reactor.stop)

         def error(err):
            print(err)

         d.addCallbacks(done, error)

   #      d2 = Deferred()

         return d
Пример #3
0
class TestEmbeddedSessions(unittest.TestCase):
   """
   Test cases for application session running embedded in router.
   """

   def setUp(self):
      """
      Setup router and router session factories.
      """
      if USE_ASYNCIO:
         self.loop = asyncio.new_event_loop()
         asyncio.set_event_loop(self.loop)

      self.router_factory = RouterFactory()
      self.session_factory = RouterSessionFactory(self.router_factory)


   def tearDown(self):
      if USE_ASYNCIO:
         self.loop.close()
         asyncio.set_event_loop(None)
         gc.collect()


   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")


   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")
Пример #4
0
   ## if asked to start an embedded application component ..
   ##
   if args.component:
      ## dynamically load the application component ..
      ##
      import importlib
      c = args.component.split('.')
      mod, klass = '.'.join(c[:-1]), c[-1]
      app = importlib.import_module(mod)
      SessionKlass = getattr(app, klass)

      ## .. and create and add an WAMP application session to
      ## run next to the router
      ##
      from autobahn.wamp import types
      session_factory.add(SessionKlass(types.ComponentConfig(realm = args.realm)))


   if args.transport == "websocket":

      ## create a WAMP-over-WebSocket transport server factory with longpoll fallback
      ##
      from autobahn.wamp.serializer import JsonSerializer, MsgPackSerializer
      from autobahn.twisted.websocket import WampWebSocketServerFactory
      from autobahn.twisted.resource import WebSocketResource
      from twisted.web.server import Site
      from twisted.web.static import File
      from autobahn.wamp.http import WampHttpResource
      ws_factory = WampWebSocketServerFactory(session_factory, debug_wamp = args.debug)
      ws_factory.setProtocolOptions(failByDrop = False)
      serializers = [MsgPackSerializer(), JsonSerializer()]
Пример #5
0
    # create a WAMP router factory
    ##
    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()

    # create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = MyRouterSession

    # start an embedded application component ..
    ##
    component_config = types.ComponentConfig(realm="realm1")
    component_session = TimeService(component_config)
    session_factory.add(component_session)

    # create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory
    transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug=False, debug_wamp=args.debug)
    transport_factory.protocol = ServerProtocol
    transport_factory._cookies = {}

    transport_factory.setProtocolOptions(failByDrop=False)

    from twisted.web.server import Site
    from twisted.web.static import File
    from autobahn.twisted.resource import WebSocketResource

    # we serve static files under "/" ..
Пример #6
0
    print("Running on reactor {}".format(reactor))

    ## create a WAMP router factory
    ##
    from autobahn.wamp.router import RouterFactory

    router_factory = RouterFactory()

    ## create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory

    session_factory = RouterSessionFactory(router_factory)

    ## [ ... ... ]
    session_factory.add(PubSubComponent())

    ## create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory

    # NB: args.wsurl MUST NOT INCLUDE a path; hence it is not really a URL; all it supports is protocol (which must be ws or wss), hostname, and port. anything after that gives a mysterious
    #   File "/usr/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 3383, in setSessionParameters
    # raise Exception("path specified for server WebSocket URL")
    transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug=True)
    transport_factory.setProtocolOptions(failByDrop=False)

    ## start the WebSocket server from an endpoint
    ##
    server = serverFromString(reactor, args.websocket)
    server.listen(transport_factory)
Пример #7
0
    ## if asked to start an embedded application component ..
    ##
    if args.component:
        ## dynamically load the application component ..
        ##
        import importlib
        c = args.component.split('.')
        mod, klass = '.'.join(c[:-1]), c[-1]
        app = importlib.import_module(mod)
        SessionKlass = getattr(app, klass)

        ## .. and create and add an WAMP application session to
        ## run next to the router
        ##
        from autobahn.wamp import types
        session_factory.add(
            SessionKlass(types.ComponentConfig(realm=args.realm)))

    if args.transport == "websocket":

        ## create a WAMP-over-WebSocket transport server factory with longpoll fallback
        ##
        from autobahn.wamp.serializer import JsonSerializer, MsgPackSerializer
        from autobahn.twisted.websocket import WampWebSocketServerFactory
        from autobahn.twisted.resource import WebSocketResource
        from twisted.web.server import Site
        from twisted.web.static import File
        from autobahn.wamp.http import WampHttpResource
        ws_factory = WampWebSocketServerFactory(session_factory,
                                                debug_wamp=args.debug)
        ws_factory.setProtocolOptions(failByDrop=False)
        serializers = [MsgPackSerializer(), JsonSerializer()]
Пример #8
0
   ## create a WAMP router factory
   ##
   from autobahn.wamp.router import RouterFactory
   router_factory = RouterFactory()


   ## create a WAMP router session factory
   ##
   from autobahn.twisted.wamp import RouterSessionFactory
   session_factory = RouterSessionFactory(router_factory)
   session_factory.session = MyRouterSession


   ## start an embedded application component ..
   ##
   session_factory.add(TimeService())


   ## create a WAMP-over-WebSocket transport server factory
   ##
   from autobahn.twisted.websocket import WampWebSocketServerFactory
   transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug_wamp = args.debug)
   transport_factory.protocol = ServerProtocol
   transport_factory._cookies = {}

   transport_factory.setProtocolOptions(failByDrop = False)


   from twisted.web.server import Site
   from twisted.web.static import File
   from autobahn.twisted.resource import WebSocketResource
Пример #9
0
def run():
    import sys, argparse
    from twisted.python import log
    from twisted.internet.endpoints import serverFromString

    ## parse command line arguments
    ##

    def_wsocket = 'ws://127.0.0.1:8080/ws'
    def_xsocket = None
    def_user = '******'
    def_secret = '123test'
    def_realm = 'realm1'
    def_topic_base = 'sys'
    def_dsn = 'dbname=autobahn host=localhost user=autouser'
    def_endpoint = 'tcp:8080'
    def_engine = 'PG9_4'

    p = argparse.ArgumentParser(
        description="basicrouter example with database")

    p.add_argument('-w',
                   '--websocket',
                   action='store',
                   dest='wsocket',
                   default=def_wsocket,
                   help='web socket ' + def_wsocket)
    p.add_argument('-x',
                   '--xsocket',
                   action='store',
                   dest='xsocket',
                   default=def_xsocket,
                   help='x socket definition, default is: None ')
    p.add_argument('-r',
                   '--realm',
                   action='store',
                   dest='realm',
                   default=def_realm,
                   help='connect to websocket using "realm", default ' +
                   def_realm)
    p.add_argument('-v',
                   '--verbose',
                   action='store_true',
                   dest='verbose',
                   default=False,
                   help='Verbose logging for debugging')
    p.add_argument('-u',
                   '--user',
                   action='store',
                   dest='user',
                   default=def_user,
                   help='connect to websocket as user, default is: ' +
                   def_user)
    p.add_argument('-s',
                   '--secret',
                   action='store',
                   dest='password',
                   default=def_secret,
                   help='users "secret" password')
    p.add_argument('--debug',
                   action='store_true',
                   dest='debug',
                   default=False,
                   help='Autobahn layer debugging')
    p.add_argument(
        '-e',
        '--engine',
        action='store',
        dest='engine',
        default=def_engine,
        help=
        'if specified, a database engine will be attached. Note engine is rooted on --topic'
    )
    p.add_argument(
        "--endpoint",
        type=str,
        default="tcp:8080",
        help=
        'Twisted server endpoint descriptor, e.g. "tcp:8080" or "unix:/tmp/mywebsocket", default is "'
        + def_endpoint + '"')
    p.add_argument(
        '-d',
        '--dsn',
        action='store',
        dest='dsn',
        default=def_dsn,
        help='if specified the database in dsn will be connected and ready')
    p.add_argument(
        '-t',
        '--topic',
        action='store',
        dest='topic_base',
        default=def_topic_base,
        help=
        'if you specify --dsn then you will need a topic to root it on, the default '
        + def_topic_base + ' is fine.')

    args = p.parse_args()
    if args.verbose:
        log.startLogging(sys.stdout)

    ## we use an Autobahn utility to install the "best" available Twisted reactor
    ##
    from autobahn.twisted.choosereactor import install_reactor
    reactor = install_reactor()
    log.msg("Running on reactor {}".format(reactor))

    # database workers...
    userdb = UserDb(topic_base=args.topic_base + '.db', debug=args.verbose)
    sessiondb = SessionDb(topic_base=args.topic_base, debug=args.verbose)

    ## create a WAMP router factory
    ##
    component_config = types.ComponentConfig(realm=args.realm)
    xomponent_config = types.ComponentConfig(realm=args.realm)
    ai = {
        'auth_type': 'wampcra',
        'auth_user': args.user,
        'auth_password': args.password
    }

    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()
    authorization_session = AuthorizeSession(component_config,
                                             topic_base=args.topic_base +
                                             '.db',
                                             debug=args.verbose,
                                             db=sessiondb,
                                             router=AuthorizeRouter)
    router_factory.router = authorization_session.ret_func

    ## create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = MyRouterSession

    log.msg("session_factory.session")

    session_factory.userdb = userdb
    session_factory.sessiondb = sessiondb

    log.msg("userdb, sessiondb")

    sessiondb_component = SessionData(component_config,
                                      session_factory.sessiondb,
                                      topic_base=args.topic_base)
    session_factory.add(sessiondb_component)
    session_factory.add(authorization_session)

    log.msg("session_factory")

    db_session = DB(component_config,
                    engine=args.engine,
                    topic_base=args.topic_base + '.db',
                    dsn=args.dsn,
                    debug=args.verbose)
    session_factory.add(db_session)
    session_factory.userdb.set_session(db_session)
    session_factory.sessiondb.set_session(db_session)

    ## create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory
    transport_factory = WampWebSocketServerFactory(session_factory,
                                                   debug=args.debug)
    transport_factory.setProtocolOptions(failByDrop=False)

    ## start the server from an endpoint
    ##
    ## this address clash detection was a goody I got from stackoverflow:
    ## http://stackoverflow.com/questions/12007316/exiting-twisted-application-after-listenfailure
    server = serverFromString(reactor, args.endpoint)

    def listen():
        srv = server.listen(transport_factory)

        def ListenFailed(reason):
            log.msg("On Startup Listen Failed with {}".format(reason))
            reactor.stop()

        srv.addErrback(ListenFailed)

    def addsession():
        log.msg("here are three sessions {} {} {}".format(
            authorization_session, sessiondb_component, db_session))
        qv = {
            "sessiondb_component": sessiondb_component._session_id,
            "db_session": db_session._session_id,
            "authorization_session": authorization_session._session_id
        }
        session_factory.sessiondb.set_system_sessions(qv)
        session_factory.sessiondb.add(0, sessiondb_component._session_id,
                                      sessiondb_component)
        session_factory.sessiondb.add(0, db_session._session_id, db_session)
        session_factory.sessiondb.add(0, authorization_session._session_id,
                                      authorization_session)

    reactor.callWhenRunning(listen)
    reactor.callWhenRunning(addsession)

    # if we set this router to be mastered by another, then start communicating with it
    if args.xsocket is not None:
        xdb = Xomponent(config=xomponent_config,
                        authinfo=ai,
                        topic_base=args.topic_base,
                        debug=args.verbose,
                        command='session',
                        action='list',
                        action_args={})
        xdb.set_session(db_session)
        runner = ApplicationRunner(args.xsocket, args.realm)
        runner.run(lambda _: xdb, start_reactor=False)

    reactor.run()
Пример #10
0
class Node:
   """
   A Crossbar.io node is the running a controller process
   and one or multiple worker processes.

   A single Crossbar.io node runs exactly one instance of
   this class, hence this class can be considered a system
   singleton.
   """

   def __init__(self, reactor, options):
      """
      Ctor.

      :param reactor: Reactor to run on.
      :type reactor: obj
      :param options: Options from command line.
      :type options: obj
      """
      self.debug = False

      self.options = options
      ## the reactor under which we run
      self._reactor = reactor

      ## shortname for reactor to run (when given via explicit option) or None
      self._reactor_shortname = options.reactor

      ## node directory
      self._cbdir = options.cbdir

      ## the node's name (must be unique within the management realm)
      self._node_id = None

      ## the node's management realm
      self._realm = None

      ## node controller session (a singleton ApplicationSession embedded
      ## in the node's management router)
      self._controller = None



   def start(self):
      """
      Starts this node. This will start a node controller and then spawn new worker
      processes as needed.
      """
      ## for now, a node is always started from a local configuration
      ##
      configfile = os.path.join(self.options.cbdir, self.options.config)
      log.msg("Starting from local configuration '{}'".format(configfile))
      config = checkconfig.check_config_file(configfile, silence = True)

      self.start_from_config(config)



   def start_from_config(self, config):

      controller_config = config.get('controller', {})

      controller_options = controller_config.get('options', {})

      controller_title = controller_options.get('title', 'crossbar-controller')

      try:
         import setproctitle
      except ImportError:
         log.msg("Warning, could not set process title (setproctitle not installed)")
      else:
         setproctitle.setproctitle(controller_title)


      ## the node's name (must be unique within the management realm)
      if 'id' in controller_config:
         self._node_id = controller_config['id']
      else:
         self._node_id = socket.gethostname()

      ## the node's management realm
      self._realm = controller_config.get('realm', 'crossbar')


      ## the node controller singleton WAMP application session
      ##
      #session_config = ComponentConfig(realm = options.realm, extra = options)

      self._controller = NodeControllerSession(self)

      ## router and factory that creates router sessions
      ##
      self._router_factory = RouterFactory(
         options = wamp.types.RouterOptions(uri_check = wamp.types.RouterOptions.URI_CHECK_LOOSE),
         debug = False)
      self._router_session_factory = RouterSessionFactory(self._router_factory)

      ## add the node controller singleton session to the router
      ##
      self._router_session_factory.add(self._controller)

      ## Detect WAMPlets
      ##
      wamplets = self._controller._get_wamplets()
      if len(wamplets) > 0:
         log.msg("Detected {} WAMPlets in environment:".format(len(wamplets)))
         for wpl in wamplets:
            log.msg("WAMPlet {}.{}".format(wpl['dist'], wpl['name']))
      else:
         log.msg("No WAMPlets detected in enviroment.")


      self.run_node_config(config)



   def _start_from_local_config(self, configfile):
      """
      Start Crossbar.io node from local configuration file.
      """
      configfile = os.path.abspath(configfile)
      log.msg("Starting from local config file '{}'".format(configfile))

      try:
         config = controller.config.check_config_file(configfile, silence = True)
      except Exception as e:
         log.msg("Fatal: {}".format(e))
         sys.exit(1)
      else:
         self.run_node_config(config)



   @inlineCallbacks
   def run_node_config(self, config):
      try:
         yield self._run_node_config(config)
      except:
         traceback.print_exc()
         self._reactor.stop()



   @inlineCallbacks
   def _run_node_config(self, config):
      """
      Setup node according to config provided.
      """

      ## fake call details information when calling into
      ## remoted procedure locally
      ##
      call_details = CallDetails(caller = 0, authid = 'node')

      controller = config.get('controller', {})


      ## start Manhole in node controller
      ##
      if 'manhole' in controller:
         yield self._controller.start_manhole(controller['manhole'], details = call_details)


      ## start local transport for management router
      ##
      if 'transport' in controller:
         yield self._controller.start_management_transport(controller['transport'], details = call_details)


      ## startup all workers
      ##
      worker_no = 1

      for worker in config.get('workers', []):

         ## worker ID, type and logname
         ##
         if 'id' in worker:
            worker_id = worker.pop('id')
         else:
            worker_id = 'worker{}'.format(worker_no)
            worker_no += 1

         worker_type = worker['type']
         worker_options = worker.get('options', {})

         if worker_type == 'router':
            worker_logname = "Router '{}'".format(worker_id)

         elif worker_type == 'container':
            worker_logname = "Container '{}'".format(worker_id)

         elif worker_type == 'guest':
            worker_logname = "Guest '{}'".format(worker_id)

         else:
            raise Exception("logic error")


         ## router/container
         ##
         if worker_type in ['router', 'container']:

            ## start a new native worker process ..
            ##
            if worker_type == 'router':
               yield self._controller.start_router(worker_id, worker_options, details = call_details)

            elif worker_type == 'container':
               yield self._controller.start_container(worker_id, worker_options, details = call_details)

            else:
               raise Exception("logic error")


            ## setup native worker generic stuff
            ##
            if 'pythonpath' in worker_options:
               added_paths = yield self._controller.call('crossbar.node.{}.worker.{}.add_pythonpath'.format(self._node_id, worker_id), worker_options['pythonpath'])
               if self.debug:
                  log.msg("{}: PYTHONPATH extended for {}".format(worker_logname, added_paths))
               else:
                  log.msg("{}: PYTHONPATH extended".format(worker_logname))

            if 'cpu_affinity' in worker_options:
               new_affinity = yield self._controller.call('crossbar.node.{}.worker.{}.set_cpu_affinity'.format(self._node_id, worker_id), worker_options['cpu_affinity'])
               log.msg("{}: CPU affinity set to {}".format(worker_logname, new_affinity))

            if 'manhole' in worker:
               yield self._controller.call('crossbar.node.{}.worker.{}.start_manhole'.format(self._node_id, worker_id), worker['manhole'])
               log.msg("{}: manhole started".format(worker_logname))


            ## setup router worker
            ##
            if worker_type == 'router':

               ## start realms on router
               ##
               realm_no = 1

               for realm in worker.get('realms', []):

                  if 'id' in realm:
                     realm_id = realm.pop('id')
                  else:
                     realm_id = 'realm{}'.format(realm_no)
                     realm_no += 1

                  ## extract schema information from WAMP-flavored Markdown
                  ##
                  schemas = None
                  if 'schemas' in realm:
                     schemas = {}
                     schema_pat = re.compile(r"```javascript(.*?)```", re.DOTALL)
                     cnt_files = 0
                     cnt_decls = 0
                     for schema_file in realm.pop('schemas'):
                        schema_file = os.path.join(self.options.cbdir, schema_file)
                        log.msg("{}: processing WAMP-flavored Markdown file {} for WAMP schema declarations".format(worker_logname, schema_file))
                        with open(schema_file, 'r') as f:
                           cnt_files += 1
                           for d in schema_pat.findall(f.read()):
                              try:
                                 o = json.loads(d)
                                 if type(o) == dict and '$schema' in o and o['$schema'] == u'http://wamp.ws/schema#':
                                    uri = o['uri']
                                    if not uri in schemas:
                                       schemas[uri] = {}
                                    schemas[uri].update(o)
                                    cnt_decls += 1
                              except Exception as e:
                                 log.msg("{}: WARNING - failed to process declaration in {} - {}".format(worker_logname, schema_file, e))
                     log.msg("{}: processed {} files extracting {} schema declarations and {} URIs".format(worker_logname, cnt_files, cnt_decls, len(schemas)))

                  yield self._controller.call('crossbar.node.{}.worker.{}.start_router_realm'.format(self._node_id, worker_id), realm_id, realm, schemas)
                  log.msg("{}: realm '{}' started".format(worker_logname, realm_id))


                  ## add roles to realm
                  ##
                  role_no = 1
                  for role in realm.get('roles', []):
                     if 'id' in role:
                        role_id = role.pop('id')
                     else:
                        role_id = 'role{}'.format(role_no)
                        role_no += 1

                     yield self._controller.call('crossbar.node.{}.worker.{}.start_router_realm_role'.format(self._node_id, worker_id), realm_id, role_id, role)
                     log.msg("{}: role '{}' started on realm '{}'".format(worker_logname, role_id, realm_id))


               ## start components to run embedded in the router
               ##
               component_no = 1

               for component in worker.get('components', []):

                  if 'id' in component:
                     component_id = component.pop('id')
                  else:
                     component_id = 'component{}'.format(component_no)
                     component_no += 1

                  yield self._controller.call('crossbar.node.{}.worker.{}.start_router_component'.format(self._node_id, worker_id), component_id, component)
                  log.msg("{}: component '{}' started".format(worker_logname, component_id))


               ## start transports on router
               ##
               transport_no = 1

               for transport in worker['transports']:

                  if 'id' in transport:
                     transport_id = transport.pop('id')
                  else:
                     transport_id = 'transport{}'.format(transport_no)
                     transport_no += 1

                  yield self._controller.call('crossbar.node.{}.worker.{}.start_router_transport'.format(self._node_id, worker_id), transport_id, transport)
                  log.msg("{}: transport '{}' started".format(worker_logname, transport_id))


            ## setup container worker
            ##
            elif worker_type == 'container':

               component_no = 1

               for component in worker.get('components', []):

                  if 'id' in component:
                     component_id = component.pop('id')
                  else:
                     component_id = 'component{}'.format(component_no)
                     component_no += 1

                  yield self._controller.call('crossbar.node.{}.worker.{}.start_container_component'.format(self._node_id, worker_id), component_id, component)
                  log.msg("{}: component '{}' started".format(worker_logname, component_id))

            else:
               raise Exception("logic error")


         elif worker_type == 'guest':

            ## start guest worker
            ##
            yield self._controller.start_guest(worker_id, worker, details = call_details)
            log.msg("{}: started".format(worker_logname))

         else:
            raise Exception("logic error")
Пример #11
0
   reactor = install_reactor()
   print("Running on reactor {}".format(reactor))

   ## create a WAMP router factory
   ##
   from autobahn.wamp.router import RouterFactory
   router_factory = RouterFactory()


   ## create a WAMP router session factory
   ##
   from autobahn.twisted.wamp import RouterSessionFactory
   session_factory = RouterSessionFactory(router_factory)
   
   ## [ ... ... ]
   session_factory.add(PubSubComponent())

   ## create a WAMP-over-WebSocket transport server factory
   ##
   from autobahn.twisted.websocket import WampWebSocketServerFactory
   
   # NB: args.wsurl MUST NOT INCLUDE a path; hence it is not really a URL; all it supports is protocol (which must be ws or wss), hostname, and port. anything after that gives a mysterious 
   #   File "/usr/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 3383, in setSessionParameters
   # raise Exception("path specified for server WebSocket URL")
   transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug = True)
   transport_factory.setProtocolOptions(failByDrop = False)

   ## start the WebSocket server from an endpoint
   ##
   server = serverFromString(reactor, args.websocket)
   server.listen(transport_factory)
Пример #12
0
        yield self.register(Sketch_Stop, u"allofw.sketch.stop")
        yield self.register(Sketch_List, u"allofw.sketch.list")
        yield self.register(Sketch_GetCode, u"allofw.sketch.get_code")

        yield self.register(Project_List, u"allofw.project.list")
        yield self.register(Project_Delete, u"allofw.project.delete")
        yield self.register(Project_UploadFile, u"allofw.project.upload_file")
        yield self.register(Project_RenameFile, u"allofw.project.rename_file")
        yield self.register(Project_ListFiles, u"allofw.project.list_files")
        yield self.register(Project_LoadProject,
                            u"allofw.project.load_project")
        yield self.register(Project_SaveProject,
                            u"allofw.project.save_project")


root = File("static")
session_factory = RouterSessionFactory(RouterFactory())
component_config = types.ComponentConfig(realm="anonymous")
session_factory.add(AllofwServer(component_config))
factory = WampWebSocketServerFactory(session_factory)
factory.startFactory()
resource = WebSocketResource(factory)
root.putChild("ws", resource)

site = Site(root)
reactor.listenTCP(int(config['webserver']['port']),
                  site,
                  interface=config['webserver']['listen'])

reactor.run()
Пример #13
0
class Node:
    """
   A Crossbar.io node is the running a controller process
   and one or multiple worker processes.

   A single Crossbar.io node runs exactly one instance of
   this class, hence this class can be considered a system
   singleton.
   """
    def __init__(self, reactor, options):
        """
      Ctor.

      :param reactor: Reactor to run on.
      :type reactor: obj
      :param options: Options from command line.
      :type options: obj
      """
        self.debug = False

        self.options = options
        ## the reactor under which we run
        self._reactor = reactor

        ## shortname for reactor to run (when given via explicit option) or None
        self._reactor_shortname = options.reactor

        ## node directory
        self._cbdir = options.cbdir

        ## the node's name (must be unique within the management realm)
        self._node_id = None

        ## the node's management realm
        self._realm = None

        ## node controller session (a singleton ApplicationSession embedded
        ## in the node's management router)
        self._controller = None

    def start(self):
        """
      Starts this node. This will start a node controller and then spawn new worker
      processes as needed.
      """
        ## for now, a node is always started from a local configuration
        ##
        configfile = os.path.join(self.options.cbdir, self.options.config)
        log.msg("Starting from local configuration '{}'".format(configfile))
        config = checkconfig.check_config_file(configfile, silence=True)

        self.start_from_config(config)

    def start_from_config(self, config):

        controller_config = config.get('controller', {})

        controller_options = controller_config.get('options', {})

        controller_title = controller_options.get('title',
                                                  'crossbar-controller')

        try:
            import setproctitle
        except ImportError:
            log.msg(
                "Warning, could not set process title (setproctitle not installed)"
            )
        else:
            setproctitle.setproctitle(controller_title)

        ## the node's name (must be unique within the management realm)
        if 'id' in controller_config:
            self._node_id = controller_config['id']
        else:
            self._node_id = socket.gethostname()

        ## the node's management realm
        self._realm = controller_config.get('realm', 'crossbar')

        ## the node controller singleton WAMP application session
        ##
        #session_config = ComponentConfig(realm = options.realm, extra = options)

        self._controller = NodeControllerSession(self)

        ## router and factory that creates router sessions
        ##
        self._router_factory = RouterFactory(options=wamp.types.RouterOptions(
            uri_check=wamp.types.RouterOptions.URI_CHECK_LOOSE),
                                             debug=False)
        self._router_session_factory = RouterSessionFactory(
            self._router_factory)

        ## add the node controller singleton session to the router
        ##
        self._router_session_factory.add(self._controller)

        ## Detect WAMPlets
        ##
        wamplets = self._controller._get_wamplets()
        if len(wamplets) > 0:
            log.msg("Detected {} WAMPlets in environment:".format(
                len(wamplets)))
            for wpl in wamplets:
                log.msg("WAMPlet {}.{}".format(wpl['dist'], wpl['name']))
        else:
            log.msg("No WAMPlets detected in enviroment.")

        self.run_node_config(config)

    def _start_from_local_config(self, configfile):
        """
      Start Crossbar.io node from local configuration file.
      """
        configfile = os.path.abspath(configfile)
        log.msg("Starting from local config file '{}'".format(configfile))

        try:
            config = controller.config.check_config_file(configfile,
                                                         silence=True)
        except Exception as e:
            log.msg("Fatal: {}".format(e))
            sys.exit(1)
        else:
            self.run_node_config(config)

    @inlineCallbacks
    def run_node_config(self, config):
        try:
            yield self._run_node_config(config)
        except:
            traceback.print_exc()
            self._reactor.stop()

    @inlineCallbacks
    def _run_node_config(self, config):
        """
      Setup node according to config provided.
      """

        ## fake call details information when calling into
        ## remoted procedure locally
        ##
        call_details = CallDetails(caller=0, authid='node')

        controller = config.get('controller', {})

        ## start Manhole in node controller
        ##
        if 'manhole' in controller:
            yield self._controller.start_manhole(controller['manhole'],
                                                 details=call_details)

        ## start local transport for management router
        ##
        if 'transport' in controller:
            yield self._controller.start_management_transport(
                controller['transport'], details=call_details)

        ## startup all workers
        ##
        worker_no = 1

        for worker in config.get('workers', []):

            ## worker ID, type and logname
            ##
            if 'id' in worker:
                worker_id = worker.pop('id')
            else:
                worker_id = 'worker{}'.format(worker_no)
                worker_no += 1

            worker_type = worker['type']
            worker_options = worker.get('options', {})

            if worker_type == 'router':
                worker_logname = "Router '{}'".format(worker_id)

            elif worker_type == 'container':
                worker_logname = "Container '{}'".format(worker_id)

            elif worker_type == 'guest':
                worker_logname = "Guest '{}'".format(worker_id)

            else:
                raise Exception("logic error")

            ## router/container
            ##
            if worker_type in ['router', 'container']:

                ## start a new native worker process ..
                ##
                if worker_type == 'router':
                    yield self._controller.start_router(worker_id,
                                                        worker_options,
                                                        details=call_details)

                elif worker_type == 'container':
                    yield self._controller.start_container(
                        worker_id, worker_options, details=call_details)

                else:
                    raise Exception("logic error")

                ## setup native worker generic stuff
                ##
                if 'pythonpath' in worker_options:
                    added_paths = yield self._controller.call(
                        'crossbar.node.{}.worker.{}.add_pythonpath'.format(
                            self._node_id, worker_id),
                        worker_options['pythonpath'])
                    if self.debug:
                        log.msg("{}: PYTHONPATH extended for {}".format(
                            worker_logname, added_paths))
                    else:
                        log.msg(
                            "{}: PYTHONPATH extended".format(worker_logname))

                if 'cpu_affinity' in worker_options:
                    new_affinity = yield self._controller.call(
                        'crossbar.node.{}.worker.{}.set_cpu_affinity'.format(
                            self._node_id, worker_id),
                        worker_options['cpu_affinity'])
                    log.msg("{}: CPU affinity set to {}".format(
                        worker_logname, new_affinity))

                if 'manhole' in worker:
                    yield self._controller.call(
                        'crossbar.node.{}.worker.{}.start_manhole'.format(
                            self._node_id, worker_id), worker['manhole'])
                    log.msg("{}: manhole started".format(worker_logname))

                ## setup router worker
                ##
                if worker_type == 'router':

                    ## start realms on router
                    ##
                    realm_no = 1

                    for realm in worker.get('realms', []):

                        if 'id' in realm:
                            realm_id = realm.pop('id')
                        else:
                            realm_id = 'realm{}'.format(realm_no)
                            realm_no += 1

                        ## extract schema information from WAMP-flavored Markdown
                        ##
                        schemas = None
                        if 'schemas' in realm:
                            schemas = {}
                            schema_pat = re.compile(r"```javascript(.*?)```",
                                                    re.DOTALL)
                            cnt_files = 0
                            cnt_decls = 0
                            for schema_file in realm.pop('schemas'):
                                schema_file = os.path.join(
                                    self.options.cbdir, schema_file)
                                log.msg(
                                    "{}: processing WAMP-flavored Markdown file {} for WAMP schema declarations"
                                    .format(worker_logname, schema_file))
                                with open(schema_file, 'r') as f:
                                    cnt_files += 1
                                    for d in schema_pat.findall(f.read()):
                                        try:
                                            o = json.loads(d)
                                            if type(
                                                    o
                                            ) == dict and '$schema' in o and o[
                                                    '$schema'] == u'http://wamp.ws/schema#':
                                                uri = o['uri']
                                                if not uri in schemas:
                                                    schemas[uri] = {}
                                                schemas[uri].update(o)
                                                cnt_decls += 1
                                        except Exception as e:
                                            log.msg(
                                                "{}: WARNING - failed to process declaration in {} - {}"
                                                .format(
                                                    worker_logname,
                                                    schema_file, e))
                            log.msg(
                                "{}: processed {} files extracting {} schema declarations and {} URIs"
                                .format(worker_logname, cnt_files, cnt_decls,
                                        len(schemas)))

                        yield self._controller.call(
                            'crossbar.node.{}.worker.{}.start_router_realm'.
                            format(self._node_id,
                                   worker_id), realm_id, realm, schemas)
                        log.msg("{}: realm '{}' started".format(
                            worker_logname, realm_id))

                        ## add roles to realm
                        ##
                        role_no = 1
                        for role in realm.get('roles', []):
                            if 'id' in role:
                                role_id = role.pop('id')
                            else:
                                role_id = 'role{}'.format(role_no)
                                role_no += 1

                            yield self._controller.call(
                                'crossbar.node.{}.worker.{}.start_router_realm_role'
                                .format(self._node_id,
                                        worker_id), realm_id, role_id, role)
                            log.msg(
                                "{}: role '{}' started on realm '{}'".format(
                                    worker_logname, role_id, realm_id))

                    ## start components to run embedded in the router
                    ##
                    component_no = 1

                    for component in worker.get('components', []):

                        if 'id' in component:
                            component_id = component.pop('id')
                        else:
                            component_id = 'component{}'.format(component_no)
                            component_no += 1

                        yield self._controller.call(
                            'crossbar.node.{}.worker.{}.start_router_component'
                            .format(self._node_id,
                                    worker_id), component_id, component)
                        log.msg("{}: component '{}' started".format(
                            worker_logname, component_id))

                    ## start transports on router
                    ##
                    transport_no = 1

                    for transport in worker['transports']:

                        if 'id' in transport:
                            transport_id = transport.pop('id')
                        else:
                            transport_id = 'transport{}'.format(transport_no)
                            transport_no += 1

                        yield self._controller.call(
                            'crossbar.node.{}.worker.{}.start_router_transport'
                            .format(self._node_id,
                                    worker_id), transport_id, transport)
                        log.msg("{}: transport '{}' started".format(
                            worker_logname, transport_id))

                ## setup container worker
                ##
                elif worker_type == 'container':

                    component_no = 1

                    for component in worker.get('components', []):

                        if 'id' in component:
                            component_id = component.pop('id')
                        else:
                            component_id = 'component{}'.format(component_no)
                            component_no += 1

                        yield self._controller.call(
                            'crossbar.node.{}.worker.{}.start_container_component'
                            .format(self._node_id,
                                    worker_id), component_id, component)
                        log.msg("{}: component '{}' started".format(
                            worker_logname, component_id))

                else:
                    raise Exception("logic error")

            elif worker_type == 'guest':

                ## start guest worker
                ##
                yield self._controller.start_guest(worker_id,
                                                   worker,
                                                   details=call_details)
                log.msg("{}: started".format(worker_logname))

            else:
                raise Exception("logic error")
Пример #14
0
    from autobahn.twisted.choosereactor import install_reactor
    reactor = install_reactor()
    if args.debug:
        print("Running on reactor {}".format(reactor))

    # create a WAMP router factory
    ##
    from autobahn.wamp.router import RouterFactory
    router_factory = RouterFactory()

    # create a WAMP router session factory
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = WebServiceLoginRouterSession

    session_factory.add(TimeService(args.realm))

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = WampWebSocketServerFactory(
        session_factory, args.wsurl, debug_wamp=args.debug)
    #transport_factory.protocol = ServerProtocol

    transport_factory.setProtocolOptions(failByDrop=False)

    from twisted.web.server import Site
    from twisted.web.static import File
    from autobahn.twisted.resource import WebSocketResource

    # we serve static files under "/" ..
    root = File(".")
Пример #15
0
class TestEmbeddedSessions(unittest.TestCase):
    """
   Test cases for application session running embedded in router.
   """
    def setUp(self):
        """
      Setup router and router session factories.
      """
        if USE_ASYNCIO:
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self.loop)

        self.router_factory = RouterFactory()
        self.session_factory = RouterSessionFactory(self.router_factory)

    def tearDown(self):
        if USE_ASYNCIO:
            self.loop.close()
            asyncio.set_event_loop(None)
            gc.collect()

    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")

    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")
Пример #16
0
                                    debug = debug,
                                    debugCodePaths = True)
   ctl_endpoint.protocol = CtlProtocol
   

   from autobahn.wamp.router import RouterFactory
   router_factory = RouterFactory()

     
   ## create a WAMP router session factory
   ##
   from autobahn.twisted.wamp import RouterSessionFactory
   session_factory = RouterSessionFactory(router_factory)
   
   ## [ ... ... ]
   session_factory.add(ModelServer())
   
   ## create a WAMP-over-WebSocket transport server factory
   ##
   from autobahn.twisted.websocket import WampWebSocketServerFactory
   wamp_factory = WampWebSocketServerFactory(session_factory, "ws://localhost:8080", debug = True)
   wamp_factory.setProtocolOptions(failByDrop = False)
   
   
   webroot = pathjoin(PROJECT_ROOT,"src","frontend")
   assets = pathjoin(PROJECT_ROOT,"assets")
   if debug:
     print "putting", webroot,"at root"
     print "putting", assets,"at assets"
   
   
Пример #17
0
   reactor = install_reactor()
   if args.debug:
      print("Running on reactor {}".format(reactor))


   ## create a WAMP router factory
   ##
   from autobahn.wamp.router import RouterFactory
   router_factory = RouterFactory()


   ## create a WAMP router session factory
   ##
   from autobahn.twisted.wamp import RouterSessionFactory
   session_factory = RouterSessionFactory(router_factory)
   session_factory.add(TestService())


   from autobahn.wamp.serializer import MsgPackSerializer
   serializer = MsgPackSerializer()

   from autobahn.twisted.rawsocket import WampRawSocketClientFactory, WampRawSocketClientProtocol
   transport_factory = WampRawSocketClientFactory(session_factory, serializer, debug = args.debug)

   class WorkerClientProtocol(WampRawSocketClientProtocol):

      def connectionMade(self):
         WampRawSocketClientProtocol.connectionMade(self)


      def connectionLost(self, reason):
Пример #18
0
def start_webserver(options,
                    protocol=vtk_wamp.ServerProtocol,
                    disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.host : the interface for the web-server to listen on
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    contextFactory = None

    use_SSL = False
    if options.sslKey and options.sslCert:
        use_SSL = True
        wsProtocol = "wss"
        from twisted.internet import ssl
        contextFactory = ssl.DefaultOpenSSLContextFactory(
            options.sslKey, options.sslCert)
    else:
        wsProtocol = "ws"

    # Create WAMP router factory
    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()

    # create a user DB
    authdb = vtk_wamp.AuthDb()

    # create a WAMP router session factory
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = vtk_wamp.CustomWampCraRouterSession
    session_factory.authdb = authdb

    # Create ApplicationSession and register protocols
    appSession = protocol(types.ComponentConfig(realm="vtkweb"))
    appSession.setAuthDB(authdb)
    session_factory.add(appSession)

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = vtk_wamp.TimeoutWampWebSocketServerFactory(session_factory, \
           url        = "%s://%s:%d" % (wsProtocol, options.host, options.port),    \
           debug      = options.debug,                                              \
           debug_wamp = options.debug,                                              \
           timeout    = options.timeout )

    root = Resource()

    # Do we serve static content or just websocket ?
    if len(options.content) > 0:
        # Static HTTP + WebSocket
        root = File(options.content)

    # Handle possibly complex ws endpoint
    if not options.nows:
        wsResource = WebSocketResource(transport_factory)
        handle_complex_resource_path(options.ws, root, wsResource)

    # Handle possibly complex lp endpoint
    if not options.nolp:
        lpResource = WampLongPollResource(session_factory)
        handle_complex_resource_path(options.lp, root, lpResource)

    if options.uploadPath != None:
        from upload import UploadPage
        uploadResource = UploadPage(options.uploadPath)
        root.putChild("upload", uploadResource)

    site = Site(root)

    if use_SSL:
        reactor.listenSSL(options.port, site, contextFactory)
    else:
        reactor.listenTCP(options.port, site)

    # Work around to force the output buffer to be flushed
    # This allow the process launcher to parse the output and
    # wait for "Start factory" to know that the WebServer
    # is running.
    if options.forceFlush:
        for i in range(200):
            log.msg("+" * 80, logLevel=logging.CRITICAL)

    # Initialize testing: checks if we're doing a test and sets it up
    testing.initialize(options, reactor, stop_webserver)

    # Start the reactor
    if options.nosignalhandlers:
        reactor.run(installSignalHandlers=0)
    else:
        reactor.run()

    # Give the testing module a chance to finalize, if necessary
    testing.finalize()
Пример #19
0
class Node:
   """
   A Crossbar.io node is the running a controller process
   and one or multiple worker processes.

   A single Crossbar.io node runs exactly one instance of
   this class, hence this class can be considered a system
   singleton.
   """

   def __init__(self, reactor, cbdir, debug = False):
      """
      Ctor.

      :param reactor: Reactor to run on.
      :type reactor: obj
      :param cbdir: Crossbar.io node directory to run from.
      :type cbdir: str
      """
      self.debug = debug

      self._reactor = reactor
      self._cbdir = cbdir
      self._worker_processes = {}

      ## node name: FIXME
      self._node_name = "{}-{}".format(socket.getfqdn(), os.getpid())
      self._node_name.replace('-', '_')
      self._node_name = '918234'

      ## node management
      self._management_url = "ws://127.0.0.1:7000"
      #self._management_url = "wss://cloud.crossbar.io"
      self._management_realm = "crossbar.cloud.aliceblue"

      ## load Crossbar.io node configuration
      ##
      cf = os.path.join(self._cbdir, 'config.json')
      with open(cf, 'rb') as infile:
         self._config = json.load(infile)


   def start(self):
      """
      Starts this node. This will start a node controller
      and then spawn new worker processes as needed.

      The node controller will watch spawned processes,
      communicate via stdio with the worker, and start
      and restart the worker processes as needed.
      """
      ## the node controller singleton WAMP application session
      ##
      self._node_controller_session = NodeControllerSession(self)

      ## router and factory that creates router sessions
      ##
      self._router_factory = RouterFactory()
      self._router_session_factory = RouterSessionFactory(self._router_factory)

      ## add the node controller singleton session to the router
      ##
      self._router_session_factory.add(self._node_controller_session)

      if True:
         ## create a WAMP-over-WebSocket transport server factory
         ##
         from autobahn.twisted.websocket import WampWebSocketServerFactory
         from twisted.internet.endpoints import serverFromString

         self._router_server_transport_factory = WampWebSocketServerFactory(self._router_session_factory, "ws://localhost:9000", debug = False)
         self._router_server_transport_factory.setProtocolOptions(failByDrop = False)


         ## start the WebSocket server from an endpoint
         ##
         self._router_server = serverFromString(self._reactor, "tcp:9000")
         self._router_server.listen(self._router_server_transport_factory)

      ## factory that creates router session transports. these are for clients
      ## that talk WAMP-WebSocket over pipes with spawned worker processes and
      ## for any uplink session to a management service
      ##
      self._router_client_transport_factory = WampWebSocketClientFactory(self._router_session_factory, "ws://localhost", debug = False)
      self._router_client_transport_factory.setProtocolOptions(failByDrop = False)

      if False:
         management_session_factory = ApplicationSessionFactory()
         management_session_factory.session = NodeManagementSession
         management_session_factory.node_controller_session = node_controller_session
         management_transport_factory = WampWebSocketClientFactory(management_session_factory, "ws://127.0.0.1:7000")
         management_transport_factory.setProtocolOptions(failByDrop = False)
         management_client = clientFromString(self._reactor, "tcp:127.0.0.1:7000")
         management_client.connect(management_transport_factory)


      ## startup the node from configuration file
      ##
      self._node_controller_session.run_node_config(self._config)
Пример #20
0
        #client_components = [Case2_Backend]
        #client_components = [Case1_Backend, Case1_Frontend]
        client_components = [Case2_Backend, Case2_Frontend]

    log = io.open(config.extra['caselog'], 'w')
    config.log = log
    config.components = []

    config.all_done = []

    for C in embedded_components:
        one_done = Deferred()
        config.all_done.append(one_done)
        c = C(config, one_done)
        config.components.append(c)
        session_factory.add(c)

    if args.transport == "websocket":

        ## create a WAMP-over-WebSocket transport server factory
        ##
        from autobahn.twisted.websocket import WampWebSocketServerFactory
        transport_factory = WampWebSocketServerFactory(session_factory,
                                                       debug_wamp=args.debug)
        transport_factory.setProtocolOptions(failByDrop=False)

    elif args.transport in ['rawsocket-json', 'rawsocket-msgpack']:

        ## create a WAMP-over-RawSocket transport server factory
        ##
        if args.transport == 'rawsocket-msgpack':
Пример #21
0
            yield sleep(1)


if __name__ == '__main__':

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

    ## 1) create a WAMP router factory
    router_factory = RouterFactory()

    ## 2) create a WAMP router session factory
    session_factory = RouterSessionFactory(router_factory)

    ## 3) Optionally, add embedded WAMP application sessions to the router
    session_factory.add(MyBackendComponent())

    ## 4) create a WAMP-over-WebSocket transport server factory
    transport_factory1 = WampWebSocketServerFactory(session_factory,
                                                    debug=False)

    ## 5) start the server from a Twisted endpoint
    server1 = serverFromString(reactor, "tcp:8080")
    server1.listen(transport_factory1)

    ## 6) create a WAMP-over-RawSocket-MsgPack transport server factory
    serializer = MsgPackSerializer()
    serializer._serializer.ENABLE_V5 = False
    transport_factory2 = WampRawSocketServerFactory(session_factory,
                                                    serializer,
                                                    debug=True)
Пример #22
0
    from autobahn.twisted.choosereactor import install_reactor
    reactor = install_reactor()
    if args.debug:
        print("Running on reactor {}".format(reactor))

    # create a WAMP router factory
    ##
    from autobahn.wamp.router import RouterFactory
    router_factory = RouterFactory()

    # create a WAMP router session factory
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = WebServiceLoginRouterSession

    session_factory.add(TimeService(args.realm))

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = WampWebSocketServerFactory(session_factory,
                                                   args.wsurl,
                                                   debug_wamp=args.debug)
    #transport_factory.protocol = ServerProtocol

    transport_factory.setProtocolOptions(failByDrop=False)

    from twisted.web.server import Site
    from twisted.web.static import File
    from autobahn.twisted.resource import WebSocketResource

    # we serve static files under "/" ..
    root = File(".")
Пример #23
0
def start_webserver(options, protocol=vtk_wamp.ServerProtocol, disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.host : the interface for the web-server to listen on
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    contextFactory = None

    use_SSL = False
    if options.sslKey and options.sslCert:
      use_SSL = True
      wsProtocol = "wss"
      from twisted.internet import ssl
      contextFactory = ssl.DefaultOpenSSLContextFactory(options.sslKey, options.sslCert)
    else:
      wsProtocol = "ws"

    # Create WAMP router factory
    from autobahn.wamp.router import RouterFactory
    router_factory = RouterFactory()

    # create a WAMP router session factory
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)

    # Register protocol
    session_factory.add(protocol())

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = vtk_wamp.TimeoutWampWebSocketServerFactory(session_factory, \
           url        = "%s://%s:%d" % (wsProtocol, options.host, options.port),    \
           debug      = options.debug,                                              \
           debug_wamp = options.debug,                                              \
           timeout    = options.timeout )

    # Do we serve static content or just websocket ?
    if len(options.content) == 0:
        # Only WebSocket
        listenWS(transport_factory, contextFactory, options.timeout)
    else:
        # Static HTTP + WebSocket
        wsResource = WebSocketResource(transport_factory)

        root = File(options.content)
        root.putChild("ws", wsResource)

        if options.uploadPath != None :
            from upload import UploadPage
            uploadResource = UploadPage(options.uploadPath)
            root.putChild("upload", uploadResource)

        site = Site(root)

        if use_SSL:
          reactor.listenSSL(options.port, site, contextFactory)
        else:
          reactor.listenTCP(options.port, site)

    # Work around to force the output buffer to be flushed
    # This allow the process launcher to parse the output and
    # wait for "Start factory" to know that the WebServer
    # is running.
    if options.forceFlush :
        for i in range(200):
            log.msg("+"*80, logLevel=logging.CRITICAL)

    # Give test client a chance to initialize a thread for itself
    # testing.initialize(opts=options)

    # Initialize testing: checks if we're doing a test and sets it up
    testing.initialize(options, reactor)

    # Start the reactor
    if options.nosignalhandlers:
        reactor.run(installSignalHandlers=0)
    else:
        reactor.run()

    # Give the testing module a chance to finalize, if necessary
    testing.finalize()
Пример #24
0
               secret=u"secret1",
               salt=u"salt123")
    userdb.add(authid=u"joe", authrole=u"user", secret=u"secret2")

    # create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = MyRouterSession
    session_factory.userdb = userdb

    # start an embedded application component ..
    ##
    component_config = types.ComponentConfig(realm=u"realm1")
    component_session = TimeService(component_config)
    session_factory.add(component_session)

    # create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory
    transport_factory = WampWebSocketServerFactory(session_factory,
                                                   args.wsurl,
                                                   debug=False,
                                                   debug_wamp=args.debug)
    transport_factory.setProtocolOptions(failByDrop=False)

    from twisted.web.server import Site
    from twisted.web.static import File
    from autobahn.twisted.resource import WebSocketResource

    # we serve static files under "/" ..
Пример #25
0
def run():
    import sys, argparse
    from twisted.python import log
    from twisted.internet.endpoints import serverFromString

    ## parse command line arguments
    ##

    def_wsocket = 'ws://127.0.0.1:8080/ws'
    def_realm = 'realm1'
    def_topic_base = 'sys'
    def_dsn = 'dbname=autobahn host=localhost user=autouser'
    def_endpoint='tcp:8080'
    def_engine = 'PG9_4'

    p = argparse.ArgumentParser(description="basicrouter example with database")

    p.add_argument('-w', '--websocket', action='store', dest='wsocket', default=def_wsocket,
                        help='web socket '+def_wsocket)
    p.add_argument('-r', '--realm', action='store', dest='realm', default=def_realm,
                        help='connect to websocket using "realm", default '+def_realm)
    p.add_argument('-v', '--verbose', action='store_true', dest='verbose',
            default=False, help='Verbose logging for debugging')
    p.add_argument('--debug', action='store_true', dest='debug',
            default=False, help='Autobahn layer debugging')
    p.add_argument('-e', '--engine', action='store', dest='engine', default=def_engine,
                        help='if specified, a database engine will be attached. Note engine is rooted on --topic')
    p.add_argument("--endpoint", type = str, default = "tcp:8080",
          help = 'Twisted server endpoint descriptor, e.g. "tcp:8080" or "unix:/tmp/mywebsocket", default is "' + def_endpoint + '"')
    p.add_argument('-d', '--dsn', action='store', dest='dsn', default=def_dsn,
                        help='if specified the database in dsn will be connected and ready')
    p.add_argument('-t', '--topic', action='store', dest='topic_base', default=def_topic_base,
                        help='if you specify --dsn then you will need a topic to root it on, the default ' + def_topic_base + ' is fine.')

    args = p.parse_args()
    if args.verbose:
        log.startLogging(sys.stdout)

    ## we use an Autobahn utility to install the "best" available Twisted reactor
    ##
    from autobahn.twisted.choosereactor import install_reactor
    reactor = install_reactor()
    log.msg("Running on reactor {}".format(reactor))

    # database workers...
    userdb = UserDb(topic_base=args.topic_base+'.db',debug=args.verbose)
    sessiondb = SessionDb(topic_base=args.topic_base,debug=args.verbose)

    ## create a WAMP router factory
    ##
    component_config = types.ComponentConfig(realm = args.realm)

    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()
    authorization_session = AuthorizeSession(component_config,
        topic_base=args.topic_base+'.db',debug=args.verbose,db=sessiondb,router=AuthorizeRouter)
    router_factory.router = authorization_session.ret_func

    ## create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = MyRouterSession

    log.msg("session_factory.session")

    session_factory.userdb = userdb
    session_factory.sessiondb = sessiondb

    log.msg("userdb, sessiondb")

    sessiondb_component = SessionData(component_config,session_factory.sessiondb,
        topic_base=args.topic_base)
    session_factory.add(sessiondb_component)
    session_factory.add(authorization_session)

    log.msg("session_factory")

    db_session = DB(component_config, engine=args.engine,
        topic_base=args.topic_base+'.db', dsn=args.dsn, debug=args.verbose)
    session_factory.add(db_session)
    session_factory.userdb.set_session(db_session)
    session_factory.sessiondb.set_session(db_session)

    ## create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory
    transport_factory = WampWebSocketServerFactory(session_factory, debug = args.debug)
    transport_factory.setProtocolOptions(failByDrop = False)


    ## start the server from an endpoint
    ##
    ## this address clash detection was a goody I got from stackoverflow:
    ## http://stackoverflow.com/questions/12007316/exiting-twisted-application-after-listenfailure
    server = serverFromString(reactor, args.endpoint)
    def listen():
        srv = server.listen(transport_factory)
        def ListenFailed(reason):
            log.msg("On Startup Listen Failed with {}".format(reason))
            reactor.stop()
        srv.addErrback(ListenFailed)

    def addsession():
        log.msg("here are three sessions {} {} {}".format(authorization_session, sessiondb_component, db_session))
        qv = {
            "sessiondb_component":sessiondb_component._session_id,
            "db_session":db_session._session_id,
            "authorization_session":authorization_session._session_id
        }
        session_factory.sessiondb.set_system_sessions(qv)
        session_factory.sessiondb.add(0, sessiondb_component._session_id, sessiondb_component)
        session_factory.sessiondb.add(0, db_session._session_id, db_session)
        session_factory.sessiondb.add(0, authorization_session._session_id, authorization_session)

    reactor.callWhenRunning(listen)
    reactor.callWhenRunning(addsession)
    reactor.run()
Пример #26
0
   ## if asked to start an embedded application component ..
   ##
   if args.component:
      ## dynamically load the application component ..
      ##
      import importlib
      c = args.component.split('.')
      mod, klass = '.'.join(c[:-1]), c[-1]
      app = importlib.import_module(mod)
      SessionKlass = getattr(app, klass)

      ## .. and create and add an WAMP application session to
      ## run next to the router
      ##
      session_factory.add(SessionKlass())


   ## create a WAMP-over-WebSocket transport server factory
   ##
   from autobahn.twisted.websocket import WampWebSocketServerFactory
   transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug = args.debug)
   transport_factory.setProtocolOptions(failByDrop = False)


   ## start the WebSocket server from an endpoint
   ##
   server = serverFromString(reactor, args.websocket)
   server.listen(transport_factory)

Пример #27
0
        print("Running on reactor {}".format(reactor))

    ## create a WAMP router factory
    ##
    from autobahn.wamp.router import RouterFactory
    router_factory = RouterFactory()

    ## create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = MyRouterSession

    ## start an embedded application component ..
    ##
    session_factory.add(TimeService())

    ## create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory
    transport_factory = WampWebSocketServerFactory(session_factory,
                                                   args.wsurl,
                                                   debug_wamp=args.debug)
    transport_factory.protocol = ServerProtocol
    transport_factory._cookies = {}

    transport_factory.setProtocolOptions(failByDrop=False)

    from twisted.web.server import Site
    from twisted.web.static import File
    from autobahn.twisted.resource import WebSocketResource
Пример #28
0
def start_webserver(options, protocol=vtk_wamp.ServerProtocol, disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.host : the interface for the web-server to listen on
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    contextFactory = None

    use_SSL = False
    if options.sslKey and options.sslCert:
      use_SSL = True
      wsProtocol = "wss"
      from twisted.internet import ssl
      contextFactory = ssl.DefaultOpenSSLContextFactory(options.sslKey, options.sslCert)
    else:
      wsProtocol = "ws"

    # Create WAMP router factory
    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()

    # create a user DB
    authdb = vtk_wamp.AuthDb()

    # create a WAMP router session factory
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = vtk_wamp.CustomWampCraRouterSession
    session_factory.authdb = authdb

    # Create ApplicationSession and register protocols
    appSession = protocol(types.ComponentConfig(realm = "vtkweb"))
    appSession.setAuthDB(authdb)
    session_factory.add(appSession)

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = vtk_wamp.TimeoutWampWebSocketServerFactory(session_factory, \
           url        = "%s://%s:%d" % (wsProtocol, options.host, options.port),    \
           debug      = options.debug,                                              \
           debug_wamp = options.debug,                                              \
           timeout    = options.timeout )

    root = Resource()

    # Do we serve static content or just websocket ?
    if len(options.content) > 0:
        # Static HTTP + WebSocket
        root = File(options.content)

    # Handle possibly complex ws endpoint
    if not options.nows:
        wsResource = WebSocketResource(transport_factory)
        handle_complex_resource_path(options.ws, root, wsResource)

    # Handle binary push WebSocket for images
    if not options.nobws:
        wsbFactory = WebSocketServerFactory( \
            url   = "%s://%s:%d" % (wsProtocol, options.host, options.port), \
            debug = options.debug)
        wsbFactory.protocol = vtk_wamp.ImagePushBinaryWebSocketServerProtocol
        wsbResource = WebSocketResource(wsbFactory)
        handle_complex_resource_path('wsb', root, wsbResource)

    # Handle possibly complex lp endpoint
    if not options.nolp:
        lpResource = WampLongPollResource(session_factory,
                                          timeout=options.timeout,
                                          debug=options.debug)
                                          #killAfter = 30000,
                                          #queueLimitBytes = 1024 * 1024,
                                          #queueLimitMessages = 1000,
                                          #debug=True,
                                          #reactor=reactor)
        handle_complex_resource_path(options.lp, root, lpResource)

    if options.uploadPath != None :
        from vtk.web.upload import UploadPage
        uploadResource = UploadPage(options.uploadPath)
        root.putChild("upload", uploadResource)

    if len(options.fsEndpoints) > 3:
        for fsResourceInfo in options.fsEndpoints.split('|'):
            infoSplit = fsResourceInfo.split('=')
            handle_complex_resource_path(infoSplit[0], root, File(infoSplit[1]))

    site = Site(root)

    if use_SSL:
      reactor.listenSSL(options.port, site, contextFactory)
    else:
      reactor.listenTCP(options.port, site)

    # flush ready line
    sys.stdout.flush()

    # Work around to force the output buffer to be flushed
    # This allow the process launcher to parse the output and
    # wait for "Start factory" to know that the WebServer
    # is running.
    if options.forceFlush :
        for i in range(200):
            log.msg("+"*80, logLevel=logging.CRITICAL)

    # Initialize testing: checks if we're doing a test and sets it up
    testing.initialize(options, reactor, stop_webserver)

    # Start the reactor
    if options.nosignalhandlers:
        reactor.run(installSignalHandlers=0)
    else:
        reactor.run()

    # Give the testing module a chance to finalize, if necessary
    testing.finalize()
Пример #29
0
      #client_components = [Case2_Backend]
      #client_components = [Case1_Backend, Case1_Frontend]
      client_components = [Case2_Backend, Case2_Frontend]

   log = io.open(config.extra['caselog'], 'w')
   config.log = log
   config.components = []

   config.all_done = []

   for C in embedded_components:
      one_done = Deferred()
      config.all_done.append(one_done)
      c = C(config, one_done)
      config.components.append(c)
      session_factory.add(c)


   if args.transport == "websocket":

      ## create a WAMP-over-WebSocket transport server factory
      ##
      from autobahn.twisted.websocket import WampWebSocketServerFactory
      transport_factory = WampWebSocketServerFactory(session_factory, debug_wamp = args.debug)
      transport_factory.setProtocolOptions(failByDrop = False)

   elif args.transport in ['rawsocket-json', 'rawsocket-msgpack']:

      ## create a WAMP-over-RawSocket transport server factory
      ##
      if args.transport == 'rawsocket-msgpack':
Пример #30
0
        def test_minimal(self):

            embedded_components, client_components = [], [
                Case2_Backend, Case2_Frontend
            ]

            ## create a WAMP router factory
            ##
            router_factory = RouterFactory()

            ## create a WAMP router session factory
            ##
            session_factory = RouterSessionFactory(router_factory)

            ## .. and create and add an WAMP application session to
            ## run next to the router
            ##
            config = types.ComponentConfig(realm=self.realm,
                                           extra={'caselog': 'case1.log'})
            try:
                log = io.open('caselog.log', 'w')
            except Exception as e:
                print(e)
                return

    #      log = io.open(config.extra['caselog'], 'w')
            config.log = log
            config.dlog = []
            config.components = []

            config.all_done = []

            for C in embedded_components:
                one_done = Deferred()
                config.all_done.append(one_done)
                c = C(config, one_done)
                config.components.append(c)
                session_factory.add(c)

            if self.transport == "websocket":

                ## create a WAMP-over-WebSocket transport server factory
                ##
                transport_factory = WampWebSocketServerFactory(
                    session_factory, debug_wamp=self.debug)
                transport_factory.setProtocolOptions(failByDrop=False,
                                                     openHandshakeTimeout=0,
                                                     closeHandshakeTimeout=0)

            elif self.transport in ['rawsocket-json', 'rawsocket-msgpack']:

                ## create a WAMP-over-RawSocket transport server factory
                ##
                if self.transport == 'rawsocket-msgpack':
                    serializer = MsgPackSerializer()
                elif self.transport == 'rawsocket-json':
                    serializer = JsonSerializer()
                else:
                    raise Exception("should not arrive here")

                transport_factory = WampRawSocketServerFactory(
                    session_factory, serializer, debug=self.debug)

            else:
                raise Exception("should not arrive here")

            ## start the server from an endpoint
            ##
            from twisted.internet import reactor
            server = serverFromString(reactor, self.server)
            d = server.listen(transport_factory)

            def onlisten(port):
                config.port = port

            d.addCallback(onlisten)

            clients = []
            clients_d = []
            for C in client_components:
                ## create a WAMP application session factory
                ##
                session_factory = ApplicationSessionFactory(config)

                one_done = Deferred()
                config.all_done.append(one_done)

                def make_make(Klass, done):
                    def make(config):
                        c = Klass(config, done)
                        config.components.append(c)
                        return c

                    return make

                ## .. and set the session class on the factory
                ##
                session_factory.session = make_make(C, one_done)

                if self.transport == "websocket":

                    serializers = [JsonSerializer()]

                    ## create a WAMP-over-WebSocket transport client factory
                    ##
                    transport_factory = WampWebSocketClientFactory(
                        session_factory,
                        serializers=serializers,
                        url=self.url,
                        debug_wamp=self.debug)

                    if True:

                        def maker(Klass):
                            class TestClientProtocol(
                                    WampWebSocketClientProtocol):
                                def onOpen(self):
                                    self.txcnt = 0
                                    self.rxcnt = 0
                                    WampWebSocketClientProtocol.onOpen(self)

                                def sendMessage(self, bytes, isBinary):
                                    self.txcnt += 1
                                    print("> : {:>3} : {:<20} : {}".format(
                                        self.txcnt, Klass.__name__, bytes))
                                    WampWebSocketClientProtocol.sendMessage(
                                        self, bytes, isBinary)

                                def onMessage(self, bytes, isBinary):
                                    self.rxcnt += 1
                                    print("< : {:>3} : {:<20} : {}".format(
                                        self.rxcnt, Klass.__name__, bytes))
                                    WampWebSocketClientProtocol.onMessage(
                                        self, bytes, isBinary)

                            return TestClientProtocol

                        transport_factory.protocol = maker(C)
                    else:
                        transport_factory.protocol = WampWebSocketClientProtocol

                    transport_factory.setProtocolOptions(
                        failByDrop=False,
                        openHandshakeTimeout=0,
                        closeHandshakeTimeout=0)

                elif self.transport in ['rawsocket-json', 'rawsocket-msgpack']:

                    ## create a WAMP-over-RawSocket transport client factory
                    ##
                    if self.transport == 'rawsocket-msgpack':
                        serializer = MsgPackSerializer()
                    elif self.transport == 'rawsocket-json':
                        serializer = JsonSerializer()
                    else:
                        raise Exception("should not arrive here")

                    transport_factory = WampRawSocketClientFactory(
                        session_factory, serializer, debug=self.debug)

                ## start the client from an endpoint
                ##
                cl = clientFromString(reactor, self.client)
                clients_d.append(cl.connect(transport_factory))

                clients.append(cl)

            config.connected_clients = None

            def client_connected(res):
                config.connected_clients = [
                    proto for success, proto in res if success
                ]

            DeferredList(clients_d).addCallback(client_connected)

            d = DeferredList(config.all_done, consumeErrors=True)

            #d = config.components[1]._done

            def done(res):
                log.flush()
                log.close()
                if config.port:
                    config.port.stopListening()
                if config.connected_clients:
                    for proto in config.connected_clients:
                        proto.transport.abortConnection()
                print("Log length: {}".format(len(config.dlog)))
                print(config.dlog)
                #from twisted.internet import reactor
                #reactor.callLater(1, reactor.stop)

            def error(err):
                print(err)

            d.addCallbacks(done, error)

            #      d2 = Deferred()

            return d
Пример #31
0
    ctl_endpoint = WebSocketServerFactory("ws://localhost:8080",
                                          debug=debug,
                                          debugCodePaths=True)
    ctl_endpoint.protocol = CtlProtocol

    from autobahn.wamp.router import RouterFactory
    router_factory = RouterFactory()

    ## create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)

    ## [ ... ... ]
    session_factory.add(ModelServer())

    ## create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory
    wamp_factory = WampWebSocketServerFactory(session_factory,
                                              "ws://localhost:8080",
                                              debug=True)
    wamp_factory.setProtocolOptions(failByDrop=False)

    webroot = pathjoin(PROJECT_ROOT, "src", "frontend")
    assets = pathjoin(PROJECT_ROOT, "assets")
    if debug:
        print "putting", webroot, "at root"
        print "putting", assets, "at assets"
Пример #32
0


if __name__ == '__main__':

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

   ## 1) create a WAMP router factory
   router_factory = wamp.RouterFactory()

   ## 2) create a WAMP router session factory
   session_factory = RouterSessionFactory(router_factory)

   ## 3) Optionally, add embedded WAMP application sessions to the router
   session_factory.add(MyBackendComponent())

   ## 4) create a WAMP-over-WebSocket transport server factory
   transport_factory1 = WampWebSocketServerFactory(session_factory, debug = False)

   ## 5) start the server from a Twisted endpoint
   server1 = serverFromString(reactor, "tcp:8080")
   server1.listen(transport_factory1)

   ## 6) create a WAMP-over-RawSocket-MsgPack transport server factory
   serializer = MsgPackSerializer()
   serializer._serializer.ENABLE_V5 = False
   transport_factory2 = WampRawSocketServerFactory(session_factory, serializer, debug = True)

   ## 7) start the server from a Twisted endpoint
   server2 = serverFromString(reactor, "tcp:8090")
Пример #33
0
class Node:
   """
   A Crossbar.io node is the running a controller process
   and one or multiple worker processes.

   A single Crossbar.io node runs exactly one instance of
   this class, hence this class can be considered a system
   singleton.
   """

   def __init__(self, reactor, options):
      """
      Ctor.

      :param reactor: Reactor to run on.
      :type reactor: obj
      :param cbdir: Crossbar.io node directory to run from.
      :type cbdir: str
      """
      self.debug = options.debug
      self._cbdir = options.cbdir

      self._reactor = reactor
      self._worker_processes = {}

      ## node name: FIXME
      self._node_name = "{}-{}".format(socket.getfqdn(), os.getpid())
      self._node_name.replace('-', '_')
      self._node_name = '918234'
      self._node_realm = 'crossbar'

      self._node_controller_session = None

      ## node management
      self._management_url = "ws://127.0.0.1:7000"
      #self._management_url = "wss://cloud.crossbar.io"
      self._management_realm = "crossbar.cloud.aliceblue"



   @inlineCallbacks
   def start(self):
      """
      Starts this node. This will start a node controller
      and then spawn new worker processes as needed.

      The node controller will watch spawned processes,
      communicate via stdio with the worker, and start
      and restart the worker processes as needed.
      """
      try:
         import setproctitle
      except ImportError:
         log.msg("Warning, could not set process title (setproctitle not installed)")
      else:
         setproctitle.setproctitle("Crossbar.io Node Controller")

      ## the node controller singleton WAMP application session
      ##
      self._node_controller_session = NodeControllerSession(self)

      ## router and factory that creates router sessions
      ##
      self._router_factory = RouterFactory(
         options = types.RouterOptions(uri_check = types.RouterOptions.URI_CHECK_LOOSE),
         debug = False)
      self._router_session_factory = RouterSessionFactory(self._router_factory)

      ## add the node controller singleton session to the router
      ##
      self._router_session_factory.add(self._node_controller_session)

      ## Detect WAMPlets
      ##
      for wpl in self._node_controller_session.list_wamplets():
         log.msg("WAMPlet detected: {}.{}".format(wpl['dist'], wpl['name']))

      yield self.start_from_local_config(configfile = os.path.join(self._cbdir, 'config.json'))

      self.start_local_management_transport(endpoint_descriptor = "tcp:9000")



   def start_remote_management_client(self):
      from crossbar.management import NodeManagementSession

      management_session_factory = ApplicationSessionFactory()
      management_session_factory.session = NodeManagementSession
      management_session_factory.node_controller_session = node_controller_session
      management_transport_factory = WampWebSocketClientFactory(management_session_factory, "ws://127.0.0.1:7000")
      management_transport_factory.setProtocolOptions(failByDrop = False)
      management_client = clientFromString(self._reactor, "tcp:127.0.0.1:7000")
      management_client.connect(management_transport_factory)



   def start_local_management_transport(self, endpoint_descriptor):
      ## create a WAMP-over-WebSocket transport server factory
      ##
      from autobahn.twisted.websocket import WampWebSocketServerFactory
      from twisted.internet.endpoints import serverFromString

      self._router_server_transport_factory = WampWebSocketServerFactory(self._router_session_factory, debug = self.debug)
      self._router_server_transport_factory.setProtocolOptions(failByDrop = False)


      ## start the WebSocket server from an endpoint
      ##
      self._router_server = serverFromString(self._reactor, endpoint_descriptor)
      self._router_server.listen(self._router_server_transport_factory)



   @inlineCallbacks
   def start_from_local_config(self, configfile):
      ## load Crossbar.io node configuration
      ##
      configfile = os.path.abspath(configfile)

      log.msg("Loading from local config '{}' ..".format(configfile))

      config = check_config_file(configfile, silence = True)

      ## startup the node from configuration file
      ##
      yield self._node_controller_session.run_node_config(config)

      log.msg("Local configuration loaded.")