Skip to content

Commit

Permalink
Merge pull request #230 from release-engineering/health-check
Browse files Browse the repository at this point in the history
Add a simple health check API endpoint
  • Loading branch information
mprahl committed Mar 1, 2019
2 parents 5872415 + 4fe1767 commit 20774e0
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
25 changes: 25 additions & 0 deletions estuary/api/health_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# SPDX-License-Identifier: GPL-3.0+

from __future__ import unicode_literals

from neomodel import db

from estuary import log


def health_check():
"""Determine the health of the API by checking if the database interactions are working."""
msg = 'Health check OK'
status = 200
try:
# Just perform a simple math operation that doesn't rely on any data being present in the
# database
results, _ = db.cypher_query('RETURN sqrt(4)')
assert results[0][0] == 2.0
except: # noqa E722
log.exception('An exception was encountered when verifying the database connection in the '
'health check API endpoint')
msg = 'The health check failed while verifying the database connection'
status = 503

return (msg, status, [('Content-Type', 'text/plain')])
2 changes: 2 additions & 0 deletions estuary/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from estuary.logger import init_logging
from estuary.error import json_error, ValidationError
from estuary.api.v1 import api_v1
from estuary.api.health_check import health_check


def load_config(app):
Expand Down Expand Up @@ -115,6 +116,7 @@ def create_app(config_obj=None):
app.register_error_handler(ServiceUnavailable, json_error)
app.register_error_handler(AuthError, json_error)
app.register_blueprint(api_v1, url_prefix='/api/v1')
app.add_url_rule('/healthcheck', view_func=health_check)
try:
from estuary.api.monitoring import monitoring_api, configure_monitoring
app.register_blueprint(monitoring_api, url_prefix='/monitoring')
Expand Down
22 changes: 22 additions & 0 deletions tests/api/test_health_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# SPDX-License-Identifier: GPL-3.0+

from __future__ import unicode_literals

from mock import patch


def test_healthcheck(client):
"""Test the health check endpoint is working."""
rv = client.get('/healthcheck')
assert rv.status_code == 200
assert rv.data.decode('utf-8') == 'Health check OK'


def test_healthcheck_failure(client):
"""Test the health check endpoint shows failures."""
with patch('estuary.api.health_check.db') as mock_db:
mock_db.cypher_query.side_effect = RuntimeError('Some failure')
rv = client.get('/healthcheck')
assert rv.status_code == 503
assert rv.data.decode('utf-8') == \
'The health check failed while verifying the database connection'

0 comments on commit 20774e0

Please sign in to comment.