Exemplo n.º 1
0
 def __init__(self, options=None, debug=False):
     """
   Ctor.
   """
     options = types.RouterOptions(
         uri_check=types.RouterOptions.URI_CHECK_LOOSE)
     RouterFactory.__init__(self, options, debug)
Exemplo n.º 2
0
    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)
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
def run_router(application_class):
    """Run autobahn router as applicaiton"""

    router_factory = RouterFactory()
    session_factory = wamp.RouterSessionFactory(router_factory)
    session_factory.add(application_class())
    transport_factory = websocket.WampWebSocketServerFactory(session_factory,
                                                             debug=False,
                                                             debug_wamp=False)
    loop = asyncio.get_event_loop()
    return loop.run_until_complete(
        loop.create_server(transport_factory, '0.0.0.0', 8080))
Exemplo n.º 5
0
        'Twisted server endpoint descriptor, e.g. "tcp:8080" or "unix:/tmp/mywebsocket".'
    )

    args = parser.parse_args()
    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()
    print("Running on reactor {}".format(reactor))

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

    ## 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
    ##
Exemplo n.º 6
0
    parser.add_argument("--endpoint", type=str, default="tcp:8080",
                        help='Twisted server endpoint descriptor, e.g. "tcp:8080" or "unix:/tmp/mywebsocket".')

    args = parser.parse_args()
    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()
    print("Running on reactor {}".format(reactor))

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

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

    # 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
    ##
        'Twisted server endpoint descriptor, e.g. "tcp:8080" or "unix:/tmp/mywebsocket".'
    )

    args = parser.parse_args()
    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()
    print("Running on reactor {}".format(reactor))

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

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

    # 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
Exemplo n.º 8
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()
Exemplo n.º 9
0
 def __init__(self, options = None, debug = False):
    """
    Ctor.
    """
    options = types.RouterOptions(uri_check = types.RouterOptions.URI_CHECK_LOOSE)
    RouterFactory.__init__(self, options, debug)
Exemplo n.º 10
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()
Exemplo n.º 11
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()
Exemplo n.º 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()