def add_check_api(): app = flask.Flask('check_api') health = HealthCheck(app, "/health") envdump = EnvironmentDump(app, "/environment") def health_check(): # TODO check that the datasource backend is working # TODO check that the active resource backends are available db_engines_ok = True maintenance = False if 1 + 1 == 2: return {'status', 'up'} elif db_engines_ok: return {'status', 'up'} elif not maintenance: return {'status', 'out_of_service'} else: return {'status', 'down'} def application_data(): return { 'maintainer': 'ElasTest', 'git_repo': 'https://github.com/elastest/elastest-service-manager' } health.add_check(health_check) envdump.add_section("application", application_data) return app
class EveHealthCheck(object): def __init__(self, app=None, healthcheck_uri='/healthcheck', *argv, **kw): self.logger = logging.getLogger(self.__module__) self.hc = HealthCheck(*argv, **kw) if app: self.init_app(app, healthcheck_uri) def init_app(self, app, healthcheck_uri='/healthcheck'): self.hc.add_check(check_wrapper(app)) uri = "{}{}".format(app.api_prefix, healthcheck_uri) app.add_url_rule(uri, uri, view_func=partial(view_health_func, self.hc), methods=['GET', 'OPTIONS']) for resource, v in app.config.get('DOMAIN', {}).items(): uri = "{}/{}{}".format(app.api_prefix, resource, healthcheck_uri) self.logger.debug("Adding uri {}".format(uri)) app.add_url_rule(uri, uri, view_func=partial(view_health_func, self.hc, resource), methods=['GET', 'OPTIONS'])
def add_check_api(): app = flask.Flask('check_api') health = HealthCheck(app, "/health") envdump = EnvironmentDump(app, "/environment") def health_check(): db_engines_ok = STORE.is_ok() # calls specific DB check resource_engine_ok = RM.is_ok() # calls specific RM check this_ok = (1 + 1 == 2) # basic local check # maintenance = False if this_ok and db_engines_ok and resource_engine_ok: return {'status', 'up'} # elif not maintenance: # return {'status', 'out_of_service'} else: return {'status', 'down'} def application_data(): return { 'maintainer': 'ElasTest', 'git_repo': 'https://github.com/elastest/elastest-service-manager' } health.add_check(health_check) envdump.add_section("application", application_data) return add_mware(app)
class HealthChecker: """ Configures a health checker """ def __init__(self, redis_storage): self._redis_store = redis_storage self._health_check = HealthCheck( failed_status=settings.HEALTH_CHECKER_FAILED_STATUS) self._health_check.add_section( 'commit', os.environ.get('HEROKU_SLUG_COMMIT', None)) self._health_check.add_section( 'release', {"version": os.environ.get('HEROKU_RELEASE_VERSION', None)}) self._health_check.add_check(self._redis_available) def _redis_available(self): try: info = self._redis_store.redis.info() except ConnectionError: return False, "Could not connect to Redis instance" except TimeoutError: return False, "Redis connection timed out" return True, info def run(self): return self._health_check.run()
def create_app(): app = connex_app app.add_api('openapi.yaml', arguments={'title': 'Provenance Service'}) # wrap the flask app and give a heathcheck url health = HealthCheck(app, "/healthcheck") health.add_check(neo4j_available) return app
def init_health_check(app): # wrap the flask app and give a heathcheck url health = HealthCheck(app, "/admin/healthcheck") envdump = EnvironmentDump(app, "/admin/environment") for check in checks: health.add_check(check) for dump in dumps: envdump.add_section(dump, dumps[dump])
def add_check_api(app): from healthcheck import HealthCheck, EnvironmentDump health = HealthCheck(app, API_PREFIX + API_HEALTHCHECK, log_on_failure=False, success_ttl=None, failed_ttl=None, failed_status=200) envdump = EnvironmentDump(app, API_PREFIX + API_ENVIRONMENT) def health_check(): try: r = requests.get(app.config['SPARK_MASTER_URL']) soup = BeautifulSoup(r.content, 'html.parser') listItems = soup.find_all('li') statusItems = [ item.text for item in listItems if 'Status:' in str(item) ] alive = True if sum(1 for item in statusItems if 'ALIVE' in str(item)) > 0 else False statusString = str(statusItems[0]) except requests.exceptions.RequestException as e: # This is the correct syntax alive = False statusString = str(e) return alive, statusString def application_data(): try: r = requests.get(app.config['SPARK_MASTER_URL']) soup = BeautifulSoup(r.content, 'html.parser') listItems = soup.find_all('li') spark = { '_'.join(k.lower().split()): " ".join(v.split()) for k, v in (item.text.replace('\n', '').split(':', 1) for item in listItems) } except requests.exceptions.RequestException as e: # This is the correct syntax spark = {'error': str(e)} return { 'spark': spark, 'maintainer': 'Savas Gioldasis ([email protected])', 'git_repo': 'https://github.com/elastest/elastest-bigdata-service', } health.add_check(health_check) envdump.add_section("application", application_data) return app
def attach_monitor(app): health = HealthCheck(app, '/status') envdump = EnvironmentDump(app, '/env', include_os=False, include_config=False, include_process=False, include_python=False) health.add_check(db_available) envdump.add_section("application", app_data)
def attach_monitor(app): """ Attach status and environment endpoints for monitoring site health """ health = HealthCheck(app, '/status') envdump = EnvironmentDump(app, '/env', include_os=False, include_config=False, include_process=False, include_python=False) health.add_check(db_available)
def __initialize_healthcheck(self, app): healthcheck_endpoint = self.config["endpoint_prefixes"]["healthcheck"] LOGGER.debug( f"Setting up healthcheck endpoint at {healthcheck_endpoint}") health = HealthCheck(app, healthcheck_endpoint) def mongo_okay(): db = get_db() stats = db.command("dbstats") return bool(stats["ok"]), "Mongo Database is UP" if stats[ "ok"] else "ERROR: Mongo Database is DOWN" health.add_check(mongo_okay)
def create_app(): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) mg.init_app(app, db) ma.init_app(app) api.init_app(app) app.cli.add_command(app_cli) health = HealthCheck(app, "/status") health.add_check(command.db_check) return app
def run_healthcheck(): """Execute healthcheck function for Document Manager to verify if it is healthy. Document Manager relies on two services being available for it to function as designed: Redis and PostgreSQL. If one is not available, or if neither are, then a ConnectionError is thrown. Successful calls will return a successful attempt at connection. """ healthcheck = HealthCheck() # Verify PostgreSQL and Redis status checks healthcheck.add_check(postgres_healthcheck) healthcheck.add_check(redis_healthcheck) return healthcheck
def register_health_check(app, db): health = HealthCheck(app, "/healthcheck") def db_available(): try: result = db.engine.execute('SELECT 1') if result: return True, 'Database OK' except Exception as e: app.logger.exception(e) return False, 'Database Issue' health.add_check(db_available)
def create_app(): app = Flask(__name__) app.config.from_object(get_env_config(os.environ.get('FLASK_ENV', 'test'))) app.register_blueprint(poem.blueprint) app.register_blueprint(hello.blueprint) # Healthcheck # TODO: can be isolated health = HealthCheck() health.add_check(dynamodb_available) app.add_url_rule("/healthcheck", "healthcheck", view_func=lambda: health.run()) return app
def health_check(app): health = HealthCheck(app, "/healthcheck") # env_dump = EnvironmentDump(app, "/environment") def db_status(): try: query_result = db.engine.execute(text("SELECT 1")) debug("oneapi-sql-logger", str(query_result)) return True, "db connection ok" except Exception as e: debug("oneapi-sql-logger", str(e)) return False, "db connection failed" health.add_check(db_status)
class BasicHealthCheckTest(unittest.TestCase): def setUp(self): self.path = '/healthcheck' self.path2 = '/healthcheck_200' self.app = flask.Flask(__name__) self.app2 = flask.Flask(__name__) self.hc = HealthCheck() self.hc2 = HealthCheck() self.client = self.app.test_client() self.client2 = self.app2.test_client() dbmongo = None service_enum = { 'mongoengine': { 'connection': dbmongo, 'lib_list': [MongoLib.MONGOENGINE] } } self.hc = HealthcheckList.setup(healthcheck = self.hc, service_list = service_enum) self.app.add_url_rule(self.path, view_func=lambda: self.hc.run()) self.app2.add_url_rule(self.path2, view_func=lambda: self.hc2.run()) def test_basic_check_success(self): response = self.client2.get(self.path2) self.assertEqual(200, response.status_code) def test_basic_check(self): response = self.client.get(self.path) Logger.info(response) self.assertEqual(500, response.status_code) def test_failing_check(self): def fail_check(): return False, "FAIL" self.hc2.add_check(fail_check) response = self.client2.get(self.path2) self.assertEqual(500, response.status_code) respon = flask.json.loads(response.data) self.assertEqual("failure", respon["status"])
def initalize_healthcheck(app): """Inject routing and route handling into the flask app""" # wrap the flask app and give a heathcheck url health = HealthCheck( app, HEALTHCHECK_PATH, success_ttl=None, success_handler=handle_success, failed_ttl=None, failed_handler=handle_failure, ) health.add_check(check_version) # Mongo Health check #health.add_check(check_mongo) return health
def main(args): prometheus_server(8081) app.config.update({'input': args.input, 'crashed': False}) health = HealthCheck() health.add_check(health_check) app.add_url_rule("/healthcheck", "healthcheck", view_func=lambda: health.run()) app.run() if app.config['crashed']: print('application crashed, exiting non-zero') sys.exit(1)
class Health(object): def __init__(self, app, endpoint='/health', checks=[]): self.health = HealthCheck(app, endpoint) # extra health checks [self.health.add_check(check) for check in checks if callable(check)]
def create_app(test_config=None): log.info("Creating python app "+__name__) flask_app = Flask(__name__) flask_app.config.update(settings.PROPS) if test_config is not None: flask_app.config.update(test_config) flask_app.register_blueprint(api_blueprint, url_prefix='/api') if test_config is None: if flask_app.config.get("COGNITO_CHECK_TOKEN_EXPIRATION") is False: log.warning("COGNITO_CHECK_TOKEN_EXPIRATION is disabled, ensure it is enabled in production environments.") if flask_app.config.get("FLASK_DEBUG") is True: log.warning("FLASK_DEBUG is enabled, ensure it is disabled in production environments.") # db initialization try: db.init_app(flask_app) except Exception as e: log.exception("Failed to initialize APP: {}".format(repr(e)), exc_info=True) # Migrations (upgrade to the latest version) with flask_app.app_context(): try: from flask_migrate import upgrade as _upgrade migrate = Migrate(flask_app, db) _upgrade() except Exception as e: log.exception("Failed to upgrade DB: {}".format(repr(e)), exc_info=True) health = HealthCheck() env_dump = EnvironmentDump(include_python=True, include_os=True, include_process=True) health.add_check(db_health) application_data = settings.application_data() # application_data['verified_aws_credentials'] = verify_aws_credentials() log.info(application_data) env_dump.add_section("application", application_data) env_dump.add_section("features", settings.features()) # Add a flask route to expose information flask_app.add_url_rule("/health", "healthcheck", view_func=lambda: health.run()) flask_app.add_url_rule("/info", "environment", view_func=lambda: env_dump.run()) return flask_app
def add_check_api(): app = flask.Flask('check_api') health = HealthCheck(app, "/healthcheck") envdump = EnvironmentDump(app, "/environment") def health_check(): # TODO check that the api backend working # TODO check that the active resource backends are available def onem2m_url_ok(): url= 'http://localhost:8000/onem2m' r = requests.response(url) return r.status_code == 200 def mems_url_ok(): url = 'http://localhost:8000/onem2m/MemsIPE' r = requests.response(url) return r.status_code == 200 #maintenance = False if 1 + 1 == 2 and onem2m_url_ok and mems_url_ok: return {'status', 'up'} #elif url_ok: # return {'status', 'up'} #elif not maintenance: # return {'status', 'out_of_service'} else: return {'status', 'down'} def application_data(): return {'maintainer': 'ElasTest', 'git_repo': 'https://github.com/elastest/elastest-device-emulator-service'} health.add_check(health_check) envdump.add_section("application", application_data) return app
succeeded += 1 celery_redis.delete(meta_key) elif status in tasks.EXCEPTION_STATES and not task_id in already_failed: new_failed.append(task_id) celery_redis.set('succeeded', succeeded) if new_failed: # Store the newly failed tasks in Redis celery_redis.lpush('failed', *new_failed) failed = list(already_failed) + new_failed return not failed, {'succeeded': succeeded, 'failed': failed} # Set up health check, don't cache results health = HealthCheck(app, '/health', success_ttl=None, failed_ttl=None) health.add_check(db_ok) health.add_check(tasks_ok) # Mount our API endpoints api.add_resource(auth.Registration, '/auth/register') api.add_resource(auth.Login, '/auth/login') api.add_resource(auth.Token, '/auth/token') api.add_resource(auth.Access, '/auth/access') api.add_resource(form.Manage, '/form') api.add_resource(form.Resolution, '/form/resolve') # UI routes auth.add_ui_routes(app) form.add_ui_routes(app) if app.config['TEST_MODE']:
@app.errorhandler(400) def bad_request(error: Exception) -> tuple: """Handle bad requests :param Exception error: Exception thrown :return: A http response :rtype: tuple """ return jsonify(_status="ERR", _error={ "code": 400, "message": str(error) }), 400 # Add environment and health check routes envdump.add_section("application", application_data) envdump.add_section("settings", application_settings) health.add_check(mongo_available) health.add_section("version", __version__) app.add_url_rule("/healthcheck", "healthcheck", view_func=health.run) app.add_url_rule("/environment", "environment", view_func=envdump.run) if __name__ != '__main__': # pragma: no cover gunicorn_logger = logging.getLogger('gunicorn.error') app.logger.handlers = gunicorn_logger.handlers logging.basicConfig(level=gunicorn_logger.level) if __name__ == "__main__": # pragma: no cover app.run(host=HOST, debug=DEBUG, port=PORT)
response.headers["Content-Type"] = "application/json" return response def _not_found_response(): response = {"code": 404, "message": "HTTP 404 Not Found"} return jsonify(response), HTTPStatus.NOT_FOUND @risk_level_api.route("/<path:invalid_path>") def _page_not_found(*args, **kwargs): return _not_found_response() casb_health = HealthCheck() casb_health.add_check(lambda: is_url_available(app.config["CASB_SAAS_URL"])) casb_health.add_check( lambda: is_login_success( app.config["CASB_SAAS_URL"], app.config["CASB_LOGIN_NAME"], app.config["CASB_LOGIN_PASSWORD"], ) ) @risk_level_api.route("/casb/healthcheck", methods=["GET"]) def _casb_risk_level_api_health_check(): if app.config["CASB_RISK_SCORE_ENABLE"]: return casb_health.run() else: return _not_found_response()
@app.before_request def track_user(): if current_user.is_authenticated: current_user.update_lat() def make_celery(app=None): app = app or create_app()[0] celery.conf.update(app.config) ext = FlaskCeleryExt(app) return ext.celery # Health-check health = HealthCheck(current_app, "/health-check") health.add_check(health_check_celery) health.add_check(health_check_db) with current_app.app_context(): current_app.config['MIGRATION_STATUS'] = check_migrations() health.add_check(health_check_migrations) # http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists @after_task_publish.connect def update_sent_state(sender=None, headers=None, **kwargs): # the task may not exist if sent using `send_task` which # sends tasks by name, so fall back to the default result backend # if that is the case. task = celery.tasks.get(sender) backend = task.backend if task else celery.backend backend.store_result(headers['id'], None, 'WAITING')
except Exception as e: pass if stop_health: return False, "Health failed" else: return True, "Health ok" def ready_check(): try: from sqlalchemy.sql import text db.session.query("1").from_statement(text("SELECT 1")).all() return True, "Ready ok" except: return True, "Not ready, database check failed." health.add_check(health_check) ready.add_check(ready_check) app.add_url_rule("/health/live", "/health/live", view_func=lambda: health.run()) app.add_url_rule("/health/ready", "/health/ready", view_func=lambda: ready.run()) if __name__ == "__main__": app.run(host="0.0.0.0", port=8083, debug=True, use_reloader=False)
health = HealthCheck() envdump = EnvironmentDump() metrics.info('app_info', 'Application info', version='1.0.3') SHEDDER_HOST = "0.0.0.0" SHEDDER_PORT = "3004" with open(r'./config.yaml') as file: locationMappings = yaml.load(file, Loader=yaml.FullLoader) def is_running(): return True, "is running" health.add_check(is_running) @app.route('/api/_cpu/updateIP', methods=['GET']) def update_ip(): url = "http://" + SHEDDER_HOST + ":" + SHEDDER_PORT + "/api/shed/updatepodslist" url = url.replace(' ', '') print("Querying api at address ", url) data = {} data['ip'] = socket.gethostbyname(socket.gethostname()) try: r = requests.post(url=url, data=data) except: print("Couldn't update shedder with the IP of this pod") return jsonify({'result': 'Sent the IP'})
def health_database(): #incase /health gives error add self is_database_working = True output = 'database is ok' try: # to check database we will execute raw query db.session.execute('SELECT 1') except Exception as e: output = str(e) is_database_working = False return is_database_working, output health.add_check(health_database) #fucntion to find the combinations of fibbonaci that add up to number num def findCombinationsUtil(arr, index, num, reducedNum, solns): fib = [0] * (num + 1) fib[1] = 1 for i in range(2, num + 1): fib[i] = fib[i - 1] + fib[i - 2] if (reducedNum < 0): return solns sum = 0 proper_c = list() if (reducedNum == 0): for n in arr: sum = sum + n
def tk_put(url, body, actor_net_id): return requests.put(url, headers={'Authorization': api_key_header(url, 'PUT', actor_net_id), 'Content-Type': 'application/json'}, data=body) def tk_delete(url, body, actor_net_id): return requests.delete(url, headers={'Authorization': api_key_header(url, 'DELETE', actor_net_id)}, data=body) def pong(): return True, "Pong" health.add_check(pong) def c_authentication(): if 'PRINCIPAL_ID' in request.headers and 'SM_USER' in request.headers: logging.debug("received an authenticated request") return True return False def abort_wrapper(code, msg=""): abort(code, message=msg) def authenticate(func): @wraps(func) def wrapper(*args, **kwargs): if not getattr(func, 'authenticated', True): return func(*args, **kwargs)
from flask import Flask from healthcheck import HealthCheck app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' health = HealthCheck(app, "/healthcheck") def app_health(): return True, "Health OK" health.add_check(app_health) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
app = Flask(__name__) config_name = os.getenv('FLASK_CONFIGURATION', 'default') app.config.from_object(config[config_name]) app.config.from_pyfile('config.cfg', silent=True) health = HealthCheck(app, "/healthcheck") envdump = EnvironmentDump(app, "/environment", include_python=True, include_os=False, include_process=False, include_config=True) def sqlite_available(): # add precise check against the database return True, "sqlite ok" health.add_check(sqlite_available) def application_data(): return {"maintainer": "Damyan Bogoev", "git_repo": "https://github.com/damyanbogoev/flask-bookshelf"} envdump.add_section("application", application_data) if __name__ == '__main__': app.run(host=os.getenv('IP', '0.0.0.0'), port=int(os.getenv('PORT', 8080)))
print("Using default debug " + str(vdebug)) app = connexion.FlaskApp(__name__, specification_dir='swagger/') app.add_api('arbolbinario.yml') CORS(app.app) health = HealthCheck() envdump = EnvironmentDump() def database_available(): return True, "database ok" health.add_check(database_available) # Add a flask route to expose information app.add_url_rule("/arbolbinario/healthcheck", "healthcheck", view_func=lambda: health.run()) app.add_url_rule("/arbolbinario/environment", "environment", view_func=lambda: envdump.run()) def run_rest_server(): app.run(host=vhost, port=vport, debug=vdebug, threaded=True,
if current_app.config['TESTING']: with app.test_request_context(): return task_base.__call__(self, *args, **kwargs) with app.app_context(): return task_base.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery celery = make_celery(current_app) # Health-check health = HealthCheck(current_app, "/health-check") envdump = EnvironmentDump(current_app, "/environment", include_config=False) health.add_check(health_check_celery) health.add_check(health_check_db) with current_app.app_context(): current_app.config['MIGRATION_STATUS'] = check_migrations() health.add_check(health_check_migrations) # http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists @after_task_publish.connect def update_sent_state(sender=None, body=None, **kwargs): # the task may not exist if sent using `send_task` which # sends tasks by name, so fall back to the default result backend # if that is the case. task = celery.tasks.get(sender) backend = task.backend if task else celery.backend backend.store_result(body['id'], None, 'WAITING')
app = Flask(__name__) health = HealthCheck(app, "/healthcheck") def website_available(): code = urllib.urlopen("http://130.211.90.87:5000").getcode() print code if code == 200: return True, "Website up" else: return False, "Something is wrong!" health.add_check(website_available) @app.route('/') def index_form(): return render_template("index.html") @app.route('/events', methods=['GET','POST']) def event_form(): if request.method == 'GET': return redirect(url_for('index_form')) name = request.form['artist'].lstrip() #Bandsintown API client = Client('bitapp') events = client.events(name)
@force_scheme('https') @homepage_blueprint.route('files', methods=['GET', 'POST']) def list_files(): path = str(request.form.get('path', '')) if request.method=='POST' \ else str(request.args.get('path', '')) files = [] if path: if not path[0]=='/': path = '/%s'%path files = list_dirs_files(path, PROJECT_ROOT) if not files: if request.method=='POST': return json.dumps({'success':True, 'ret': 'No such folder or empty'}) files = [] if request.method=='POST': return json.dumps({'success':True, 'ret':files}) return render_template( 'list_files.html', ret=files, file_scope=PROJECT_ROOT ) # set healthcheck URL from dotcom import app health = HealthCheck(app, "/statuses") health.add_check(mongo_available) health.add_check(flask_available)
description: Healthcheck extensions for app """ from healthcheck import HealthCheck, EnvironmentDump from flask import current_app from sqlalchemy.orm import scoped_session # Configure health checks def sqlalchemy_available(): "Check the SQLAlchemy engine is connected" try: db = current_app.config['SQLALCHEMY_DB'] with db.engine.connect() as connection: connection.execute('SELECT 1;') return True, 'Database connection healthy' except Exception as err: return False, 'Database connection unhealthy: {}'.format(str(err)) health = HealthCheck() health.add_check(sqlalchemy_available) # Configure env dump def application_data(): return { "maintainer": "Jess Robertson", "git_repository": "https://github.com/igsn/igsn-registry-mvp.git" } envdump = EnvironmentDump(include_process=False,) envdump.add_section("application", application_data)
app = Flask(__name__) # wrap the flask app and give a heathcheck url health = HealthCheck(app, "/healthcheck") envdump = EnvironmentDump(app, "/environment") # add your own check function to the healthcheck def redis_available(): client = _redis_client() info = client.info() return True, "redis ok" health.add_check(redis_available) # add your own data to the environment dump def application_data(): return { "maintainer": "MattPinner", "git_repo": "https://github.com/touchtechio/tensorflask" } envdump.add_section("application", application_data) @app.route('/') def hello_world():