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 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)
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(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 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")
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 start_runner(): ready_deferred = defer.Deferred() logger.debug('[CrochetReactor] start bootstrap') def register_session(config): logger.debug('[CrochetReactor] start register_session') self._async_session = _AsyncSession(config=config, join_config=join_config) self._session = SyncSession(self._callbacks_runner, self._on_challenge_callback) self._async_session.connect_to_sync(self._session) self._session.connect_to_async(self._async_session) def resolve(result): logger.debug('[CrochetReactor] callback resolve: %s' % result) ready_deferred.callback(result) return result self._async_session.on_join_defer.addCallback(resolve) def resolve_error(failure): logger.debug('[CrochetReactor] errback resolve_error: %s' % failure) ready_deferred.errback(failure) self._async_session.on_join_defer.addErrback(resolve_error) return self._async_session self._async_runner = ApplicationRunner(**kwargs) d = self._async_runner.run(register_session, start_reactor=False) def connect_error(failure): ready_deferred.errback(failure) d.addErrback(connect_error) logger.debug('[CrochetReactor] end bootstrap') return ready_deferred
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 test_runner_no_run(self, fakereactor): fakereactor.connectTCP = Mock(side_effect=raise_error) runner = ApplicationRunner(u'ws://fake:1234/ws', u'dummy realm') try: yield runner.run(raise_error, start_reactor=False) self.fail() # should have raise an exception, via Deferred except RuntimeError as e: # make sure it's "our" exception self.assertEqual(e.args[0], "we always fail") # neither reactor.run() NOR reactor.stop() should have been called # (just connectTCP() will have been called) self.assertEqual(fakereactor.run.call_count, 0) self.assertEqual(fakereactor.stop.call_count, 0)
def test_runner_no_run_happypath(self, fakereactor): proto = Mock() fakereactor.connectTCP = Mock(return_value=succeed(proto)) runner = ApplicationRunner(u'ws://fake:1234/ws', u'dummy realm') d = runner.run(Mock(), start_reactor=False) # shouldn't have actually connected to anything # successfully, and the run() call shouldn't have inserted # any of its own call/errbacks. (except the cleanup handler) self.assertFalse(d.called) self.assertEqual(1, len(d.callbacks)) # neither reactor.run() NOR reactor.stop() should have been called # (just connectTCP() will have been called) self.assertEqual(fakereactor.run.call_count, 0) self.assertEqual(fakereactor.stop.call_count, 0)
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 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 onJoin(self, details): uplink_config = self.config.extra['uplink'] uplink_realm = details.realm uplink_transport = uplink_config['transport'] extra = { 'onready': Deferred(), 'local': self, } runner = ApplicationRunner(url=uplink_transport['url'], realm=uplink_realm, extra=extra) yield runner.run(RemoteSession, start_reactor=False) edge_session = yield extra['onready'] yield self._setup_event_forwarding(edge_session) if self.config.extra and 'onready' in self.config.extra: self.config.extra['onready'].callback(self)
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 test_runner_no_run(self, fakereactor): fakereactor.connectTCP = Mock(side_effect=raise_error) runner = ApplicationRunner(u'ws://fake:1234/ws', u'dummy realm') try: yield runner.run(raise_error, start_reactor=False) self.fail() # should have raise an exception, via Deferred except RuntimeError as e: # make sure it's "our" exception self.assertEqual(e.message, "we always fail") # neither reactor.run() NOR reactor.stop() should have been called # (just connectTCP() will have been called) run_calls = filter(lambda mc: mc.count('run'), fakereactor.method_calls) stop_calls = filter(lambda mc: mc.count('stop'), fakereactor.method_calls) self.assertEqual(len(run_calls), 0) self.assertEqual(len(stop_calls), 0)
print "Running download cmd " + downloadcmd 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)
An application component providing procedures with different kinds of arguments. """ @inlineCallbacks def onJoin(self, details): print("session attached") def square(val, details=None): print("square called from: {}".format(details.caller)) if val < 0: self.publish('com.myapp.square_on_nonpositive', val) elif val == 0: if details.caller: options = PublishOptions(exclude=[details.caller]) else: options = None self.publish('com.myapp.square_on_nonpositive', val, options=options) return val * val yield self.register(square, 'com.myapp.square', RegisterOptions(details_arg='details')) print("procedure registered") if __name__ == '__main__': from autobahn.twisted.wamp import ApplicationRunner runner = ApplicationRunner("ws://127.0.0.1:8080/ws", "realm1") runner.run(Component)
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)
"""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)
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)
def make(config): if config: return IRCComponent(config) else: ## if no config given, return a description of this WAMPlet .. return {'label': 'An IRC bot service component', 'description': 'This component provides IRC bot services via WAMP.'} if __name__ == '__main__': from autobahn.twisted.wamp import ApplicationRunner extra = { "server": "tcp:irc.freenode.net:6667" } ## test drive the component during development .. runner = ApplicationRunner( url = "ws://localhost:8080/ws", realm = "realm1", extra = extra, debug = False, ## low-level WebSocket debugging debug_wamp = False, ## WAMP protocol-level debugging debug_app = True) ## app-level debugging runner.run(make)
help='WAMP realm to join (default: "realm1")') args = parser.parse_args() # 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() # on Windows, we need port to be an integer args.port = int(args.port) 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 runner = ApplicationRunner(args.router, args.realm, extra={'port': args.port, 'baudrate': args.baudrate}) # start the component and the Twisted reactor .. runner.run(WampAdcpComponent, auto_reconnect=True)
def ping(): return def add2(a, b): return a + b def stars(nick="somebody", stars=0): return u"{} starred {}x".format(nick, stars) def orders(product, limit=5): return [u"Product {}".format(i) for i in range(50)][:limit] def arglen(*args, **kwargs): return [len(args), len(kwargs)] yield self.register(ping, u'com.arguments.ping') yield self.register(add2, u'com.arguments.add2') yield self.register(stars, u'com.arguments.stars') yield self.register(orders, u'com.arguments.orders') yield self.register(arglen, u'com.arguments.arglen') print("Procedures registered; ready for frontend.") if __name__ == '__main__': runner = ApplicationRunner( environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), u"realm1", ) runner.run(Component)
print("session attached") self.received = 0 sub = yield self.subscribe(self.on_event, u'com.myapp.hello') print("Subscribed to com.myapp.hello with {}".format(sub.id)) def on_event(self, i): print("Got event: {}".format(i)) self.received += 1 # self.config.extra for configuration, etc. (see [A]) if self.received > self.config.extra['max_events']: print("Received enough events; disconnecting.") self.leave() def onDisconnect(self): print("disconnected") if reactor.running: reactor.stop() if __name__ == '__main__': import six url = os.environ.get('CBURL', u'ws://localhost:8080/ws') realm = os.environ.get('CBREALM', u'realm1') # any extra info we want to forward to our ClientSession (in self.config.extra) extra = dict( max_events=5, # [A] pass in additional configuration ) runner = ApplicationRunner(url=url, realm=realm, extra=extra) runner.run(ClientSession, auto_reconnect=True)
class Component(ApplicationSession): """ Application component that calls procedures which produce complex results and showing how to access those. """ @inlineCallbacks def onJoin(self, details): print("session attached") res = yield self.call('com.myapp.add_complex', 2, 3, 4, 5) print("Result: {} + {}i".format(res.kwresults['c'], res.kwresults['ci'])) res = yield self.call('com.myapp.split_name', 'Homer Simpson') print("Forname: {}, Surname: {}".format(res.results[0], res.results[1])) self.leave() def onDisconnect(self): print("disconnected") reactor.stop() if __name__ == '__main__': url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component)
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
def pub(a): print 'Server received a pub with ', a class Component(ApplicationSession): """ Application component that provides procedures which return complex results. """ @inlineCallbacks def onJoin(self, details): print "session attached" yield self.publish('pd/hello') print "procedures registered" if __name__ == '__main__': runner = ApplicationRunner( environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8000/ws"), u"pd", debug_wamp=False, # optional; log many WAMP details debug=False, # optional; log even more details ) runner.run(Component)
## (try to) publish to a couple of topics we are not allowed to publish to (so this should fail) ## for topic in ['com.example.topic2', 'com.foobar.topic2']: try: yield self.publish(topic, "hello", options=PublishOptions(acknowledge=True)) print("ok, event published to topic {}".format(topic)) except Exception as e: print("publication to topic {} failed - this is expected: {}". format(topic, e)) self.leave() def onLeave(self, details): print("Client session left: {}".format(details)) self.disconnect() def onDisconnect(self): print("Client session disconnected.") reactor.stop() if __name__ == '__main__': from autobahn.twisted.wamp import ApplicationRunner runner = ApplicationRunner(url='ws://localhost:8080/ws', realm='realm1') runner.run(ClientSession)
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)
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)
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)
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)
def run(self, make, adapter, start_reactor=False): ApplicationRunner.run(self, make, start_reactor) self.adapter = adapter
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)
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)
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)
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner from twisted.internet.defer import inlineCallbacks class MyComponent(ApplicationSession): @inlineCallbacks def onJoin(self, details): print("session ready") try: res = yield self.call(u'com.myapp.add2', 2, 3) print("call result: {}".format(res)) except Exception as e: print("call error: {0}".format(e)) if __name__ == '__main__': runner = ApplicationRunner(url=u"ws://localhost:8080/ws", realm=u"realm1") runner.run(MyComponent)
except NameError: # 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 # 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)
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
# txaio.start_logging(level='debug' if args.debug else 'info') # # This is just a wrapper for our configuration, the conf object is passed through # to our service in the 'extra' parameter. logger_conf = MicroServiceConfig(args.profile) # # If you hit control+C, it tends to interrupt the retry cycle and generate an # unsightly traceback, this just tidies that up a little. def orderlyShutdown(): logger.log.info('* microservice - shutdown logger') logger.stop() # # This is our connection to the logging realm for infrastructure traffic that # should be partitioned off from application traffic. logger = ApplicationRunner( url=logger_conf.server_url, realm=logger_conf.realm, ssl=ssl.DefaultOpenSSLContextFactory( privateKeyFileName=CLIENT_KEY.format(logger_conf.name), certificateFileName=CLIENT_CRT.format(logger_conf.name)), extra={'conf': logger_conf}) reactor.addSystemEventTrigger('before', 'shutdown', orderlyShutdown) logger.run(ClientSession, auto_reconnect=True)
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)
def connect(self): print(self.args['router-addr']) runner = ApplicationRunner( u"ws://" + self.args['router-addr'] + "/ws", strtypes.cast_unicode(self.args['router-realm'])) runner.run(Client)
""" Application component that consumes progressive results. """ @inlineCallbacks def onJoin(self, details): print("session attached") def on_progress(i): print("Progress: {}".format(i)) res = yield self.call(u'com.myapp.longop', 3, options=CallOptions(on_progress=on_progress)) print("Final: {}".format(res)) self.leave() def onDisconnect(self): print("disconnected") reactor.stop() 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(Component)
from twisted.internet.defer import inlineCallbacks from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner import sys def on_event(*args, **kwargs): if args: print('*' + str(kwargs) + '*' + '*'.join(str(event) for event in args)) else: print('*' + str(kwargs)) class StreamBook(ApplicationSession): """ Session that defines which connection to listen to and how to parse a new input from Poloniex's WAMP server. """ @inlineCallbacks def onJoin(self, details): yield self.subscribe(on_event, self.config.extra['topic_connection']) if __name__ == "__main__": pair = sys.argv[1] subscriber = ApplicationRunner(u"wss://api.poloniex.com:443", u"realm1", extra={'topic_connection': pair}) subscriber.run(StreamBook)
def start_ticker(): session = MyAppSession(ComponentConfig(u'realm1', {})) runner = ApplicationRunner(u'wss://api.poloniex.com:443', u'realm1') runner.run(session, auto_reconnect=True)