def run(ctx, **kwargs): from raiden.api.python import RaidenAPI from raiden.ui.console import Console # TODO: # - Ask for confirmation to quit if there are any locked transfers that did # not timeout. (listen_host, listen_port) = split_endpoint(kwargs['listen_address']) with socket_factory(listen_host, listen_port) as mapped_socket: kwargs['socket'] = mapped_socket.socket app_ = ctx.invoke(app, **kwargs) # spawn address registration to avoid block while waiting for the next block registry_event = gevent.spawn( app_.discovery.register, app_.raiden.address, mapped_socket.external_ip, mapped_socket.external_port, ) app_.raiden.register_registry( app_.raiden.chain.default_registry.address) domain_list = [] if kwargs['rpccorsdomain']: if ',' in kwargs['rpccorsdomain']: for domain in kwargs['rpccorsdomain'].split(','): domain_list.append(str(domain)) else: domain_list.append(str(kwargs['rpccorsdomain'])) if ctx.params['rpc']: raiden_api = RaidenAPI(app_.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api, cors_domain_list=domain_list) Greenlet.spawn(api_server.run, ctx.params['api_port'], debug=False, use_evalex=False) print( "The RPC server is now running at http://localhost:{}/.\n\n" "See the Raiden documentation for all available endpoints at\n" "https://github.com/raiden-network/raiden/blob/master/docs/Rest-Api.rst" .format(ctx.params['api_port'], )) if ctx.params['console']: console = Console(app_) console.start() registry_event.join() # wait for interrupt event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) event.wait() app_.stop(graceful=True)
def run(ctx, **kwargs): if ctx.invoked_subcommand is None: from raiden.api.python import RaidenAPI from raiden.ui.console import Console slogging.configure(kwargs['logging'], log_file=kwargs['logfile']) # TODO: # - Ask for confirmation to quit if there are any locked transfers that did # not timeout. (listen_host, listen_port) = split_endpoint(kwargs['listen_address']) with socket_factory(listen_host, listen_port) as mapped_socket: kwargs['mapped_socket'] = mapped_socket app_ = ctx.invoke(app, **kwargs) domain_list = [] if kwargs['rpccorsdomain']: if ',' in kwargs['rpccorsdomain']: for domain in kwargs['rpccorsdomain'].split(','): domain_list.append(str(domain)) else: domain_list.append(str(kwargs['rpccorsdomain'])) http_server = None if ctx.params['rpc']: raiden_api = RaidenAPI(app_.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api, cors_domain_list=domain_list) (api_host, api_port) = split_endpoint(kwargs["api_address"]) http_server = WSGIServer((api_host, api_port), api_server.flask_app, log=slogging.getLogger('flask')) http_server.start() print( "The Raiden API RPC server is now running at http://{}:{}/.\n\n" "See the Raiden documentation for all available endpoints at\n" "https://github.com/raiden-network/raiden/blob/master" "/docs/Rest-Api.rst".format( api_host, api_port, )) if ctx.params['console']: console = Console(app_) console.start() # wait for interrupt event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) event.wait() if http_server: http_server.stop(5) app_.stop(leave_channels=False)
def _run_smoketest(): print_step('Starting Raiden') config = deepcopy(App.DEFAULT_CONFIG) if args.get('extra_config', dict()): merge_dict(config, args['extra_config']) del args['extra_config'] args['config'] = config # invoke the raiden app app = run_app(**args) raiden_api = RaidenAPI(app.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api) (api_host, api_port) = split_endpoint(args['api_address']) api_server.start(api_host, api_port) raiden_api.channel_open( registry_address=contract_addresses[ CONTRACT_TOKEN_NETWORK_REGISTRY], token_address=to_canonical_address(token.contract.address), partner_address=to_canonical_address(TEST_PARTNER_ADDRESS), ) raiden_api.set_total_channel_deposit( contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY], to_canonical_address(token.contract.address), to_canonical_address(TEST_PARTNER_ADDRESS), TEST_DEPOSIT_AMOUNT, ) token_addresses = [to_checksum_address(token.contract.address)] success = False try: print_step('Running smoketest') error = run_smoketests( app.raiden, args['transport'], token_addresses, contract_addresses[CONTRACT_ENDPOINT_REGISTRY], debug=debug, ) if error is not None: append_report('Smoketest assertion error', error) else: success = True finally: app.stop() node = ethereum[0] node.send_signal(2) err, out = node.communicate() append_report('Ethereum stdout', out) append_report('Ethereum stderr', err) if success: print_step(f'Smoketest successful') else: print_step(f'Smoketest had errors', error=True) return success
def _run_app(): # this catches exceptions raised when waiting for the stalecheck to complete try: app_ = ctx.invoke(app, **kwargs) except EthNodeCommunicationError as err: sys.exit(1) domain_list = [] if kwargs['rpccorsdomain']: if ',' in kwargs['rpccorsdomain']: for domain in kwargs['rpccorsdomain'].split(','): domain_list.append(str(domain)) else: domain_list.append(str(kwargs['rpccorsdomain'])) api_server = None if ctx.params['rpc']: raiden_api = RaidenAPI(app_.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer( rest_api, cors_domain_list=domain_list, web_ui=ctx.params['web_ui'], eth_rpc_endpoint=ctx.params['eth_rpc_endpoint'], ) (api_host, api_port) = split_endpoint(kwargs['api_address']) api_server.start(api_host, api_port) print( 'The Raiden API RPC server is now running at http://{}:{}/.\n\n' 'See the Raiden documentation for all available endpoints at\n' 'http://raiden-network.readthedocs.io/en/stable/rest_api.html'. format( api_host, api_port, )) if ctx.params['console']: console = Console(app_) console.start() # wait for interrupt event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) gevent.signal(signal.SIGUSR1, toogle_cpu_profiler) gevent.signal(signal.SIGUSR2, toggle_trace_profiler) event.wait() print('Signal received. Shutting down ...') if api_server: api_server.stop() return app_
def start_apiserver(raiden_app, rest_api_port_number): raiden_api = RaidenAPI(raiden_app.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api) api_server.flask_app.config['SERVER_NAME'] = 'localhost:{}'.format(rest_api_port_number) api_server.start(port=rest_api_port_number) wait_for_listening_port(rest_api_port_number) return api_server
def api_test_server(): # Initializing it without raiden_service.api here since that is a # function scope fixture. We will inject it to rest_api object later rest_api = RestAPI(None) api_server = APIServer(rest_api) # TODO: Find out why tests fail with debug=True g = Greenlet.spawn(api_server.run, 5001, debug=False, use_evalex=False) yield rest_api # At sessions teardown kill the greenlet g.kill(block=True, timeout=10) del rest_api del api_server
def create_api_server(raiden_app: App, port_number: int) -> APIServer: raiden_api = RaidenAPI(raiden_app.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api, config={'host': 'localhost', 'port': port_number}) api_server.flask_app.config['SERVER_NAME'] = 'localhost:{}'.format(port_number) api_server.start() # Fixes flaky test, were requests are done prior to the server initializing # the listening socket. # https://github.com/raiden-network/raiden/issues/389#issuecomment-305551563 wait_for_listening_port(port_number) return api_server
def run(ctx, external_listen_address, **kwargs): # TODO: # - Ask for confirmation to quit if there are any locked transfers that did # not timeout. if not external_listen_address: # notify('if you are behind a NAT, you should set # `external_listen_address` and configure port forwarding on your router') external_listen_address = kwargs['listen_address'] ctx.params.pop('external_listen_address') app_ = ctx.invoke(app, **kwargs) app_.discovery.register( app_.raiden.address, *split_endpoint(external_listen_address) ) app_.raiden.register_registry(app_.raiden.chain.default_registry.address) if ctx.params['rpc']: # instance of the raiden-api raiden_api = app_.raiden.api # wrap the raiden-api with rest-logic and encoding rest_api = RestAPI(raiden_api) # create the server and link the api-endpoints with flask / flask-restful middleware api_server = APIServer(rest_api) # run the server Greenlet.spawn(api_server.run, ctx.params['api_port'], debug=False, use_evalex=False) print( "The RPC server is now running", "at http://localhost:{0}/.".format(ctx.params['api_port']) ) print( "See the Raiden documentation for all available endpoints at", "https://github.com/raiden-network/raiden/blob/master/docs/api.rst" ) if ctx.params['console']: console = Console(app_) console.start() # wait for interrupt event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) event.wait() app_.stop()
def start_api_server(rpc_client: JSONRPCClient, config: RestApiConfig, eth_rpc_endpoint: str) -> APIServer: api = RestAPI(rpc_client=rpc_client) api_server = APIServer(rest_api=api, config=config, eth_rpc_endpoint=eth_rpc_endpoint) api_server.start() url = f"http://{config.host}:{config.port}/" print(f"The Raiden API RPC server is now running at {url}.\n\n" f"See the Raiden documentation for all available endpoints at\n" f"{DOC_URL}") return api_server
def start_apiserver(raiden_app: App, rest_api_port_number: Port) -> APIServer: raiden_api = RaidenAPI(raiden_app.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api, config=RestApiConfig(host=Host("localhost"), port=rest_api_port_number)) # required for url_for api_server.flask_app.config[ "SERVER_NAME"] = f"localhost:{rest_api_port_number}" api_server.start() wait_for_listening_port(rest_api_port_number) return api_server
def api_backend(raiden_network, rest_api_port_number): raiden_api = RaidenAPI(raiden_network[0].raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api) api_server.flask_app.config['SERVER_NAME'] = 'localhost:{}'.format( rest_api_port_number) api_server.start(port=rest_api_port_number) # Fixes flaky test, were requests are done prior to the server initializing # the listening socket. # https://github.com/raiden-network/raiden/issues/389#issuecomment-305551563 wait_for_listening_port(rest_api_port_number) yield api_server, rest_api api_server.stop(timeout=10)
def run(ctx, **kwargs): # TODO: # - Ask for confirmation to quit if there are any locked transfers that did # not timeout. (listen_host, listen_port) = split_endpoint(kwargs['listen_address']) with socket_factory(listen_host, listen_port) as mapped_socket: kwargs['socket'] = mapped_socket.socket app_ = ctx.invoke(app, **kwargs) app_.discovery.register( app_.raiden.address, mapped_socket.external_ip, mapped_socket.external_port, ) app_.raiden.register_registry( app_.raiden.chain.default_registry.address) if ctx.params['rpc']: raiden_api = RaidenAPI(app_.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api) Greenlet.spawn(api_server.run, ctx.params['api_port'], debug=False, use_evalex=False) print( "The RPC server is now running at http://localhost:{}/.\n\n" "See the Raiden documentation for all available endpoints at\n" "https://github.com/raiden-network/raiden/blob/master/docs/api.rst" .format(ctx.params['api_port'], )) if ctx.params['console']: console = Console(app_) console.start() # wait for interrupt event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) event.wait() app_.stop()
def start_apiserver(raiden_app, rest_api_port_number): raiden_api = RaidenAPI(raiden_app.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api, config={ "host": "localhost", "port": rest_api_port_number }) # required for url_for api_server.flask_app.config["SERVER_NAME"] = "localhost:{}".format( rest_api_port_number) api_server.start() wait_for_listening_port(rest_api_port_number) return api_server
def start_apiserver(raiden_app, rest_api_port_number): raiden_api = RaidenAPI(raiden_app.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api, config={ 'host': 'localhost', 'port': rest_api_port_number }) # required for url_for api_server.flask_app.config['SERVER_NAME'] = 'localhost:{}'.format( rest_api_port_number) api_server.start() wait_for_listening_port(rest_api_port_number) return api_server
def api_backend(rest_api_port_number): # Initializing it without raiden_service.api here since that is a # function scope fixture. We will inject it to rest_api object later rest_api = RestAPI(None) api_server = APIServer(rest_api) api_server.flask_app.config['SERVER_NAME'] = 'localhost:{}'.format(rest_api_port_number) # TODO: Find out why tests fail with debug=True server = Greenlet.spawn( api_server.run, rest_api_port_number, debug=False, use_evalex=False, ) yield api_server, rest_api server.kill(block=True, timeout=10)
def create_api_server(raiden_app: App, port_number: int) -> APIServer: raiden_api = RaidenAPI(raiden_app.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api, config={ "host": "localhost", "port": port_number, "explorerendpoint": "localhost:8080", "discoverable": False }) api_server.flask_app.config["SERVER_NAME"] = "localhost:{}".format( port_number) api_server.start() # Fixes flaky test, were requests are done prior to the server initializing # the listening socket. # https://github.com/raiden-network/raiden/issues/389#issuecomment-305551563 wait_for_listening_port(port_number) return api_server
def _run_smoketest(): # invoke the raiden app app_ = ctx.invoke(app, **args) raiden_api = RaidenAPI(app_.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api) (api_host, api_port) = split_endpoint(args['api_address']) api_server.start(api_host, api_port) success = False try: print('[4/5] running smoketests...') error = run_smoketests(app_.raiden, smoketest_config, debug=debug) if error is not None: append_report('smoketest assertion error', error) else: success = True finally: app_.stop() ethereum.send_signal(2) err, out = ethereum.communicate() append_report('geth init stdout', ethereum_config['init_log_out'].decode('utf-8')) append_report('geth init stderr', ethereum_config['init_log_err'].decode('utf-8')) append_report('ethereum stdout', out) append_report('ethereum stderr', err) append_report('smoketest configuration', json.dumps(smoketest_config)) if success: print( '[5/5] smoketest successful, report was written to {}'.format( report_file)) else: print( '[5/5] smoketest had errors, report was written to {}'.format( report_file)) return success
def api_backend(rest_api_port_number): # Initializing it without raiden_service.api here since that is a # function scope fixture. We will inject it to rest_api object later rest_api = RestAPI(None) api_server = APIServer(rest_api) api_server.flask_app.config['SERVER_NAME'] = 'localhost:{}'.format(rest_api_port_number) # TODO: Find out why tests fail with debug=True server = Greenlet.spawn( api_server.run, port=rest_api_port_number, debug=False, use_evalex=False, ) # Fixes flaky test, were requests are done prior to the server initializing # the listening socket. # https://github.com/raiden-network/raiden/issues/389#issuecomment-305551563 wait_for_listening_port(rest_api_port_number) yield api_server, rest_api server.kill(block=True, timeout=10)
def api_backend(raiden_network, rest_api_port_number): raiden_api = RaidenAPI(raiden_network[0].raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api) api_server.flask_app.config['SERVER_NAME'] = 'localhost:{}'.format( rest_api_port_number) # TODO: Find out why tests fail with debug=True server = Greenlet.spawn( api_server.run, port=rest_api_port_number, debug=False, use_evalex=False, ) # Fixes flaky test, were requests are done prior to the server initializing # the listening socket. # https://github.com/raiden-network/raiden/issues/389#issuecomment-305551563 wait_for_listening_port(rest_api_port_number) yield api_server, rest_api server.kill(block=True, timeout=10)
def smoketest(ctx, debug, **kwargs): """ Test, that the raiden installation is sane. """ from raiden.api.python import RaidenAPI from raiden.blockchain.abi import get_static_or_compile from raiden.utils import get_contract_path # Check the solidity compiler early in the smoketest. # # Binary distributions don't need the solidity compiler but source # distributions do. Since this is checked by `get_static_or_compile` # function, use it as a proxy for validating the setup. get_static_or_compile( get_contract_path('HumanStandardToken.sol'), 'HumanStandardToken', ) report_file = tempfile.mktemp(suffix='.log') open(report_file, 'w+') def append_report(subject, data): with open(report_file, 'a', encoding='UTF-8') as handler: handler.write('{:=^80}'.format(' %s ' % subject.upper()) + os.linesep) if data is not None: if isinstance(data, bytes): data = data.decode() handler.writelines([data + os.linesep]) append_report('raiden version', json.dumps(get_system_spec())) append_report('raiden log', None) print('[1/5] getting smoketest configuration') smoketest_config = load_or_create_smoketest_config() print('[2/5] starting ethereum') ethereum, ethereum_config = start_ethereum(smoketest_config['genesis']) print('[3/5] starting raiden') # setup logging to log only into our report file slogging.configure(':DEBUG', log_file=report_file) root = slogging.getLogger() for handler in root.handlers: if isinstance(handler, slogging.logging.StreamHandler): root.handlers.remove(handler) break # setup cli arguments for starting raiden args = dict( discovery_contract_address=smoketest_config['contracts'] ['discovery_address'], registry_contract_address=smoketest_config['contracts'] ['registry_address'], eth_rpc_endpoint='http://127.0.0.1:{}'.format(ethereum_config['rpc']), keystore_path=ethereum_config['keystore'], address=ethereum_config['address'], ) for option in app.params: if option.name in args.keys(): args[option.name] = option.process_value(ctx, args[option.name]) else: args[option.name] = option.default password_file = os.path.join(args['keystore_path'], 'password') with open(password_file, 'w') as handler: handler.write('password') args['mapped_socket'] = None args['password_file'] = click.File()(password_file) args['datadir'] = args['keystore_path'] args['api_address'] = 'localhost:' + str( next(get_free_port('127.0.0.1', 5001))) args['sync_check'] = False # invoke the raiden app app_ = ctx.invoke(app, **args) raiden_api = RaidenAPI(app_.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api) (api_host, api_port) = split_endpoint(args['api_address']) api_server.start(api_host, api_port) success = False try: print('[4/5] running smoketests...') error = run_smoketests(app_.raiden, smoketest_config, debug=debug) if error is not None: append_report('smoketest assertion error', error) else: success = True finally: app_.stop() ethereum.send_signal(2) err, out = ethereum.communicate() append_report('geth init stdout', ethereum_config['init_log_out'].decode('utf-8')) append_report('geth init stderr', ethereum_config['init_log_err'].decode('utf-8')) append_report('ethereum stdout', out) append_report('ethereum stderr', err) append_report('smoketest configuration', json.dumps(smoketest_config)) if success: print('[5/5] smoketest successful, report was written to {}'.format( report_file)) else: print('[5/5] smoketest had errors, report was written to {}'.format( report_file)) sys.exit(1)
def _run_smoketest(): print_step('Starting Raiden') config = deepcopy(App.DEFAULT_CONFIG) if args.get('extra_config', dict()): merge_dict(config, args['extra_config']) del args['extra_config'] args['config'] = config raiden_stdout = StringIO() with contextlib.redirect_stdout(raiden_stdout): app = run_app(**args) try: raiden_api = RaidenAPI(app.raiden) rest_api = RestAPI(raiden_api) (api_host, api_port) = split_endpoint(args['api_address']) api_server = APIServer(rest_api, config={ 'host': api_host, 'port': api_port }) api_server.start() block = app.raiden.get_block_number( ) + DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS # Proxies now use the confirmed block hash to query the chain for # prerequisite checks. Wait a bit here to make sure that the confirmed # block hash contains the deployed token network or else things break wait_for_block( raiden=app.raiden, block_number=block, retry_timeout=1.0, ) raiden_api.channel_open( registry_address=contract_addresses[ CONTRACT_TOKEN_NETWORK_REGISTRY], token_address=to_canonical_address(token.contract.address), partner_address=to_canonical_address(TEST_PARTNER_ADDRESS), ) raiden_api.set_total_channel_deposit( contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY], to_canonical_address(token.contract.address), to_canonical_address(TEST_PARTNER_ADDRESS), TEST_DEPOSIT_AMOUNT, ) token_addresses = [to_checksum_address(token.contract.address)] success = False print_step('Running smoketest') error = run_smoketests( app.raiden, args['transport'], token_addresses, contract_addresses[CONTRACT_ENDPOINT_REGISTRY], debug=debug, orig_stdout=stdout, ) if error is not None: append_report('Smoketest assertion error', error) else: success = True finally: app.stop() app.raiden.get() node = ethereum[0] node.send_signal(2) err, out = node.communicate() append_report('Ethereum stdout', out) append_report('Ethereum stderr', err) append_report('Raiden Node stdout', raiden_stdout.getvalue()) if success: print_step(f'Smoketest successful') else: print_step(f'Smoketest had errors', error=True) return success
def run(ctx, **kwargs): if ctx.invoked_subcommand is None: from raiden.api.python import RaidenAPI from raiden.ui.console import Console slogging.configure( kwargs['logging'], log_json=kwargs['log_json'], log_file=kwargs['logfile'] ) # TODO: # - Ask for confirmation to quit if there are any locked transfers that did # not timeout. (listen_host, listen_port) = split_endpoint(kwargs['listen_address']) try: with socket_factory(listen_host, listen_port) as mapped_socket: kwargs['mapped_socket'] = mapped_socket app_ = ctx.invoke(app, **kwargs) domain_list = [] if kwargs['rpccorsdomain']: if ',' in kwargs['rpccorsdomain']: for domain in kwargs['rpccorsdomain'].split(','): domain_list.append(str(domain)) else: domain_list.append(str(kwargs['rpccorsdomain'])) if ctx.params['rpc']: raiden_api = RaidenAPI(app_.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer( rest_api, cors_domain_list=domain_list, web_ui=ctx.params['web_ui'], ) (api_host, api_port) = split_endpoint(kwargs["api_address"]) api_server.start(api_host, api_port) print( "The Raiden API RPC server is now running at http://{}:{}/.\n\n" "See the Raiden documentation for all available endpoints at\n" "https://github.com/raiden-network/raiden/blob/master" "/docs/Rest-Api.rst".format( api_host, api_port, ) ) if ctx.params['console']: console = Console(app_) console.start() # wait for interrupt event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) gevent.signal(signal.SIGUSR1, toogle_cpu_profiler) gevent.signal(signal.SIGUSR2, toggle_trace_profiler) event.wait() try: api_server.stop() except NameError: pass except socket.error as v: if v.args[0] == errno.EADDRINUSE: print("ERROR: Address %s:%s is in use. " "Use --listen-address <host:port> to specify port to listen on." % (listen_host, listen_port)) sys.exit(1) raise app_.stop(leave_channels=False) else: # Pass parsed args on to subcommands. ctx.obj = kwargs
def run(ctx, **kwargs): # pylint: disable=too-many-locals,too-many-branches,too-many-statements if ctx.invoked_subcommand is None: print('Welcome to Raiden, version {}!'.format( get_system_spec()['raiden'])) from raiden.ui.console import Console from raiden.api.python import RaidenAPI slogging.configure(kwargs['logging'], log_json=kwargs['log_json'], log_file=kwargs['logfile']) if kwargs['logfile']: # Disable stream logging root = slogging.getLogger() for handler in root.handlers: if isinstance(handler, slogging.logging.StreamHandler): root.handlers.remove(handler) break # TODO: # - Ask for confirmation to quit if there are any locked transfers that did # not timeout. (listen_host, listen_port) = split_endpoint(kwargs['listen_address']) try: with SocketFactory(listen_host, listen_port, strategy=kwargs['nat']) as mapped_socket: kwargs['mapped_socket'] = mapped_socket app_ = ctx.invoke(app, **kwargs) domain_list = [] if kwargs['rpccorsdomain']: if ',' in kwargs['rpccorsdomain']: for domain in kwargs['rpccorsdomain'].split(','): domain_list.append(str(domain)) else: domain_list.append(str(kwargs['rpccorsdomain'])) if ctx.params['rpc']: raiden_api = RaidenAPI(app_.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer( rest_api, cors_domain_list=domain_list, web_ui=ctx.params['web_ui'], eth_rpc_endpoint=ctx.params['eth_rpc_endpoint'], ) (api_host, api_port) = split_endpoint(kwargs['api_address']) api_server.start(api_host, api_port) print( 'The Raiden API RPC server is now running at http://{}:{}/.\n\n' 'See the Raiden documentation for all available endpoints at\n' 'http://raiden-network.readthedocs.io/en/stable/rest_api.html' .format( api_host, api_port, )) if ctx.params['console']: console = Console(app_) console.start() # wait for interrupt event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) gevent.signal(signal.SIGUSR1, toogle_cpu_profiler) gevent.signal(signal.SIGUSR2, toggle_trace_profiler) event.wait() print('Signal received. Shutting down ...') try: api_server.stop() except NameError: pass except socket.error as v: if v.args[0] == errno.EADDRINUSE: print( 'ERROR: Address %s:%s is in use. ' 'Use --listen-address <host:port> to specify port to listen on.' % (listen_host, listen_port)) sys.exit(1) raise app_.stop(leave_channels=False) else: # Pass parsed args on to subcommands. ctx.obj = kwargs
self._mine_new_block_try() return channel def get_new_events(self): while self.event_queue.empty(): sleep(1) event_list = self._consume_event_queue() self._mine_new_block_try() return event_list def transfer(self): raise NotImplementedError() def exchange(self): raise NotImplementedError() def expect_exchange(self): raise NotImplementedError() if __name__ == '__main__': mock_api = MockAPI() rest_api = RestAPI(mock_api) api_server = APIServer(rest_api) api_server._add_default_resources() api_server.run(5001, debug=True)
def _start_services(self): from raiden.api.python import RaidenAPI config = deepcopy(App.DEFAULT_CONFIG) config["reveal_timeout"] = self._options["default_reveal_timeout"] config["settle_timeout"] = self._options["default_settle_timeout"] if self._options.get("extra_config", dict()): merge_dict(config, self._options["extra_config"]) del self._options["extra_config"] self._options["config"] = config if self._options["showconfig"]: print("Configuration Dump:") dump_config(config) dump_cmd_options(self._options) dump_module("settings", settings) dump_module("constants", constants) # this catches exceptions raised when waiting for the stalecheck to complete try: app_ = run_app(**self._options) except (ConnectionError, ConnectTimeout, RequestsConnectionError): print(ETHEREUM_NODE_COMMUNICATION_ERROR) sys.exit(1) except RuntimeError as e: click.secho(str(e), fg="red") sys.exit(1) except EthNodeInterfaceError as e: click.secho(str(e), fg="red") sys.exit(1) tasks = [app_.raiden] # RaidenService takes care of Transport and AlarmTask domain_list = [] if self._options["rpccorsdomain"]: if "," in self._options["rpccorsdomain"]: for domain in self._options["rpccorsdomain"].split(","): domain_list.append(str(domain)) else: domain_list.append(str(self._options["rpccorsdomain"])) self._raiden_api = RaidenAPI(app_.raiden) if self._options["rpc"]: rest_api = RestAPI(self._raiden_api) (api_host, api_port) = split_endpoint(self._options["api_address"]) if not api_port: api_port = Port(settings.DEFAULT_HTTP_SERVER_PORT) api_server = APIServer( rest_api, config={"host": api_host, "port": api_port}, cors_domain_list=domain_list, web_ui=self._options["web_ui"], eth_rpc_endpoint=self._options["eth_rpc_endpoint"], ) try: api_server.start() except APIServerPortInUseError: click.secho( f"ERROR: API Address {api_host}:{api_port} is in use. " f"Use --api-address <host:port> to specify a different port.", fg="red", ) sys.exit(1) print( "The Raiden API RPC server is now running at http://{}:{}/.\n\n" "See the Raiden documentation for all available endpoints at\n" "http://raiden-network.readthedocs.io/en/stable/rest_api.html".format( api_host, api_port ) ) tasks.append(api_server) if self._options["console"]: from raiden.ui.console import Console console = Console(app_) console.start() tasks.append(console) # spawn a greenlet to handle the version checking version = get_system_spec()["raiden"] tasks.append(gevent.spawn(check_version, version)) # spawn a greenlet to handle the gas reserve check tasks.append(gevent.spawn(check_gas_reserve, app_.raiden)) # spawn a greenlet to handle the periodic check for the network id tasks.append( gevent.spawn( check_network_id, app_.raiden.rpc_client.chain_id, app_.raiden.rpc_client.web3 ) ) spawn_user_deposit_task = app_.user_deposit and ( self._options["pathfinding_service_address"] or self._options["enable_monitoring"] ) if spawn_user_deposit_task: # spawn a greenlet to handle RDN deposits check tasks.append(gevent.spawn(check_rdn_deposits, app_.raiden, app_.user_deposit)) # spawn a greenlet to handle the functions self._startup_hook() # wait for interrupt event: "AsyncResult[None]" = AsyncResult() def sig_set(sig=None, _frame=None): event.set(sig) gevent.signal(signal.SIGQUIT, sig_set) gevent.signal(signal.SIGTERM, sig_set) gevent.signal(signal.SIGINT, sig_set) # quit if any task exits, successfully or not for task in tasks: task.link(event) try: event.get() print("Signal received. Shutting down ...") except (ConnectionError, ConnectTimeout, RequestsConnectionError): print(ETHEREUM_NODE_COMMUNICATION_ERROR) sys.exit(1) except RaidenError as ex: click.secho(f"FATAL: {ex}", fg="red") except Exception as ex: file = NamedTemporaryFile( "w", prefix=f"raiden-exception-{datetime.utcnow():%Y-%m-%dT%H-%M}", suffix=".txt", delete=False, ) with file as traceback_file: traceback.print_exc(file=traceback_file) click.secho( f"FATAL: An unexpected exception occured. " f"A traceback has been written to {traceback_file.name}\n" f"{ex}", fg="red", ) finally: self._shutdown_hook() app_.stop() def stop_task(task): try: if isinstance(task, Runnable): task.stop() else: task.kill() finally: task.get() # re-raise gevent.joinall( [gevent.spawn(stop_task, task) for task in tasks], app_.config.get("shutdown_timeout", settings.DEFAULT_SHUTDOWN_TIMEOUT), raise_error=True, ) return app_
def _run_app(self): from raiden.ui.console import Console from raiden.api.python import RaidenAPI # this catches exceptions raised when waiting for the stalecheck to complete try: app_ = run_app(**self._options) except EthNodeCommunicationError: print( '\n' 'Could not contact the ethereum node through JSON-RPC.\n' 'Please make sure that JSON-RPC is enabled for these interfaces:\n' '\n' ' eth_*, net_*, web3_*\n' '\n' 'geth: https://github.com/ethereum/go-ethereum/wiki/Management-APIs\n', ) sys.exit(1) domain_list = [] if self._options['rpccorsdomain']: if ',' in self._options['rpccorsdomain']: for domain in self._options['rpccorsdomain'].split(','): domain_list.append(str(domain)) else: domain_list.append(str(self._options['rpccorsdomain'])) self._raiden_api = RaidenAPI(app_.raiden) api_server = None if self._options['rpc']: rest_api = RestAPI(self._raiden_api) api_server = APIServer( rest_api, cors_domain_list=domain_list, web_ui=self._options['web_ui'], eth_rpc_endpoint=self._options['eth_rpc_endpoint'], ) (api_host, api_port) = split_endpoint(self._options['api_address']) try: api_server.start(api_host, api_port) except APIServerPortInUseError: print( 'ERROR: API Address %s:%s is in use. ' 'Use --api-address <host:port> to specify port to listen on.' % (api_host, api_port), ) sys.exit(1) print( 'The Raiden API RPC server is now running at http://{}:{}/.\n\n' 'See the Raiden documentation for all available endpoints at\n' 'http://raiden-network.readthedocs.io/en/stable/rest_api.html'. format( api_host, api_port, ), ) if self._options['console']: console = Console(app_) console.start() # spawn a greenlet to handle the version checking gevent.spawn(check_version) # spawn a greenlet to handle the gas reserve check gevent.spawn(check_gas_reserve, app_.raiden) self._startup_hook() # wait for interrupt event = RaidenGreenletEvent() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) try: event.wait() print('Signal received. Shutting down ...') except RaidenError as ex: click.secho(f'FATAL: {ex}', fg='red') except Exception as ex: with NamedTemporaryFile( 'w', prefix= f'raiden-exception-{datetime.utcnow():%Y-%m-%dT%H-%M}', suffix='.txt', delete=False, ) as traceback_file: traceback.print_exc(file=traceback_file) click.secho( f'FATAL: An unexpected exception occured. ' f'A traceback has been written to {traceback_file.name}\n' f'{ex}', fg='red', ) finally: self._shutdown_hook() if api_server: api_server.stop() return app_
def _run_smoketest(): print_step('Starting Raiden') # invoke the raiden app app = run_app(**args) raiden_api = RaidenAPI(app.raiden) rest_api = RestAPI(raiden_api) api_server = APIServer(rest_api) (api_host, api_port) = split_endpoint(args['api_address']) api_server.start(api_host, api_port) raiden_api.channel_open( contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY], to_canonical_address(token.contract.address), to_canonical_address(TEST_PARTNER_ADDRESS), None, None, ) raiden_api.set_total_channel_deposit( contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY], to_canonical_address(token.contract.address), to_canonical_address(TEST_PARTNER_ADDRESS), TEST_DEPOSIT_AMOUNT, ) smoketest_config['contracts'][ 'registry_address'] = to_checksum_address( contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY], ) smoketest_config['contracts'][ 'secret_registry_address'] = to_checksum_address( contract_addresses[CONTRACT_SECRET_REGISTRY], ) smoketest_config['contracts'][ 'discovery_address'] = to_checksum_address( contract_addresses[CONTRACT_ENDPOINT_REGISTRY], ) smoketest_config['contracts']['token_address'] = to_checksum_address( token.contract.address, ) success = False try: print_step('Running smoketest') error = run_smoketests(app.raiden, smoketest_config, debug=debug) if error is not None: append_report('Smoketest assertion error', error) else: success = True finally: app.stop() ethereum.send_signal(2) err, out = ethereum.communicate() append_report('Ethereum init stdout', ethereum_config['init_log_out'].decode('utf-8')) append_report('Ethereum init stderr', ethereum_config['init_log_err'].decode('utf-8')) append_report('Ethereum stdout', out) append_report('Ethereum stderr', err) append_report('Smoketest configuration', json.dumps(smoketest_config)) if success: print_step( f'Smoketest successful, report was written to {report_file}') else: print_step( f'Smoketest had errors, report was written to {report_file}', error=True) return success
def run_smoketest( print_step: Callable, append_report: Callable, args: Dict[str, Any], contract_addresses: List[Address], token: ContractProxy, debug: bool, ethereum_nodes: List[HTTPExecutor], ): print_step('Starting Raiden') config = deepcopy(App.DEFAULT_CONFIG) extra_config = args.pop('extra_config', None) if extra_config: merge_dict(config, extra_config) args['config'] = config # Should use basic routing in the smoke test for now # TODO: If we ever utilize a PFS in the smoke test we # need to use the deployed service registry, register the # PFS service there and then change this argument. args['routing_mode'] = RoutingMode.BASIC raiden_stdout = StringIO() maybe_redirect_stdout = contextlib.redirect_stdout(raiden_stdout) if debug: maybe_redirect_stdout = contextlib.nullcontext() with maybe_redirect_stdout: success = False app = None try: app = run_app(**args) raiden_api = RaidenAPI(app.raiden) rest_api = RestAPI(raiden_api) (api_host, api_port) = split_endpoint(args['api_address']) api_server = APIServer(rest_api, config={ 'host': api_host, 'port': api_port }) api_server.start() block = app.raiden.get_block_number( ) + DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS # Proxies now use the confirmed block hash to query the chain for # prerequisite checks. Wait a bit here to make sure that the confirmed # block hash contains the deployed token network or else things break wait_for_block( raiden=app.raiden, block_number=block, retry_timeout=1.0, ) raiden_api.channel_open( registry_address=contract_addresses[ CONTRACT_TOKEN_NETWORK_REGISTRY], token_address=to_canonical_address(token.contract.address), partner_address=to_canonical_address(TEST_PARTNER_ADDRESS), ) raiden_api.set_total_channel_deposit( contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY], to_canonical_address(token.contract.address), to_canonical_address(TEST_PARTNER_ADDRESS), TEST_DEPOSIT_AMOUNT, ) token_addresses = [to_checksum_address(token.contract.address)] print_step('Running smoketest') error = smoketest_perform_tests( app.raiden, args['transport'], token_addresses, contract_addresses[CONTRACT_ENDPOINT_REGISTRY], ) if error is not None: append_report('Smoketest assertion error', error) else: success = True except: # noqa pylint: disable=bare-except if debug: import pdb # The pylint comment is required when pdbpp is installed pdb.post_mortem() # pylint: disable=no-member else: error = traceback.format_exc() append_report('Smoketest execution error', error) finally: if app is not None: app.stop() app.raiden.get() node_executor = ethereum_nodes[0] node = node_executor.process node.send_signal(signal.SIGINT) try: node.wait(10) except TimeoutExpired: print_step('Ethereum node shutdown unclean, check log!', error=True) node.kill() if isinstance(node_executor.stdio, tuple): logfile = node_executor.stdio[1] logfile.flush() logfile.seek(0) append_report('Ethereum Node log output', logfile.read()) append_report('Raiden Node stdout', raiden_stdout.getvalue()) if success: print_step(f'Smoketest successful') else: print_step(f'Smoketest had errors', error=True) return success
def _start_services(self): from raiden.ui.console import Console from raiden.api.python import RaidenAPI config = deepcopy(App.DEFAULT_CONFIG) if self._options.get('extra_config', dict()): merge_dict(config, self._options['extra_config']) del self._options['extra_config'] self._options['config'] = config if self._options['showconfig']: print('Configuration Dump:') dump_config(config) dump_cmd_options(self._options) dump_module('settings', settings) dump_module('constants', constants) # this catches exceptions raised when waiting for the stalecheck to complete try: app_ = run_app(**self._options) except (EthNodeCommunicationError, RequestsConnectionError): print(ETHEREUM_NODE_COMMUNICATION_ERROR) sys.exit(1) except EthNodeInterfaceError as e: click.secho(str(e), fg='red') sys.exit(1) tasks = [app_.raiden] # RaidenService takes care of Transport and AlarmTask domain_list = [] if self._options['rpccorsdomain']: if ',' in self._options['rpccorsdomain']: for domain in self._options['rpccorsdomain'].split(','): domain_list.append(str(domain)) else: domain_list.append(str(self._options['rpccorsdomain'])) self._raiden_api = RaidenAPI(app_.raiden) if self._options['rpc']: rest_api = RestAPI(self._raiden_api) api_server = APIServer( rest_api, cors_domain_list=domain_list, web_ui=self._options['web_ui'], eth_rpc_endpoint=self._options['eth_rpc_endpoint'], ) (api_host, api_port) = split_endpoint(self._options['api_address']) try: api_server.start(api_host, api_port) except APIServerPortInUseError: click.secho( f'ERROR: API Address {api_host}:{api_port} is in use. ' f'Use --api-address <host:port> to specify a different port.', fg='red', ) sys.exit(1) print( 'The Raiden API RPC server is now running at http://{}:{}/.\n\n' 'See the Raiden documentation for all available endpoints at\n' 'http://raiden-network.readthedocs.io/en/stable/rest_api.html'.format( api_host, api_port, ), ) tasks.append(api_server) if self._options['console']: console = Console(app_) console.start() tasks.append(console) # spawn a greenlet to handle the version checking version = get_system_spec()['raiden'] if version is not None: tasks.append(gevent.spawn(check_version, version)) # spawn a greenlet to handle the gas reserve check tasks.append(gevent.spawn(check_gas_reserve, app_.raiden)) self._startup_hook() # wait for interrupt event = AsyncResult() def sig_set(sig=None, _frame=None): event.set(sig) gevent.signal(signal.SIGQUIT, sig_set) gevent.signal(signal.SIGTERM, sig_set) gevent.signal(signal.SIGINT, sig_set) # quit if any task exits, successfully or not for task in tasks: task.link(event) try: event.get() print('Signal received. Shutting down ...') except (EthNodeCommunicationError, RequestsConnectionError): print(ETHEREUM_NODE_COMMUNICATION_ERROR) sys.exit(1) except RaidenError as ex: click.secho(f'FATAL: {ex}', fg='red') except Exception as ex: with NamedTemporaryFile( 'w', prefix=f'raiden-exception-{datetime.utcnow():%Y-%m-%dT%H-%M}', suffix='.txt', delete=False, ) as traceback_file: traceback.print_exc(file=traceback_file) click.secho( f'FATAL: An unexpected exception occured. ' f'A traceback has been written to {traceback_file.name}\n' f'{ex}', fg='red', ) finally: self._shutdown_hook() def stop_task(task): try: if isinstance(task, Runnable): task.stop() else: task.kill() finally: task.get() # re-raise gevent.joinall( [gevent.spawn(stop_task, task) for task in tasks], app_.config.get('shutdown_timeout', settings.DEFAULT_SHUTDOWN_TIMEOUT), raise_error=True, ) return app_
def _start_services(self): from raiden.ui.console import Console from raiden.api.python import RaidenAPI config = deepcopy(App.DEFAULT_CONFIG) if self._options.get('extra_config', dict()): merge_dict(config, self._options['extra_config']) del self._options['extra_config'] self._options['config'] = config if self._options['showconfig']: print('Configuration Dump:') dump_config(config) dump_cmd_options(self._options) dump_module('settings', settings) dump_module('constants', constants) # this catches exceptions raised when waiting for the stalecheck to complete try: app_ = run_app(**self._options) except (EthNodeCommunicationError, RequestsConnectionError): print(ETHEREUM_NODE_COMMUNICATION_ERROR) sys.exit(1) except RuntimeError as e: click.secho(str(e), fg='red') sys.exit(1) except EthNodeInterfaceError as e: click.secho(str(e), fg='red') sys.exit(1) tasks = [app_.raiden ] # RaidenService takes care of Transport and AlarmTask domain_list = [] if self._options['rpccorsdomain']: if ',' in self._options['rpccorsdomain']: for domain in self._options['rpccorsdomain'].split(','): domain_list.append(str(domain)) else: domain_list.append(str(self._options['rpccorsdomain'])) self._raiden_api = RaidenAPI(app_.raiden) if self._options['discoverable']: node_address = to_checksum_address(self._raiden_api.address) rns_domain = None if self._options['rnsdomain']: rns_domain = self._options['rnsdomain'] try: rns_resolved_address = self._raiden_api.raiden.chain.get_address_from_rns( self._options['rnsdomain']) if rns_resolved_address == RNS_ADDRESS_ZERO: click.secho( 'Cannot register into the Lumino Explorer. Your RNS domain is not registered' ) sys.exit(1) elif rns_resolved_address != node_address: click.secho( 'Cannot register into the Lumino Explorer. Your RNS domain does not match with the node RSK address. The RNS domain is owned by ' + rns_resolved_address) sys.exit(1) except BadFunctionCallOutput: click.secho( "Unable to interact with RNS Public Resolver. Your node will be registered without RNS domain." ) register(node_address, rns_domain) else: if self._options['rnsdomain']: try: self._raiden_api.raiden.chain.get_address_from_rns( self._options['rnsdomain']) except BadFunctionCallOutput: click.secho( "Unable to interact with RNS Public Resolver. Please check youre interacting with the correct contract." ) sys.exit(1) self._raiden_api = RaidenAPI(app_.raiden) if self._options['rpc']: rest_api = RestAPI(self._raiden_api) (api_host, api_port) = split_endpoint(self._options['api_address']) api_server = APIServer( rest_api, config={ 'host': api_host, 'port': api_port, 'rnsdomain': self._options['rnsdomain'], 'rskendpoint': self._options['eth_rpc_endpoint'] }, cors_domain_list=domain_list, web_ui=self._options['web_ui'], eth_rpc_endpoint=self._options['eth_rpc_endpoint'], ) try: api_server.start() except APIServerPortInUseError: click.secho( f'ERROR: API Address {api_host}:{api_port} is in use. ' f'Use --api-address <host:port> to specify a different port.', fg='red', ) sys.exit(1) print( 'The Lumino API RPC server is now running at http://{}:{}/.\n\n' .format( api_host, api_port, ), ) tasks.append(api_server) if self._options['console']: console = Console(app_) console.start() tasks.append(console) # spawn a greenlet to handle the version checking version = get_system_spec()['raiden'] tasks.append(gevent.spawn(check_version, version)) # spawn a greenlet to handle the gas reserve check tasks.append(gevent.spawn(check_gas_reserve, app_.raiden)) self._startup_hook() # wait for interrupt event = AsyncResult() def sig_set(sig=None, _frame=None): event.set(sig) gevent.signal(signal.SIGQUIT, sig_set) gevent.signal(signal.SIGTERM, sig_set) gevent.signal(signal.SIGINT, sig_set) # quit if any task exits, successfully or not for task in tasks: task.link(event) try: event.get() print('Signal received. Shutting down ...') except (EthNodeCommunicationError, RequestsConnectionError): print(ETHEREUM_NODE_COMMUNICATION_ERROR) sys.exit(1) except RaidenError as ex: click.secho(f'FATAL: {ex}', fg='red') except Exception as ex: file = NamedTemporaryFile( 'w', prefix=f'raiden-exception-{datetime.utcnow():%Y-%m-%dT%H-%M}', suffix='.txt', delete=False, ) with file as traceback_file: traceback.print_exc(file=traceback_file) click.secho( f'FATAL: An unexpected exception occured. ' f'A traceback has been written to {traceback_file.name}\n' f'{ex}', fg='red', ) finally: self._shutdown_hook() def stop_task(task): try: if isinstance(task, Runnable): task.stop() else: task.kill() finally: task.get() # re-raise gevent.joinall( [gevent.spawn(stop_task, task) for task in tasks], app_.config.get('shutdown_timeout', settings.DEFAULT_SHUTDOWN_TIMEOUT), raise_error=True, ) return app_