コード例 #1
0
def init_app(app):
    health = HealthCheck(app, '/healthcheck')
    health.add_check(redis_healthcheck)
    health.add_check(postgres_healthcheck)
    envdump = EnvironmentDump(app, '/environment')
    envdump.add_section("application", application_data)
コード例 #2
0
from flask import Flask

from healthcheck import EnvironmentDump
from healthcheck import HealthCheck

app = Flask(__name__)

health = HealthCheck(app, '/healthcheck')
envdump = EnvironmentDump(app, '/environment')


def application_data():
    return {
        'maintainer': 'Charlie Lewis',
        'git_repo': 'https://github.com/CyberReboot/vent',
        'app': 'rq_dashboard'
    }


envdump.add_section('application', application_data)
コード例 #3
0
def environment_details():
    envdump = EnvironmentDump(include_config=False)
    return envdump.dump_environment()
コード例 #4
0
ファイル: __init__.py プロジェクト: phenry/dtp-healthcheck
        handler.setLevel(logging.INFO)
        formatter = logging.Formatter(
            "%(asctime)s %(name)-12s %(levelname)-8s %(message)s")
        handler.setFormatter(formatter)
        app.logger.addHandler(handler)


setup_logging()

for url in urls:
    app.logger.info("URL to check: %s" % url)

health = HealthCheck(app, "/check")
#envdump = EnvironmentDump(app, "/environment")
envdump = EnvironmentDump(app,
                          "/environment",
                          include_process=False,
                          include_config=False)


def check_1():
    url = urls[0]
    r = requests.get(url)
    if r.status_code == 200: return True, "OK %s" % url
    else: return False, "KO %s" % url


def check_2():
    url = urls[1]
    r = requests.get(url)
    if r.status_code == 200: return True, "OK %s" % url
    else: return False, "KO %s" % url
コード例 #5
0
        def __call__(self, *args, **kwargs):
            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
コード例 #6
0
app = Flask(__name__)
cors = CORS(app)
api = Api(app, version='__version__', title='{{cookiecutter.project_name}}',
          description='{{cookiecutter.project_short_description}}')
ns = api.namespace('{{cookiecutter.repo_name}}', description='{{cookiecutter.project_name}}')
request_model = api.model('Input data', {
    'data': fields.String(description='Data to predict', required=True)
})
response_model = api.model('Result', {
    'result': fields.String(description="Result"),
})


health = HealthCheck(app, "/healthcheck")
envdump = EnvironmentDump(app, "/environment")


@ns.route('/predict')
class Predictor(Resource):
    @api.expect(request_model, validate=False)
    @api.response(200, 'Success', response_model)
    def post(self):
        data = request.json
        # TODO Implement
        raise NotImplementedError


logging.info("Reading the model from {}".format(DEFAULT_DATA_PATH))
model = joblib.load(DEFAULT_DATA_PATH)
コード例 #7
0
ファイル: app.py プロジェクト: FanThreeSixty/mockerena
from pymongo.errors import ServerSelectionTimeoutError

from mockerena import __author__, __email__, __version__
from mockerena.errors import ERROR_404, ERROR_422
from mockerena.format import format_output
from mockerena.generate import fake, generate_data
from mockerena.models.schema import CUSTOM_SCHEMA
from mockerena.settings import DEBUG, DEFAULT_FILE_FORMAT, DEFAULT_INCLUDE_HEAD, DEFAULT_SIZE, \
    DEFAULT_QUOTE_CHARACTER, DEFAULT_EXCLUDE_NULL, DEFAULT_DELIMITER, DEFAULT_KEY_SEPARATOR, \
    DEFAULT_IS_NESTED, DEFAULT_RESPONSES, ENV, HOST, PORT, SECRET_KEY
from mockerena.swagger import TEMPLATE

app = Eve(__name__,
          settings=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                'settings.py'))
envdump = EnvironmentDump(include_python=False, include_process=False)
health = HealthCheck()
swagger = Swagger(app, template=TEMPLATE)
app.config.update(ENV=ENV, DEBUG=DEBUG, SECRET_KEY=SECRET_KEY)


def application_data() -> dict:
    """Returns information about the application

    :return: A map of application information
    :rtype: dict
    """

    return {
        "version": __version__,
        "maintainer": __author__,
コード例 #8
0
ファイル: check.py プロジェクト: damyanbogoev/flask-bookshelf
import os
from flask import Flask
from healthcheck import HealthCheck, EnvironmentDump
from bookshelf.config import config


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)
コード例 #9
0
 def _hc(self):
     return EnvironmentDump(self.app, self.path)
コード例 #10
0
ファイル: manage.py プロジェクト: halb-tessella/rest_api
    else:
        #NOTE: passing true, otherwise google appengine will not make any path available
        return True, "cannot find indices..."


def dummy():
    return True, "we are live!"


health.add_check(dummy)
health.add_check(es_available)
health.add_check(es_index_exists)

envdump = EnvironmentDump(app,
                          "/environment",
                          include_python=False,
                          include_os=False,
                          include_process=False)
manager = Manager(app)


@manager.command
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
コード例 #11
0
from werkzeug.wsgi import DispatcherMiddleware

from .config import APP_CONFIG
from .parser import ParserAPI

APP = flask.Flask(__name__)
APP.config.update(APP_CONFIG)

APP.add_url_rule('/v1/parser',
                 view_func=ParserAPI.as_view('parser'),
                 methods=['POST'],
                 strict_slashes=False)
HealthCheck(app=APP, path='/health')
EnvironmentDump(app=APP,
                path="/health/env",
                include_python=False,
                include_os=False,
                include_process=False,
                include_config=True)

APP.wsgi_app = DispatcherMiddleware(APP.wsgi_app, {
    '/metrics': make_wsgi_app(),
})
LOGGING_FORMAT = '%(asctime)s [%(levelname)s] %(name)s:%(funcName)s:%(lineno)d - %(message)s'
logging.basicConfig(
    format=LOGGING_FORMAT,
    stream=sys.stdout,
    level=logging.INFO,
)

structlog.configure(
    processors=[
コード例 #12
0
from flask import Flask
from healthcheck import HealthCheck, EnvironmentDump

app = Flask(__name__)

health = HealthCheck(app, "/healthcheck")
envdump = EnvironmentDump(app, "/environment")


def application_data():
    return {
        "maintainer": "Swapnil Khedekar",
        "git_repo": "https://github.com/swapnil-k/flask-healthcheck"
    }


envdump.add_section("application", application_data)

app.add_url_rule("/healthcheck", "healthcheck", view_func=lambda: health.run())
app.add_url_rule("/environment",
                 "environment",
                 view_func=lambda: envdump.run())

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0")
コード例 #13
0
from flask.ext.cors import CORS
from healthcheck import EnvironmentDump
from healthcheck import HealthCheck

from api.endpoints.game import GamesView
from api.endpoints.turn import TurnsView
from api.endpoints.user import UsersView
from api.models import db
from api.services import bcrypt
from api.services import mail


compress = Compress()
cors = CORS()
health = HealthCheck()
environment = EnvironmentDump()


def create_app(config_class):
    app = Flask(__name__, template_folder='../templates')
    app.config.from_object(config_class)

    db.init_app(app)
    bcrypt.init_app(app)
    compress.init_app(app)
    cors.init_app(app, origins=app.config.get('ALLOWED_HOSTS', '*'))
    environment.init_app(app, '/environment')
    health.init_app(app, '/healthcheck')
    mail.init_app(app)

    api_views = [GamesView, TurnsView, UsersView]
コード例 #14
0
ファイル: api.py プロジェクト: N-Coder/mensabot
        if passed:
            message = "OK"
            if self.success_handler:
                message = self.success_handler(results)

            return message, self.success_status, self.success_headers
        else:
            message = "NOT OK"
            if self.failed_handler:
                message = self.failed_handler(results)

            return message, self.failed_status, self.failed_headers


health = FilteredHealthCheck(app, "/healthcheck")
envdump = EnvironmentDump(app, "/environment")


def json_version():
    from mensabot.format import get_version
    return get_version()


envdump.add_section("version", json_version)


@health.add_check
def tasks_running():
    from mensabot.bot.tasks import SCHED, SCHED_TASK_COUNT, task_name
    tasks = len(SCHED.queue)
    task_names = [task_name(task) for task in SCHED.queue]
コード例 #15
0
from flask import Flask
from healthcheck import HealthCheck, EnvironmentDump

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)

コード例 #16
0
ファイル: catalog.py プロジェクト: kris-hansen/catalog
from flask import make_response
import requests
from lxml import etree
#Using a combination of inspect and HealthCheck for intrinsic app monitoring
from healthcheck import HealthCheck, EnvironmentDump
from sqlalchemy import inspect
import sys
sys.stdout = sys.stderr

CLIENT_ID = json.loads(
    open('/var/www/catalog/client_secrets.json', 'r').read())['web']['client_id']
APPLICATION_NAME = "FundFintech"

app = Flask(__name__)
health = HealthCheck(app, "/healthcheck")
envdump = EnvironmentDump(app, "/environment")

# Set up database and ORM
engine = create_engine(
    'postgresql+psycopg2://catalog:halemaumau!@localhost/catalog')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()
##Security and Oauth
# Google routes and functions
## Basic Health Check App Monitoring
def database_available():
	dbhealth = inspect(session)
	return True, "Database OK"
# Provide additional information for environment dump
コード例 #17
0
from flask import request
import yaml
import psutil
import json
import os
import socket
import hashlib
import requests

from healthcheck import HealthCheck, EnvironmentDump
from prometheus_flask_exporter import PrometheusMetrics

app = Flask(__name__)
metrics = PrometheusMetrics(app)
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)
コード例 #18
0
import tensorflow_datasets as tfds
# import google.cloud.logging as glog
#
# client = glog.Client()
# client.setup_logging()


import logging

model = tf.keras.models.load_model('sentiment_analysis.hdf5')
logging.info("model loaded")
text_encoder = tfds.features.text.TokenTextEncoder.load_from_file('sa_encoder.vocab')

app = Flask(__name__)
health = HealthCheck()
envdump = EnvironmentDump()
app.add_url_rule("/health", "healthcheck", view_func=lambda: health.run())
app.add_url_rule("/environment", "environment", view_func=lambda: envdump.run())

def application_data():
    return {"maintainer": "Varsha Chawan",
            "git_repo": "https://github.com/varsharanichawan"}

envdump.add_section("application", application_data)

# add your own check function to the healthcheck
def model_available():
    if model and text_encoder:
        return True, "Model and Vocab ok"

コード例 #19
0
ファイル: hc.py プロジェクト: CyberReboot/vent
from flask import Flask

from healthcheck import EnvironmentDump
from healthcheck import HealthCheck

app = Flask(__name__)

health = HealthCheck(app, '/healthcheck')
envdump = EnvironmentDump(app, '/environment')


def application_data():
    return {'maintainer': 'Charlie Lewis',
            'git_repo': 'https://github.com/CyberReboot/vent',
            'app': 'rmq_es_connector'}


envdump.add_section('application', application_data)
コード例 #20
0
from comicnews.config import config
from flask import Flask
from healthcheck import HealthCheck, EnvironmentDump
import os

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": "dungntnew",
        "git_repo": "[email protected]:dungntnew/comicsnews.git"
コード例 #21
0
 def _hc(self):
     return EnvironmentDump()
コード例 #22
0
import socket
from flask import Flask, request
from healthcheck import HealthCheck, EnvironmentDump
# Docs: https://flask-mysqldb.readthedocs.io/en/latest/
from flask_mysqldb import MySQL
import os

application = Flask(__name__)
health = HealthCheck(application, "/healthcheck")
envdump = EnvironmentDump(application, "/environment")

# If there is a mysql backend, then use it.
mysql_backend = True
try:
    # FIXME: This may always evaluate as it seems like these env vars are
    # populated with values like ****** and null...
    application.config['MYSQL_USER'] = os.environ.get('MYSQL_USER')
    application.config['MYSQL_PASSWORD'] = os.environ.get('MYSQL_PASSWORD')
    application.config['MYSQL_DB'] = os.environ.get('MYSQL_DB')
    application.config['MYSQL_HOST'] = os.environ.get('MYSQL_HOST')
except:
    mysql_backend = False

if mysql_backend:
    mysql = MySQL(application)


@application.route("/")
def hello():
    # FIXME: return json?
    return "Hello from {} to {}".format(socket.gethostname(),