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 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) api_server.flask_app.config['SERVER_NAME'] = 'localhost:{}'.format(port_number) api_server.start(port=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(port_number) return api_server
def _run_app(): # this catches exceptions raised when waiting for the stalecheck to complete try: app_ = ctx.invoke(app, **kwargs) 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 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']) 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 ctx.params['console']: console = Console(app_) console.start() # spawning a thread to handle the version checking gevent.spawn(check_version) # 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) 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='raiden-exception', 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', ) if api_server: api_server.stop() return app_
def _run_smoketest(): print_step('Starting Raiden') # 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) 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('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): try: # 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 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() 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_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() 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, ) 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 _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['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'] 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 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) 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 args["one_to_n_contract_address"] = None 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 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.run(5001, debug=True)
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( 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, ) 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 _start_services(self): 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["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 }, 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.chain.network_id, app_.raiden.chain.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() 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_
def _run_app(): # this catches exceptions raised when waiting for the stalecheck to complete try: app_ = ctx.invoke(app, **kwargs) except EthNodeCommunicationError: 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']) 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 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() print('Signal received. Shutting down ...') if api_server: api_server.stop() return app_
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'])) 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" "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() try: api_server.stop() except NameError: pass app_.stop(leave_channels=False)
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') 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 _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['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'] 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_
def run_smoketest( print_step: Callable, args: Dict[str, Any], contract_addresses: Dict[str, Address], token: ContractProxy, ): print_step("Starting Raiden") app = None api_server = 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=TokenNetworkRegistryAddress( contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY]), token_address=TokenAddress( to_canonical_address(token.contract.address)), partner_address=ConnectionManager.BOOTSTRAP_ADDR, ) raiden_api.set_total_channel_deposit( registry_address=TokenNetworkRegistryAddress( contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY]), token_address=TokenAddress( to_canonical_address(token.contract.address)), partner_address=ConnectionManager.BOOTSTRAP_ADDR, total_deposit=TEST_DEPOSIT_AMOUNT, ) token_addresses = [to_checksum_address(token.contract.address)] print_step("Running smoketest") raiden_service = app.raiden token_network_added_events = raiden_service.default_registry.filter_token_added_events( ) events_token_addresses = [ event["args"]["token_address"] for event in token_network_added_events ] assert events_token_addresses == token_addresses token_networks = views.get_token_identifiers( views.state_from_raiden(raiden_service), raiden_service.default_registry.address) assert len(token_networks) == 1 channel_state = views.get_channelstate_for( chain_state=views.state_from_raiden(raiden_service), token_network_registry_address=raiden_service.default_registry. address, token_address=token_networks[0], partner_address=ConnectionManager.BOOTSTRAP_ADDR, ) assert channel_state distributable = channel.get_distributable(channel_state.our_state, channel_state.partner_state) assert distributable == TEST_DEPOSIT_AMOUNT assert distributable == channel_state.our_state.contract_balance assert channel.get_status(channel_state) == ChannelState.STATE_OPENED port_number = raiden_service.config["api_port"] response = requests.get( f"http://localhost:{port_number}/api/v1/channels") assert response.status_code == HTTPStatus.OK response_json = json.loads(response.content) assert response_json[0]["partner_address"] == to_checksum_address( ConnectionManager.BOOTSTRAP_ADDR) assert response_json[0]["state"] == "opened" assert response_json[0]["balance"] > 0 finally: if api_server is not None: api_server.stop() api_server.get() if app is not None: app.stop() app.raiden.get()