def run_server(): """Configure and launch the API server.""" log_level = Conf.log_level() config.debug = (log_level == logging.DEBUG) logging.basicConfig(level=log_level) logger = logging.getLogger(__name__) logging.getLogger('jsonrpcserver.dispatcher.response').setLevel(log_level) methods = build_methods() app = web.Application() app['config'] = dict() app['config']['args'] = Conf.args() app['config']['hive.MAX_DB_ROW_RESULTS'] = 100000 app['config'][ 'hive.DB_QUERY_LIMIT'] = app['config']['hive.MAX_DB_ROW_RESULTS'] + 1 app['config']['hive.logger'] = logger #async def init_db(app): # args = app['config']['args'] # db = make_url(args.database_url) # engine = await create_engine(user=db.username, # database=db.database, # password=db.password, # host=db.host, # port=db.port, # **db.query) # app['db'] = engine # #async def close_db(app): # app['db'].close() # await app['db'].wait_closed() # #app.on_startup.append(init_db) #app.on_cleanup.append(close_db) async def head_age(request): """Get hive head block age in seconds. 500 if greater than 15s.""" #pylint: disable=unused-argument healthy_age = 15 # hive is synced if head block within 15s curr_age = (await hive_api.db_head_state())['db_head_age'] status = 500 if curr_age > healthy_age else 200 return web.Response(status=status, text=str(curr_age)) async def health(request): """Get hive health data. 500 if behind by more than a few secs.""" #pylint: disable=unused-argument is_syncer = Conf.get('sync_to_s3') max_head_age = (Conf.get('trail_blocks') + 1) * 3 try: state = await hive_api.db_head_state() except OperationalError as e: if 'could not connect to server: Connection refused' in str(e): logging.error("hive /health could not connect to db") state = None else: raise e if not state: status = 500 result = 'db not available' elif not is_syncer and state['db_head_age'] > max_head_age: status = 500 result = 'head block age (%s) > max (%s); head block num: %s' % ( state['db_head_age'], max_head_age, state['db_head_block']) else: status = 200 result = 'head block age is %d, head block num is %d' % ( state['db_head_age'], state['db_head_block']) return web.json_response( status=status, data=dict(state=state, result=result, status='OK' if status == 200 else 'WARN', sync_service=is_syncer, source_commit=os.environ.get('SOURCE_COMMIT'), schema_hash=os.environ.get('SCHEMA_HASH'), docker_tag=os.environ.get('DOCKER_TAG'), timestamp=datetime.utcnow().isoformat())) async def jsonrpc_handler(request): """Handles all hive jsonrpc API requests.""" request = await request.text() response = await methods.dispatch(request) return web.json_response(response, status=200, headers={'Access-Control-Allow-Origin': '*'}) app.router.add_get('/.well-known/healthcheck.json', health) app.router.add_get('/head_age', head_age) app.router.add_get('/health', health) app.router.add_post('/', jsonrpc_handler) web.run_app(app, port=app['config']['args'].http_server_port)
def run_server(): log_level = Conf.log_level() config.debug = (log_level == logging.DEBUG) logging.basicConfig(level=log_level) logger = logging.getLogger(__name__) logging.getLogger('jsonrpcserver.dispatcher.response').setLevel(log_level) methods = build_methods() app = web.Application() app['config'] = dict() app['config']['args'] = Conf.args() app['config']['hive.MAX_DB_ROW_RESULTS'] = 100000 app['config'][ 'hive.DB_QUERY_LIMIT'] = app['config']['hive.MAX_DB_ROW_RESULTS'] + 1 app['config']['hive.logger'] = logger async def init_db(app): args = app['config']['args'] db = make_url(args.database_url) engine = await create_engine(user=db.username, database=db.database, password=db.password, host=db.host, port=db.port, **db.query) app['db'] = engine async def close_db(app): app['db'].close() await app['db'].wait_closed() app.on_startup.append(init_db) app.on_cleanup.append(close_db) async def health(request): #pylint: disable=unused-argument state = await hive_api.db_head_state() max_head_age = (Conf.get('trail_blocks') + 1) * 3 if state['db_head_age'] > max_head_age: status = 500 result = 'head block age (%s) > max (%s); head block num: %s' % ( state['db_head_age'], max_head_age, state['db_head_block']) else: status = 200 result = 'head block age is %d, head block num is %d' % ( state['db_head_age'], state['db_head_block']) return web.json_response( status=status, data=dict(state=state, result=result, status='OK' if status == 200 else 'WARN', source_commit=os.environ.get('SOURCE_COMMIT'), schema_hash=os.environ.get('SCHEMA_HASH'), docker_tag=os.environ.get('DOCKER_TAG'), timestamp=datetime.utcnow().isoformat())) async def jsonrpc_handler(request): request = await request.text() response = await methods.dispatch(request) return web.json_response(response, status=200, headers={'Access-Control-Allow-Origin': '*'}) app.router.add_get('/health', health) app.router.add_post('/', jsonrpc_handler) web.run_app(app, port=app['config']['args'].http_server_port)