~homeworkprod/byceps

ref: 342e5296ae417372e544ce931b442e98301c17a1 byceps/byceps/blueprints/monitoring/healthcheck/views.py -rw-r--r-- 1.3 KiB
342e5296 — Jochen Kupperschmidt Require body blocks in base templates 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
byceps.blueprints.monitoring.healthcheck
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from flask import current_app
from flask.json import dumps

from sqlalchemy.exc import OperationalError

from ....database import db
from ....util.framework.blueprint import create_blueprint


blueprint = create_blueprint('healthcheck', __name__)


@blueprint.route('')
def health():
    """Return health status as JSON.

    Adheres to "Health Check Response Format for HTTP APIs"
    (draft-inadarei-api-health-check-03). See
    https://inadarei.github.io/rfc-healthcheck/#rfc.section.3
    for details.
    """
    rdbms_ok = _is_rdbms_ok()

    data = {
        'status': 'ok',
        'details': {
            'rdbms': [
                {
                    'status': 'ok' if rdbms_ok else 'fail',
                },
            ],
        },
    }

    json = dumps(data) + '\n'
    status_code = 503 if not rdbms_ok else 200

    return current_app.response_class(
        json, status=status_code, content_type='application/health+json'
    )


def _is_rdbms_ok():
    try:
        db.session.execute('SELECT 1')
        return True
    except OperationalError:
        return False