Skip to content

Commit

Permalink
Merge pull request openedx-unsupported#59 from edx/health-page-fix
Browse files Browse the repository at this point in the history
Returning HTTP 503 if service is unhealthy
  • Loading branch information
clintonb committed Feb 18, 2015
2 parents 347cce5 + c4765ef commit a7317a7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
6 changes: 3 additions & 3 deletions analyticsdataserver/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def test_authentication_check_success(self):
def test_health(self):
self.assert_database_health('OK')

def assert_database_health(self, status):
def assert_database_health(self, status, status_code=200):
response = self.client.get('/health', follow=True)
self.assertEquals(
response.data,
Expand All @@ -57,7 +57,7 @@ def assert_database_health(self, status):
}
}
)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.status_code, status_code)

@staticmethod
@contextmanager
Expand All @@ -71,7 +71,7 @@ def test_read_setting(self):
databases['reporting'] = {}

with self.override_database_connections(databases):
self.assert_database_health('UNAVAILABLE')
self.assert_database_health('UNAVAILABLE', status_code=503)

# Workaround to remove a setting from django settings. It has to be used in override_settings and then deleted.
@override_settings(ANALYTICS_DATABASE='reporting')
Expand Down
14 changes: 9 additions & 5 deletions analyticsdataserver/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,21 @@ class HealthView(APIView):
permission_classes = (permissions.AllowAny,)

def get(self, request, *args, **kwargs): # pylint: disable=unused-argument
overall_status = 'UNAVAILABLE'
db_conn_status = 'UNAVAILABLE'
OK = 'OK'
UNAVAILABLE = 'UNAVAILABLE'

overall_status = UNAVAILABLE
db_conn_status = UNAVAILABLE

try:
connection_name = getattr(settings, 'ANALYTICS_DATABASE', 'default')
cursor = connections[connection_name].cursor()
try:
cursor.execute("SELECT 1")
cursor.fetchone()
overall_status = 'OK'
db_conn_status = 'OK'

overall_status = OK
db_conn_status = OK
finally:
cursor.close()
except Exception: # pylint: disable=broad-except
Expand All @@ -92,4 +96,4 @@ def get(self, request, *args, **kwargs): # pylint: disable=unused-argument
}
}

return Response(response)
return Response(response, status=200 if overall_status == OK else 503)

0 comments on commit a7317a7

Please sign in to comment.