def connect(cls, url=None, realm=None, test_runner=None, user=None, secret=None): print "Connecting to the url: '%s', realm: '%s'" % (url, realm) cls.test_runner = test_runner runner = ApplicationRunner(url=url, realm=realm) runner.run(cls, start_reactor=False)
def onJoin(self, details): print("CoreBridge session ready: {}".format(details)) extra = { 'onready': Deferred(), 'core': self } runner = ApplicationRunner(url=self.config.extra['edge'], realm=details.realm, extra=extra) runner.run(EdgeBridge, start_reactor=False) other_session = yield extra['onready'] # setup event forwarding # @inlineCallbacks def on_subscription_create(sub, sub_details, details=None): print(sub, sub_details, details) uri = sub_details['uri'] def on_event(*args, **kwargs): details = kwargs.pop('details') self.publish(uri, *args, **kwargs) yield other_session.subscribe(on_event, uri) yield self.subscribe(on_subscription_create, u"wamp.subscription.on_create", options=SubscribeOptions(details_arg="details")) print("CoreBridge: EdgeBridge established")
class WebsocketClient(BaseClient): """this implements a connection through the websocket protocol.""" def __init__(self, curr_base, curr_quote, secret, config): # runner_config = {'url': u"wss://api.poloniex.com", 'realm': u"realm1"} BaseClient.__init__(self, curr_base, curr_quote, secret, config) self.hostname = WEBSOCKET_HOST self.signal_debug = Signal() def run(self): self.runner = ApplicationRunner(url=u"wss://api.poloniex.com", realm=u"realm1", extra={'client': self}) self.runner.run(PoloniexComponent, start_reactor=False) def _recv_thread_func(self): """connect to the websocket and start receiving in an infinite loop. Try to reconnect whenever connection is lost. Each received json string will be dispatched with a signal_recv signal""" try: self.run() reactor.run(installSignalHandlers=0) except Exception as exc: self.debug("Reactor exception:", exc) self.debug(traceback.format_exc()) def send(self, json_str): """send the json encoded string over the websocket""" self._try_send_raw(json_str)
def run(self): for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]: signal.signal(sig, self.handler) ## Start logging to logfile ## log.startLogging(open(LOG_FILE, 'w')) ## create embedded web server for static files ## from twisted.internet import reactor log.msg("Using Twisted reactor {0}".format(reactor.__class__)) from twisted.web.server import Site from twisted.web.static import File reactor.listenTCP(WEB_PORT, Site(File(WEB_DIRECTORY))) ## run WAMP application component ## from autobahn.twisted.wamp import ApplicationRunner runner = ApplicationRunner('ws://localhost:8080', u"realm1", None, None, True) ## start the component and the Twisted reactor .. ## runner.run(APComponent)
def run(url="wss://api.checkmy.ws/live", realm="live", authid=None, secret=None, debug=False): url = environ.get('WAMP_URL', url) realm = environ.get('WAMP_REALM', realm) authid = environ.get('WAMP_AUTHID', authid) secret = environ.get('WAMP_SECRET', secret) if authid is None or secret is None: raise EnvironmentError("'WAMP_AUTHID' or 'WAMP_SECRET' was not defined") config = { 'url': url.decode(), 'realm': realm.decode(), 'extra': { 'authid': authid, 'secret': secret } } if 'dev' in url: config['ssl'] = CertificateOptions(verify=False) runner = ApplicationRunner(**config) LoopingCall(heartbeat).start(10, now=False) try: runner.run(Live) except Exception: print(traceback.format_exc()) # Safety sleep time.sleep(3)
def main(): config = ConfigParser() config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini') config.read(config_file) logger.setLevel(getattr(logging, config.get('logging', 'level'))) logging.basicConfig(format='[%(levelname)-5s] %(asctime)-15s %(name)10s %(message)s') host = config.get('main', 'host') port = config.get('main', 'port') address = u'ws://{}:{}/ws'.format(host, port) realm = u'mars' logger.info('Initializing rover interface...') rover = Rover(config) rover.start() logger.info('Connecting to {} in realm "{}"...'.format(address, realm)) runner = ApplicationRunner(address, realm, extra={ 'config': config, 'rover': rover }) # Start application try: runner.run(Component) except NoRouteError: logger.error('Error connecting to {} {}'.format(address, realm)) finally: rover.stop()
def main(): args = parse_args() app = QApplication(argv) qt5reactor.install() runner = ApplicationRunner(args.url, u'crossbardemo', extra=vars(args)) runner.run(make)
def start_crossbar(self): running_deferred = Deferred() extra = dict(running=running_deferred) self.xbar_runner_kwargs['extra'] = extra xbar_runner = ApplicationRunner(**self.xbar_runner_kwargs) xbar_runner.run(self.xbar_component, start_reactor=False, auto_reconnect=True) session = yield running_deferred returnValue(session)
def play(url, rname, strategy): global agent global roomName agent = strategy roomName = rname print("Connecting to server %s ..." % (url)) runner = ApplicationRunner(url=url, realm=u"ballfight") runner.run(BallfightConnector)
def test_omitted_SSLContext_secure(self): ''' Ensure that loop.create_connection is called with ssl=True if no ssl argument is passed to the __init__ method of ApplicationRunner and the websocket URL starts with "wss:". ''' loop = Mock() loop.run_until_complete = Mock(return_value=(Mock(), Mock())) with patch.object(asyncio, 'get_event_loop', return_value=loop): runner = ApplicationRunner(u'wss://127.0.0.1:8080/wss', u'realm') runner.run('_unused_') self.assertIs(True, loop.create_connection.call_args[1]['ssl'])
def main(): args, _ = get_args() if args.debug: txaio.start_logging(level='debug') else: txaio.start_logging(level='info') # create and start app runner for our app component .. extra = {"args": args} runner = ApplicationRunner(url=args.router, realm=args.realm, extra=extra) runner.run(SubscriptionPrinter, auto_reconnect=True)
def boot_master(websocket_uri, debug=False, trace=False): print 'INFO: Starting WebSocket master service on', websocket_uri """ factory = MasterServerFactory(websocket_uri, debugWamp = True) websocket.listenWS(factory) client_factory = MasterClientFactory(websocket_uri, debug=False, debugCodePaths=False, debugWamp=debug, debugApp=False) websocket.connectWS(client_factory) """ runner = ApplicationRunner(websocket_uri, u'kotori-realm', debug=trace, debug_wamp=debug, debug_app=debug) runner.run(Component, start_reactor=False)
def main(): # parse command line arguments global scanners args, _ = get_args() setup_logging(args.debug) scanners, q = start_scanners(args) # create and start app runner for our app component .. extra = {"args": args, "queue": q} runner = ApplicationRunner(url=args.router, realm=args.realm, extra=extra) runner.run(BarcodeSender, auto_reconnect=True)
class WampClientContainer(object): def __init__(self, host, port, realm, component=WampComponent): self.host = unicode(host) self.port = unicode(port) self.realm = unicode(realm) self.connection_str = unicode("ws://{0}:{1}/ws".format(self.host, self.port)) self.component = component self.runner = None def run(self, start_reactor=False): self.runner = ApplicationRunner(url=self.connection_str, realm=self.realm) self.runner.run(self.component, start_reactor=start_reactor)
def boot_node(websocket_uri, debug=False, trace=False): print 'INFO: Starting node service, connecting to', websocket_uri # connect to master service """ global node_manager node_manager = NodeManager(websocket_uri, debug=debug) reactor.callLater(0, node_manager.master_connect) """ runner = ApplicationRunner(websocket_uri, u'kotori-realm', debug=trace, debug_wamp=debug, debug_app=debug) runner.run(KotoriNode, start_reactor=False)
def run(): prog = os.path.basename(__file__) def_wsocket = 'ws://127.0.0.1:8080/ws' def_user = '******' def_secret = 'dbsecret' def_realm = 'realm1' def_topic_base = 'com.db' # http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text p = argparse.ArgumentParser(description="db admin manager for autobahn", formatter_class=SmartFormatter) p.add_argument('-w', '--websocket', action='store', dest='wsocket', default=def_wsocket, help='web socket definition, default is: '+def_wsocket) p.add_argument('-r', '--realm', action='store', dest='realm', default=def_realm, help='connect to websocket using realm, default is: '+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('-e', '--engine', action='store', dest='engine', default=None, help='if specified, a database engine will be attached.' + ' Note engine is rooted on --topic.' + ' Valid engine options are PG, MYSQL or SQLITE') p.add_argument('-d', '--dsn', action='store', dest='dsn', default=None, help='R|if specified the database in dsn will be connected and ready.\n' + 'dsns are unique to the engine being used. Valid examples:' + '\n-----------' + '\nPG: dbname=autobahn host=192.168.200.230 user=autouser password=testpass' + '\nMYSQL: database=autobahn user=autouser password=passtest' + '\nSQLITE: Z') 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) component_config = types.ComponentConfig(realm=args.realm) ai = { 'auth_type':'wampcra', 'auth_user':args.user, 'auth_password':args.password } mdb = DB(config=component_config, authinfo=ai,engine=args.engine,topic_base=args.topic_base,dsn=args.dsn, debug=args.verbose) runner = ApplicationRunner(args.wsocket, args.realm) runner.run(lambda _: mdb)
def build(self): """ Entry point of Kivy UI component. """ # WAMP session self.session = None # run our WAMP application component runner = ApplicationRunner(url = u"ws://localhost:8080/ws", realm = u"realm1", extra = dict(ui=self)) runner.run(MyComponent, start_reactor=False) # setup the Kivy UI root = self.setup_gui() return root
def test_explicit_SSLContext(self): ''' Ensure that loop.create_connection is called with the exact SSL context object that is passed (as ssl) to the __init__ method of ApplicationRunner. ''' loop = Mock() loop.run_until_complete = Mock(return_value=(Mock(), Mock())) with patch.object(asyncio, 'get_event_loop', return_value=loop): ssl = {} runner = ApplicationRunner(u'ws://127.0.0.1:8080/ws', u'realm', ssl=ssl) runner.run('_unused_') self.assertIs(ssl, loop.create_connection.call_args[1]['ssl'])
def main_entry(args=None): from autobahn.twisted.wamp import ApplicationRunner parser = argparse.ArgumentParser() parser.add_argument('url', metavar='URL', type=unicode, help="URL to websocket of WAMP server") parser.add_argument('scopes', metavar='SCOPE', type=str, help="scope mappings: /rsb/scope [<][-]message_type[-][>] wamp.scope") args = sys.argv[1:] if args is None else args args = parser.parse_args(args) runner = ApplicationRunner(url=args.url, realm=u"realm1") try: runner.run(partial(Client, scopes=args.scopes)) except KeyboardInterrupt or Exception: raise KeyboardInterrupt print "shutting down client..."
def run(): prog = os.path.basename(__file__) def_wsocket = 'ws://127.0.0.1:8080/ws' def_user = '******' def_secret = 'clientsecret' def_realm = 'realm1' def_topic_base = 'com.db' def_db_call = 'query' def_db_query = 'select 1' def_db_args = '{}' p = argparse.ArgumentParser(description="run sqlbridge command") p.add_argument('-w', '--websocket', action='store', dest='wsocket', default=def_wsocket, help='web socket definition, default is: '+def_wsocket) p.add_argument('-r', '--realm', action='store', dest='realm', default=def_realm, help='connect to websocket using realm, default is: '+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('-t', '--topic', action='store', dest='topic_base', default=def_topic_base, help='your query will be executed against this topic base, the default: ' + def_topic_base) p.add_argument('-c', '--call', action='store', dest='db_call', default=def_db_call, help='this is concatenated with topic_base after prepending a dot, default : ' + def_db_call) p.add_argument('-q', '--query', action='store', dest='db_query', default=def_db_query, help='this is the first argument to db_call, if db_call is operation or query then this is the sql query to run. If the operation is watch then this is the LISTEN to watch : ' + def_db_query) p.add_argument('-a', '--args', action='store', dest='db_args', default=def_db_args, help='if your query requires arguments they can be specified in json format here, default is a blank dictionary : ' + def_db_args) args = p.parse_args() if args.verbose: log.startLogging(sys.stdout) component_config = types.ComponentConfig(realm=args.realm) ai = { 'auth_type':'wampcra', 'auth_user':args.user, 'auth_password':args.password } mdb = Component(config=component_config, authinfo=ai,topic_base=args.topic_base,debug=args.verbose, db_call=args.db_call,db_query=args.db_query,db_args=json.loads(args.db_args)) runner = ApplicationRunner(args.wsocket, args.realm) runner.run(lambda _: mdb)
class WampApplication(object): def __init__(self, url, realm=u'kotori', session_class=WampSession, config=None): """ url: ws://master.example.com:9000/ws """ self.url = url self.realm = realm self.session_class = session_class self.config = config def make(self): # connect to crossbar router/broker self.runner = ApplicationRunner(self.url, self.realm, extra=dict(self.config)) # run application session self.deferred = self.runner.run(self.session_class, start_reactor=False) def croak(ex, *args): log.error('Problem in {name}, please check if "crossbar" WAMP broker is running. args={args}'.format( name=self.__class__.__name__, args=args)) log.error("{ex}, args={args!s}", ex=ex.getTraceback(), args=args) reactor.stop() raise ex self.deferred.addErrback(croak)
def launchWAMPSub(rpcApi): pid = os.getpid() try: logging.info('Launch Parser with launchWAMPSub on {}'.format(urlCrossbar)) fd = open('/var/run/im/im_parser_websocket_sub_supervisor.pid', 'w') fd.write(str(pid)) fd.close() runner = ApplicationRunner(url=u"ws://{0}:{1}/ws".format(urlCrossbar, portCrossbar), realm=realmCrossbar, extra={'pid':pid, 'rpcApi':rpcApi}) runner.run(WAMPSub) except Exception, e: logging.error('Parser with launchWAMPSub error : {0}'.format(e)) os.kill(pid, signal.SIGTERM) pass
def start_wamp_component(self): """ Create a WAMP session and start the WAMP component """ self.session = None # adapt to fit the Crossbar.io instance you're using url, realm = u"ws://localhost:8080/ws", u"crossbardemo" # Create our WAMP application component runner = ApplicationRunner(url=url, realm=realm, extra=dict(ui=self.root)) # Start our WAMP application component without starting the reactor because # that was already started by kivy runner.run(VotesWampComponent, start_reactor=False)
def run(on_ready, keyfile='mykey'): if not keyfile: keyfile = os.path.join(os.path.expanduser('~'), '.ssh', 'id_ed25519') key = cryptosign.SigningKey.from_ssh_key(keyfile) extra = { u'key': key, u'on_ready': on_ready } runner = ApplicationRunner( u'ws://127.0.0.1:8080/ws', None, extra=extra, ) runner.run(CDCClient)
def onJoin(self, details): print("CoreBridge joined: {}".format(details)) extra = { 'onready': Deferred(), 'core': self } runner = ApplicationRunner(url=self.config.extra['edge'], realm=details.realm, extra=extra) runner.run(EdgeBridge, start_reactor=False) edge_session = yield extra['onready'] yield self._setup_event_forwarding(edge_session) if self.config and 'onready' in self.config.extra: self.config.extra['onready'].callback(self) print("CoreBridge ready")
def main(): config = ConfigParser() config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini') config.read(config_file) logger.setLevel(getattr(logging, config.get('logging', 'level'))) logging.basicConfig(format='[%(levelname)-5s] %(asctime)-15s %(name)10s %(message)s') host = config.get('main', 'host') port = config.get('main', 'port') address = u'ws://{}:{}/ws'.format(host, port) realm = u'mars' # Start application logger.info('Connecting to {} in realm "{}"...'.format(address, realm)) runner = ApplicationRunner(address, realm, extra={ 'config': config, 'rover_id': 1 }) runner.run(Component)
def start_wamp_component(self): """ Create a WAMP session and start the WAMP component """ self.session = None # Alas! demo.crossbar.io needs an older version of autobahn :-( from autobahn import __version__ as v if v < '0.10.2': url, realm = u"wss://demo.crossbar.io/ws", u"crossbardemo" else: url, realm = u"ws://localhost:8080/ws", u"realm1" # Create our WAMP application component runner = ApplicationRunner(url=url, realm=realm, extra=dict(ui=self.root)) # Start our WAMP application component without starting the reactor because # that was already started by kivy runner.run(VotesWampComponent, start_reactor=False)
def launchLivelog(queue, radius_agent_name): pid = os.getpid() try: if not os.path.isfile('/var/run/im/im_agent_websocket_live_freeradius.pid'): path, filename = os.path.split('/var/run/im/im_agent_websocket_live_freeradius.pid') if not os.path.isdir(path): os.makedirs(path) open('/var/run/im/im_agent_websocket_live_freeradius.pid', 'a').close() fd = open('/var/run/im/im_agent_websocket_live_freeradius.pid', 'w') fd.write(str(pid)) fd.close() runner = ApplicationRunner(url=u"ws://{0}:{1}/ws".format(urlCrossbar, portCrossbar), realm=realmCrossbar, extra={'queue':queue, 'pid':pid, 'radius_agent_name':radius_agent_name}) runner.run(LiveLog) except Exception, e: logging.error('launchLivelog error : {0}'.format(e)) os.kill(pid, signal.SIGTERM) pass
def __init__(self, url, realm, parent=None): super(VotesWindow, self).__init__(parent) self.setupUi(self) self.url = url self.realm = realm self.session = None self.votes = { 'Banana': self.bananaVotes, 'Chocolate': self.chocolateVotes, 'Lemon': self.lemonVotes } # Factory method for ApplicationRunner.run(..) def make(config): self.session = VotesSession(config) self.session.joinedSession.connect(self.onJoinedSession) self.session.leftSession.connect(self.onLeftSession) return self.session runner = ApplicationRunner(url, realm) runner.run(make, start_reactor=False)
class NetMonitor( object ): def __init__( self, reactor, ws ): self._reactor = reactor self._ws = ws self._runner = ApplicationRunner( self._ws, u"realm1", debug_wamp=False, # optional; log many WAMP details debug=False, # optional; log even more details extra=dict(parent=self) ) self._runner.run( AppSession, start_reactor=False ) def start( self, session ): self._session = session self._reactor.callLater( 0, self.pub_event ) def pub_event( self ): e = random_event() self._session.publish('netmonitor.event', e ) self._reactor.callLater( 5, self.pub_event )
dest='cskey', type=str, help= 'Private WAMP-cryptosign authentication key (32 bytes as HEX encoded string)' ) args = parser.parse_args() if args.debug: txaio.start_logging(level='debug') else: txaio.start_logging(level='info') extra = { 'ethkey': binascii.a2b_hex(args.ethkey), 'cskey': binascii.a2b_hex(args.cskey), } runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra, serializers=[CBORSerializer()]) try: runner.run(XbrDelegate, auto_reconnect=True) except Exception as e: print(e) sys.exit(1) else: sys.exit(0)
args = parser.parse_args() # start logging if args.debug: txaio.start_logging(level='debug') else: txaio.start_logging(level='info') # any extra info we want to forward to our ClientSession (in self.config.extra) extra = {'auth': True} if args.ssl: st_cert=open(args.ca_cert_file, 'rt').read() c=OpenSSL.crypto ca_cert=c.load_certificate(c.FILETYPE_PEM, st_cert) st_cert=open(args.intermediate_cert_file, 'rt').read() intermediate_cert=c.load_certificate(c.FILETYPE_PEM, st_cert) certs = OpenSSLCertificateAuthorities([ca_cert, intermediate_cert]) ssl_con = CertificateOptions(trustRoot=certs) # now actually run a WAMP client using our session class ClientSession runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra, ssl=ssl_con) else: # now actually run a WAMP client using our session class ClientSession runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) runner.run(AppSession, auto_reconnect=True)
def start(self, cdc_mode=False): """ Starts this node. This will start a node controller and then spawn new worker processes as needed. """ if not self._config: raise Exception("No node configuration loaded") controller_config = self._config.get('controller', {}) controller_options = controller_config.get('options', {}) # set controller process title # try: import setproctitle except ImportError: self.log.warn( "Warning, could not set process title (setproctitle not installed)" ) else: setproctitle.setproctitle( controller_options.get('title', 'crossbar-controller')) # the node controller realm # self._realm = controller_config.get(u'realm', u'crossbar') # the node's name (must be unique within the management realm when running # in "managed mode") # if 'id' in controller_config: self._node_id = controller_config['id'] self.log.info("Node ID '{node_id}' set from config", node_id=self._node_id) elif 'CDC_ID' in os.environ: self._node_id = u'{}'.format(os.environ['CDC_ID']) self.log.info( "Node ID '{node_id}' set from environment variable CDC_ID", node_id=self._node_id) else: self._node_id = u'{}'.format(socket.gethostname()) self.log.info("Node ID '{node_id}' set from hostname", node_id=self._node_id) # standalone vs managed mode # if 'cdc' in controller_config and controller_config['cdc'].get( 'enabled', False): self._prepare_node_keys() cdc_config = controller_config['cdc'] # CDC connecting transport # if 'transport' in cdc_config: transport = cdc_config['transport'] if 'tls' in transport['endpoint']: hostname = transport['endpoint']['tls']['hostname'] else: raise Exception( "TLS activated on CDC connection, but 'hostname' not provided" ) self.log.warn( "CDC transport configuration overridden from node config!") else: transport = { "type": u"websocket", "url": u"wss://devops.crossbario.com/ws", "endpoint": { "type": u"tcp", "host": u"devops.crossbario.com", "port": 443, "timeout": 5, "tls": { "hostname": u"devops.crossbario.com" } } } hostname = u'devops.crossbario.com' # CDC management realm # if 'realm' in cdc_config: realm = cdc_config['realm'] self.log.info("CDC management realm '{realm}' set from config", realm=realm) elif 'CDC_REALM' in os.environ: realm = u"{}".format(os.environ['CDC_REALM']).strip() self.log.info( "CDC management realm '{realm}' set from enviroment variable CDC_REALM", realm=realm) else: raise Exception( "CDC management realm not set - either 'realm' must be set in node configuration, or in CDC_REALM enviroment variable" ) # CDC authentication credentials (for WAMP-CRA) # authid = self._node_id if 'secret' in cdc_config: authkey = cdc_config['secret'] self.log.info("CDC authentication secret loaded from config") elif 'CDC_SECRET' in os.environ: authkey = u"{}".format(os.environ['CDC_SECRET']).strip() self.log.info( "CDC authentication secret loaded from environment variable CDC_SECRET" ) else: raise Exception( "CDC authentication secret not set - either 'secret' must be set in node configuration, or in CDC_SECRET enviroment variable" ) # extra info forwarded to CDC client session # extra = { 'node': self, 'onready': Deferred(), 'onexit': Deferred(), 'authid': authid, 'authkey': authkey } runner = ApplicationRunner(url=transport['url'], realm=realm, extra=extra, ssl=optionsForClientTLS(hostname), debug=False) try: self.log.info("Connecting to CDC at '{url}' ..", url=transport['url']) yield runner.run(NodeManagementSession, start_reactor=False) # wait until we have attached to the uplink CDC self._manager = yield extra['onready'] except Exception as e: raise Exception("Could not connect to CDC - {}".format(e)) # in managed mode, a node - by default - only shuts down when explicitly asked to, # or upon a fatal error in the node controller self._node_shutdown_triggers = [ checkconfig.NODE_SHUTDOWN_ON_SHUTDOWN_REQUESTED ] self.log.info( "Connected to Crossbar.io DevOps Center (CDC)! Your node runs in managed mode." ) else: self._manager = None # in standalone mode, a node - by default - is immediately shutting down whenever # a worker exits (successfully or with error) self._node_shutdown_triggers = [ checkconfig.NODE_SHUTDOWN_ON_WORKER_EXIT ] # allow to override node shutdown triggers # if 'shutdown' in controller_options: self.log.info( "Overriding default node shutdown triggers with {} from node config" .format(controller_options['shutdown'])) self._node_shutdown_triggers = controller_options['shutdown'] else: self.log.info("Using default node shutdown triggers {}".format( self._node_shutdown_triggers)) # router and factory that creates router sessions # self._router_factory = RouterFactory(self._node_id) self._router_session_factory = RouterSessionFactory( self._router_factory) rlm_config = {'name': self._realm} rlm = RouterRealm(None, rlm_config) # create a new router for the realm router = self._router_factory.start_realm(rlm) # add a router/realm service session cfg = ComponentConfig(self._realm) rlm.session = RouterServiceSession(cfg, router) self._router_session_factory.add(rlm.session, authrole=u'trusted') if self._manager: self._bridge_session = NodeManagementBridgeSession( cfg, self, self._manager) self._router_session_factory.add(self._bridge_session, authrole=u'trusted') else: self._bridge_session = None # the node controller singleton WAMP application session # self._controller = NodeControllerSession(self) # add the node controller singleton session to the router # self._router_session_factory.add(self._controller, authrole=u'trusted') # Detect WAMPlets # wamplets = self._controller._get_wamplets() if len(wamplets) > 0: self.log.info("Detected {wamplets} WAMPlets in environment:", wamplets=len(wamplets)) for wpl in wamplets: self.log.info("WAMPlet {dist}.{name}", dist=wpl['dist'], name=wpl['name']) else: self.log.debug("No WAMPlets detected in enviroment.") panic = False try: yield self._startup(self._config) # Notify systemd that crossbar is fully up and running # This has no effect on non-systemd platforms try: import sdnotify sdnotify.SystemdNotifier().notify("READY=1") except: pass except ApplicationError as e: panic = True self.log.error("{msg}", msg=e.error_message()) except Exception: panic = True traceback.print_exc() if panic: try: self._reactor.stop() except twisted.internet.error.ReactorNotRunning: pass
self.diceThrown = False # used with Phase.BUY to decide which agent MORTGAGE & SELL_HOUSES # should be called for self.bsmAgentId = PLAY_ORDER[0] self.auctionStarted = False self.tradeCounter = 0 self.mapper = Mapper(self) for agentId in PLAY_ORDER: sessionId = self.agents[agentId]['sessionId'] uri = self.endpoints['RESPONSE'].format(self.gameId, sessionId) sub = yield self.subscribe( partial(self.mapper.response, sessionId), uri) self.agents[agentId]['subKeys'].append(sub) self.mapper.request() if __name__ == '__main__': if len(sys.argv) < 4: sys.exit("Not enough arguments") import six url = environ.get("CBURL", u"ws://127.0.0.1:4000/ws") if six.PY2 and type(url) == six.binary_type: url = url.decode('utf8') realm = environ.get('CBREALM', u'realm1') runner = ApplicationRunner(url, realm) runner.run(Adjudicator)
def start_ticker(): session = MyAppSession(ComponentConfig(u'realm1', {})) runner = ApplicationRunner(u'wss://api.poloniex.com:443', u'realm1') runner.run(session, auto_reconnect=True)
counter = 1 while counter <= self.NUM: msg = u'Counter is at {}'.format(counter) topic = u'com.myapp.hello' pub = yield self.publish(topic, msg, options=options) self.log.info('event published: {pub}', pub=pub) topic = u'com.myapp.encrypted.hello' pub = yield self.publish(topic, msg, options=options) self.log.info('event published: {pub}', pub=pub) if delay: yield sleep(1) counter += 1 def onLeave(self, details): self.log.info('session left: {details}', details=details) ApplicationSession.onLeave(self, details) def onDisconnect(self): ApplicationSession.onDisconnect(self) from twisted.internet import reactor reactor.stop() if __name__ == '__main__': txaio.start_logging(level='info') runner = ApplicationRunner(u"ws://127.0.0.1:8080", u"realm1") runner.run(Component1)
# parse command line parameters parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output.') parser.add_argument( '--url', dest='url', type=six.text_type, default=url, help='The router URL (default: "ws://localhost:8080/ws").') parser.add_argument('--realm', dest='realm', type=six.text_type, default=realm, help='The realm to join (default: "realm1").') args = parser.parse_args() # start logging if args.debug: txaio.start_logging(level='debug') else: txaio.start_logging(level='info') # now actually run a WAMP client using our session class ClientSession runner = ApplicationRunner(url=args.url, realm=args.realm) runner.run(AppSession)
def unicode(s, *_): return s def to_unicode(s): return unicode(s, "utf-8") parser = argparse.ArgumentParser() parser.add_argument("server_ip", type=to_unicode) parser.add_argument("port", type=to_unicode) parser.add_argument("realm", type=to_unicode) parser.add_argument("key", type=to_unicode) parser.add_argument("datapath", type=to_unicode) args = parser.parse_args() ai_sv = "rs://" + args.server_ip + ":" + args.port ai_realm = args.realm # create a Wamp session object session = Component(ComponentConfig(ai_realm, {})) # initialize the msgpack serializer serializer = MsgPackSerializer() # use Wamp-over-rawsocket runner = ApplicationRunner(ai_sv, ai_realm, serializers=[serializer]) runner.run(session, auto_reconnect=False)
return reactome_utils.get_pathway(pathway_id=pathway_id) # DATABASE def get_uploads_list(id_token): return self.dbm.get_uploads_list(id_token=id_token) def get_observations_list(id_token): return self.dbm.get_observations_list(id_token=id_token) def get_pathways_list(id_token): return self.dbm.get_pathways_list(id_token=id_token) # REGISTER try: yield self.register(google_auth, u"google.auth") yield self.register(get_reactome_pathways_list, u"reactome.pathwayslist") yield self.register(get_reactome_pathway, u"reactome.pathway") yield self.register(get_uploads_list, u"db.uploadslist") yield self.register(get_observations_list, u"db.observationsList") yield self.register(get_pathways_list, u"db.pathwaysList") print("...[wamp] Registered") except Exception as e: print("...[wamp] could not register: {0}".format(e)) if __name__ == "__main__": cert = crypto.load_certificate(crypto.FILETYPE_PEM,six.u(open('.crossbar/example.cert.pem', "r").read())) options = CertificateOptions(trustRoot=OpenSSLCertificateAuthorities([cert])) # runner = ApplicationRunner(url=u"wss://127.0.0.1:443/ws", realm=u"realm1", ssl=options) # runner = ApplicationRunner(url=u"wss://127.0.0.1:4433", realm=u"realm1", ssl=options) runner = ApplicationRunner(url=u"ws://127.0.0.1:4433", realm=u"realm1") runner.run(WAMPComponent)
def start_link(self, link_id, link_config, caller): assert type(link_id) == str assert isinstance(link_config, RLinkConfig) assert isinstance(caller, SessionIdent) if link_id in self._links: raise ApplicationError( 'crossbar.error.already_running', 'router link {} already running'.format(link_id)) # setup local session # local_extra = { 'other': None, 'on_ready': Deferred(), 'rlink': link_id, # 'forward_events': False, 'forward_events': link_config.forward_local_events, } local_realm = self._realm.config['name'] local_authid = link_config.authid or util.generate_serial_number() local_authrole = 'trusted' local_config = ComponentConfig(local_realm, local_extra) local_session = RLinkLocalSession(local_config) # setup remote session # remote_extra = { 'rlink_manager': self, 'other': None, 'on_ready': Deferred(), 'authid': link_config.authid, 'exclude_authid': link_config.exclude_authid, 'forward_events': link_config.forward_remote_events, 'forward_invocations': link_config.forward_remote_invocations, } remote_realm = link_config.realm remote_config = ComponentConfig(remote_realm, remote_extra) remote_session = RLinkRemoteSession(remote_config) # cross-connect the two sessions # local_extra['other'] = remote_session remote_extra['other'] = local_session # the rlink # rlink = RLink(link_id, link_config) self._links[link_id] = rlink # create connecting client endpoint # connecting_endpoint = create_connecting_endpoint_from_config( link_config.transport['endpoint'], self._controller.cbdir, self._controller._reactor, self.log) try: # connect the local session # self._realm.controller.router_session_factory.add( local_session, self._realm.router, authid=local_authid, authrole=local_authrole, authextra=local_extra) yield local_extra['on_ready'] # connect the remote session # # remote connection parameters to ApplicationRunner: # # url: The WebSocket URL of the WAMP router to connect to (e.g. ws://somehost.com:8090/somepath) # realm: The WAMP realm to join the application session to. # extra: Optional extra configuration to forward to the application component. # serializers: List of :class:`autobahn.wamp.interfaces.ISerializer` (or None for default serializers). # ssl: None or :class:`twisted.internet.ssl.CertificateOptions` # proxy: Explicit proxy server to use; a dict with ``host`` and ``port`` keys # headers: Additional headers to send (only applies to WAMP-over-WebSocket). # max_retries: Maximum number of reconnection attempts. Unlimited if set to -1. # initial_retry_delay: Initial delay for reconnection attempt in seconds (Default: 1.0s). # max_retry_delay: Maximum delay for reconnection attempts in seconds (Default: 60s). # retry_delay_growth: The growth factor applied to the retry delay between reconnection attempts (Default 1.5). # retry_delay_jitter: A 0-argument callable that introduces nose into the delay. (Default random.random) # remote_runner = ApplicationRunner(url=link_config.transport['url'], realm=remote_realm, extra=remote_extra) yield remote_runner.run(remote_session, start_reactor=False, auto_reconnect=True, endpoint=connecting_endpoint, reactor=self._controller._reactor) yield remote_extra['on_ready'] except: # make sure to remove the half-initialized link from our map .. del self._links[link_id] # .. and then re-raise raise # the router link is established: store final infos rlink.started = time_ns() rlink.started_by = caller rlink.local = local_session rlink.remote = remote_session return rlink
os.system(downloadcmd) print "S3 download is complete" return destfile def rebuild_inmemory_cache(self): for file in os.listdir(self.cache_dir): self.cachedFilesMap[self.s3url + file] = self.cache_dir + file class RPiAudioPlaybackComponent(ApplicationSession): cache = LocalAudioCacheStore( "/home/pi/.audio/", "https://s3.amazonaws.com/makeandbuild/courier/audio/") @inlineCallbacks def onJoin(self, details): print "RPiAudioPlaybackComponent is online!" yield self.register(self) yield self.subscribe(self) @wamp.subscribe(u'com.makeandbuild.rpi.audio.play') def play_sound(self, audio_info): self.cache.play_cached_file(audio_info) if __name__ == '__main__': runner = ApplicationRunner("ws://courier.makeandbuildatl.com:9015/ws", "coffee") runner.run(RPiAudioPlaybackComponent)
action='store_true', help='Enable debug output.') parser.add_argument( '--url', dest='url', type=six.text_type, default=url, help='The router URL (default: "ws://localhost:8080/ws").') parser.add_argument('--realm', dest='realm', type=six.text_type, default=realm, help='The realm to join (default: "realm1").') args = parser.parse_args() if args.debug: txaio.start_logging(level='debug') else: txaio.start_logging(level='info') # custom configuration data extra = { # GPI pin of buzzer u'light_sensor_pin': 14, } # create and start app runner for our app component .. runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) runner.run(LightSensorComponent, auto_reconnect=True)
from os import environ from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from autobahn.twisted.wamp import Session, ApplicationRunner class Component(Session): """ An application component calling the different backend procedures. """ def onJoin(self, details): print("session attached {}".format(details)) return self.leave() if __name__ == '__main__': runner = ApplicationRunner( environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), "crossbardemo", ) def make(config): session = Component(config) session.add_authenticator("wampcra", authid='username', secret='p4ssw0rd') return session runner.run(make)
reg = yield self.subscribe(on_event, TOPIC, options=SubscribeOptions(details=True)) self.log.info('subscribed to topic {topic}: registration={reg}', topic=TOPIC, reg=reg) pid = os.getpid() seq = 1 while True: pub = yield self.publish( TOPIC, pid, seq, os.urandom(8), options=PublishOptions(acknowledge=True, exclude_me=False), ) self.log.info('event published: publication={pub}\n', pub=pub) seq += 1 yield sleep(1) if __name__ == '__main__': txaio.start_logging(level='info') runner = ApplicationRunner('rs://localhost:8080', 'realm1') # runner = ApplicationRunner('ws://localhost:8080/ws', 'realm1') runner.run(MySession)
"--web", type=int, default=8080, help='Web port to use for embedded Web server. Use 0 to disable.') parser.add_argument( "--router", type=str, default=None, help= 'If given, connect to this WAMP router. Else run an embedded router on 9000.' ) args = parser.parse_args() if args.debug: from twisted.python import log log.startLogging(sys.stdout) # run WAMP application component ## from autobahn.twisted.wamp import ApplicationRunner runner = ApplicationRunner( environ.get("AUTOBAHN_DEMO_ROUTER", "ws://localhost:8080/ws"), u"crossbardemo", debug_wamp=False, # optional; log many WAMP details debug=False, # optional; log even more details ) runner.run(Calculator)
# We implement this method which is called when this ApplicationSession registers with the WAMP router. # (happens in __main__ block) # This is where we setup our pub/sub stuff # Using inlineCallbacks instead of Deferreds because the code examples use this # TODO: rewrite in Deferreds, or understand wtf @inlineCallbacks decorator does @inlineCallbacks def onJoin(self, details): self.id = details.session print("CREATING NEW SESSION WITH ID {}".format(self.id)) self.world = World(self) # Add a register RPC and listen for playermove events try: yield self.subscribe(self.world.move_player, u'com.autobahntest.playermove') yield self.subscribe(self.world.remove_player, u'com.autobahntest.playerleft') yield self.register(self.world.register_player, u'com.autobahntest.register') except Exception as e: print("Could not sub to topic : {}".format(e)) def onLeave(self, details): pass if __name__ == '__main__': runner = ApplicationRunner(url=u'ws://127.0.0.1:8080/ws', realm=u'realm1') runner.run(PlayerMoveComponent)
from os import environ from twisted.internet.defer import inlineCallbacks from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner # or: from autobahn.asyncio.wamp import ApplicationSession class MyComponent(ApplicationSession): @inlineCallbacks def onJoin(self, details): # listening for the corresponding message from the "backend" # (any session that .publish()es to this topic). def onevent(msg): print("Got event: {}".format(msg)) yield self.subscribe(onevent, u'com.myapp.hello') # call a remote procedure. res = yield self.call(u'com.myapp.add2', 2, 3) print("Got result: {}".format(res)) if __name__ == '__main__': runner = ApplicationRunner( environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), u"crossbardemo", debug=False, # optional; log even more details ) runner.run(MyComponent)
"""Move the global brightness down a single tick""" self.brightness_tgt = self.brightness_tgt.next_dn(self.brightness_tgt) self.global_brightness_publish() return {"brightness": self.brightness_tgt.value} @wamp.register("com.lambentri.edge.la4.machine.gb.set") def global_brightness_value_set(self, value: int): """Set the global brightness""" self.brightness_tgt = BrightnessEnum(value) self.global_brightness_publish() return {"brightness": self.brightness_tgt.value} @wamp.register("com.lambentri.edge.la4.machine.gb.get") def global_brightness_value_get(self): """get the global brightness""" return {"brightness": self.brightness_tgt.value} @inlineCallbacks def onJoin(self, details): print("joined") self.regs = yield self.register(self) self.subs = yield self.subscribe(self) self.document() if __name__ == '__main__': url = os.environ.get("XBAR_ROUTER", u"ws://127.0.0.1:8083/ws") realm = u"realm1" runner = ApplicationRunner(url, realm) runner.run(LambentMachine, auto_reconnect=True)
if __name__ == '__main__': # Crossbar.io connection configuration url = os.environ.get('CBURL', u'ws://localhost:8080/ws') realm = os.environ.get('CBREALM', u'realm1') # parse command line parameters parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output.') parser.add_argument('--url', dest='url', type=six.text_type, default=url, help='The router URL (default: "ws://localhost:8080/ws").') parser.add_argument('--realm', dest='realm', type=six.text_type, default=realm, help='The realm to join (default: "realm1").') args = parser.parse_args() # start logging if args.debug: txaio.start_logging(level='debug') else: txaio.start_logging(level='info') # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { u'foobar': u'A custom value' } # now actually run a WAMP client using our session class ClientSession runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) runner.run(ClientSession, auto_reconnect=True)
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### from twisted.internet.defer import inlineCallbacks from autobahn.twisted.util import sleep from autobahn.twisted.wamp import ApplicationSession class Component(ApplicationSession): """ An application component that publishes an event every second. """ @inlineCallbacks def onJoin(self, details): print("session attached") counter = 0 while True: print(".") self.publish('com.myapp.topic1', counter) counter += 1 yield sleep(1) if __name__ == '__main__': from autobahn.twisted.wamp import ApplicationRunner runner = ApplicationRunner("ws://127.0.0.1:8080/ws", "realm1") runner.run(Component)
opt = CertificateOptions(trustRoot=OpenSSLCertificateAuthorities([cert])) # Check variables setup when creating the Docker container. required_env = ['SQL_HOST', 'SQL_USER', 'SQL_PASSWD', 'SQL_DB'] for var in required_env: try: environ[var] except KeyError: print("Required environment variable {} is missing. \ Check your environment setup and try again.".format(var)) # SQL Config # User/password just for development purposes, obviously change in production. SQL_CONFIG = { 'host': environ['SQL_HOST'], 'user': environ['SQL_USER'], 'passwd': environ['SQL_PASSWD'], 'db': environ['SQL_DB'] } # Start our component. runner = ApplicationRunner( "wss://%s:%d/ws" % (sisock.base.SISOCK_HOST, sisock.base.SISOCK_PORT), sisock.base.REALM, ssl=opt) runner.run( G3ReaderServer(ComponentConfig(sisock.base.REALM, {}), sql_config=SQL_CONFIG))
def run(self, make, adapter, start_reactor=False): ApplicationRunner.run(self, make, start_reactor) self.adapter = adapter
"--router", type=str, default=None, help= 'If given, connect to this WAMP router. Else run an embedded router on 9000.' ) args = parser.parse_args() from twisted.python import log log.startLogging(sys.stdout) # import Twisted reactor from twisted.internet import reactor print("Using Twisted reactor {0}".format(reactor.__class__)) # create embedded web server for static files if args.web: from twisted.web.server import Site from twisted.web.static import File reactor.listenTCP(args.web, Site(File("."))) # run WAMP application component from autobahn.twisted.wamp import ApplicationRunner router = args.router or u'ws://127.0.0.1:9000' runner = ApplicationRunner(router, u"realm1", standalone=not args.router) # start the component and the Twisted reactor .. runner.run(DbusNotifier)
from twisted.python import log log.startLogging(sys.stdout) ## import Twisted reactor ## if sys.platform == 'win32': ## on windows, we need to use the following reactor for serial support ## http://twistedmatrix.com/trac/ticket/3802 ## from twisted.internet import win32eventreactor win32eventreactor.install() from twisted.internet import reactor print("Using Twisted reactor {0}".format(reactor.__class__)) ## create embedded web server for static files ## # if args.web: # from twisted.web.server import Site # from twisted.web.static import File # reactor.listenTCP(args.web, Site(File("."))) ## run WAMP application component ## from autobahn.twisted.wamp import ApplicationRunner router = 'ws://localhost:8080' runner = ApplicationRunner(router, u"realm1") runner.run(McuComponent)
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output.') parser.add_argument( '--url', dest='url', type=str, default='ws://localhost:8080/ws', help='The router URL (default: "ws://localhost:8080/ws").') parser.add_argument('--realm', dest='realm', type=str, default='realm1', help='The realm to join (default: "realm1").') args = parser.parse_args() if args.debug: txaio.start_logging(level='debug') else: txaio.start_logging(level='info') extra = {'foobar': 'A custom value'} runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) runner.run(ClientSession)
parser.add_argument("--realm", type=six.text_type, default=u"crossbardemo", help='WAMP router realm.') args = parser.parse_args() if args.debug: txaio.start_logging(level='debug') else: txaio.start_logging(level='info') # custom configuration data extra = { # PIN numbering mode (use "bcm" or "board") "pin_mode": "bcm", # these Pins are wired to digouts "digout_pins": [13, 19, 5, 6], # these Pins are wired to digins "digin_pins": [20, 21], # we will scan the digins at this rate (Hz) "scan_rate": 50 } # create and start app runner for our app component .. runner = ApplicationRunner(url=args.router, realm=args.realm, extra=extra) runner.run(DispenserAdapter, auto_reconnect=True)
self.log.info('session left: {}'.format(details)) self.disconnect() def onDisconnect(self): self.log.info('transport disconnected') if __name__ == '__main__': print ('parse command line parameters') parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output.') parser.add_argument('--url', dest='url', type=six.text_type, default=u'ws://localhost:8080/ws', help='The router URL (default: "ws://104.199.76.81:8080/ws").') # parser.add_argument('--router', type=six.text_type,default=u'ws://104.199.76.81:8080/ws',help='WAMP router URL.') # parser.add_argument('--realm',type=six.text_type, default='realm1',help='WAMP router realm.') parser.add_argument('--realm', dest='realm', type=six.text_type, default='realm1', help='The realm to join (default: "realm1").') args = parser.parse_args() print(args) # now actually run a WAMP client using our session class ClientSession runner = ApplicationRunner(url=args.url, realm=args.realm) print(runner) runner.run(Zaehler, auto_reconnect=True)
# Define 'unicode' for Python 3 def unicode(s, *_): return s def to_unicode(s): return unicode(s, "utf-8") parser = argparse.ArgumentParser() parser.add_argument("server_ip", type=to_unicode) parser.add_argument("port", type=to_unicode) parser.add_argument("realm", type=to_unicode) parser.add_argument("key", type=to_unicode) parser.add_argument("datapath", type=to_unicode) args = parser.parse_args() ai_sv = "rs://" + args.server_ip + ":" + args.port ai_realm = args.realm with U.single_threaded_session(): # create a Wamp session object session = Component(ComponentConfig(ai_realm, {})) # initialize the msgpack serializer serializer = MsgPackSerializer() # use Wamp-over-rawsocket runner = ApplicationRunner(ai_sv, ai_realm, serializers=[serializer]) runner.run(session, auto_reconnect=True)
from twisted.python import log log.startLogging(sys.stdout) # import Twisted reactor # if sys.platform == 'win32': # on windows, we need to use the following reactor for serial support # http://twistedmatrix.com/trac/ticket/3802 ## from twisted.internet import win32eventreactor win32eventreactor.install() from twisted.internet import reactor print("Using Twisted reactor {0}".format(reactor.__class__)) # run WAMP application component # from autobahn.twisted.wamp import ApplicationRunner extra = { 'wpad_id': args.wpad_id, 'port': args.port, 'baudrate': args.baudrate, 'debug': args.debug } runner = ApplicationRunner(args.router, args.realm, extra=extra) # start the component and the Twisted reactor .. # runner.run(WpadMonitor)
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) self.log.info("Starting from node configuration file '{configfile}'", configfile=configfile) self._config = check_config_file(configfile, silence=True) controller_config = self._config.get('controller', {}) controller_options = controller_config.get('options', {}) controller_title = controller_options.get('title', 'crossbar-controller') try: import setproctitle except ImportError: self.log.warn("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() if 'manager' in controller_config: extra = { 'onready': Deferred() } realm = controller_config['manager']['realm'] transport = controller_config['manager']['transport'] runner = ApplicationRunner(url=transport['url'], realm=realm, extra=extra) runner.run(NodeManagementSession, start_reactor=False) # wait until we have attached to the uplink CDC self._management_session = yield extra['onready'] self.log.info("Node is connected to Crossbar.io DevOps Center (CDC)") else: self._management_session = None # the node's management realm self._realm = controller_config.get('realm', 'crossbar') # router and factory that creates router sessions # self._router_factory = RouterFactory() self._router_session_factory = RouterSessionFactory(self._router_factory) rlm = RouterRealm(None, {'name': self._realm}) # create a new router for the realm router = self._router_factory.start_realm(rlm) # add a router/realm service session cfg = ComponentConfig(self._realm) rlm.session = RouterServiceSession(cfg, router) self._router_session_factory.add(rlm.session, authrole=u'trusted') if self._management_session: self._bridge_session = NodeManagementBridgeSession(cfg, self._management_session) self._router_session_factory.add(self._bridge_session, authrole=u'trusted') else: self._bridge_session = None # the node controller singleton WAMP application session # self._controller = NodeControllerSession(self) # add the node controller singleton session to the router # self._router_session_factory.add(self._controller, authrole=u'trusted') # Detect WAMPlets # wamplets = self._controller._get_wamplets() if len(wamplets) > 0: self.log.info("Detected {wamplets} WAMPlets in environment:", wamplets=len(wamplets)) for wpl in wamplets: self.log.info("WAMPlet {dist}.{name}", dist=wpl['dist'], name=wpl['name']) else: self.log.info("No WAMPlets detected in enviroment.") try: yield self._startup(self._config) except: traceback.print_exc() try: self._reactor.stop() except twisted.internet.error.ReactorNotRunning: pass