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 create_app() -> Flask: app = Flask(__name__) # Always use dev config app.config.from_object('config_dev') # *Should* load prod config when deployed into Docker container if os.getenv('LEARN_FLASK_CONFIG') is not None: app.config.from_envvar('LEARN_FLASK_CONFIG') # Set logging log_file = app.config['LOG_LOC'] + app.config['LOG_FILE'] logging.basicConfig(level=app.config['LOG_LEVEL'], format=('%(levelname)s %(asctime)s %(name)s ' 'LrnFlsk %(threadName)s: %(message)s'), datefmt='%Y-%m-%d %H:%M:%S', filename=log_file) # Register blueprints app.register_blueprint(bye, url_prefix='/bye') app.register_blueprint(hello, url_prefix='/hello') app.register_blueprint(sqs, url_prefix='/sqs') # Setup system check endpoints health = HealthCheck() envdump = EnvironmentDump() app.add_url_rule('/healthcheck', 'healthcheck', view_func=lambda: health.run()) app.add_url_rule('/environment', 'environment', view_func=lambda: envdump.run()) return app
def test_custom_section_function_failing_check(self): hc = HealthCheck(checkers=[self.check_throws_exception]) hc.add_section("custom_section", lambda: "My custom section") message, status, headers = hc.run() self.assertEqual(500, status) jr = json.loads(message) self.assertEqual("My custom section", jr["custom_section"])
def test_custom_section_signature_value_failing_check(self): hc = HealthCheck(checkers=[self.check_throws_exception], custom_section="My custom section") message, status, headers = hc.run() self.assertEqual(500, status) jr = json.loads(message) self.assertEqual("My custom section", jr["custom_section"])
def test_custom_section_signature_value_success_check(self): hc = HealthCheck(checkers=[self.check_that_works], custom_section="My custom section") message, status, headers = hc.run() self.assertEqual(200, status) jr = json.loads(message) self.assertEqual("My custom section", jr["custom_section"])
def test_custom_section_function_success_check(self): hc = HealthCheck(checkers=[self.check_that_works]) hc.add_section("custom_section", lambda: "My custom section") message, status, headers = hc.run() self.assertEqual(200, status) jr = json.loads(message) self.assertEqual("My custom section", jr["custom_section"])
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 add_health_check(app): health = HealthCheck() envdump = EnvironmentDump() health.add_section("application", application_data) envdump.add_section("application", application_data) app.add_url_rule("/healthz", "healthcheck", view_func=lambda: health.run()) app.add_url_rule("/environment", "environment", view_func=lambda: envdump.run())
def test_custom_section_prevent_duplication(self): def broke_section(): raise Exception("My broke section") hc = HealthCheck(checkers=[self.check_adition_works], custom_section=broke_section) message, status, headers = hc.run() self.assertEqual(200, status) jr = json.loads(message) self.assertNotIn("custom_section", jr)
def get_ping(): response = {} health = HealthCheck() response['message'] = constants.hc_success (system_data, status, c_t) = health.run() response['code'] = status if status != 200: response['code'] = constants.failure_code response['message'] = constants.hc_failure return response
def test_custom_section_signature_success_check(self): def custom_section(): return "My custom section" hc = HealthCheck(checkers=[self.check_adition_works], custom_section=custom_section) message, status, headers = hc.run() self.assertEqual(200, status) jr = json.loads(message) self.assertEqual("My custom section", jr["custom_section"])
def test_default_timeout_should_success_check(self): def timeout_check(): import time time.sleep(10) return True, "Waited for 10 seconds" hc = HealthCheck(checkers=[timeout_check]) message, status, headers = hc.run() self.assertEqual(200, status) jr = json.loads(message) self.assertEqual("success", jr["status"])
def test_should_run_only_filtered_checks(self): check = 'check_that_works' hc = HealthCheck( checkers=[self.check_that_works, self.check_throws_exception]) message, status, headers = hc.run(check) self.assertEqual(200, status) jr = json.loads(message) self.assertEqual("success", jr["status"]) self.assertEqual(len(jr["results"]), 1)
def test_error_timeout_function_should_failing_check(self): def timeout_check(): import time time.sleep(5) return True, "Waited for 10 seconds" hc = HealthCheck(checkers=[timeout_check], error_timeout=2) message, status, headers = hc.run() self.assertEqual(500, status) jr = json.loads(message) self.assertEqual("failure", jr["status"])
def create_app(): app = Flask(__name__) app.config.from_object(get_env_config(os.environ.get('FLASK_ENV', 'test'))) app.register_blueprint(hello.blueprint) # Healthcheck # TODO: can be isolated health = HealthCheck() app.add_url_rule("/healthcheck", "healthcheck", view_func=lambda: health.run()) return app
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)
def create_app(): app = Flask(__name__) health = HealthCheck() envdump = EnvironmentDump() CORS(app) blueprint = Blueprint('api', __name__) api.init_app(blueprint) api.add_namespace(hello_world_ns, '/hello-world') app.register_blueprint(blueprint) app.add_url_rule("/health-check", "healthcheck", view_func=lambda: health.run()) app.add_url_rule("/environment", "environment", view_func=lambda: envdump.run()) return app
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 create_app(): app = Flask(__name__) health = HealthCheck() envdump = EnvironmentDump() CORS(app) blueprint = Blueprint('api', __name__) api.init_app(blueprint) api.add_namespace(drawee_event_ns, '/draweeEvent') app.register_blueprint(blueprint) app.add_url_rule("/health-check", "healthcheck", view_func=lambda: health.run()) app.add_url_rule("/environment", "environment", view_func=lambda: envdump.run()) db = DBContext(engine).__enter__() Migrate(app, db) return app
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)
solns2 = list() for k in range(prev, num + 1): if k in fib: arr[index] = k solns2 = findCombinationsUtil(arr, index + 1, num, reducedNum - k, solns) #recursion return solns2 #endpoint for the fibonacci sequence @app.route('/fib/<int:number>', methods=['GET']) @cache.cached(timeout=50) def fib(number): arr = [0] * number solns = findCombinationsUtil(arr, 0, number, number, []) data = fib_database(number, str(solns)) #assigning data to the database db.session.add(data) db.session.commit() return jsonify(str(solns)) #endpoint for healthcheck app.add_url_rule("/health", "healthcheck", view_func=lambda: health.run()) #main if __name__ == '__main__': app.run(debug=True)
def healthz(): health = HealthCheck() health.add_section("application", application_data) return health.run()
import connexion import repositories.db as DB import repositories.models as models from healthcheck import HealthCheck app = connexion.App(__name__, specification_dir='./') app.add_api('swagger.yaml') app_health = HealthCheck() DB.connect_db() # TODO: override app_health to include mongoDB connection test app.add_url_rule("/vapehealthcheck", "vapehealthcheck", view_func=lambda: app_health.run()) # test to insert data to the data base, meant to be removed later # TODO: remove this... and implement unit test @app.route("/test") def test(): org = models.Organization(organization_name="Husky", organization_address="St. Johns") sensor = models.Sensor(sensor_name="test name", sensor_status=models.SensorStatus.DECOMMISSIONED, organization=org) sensor.save() return sensor.to_json() if __name__ == '__main__': app.run(port=8822)
response_message = 'Send Produce Topic Success' except Exception as e: print(e) response_message = 'Send Produce Topic Failed' return response_message # Kafka success message def success(rec): print('> message delivered to %s with partition %d and offset %d' % (rec.topic, rec.partition, rec.offset)) # Kafka exception message def error(exception): print('> message unsent with exception:', exception) if __name__ == '__main__': # Create the application instance app = connexion.App(__name__, specification_dir='openapi/') CORS(app.app) # Add a flask route to expose information app.add_url_rule('/api/predictor/health', 'healthcheck', view_func=lambda: health.run()) # Read the swagger.yml file to configure the endpoints app.add_api('swagger.yaml') app.run(threaded=False)
@app.route('/pdf_file/<file_name>', methods=['GET']) def render_pdf_file(file_name): base_path = "uploads/" + file_name + '/pdfs' file_name = 'stitched.pdf' print('BASE_PATH-', base_path, "File_name->", file_name) return send_from_directory(base_path, file_name) api.add_resource(ExtractData, "/extract") # Flask route to expose Health Check information app.add_url_rule("/healthcheck", "healthcheck", view_func=lambda: de_health.run()) @app.before_request def log_request(): app.logger.info("Request:\n{}".format(request.get_json())) @app.after_request def log_response(response): #app.logger.info("Response:\n{}".format(response.data.decode())) return response if __name__ == "__main__": app.run(debug=False, host=constant.HOST, port=constant.PORT_NUMBER)
from flask import Blueprint from healthcheck import HealthCheck bp = Blueprint('healthcheck', __name__) health = HealthCheck() def x_dependencie(): check = True return check, 'X dependencie OK' health.add_check(x_dependencie) bp.add_url_rule('/healthcheck', 'healthcheck', view_func=lambda: health.run())
def test_success_check(self): hc = HealthCheck(checkers=[self.check_adition_works]) message, status, headers = hc.run() self.assertEqual(200, status) jr = json.loads(message) self.assertEqual("success", jr["status"])
def test_failing_check(self): hc = HealthCheck(checkers=[self.check_throws_exception]) message, status, headers = hc.run() self.assertEqual(500, status) jr = json.loads(message) self.assertEqual("failure", jr["status"])
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, use_reloader=False) if __name__ == '__main__': run_rest_server()
app.register_blueprint(healthz, url_prefix="/healthz") #health = HealthCheck() # wrap the flask app and give a heathcheck url health = HealthCheck(app, "/healthcheck") # on the terminal type: curl http://127.0.0.1:8080/ # returns hello world when we use GET. @app.route('/', methods=['GET', 'POST']) def home(): if (request.method == 'GET'): data = "hello world" #return jsonify({'data': data}) return data def site_available(): return True, "UP" health.add_check(site_available) app.add_url_rule("/healthcheck", "healthcheck", health.run()) # driver function if __name__ == '__main__': app.run(host='127.0.0.1', port=8080, debug=True)