Skip to content

Commit

Permalink
Add service_health view function
Browse files Browse the repository at this point in the history
  • Loading branch information
DavisRayM committed Jun 2, 2021
1 parent af8af2a commit e9206c7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
5 changes: 4 additions & 1 deletion onadata/apps/main/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,10 @@
re_path(r'^favicon\.ico',
RedirectView.as_view(url='/static/images/favicon.ico',
permanent=True)),
re_path(r'^static/(?P<path>.*)$', staticfiles_views.serve)
re_path(r'^static/(?P<path>.*)$', staticfiles_views.serve),

# Health check
re_path(r'^service_health$', main_views.service_health)
]

CUSTOM_URLS = getattr(settings, 'CUSTOM_MAIN_URLS', None)
Expand Down
35 changes: 35 additions & 0 deletions onadata/apps/main/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.files.storage import default_storage, get_storage_class
from django.db import IntegrityError, OperationalError
from django.http import (HttpResponse, HttpResponseBadRequest,
Expand Down Expand Up @@ -1423,6 +1424,40 @@ def enketo_preview(request, username, id_string):
return HttpResponseRedirect(enketo_preview_url)


def service_health(request):
"""
This endpoint checks whether the various services(Database, Cache, e.t.c )
of the application are running as expected. Returns a 200 Status code if
all is well and a 500 if a service is down
"""
service_degraded = False
service_statuses = {}

# Check if Database connections are present & data is retrievable
for database in getattr(settings, 'DATABASES').keys():
try:
XForm.objects.using(database).first()
except Exception as e:
service_statuses[f'{database}-Database'] = f'Degraded state; {e}'
else:
service_statuses[f'{database}-Database'] = 'OK'

# Check if cache is accessible
try:
cache.set('ping', 'pong')
service_degraded = not (cache.get('ping') == 'pong')
except Exception as e:
service_statuses['Cache-Service'] = f'Degraded state; {e}'
service_degraded = False
else:
service_statuses['Cache-Service'] = 'OK'

return HttpResponse(
json.dumps(service_statuses),
status=500 if service_degraded else 200,
content_type='application/json')


@require_GET
@login_required
def username_list(request):
Expand Down

0 comments on commit e9206c7

Please sign in to comment.