Repository: WordPress/openverse-api

Issue:
/healthcheck endpoint should check for Elasticsearch availability (original #487)
This issue has been migrated from the [CC Search API repository](https://github.com/creativecommons/cccatalog-api/issues/487)

```
Author: aldenstpage
Date: Wed May 06 2020
Labels: ✨ goal: improvement,🏷 status: label work required,🙅 status: discontinued
```
During deployments, our load balancer repeatedly polls the `/healthcheck` endpoint to check that the server is reachable. If this check succeeds, the newly deployed instance starts receiving production traffic. Right now, if Elasticsearch is not responsive, `/healthcheck` will still return `200 OK`.

The healthcheck endpoint should check the health of the `image` index in Elasticsearch using the [cluster health API](https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-health.html). If it is unavailable, return error 500. Log an informative message explaining why the healthcheck failed.

Because the healthcheck endpoint may be called many times, and Elasticsearch calls are not free, we should cache the response of Elasticsearch for up to 10 seconds per call.
--------
### Original Comments: 

*madewithkode* commented on Fri May 08 2020:

>Hi Alden, this looks interesting, I'd love to work on it.
  
[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-625824482)


*madewithkode* commented on Fri May 08 2020:

>Hi Alden in order to check the health of the `image` index in the /healthcheck view, I'm trying to use the urllib's `urlopen()` method to make a request to Elasticsearch's  cluster API this way:

`cluster_response = urlopen('http://0.0.0.0:8000/_cluster/health/image')`

However, I keep getting a 404. Is there something I'm doing wrong?
[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-625854788)


*madewithkode* commented on Fri May 08 2020:

>> Hi Alden in order to check the health of the `image` index in the /healthcheck view, I'm trying to use the urllib's `urlopen()` method to make a request to Elasticsearch's cluster API this way:
> 
> `cluster_response = urlopen('http://0.0.0.0:8000/_cluster/health/image')`
> 
> However, I keep getting a 404. Is there something I'm doing wrong?

Figured this, didn't know elastic search was running on a seperate host/port :)
[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-625905259)


*aldenstpage* commented on Fri May 08 2020:

>That's great! 

It would be best to use the equivalent `elasticsearch-py` or `elasticsearch-dsl` query instead of making direct calls to the REST API (you can get an instance of the connection to Elasticsearch from `search_controller.py`). [Here's](https://discuss.elastic.co/t/how-to-get-cluster-health-using-python-api/25431) an example for getting the cluster health; there ought to also be a way to narrow the query to the `image` index.
[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-625995563)


*madewithkode* commented on Sat May 09 2020:

>Alright...would look at the suggestion.

On Fri, May 8, 2020, 21:06 Alden S Page <notifications@github.com> wrote:

> It would be best to use the equivalent elasticsearch-py query instead of
> making direct calls to the REST API. Here's
> <https://discuss.elastic.co/t/how-to-get-cluster-health-using-python-api/25431>
> an example for getting the cluster health; there ought to also be a way to
> narrow the query to the image index.
>
> —
> You are receiving this because you commented.
> Reply to this email directly, view it on GitHub
> <https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-625995563>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AGFLMYA5WLAQPO5GYZNX5BTRQRQ5RANCNFSM4M2V5EKA>
> .
>

[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-626130991)


*madewithkode* commented on Sat May 09 2020:

>Hi Alden, I'm here again :)
I'd love to ask, what status specifically signifies the availability of the `image` index. 
`red`, `yellow` or `green` ? or should i leave out this detail in the query since I'm using an already established connection instance from `search_controller.py` which waits for a `yellow` status by default.
[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-626164842)


*madewithkode* commented on Sat May 09 2020:

>### Update: 
I've successfully managed to query the health of the entire cluster, using the Elasticsearch connection instance gotten from `search_controller.py`. However when i try to limit the health check to just the `image` index, the request never resolves and continues to run forever with no response. And when i try to specify a timeout for the request, i get an "Illegal argument exception" even though `timeout` is a valid kwarg referenced in the [API docs](https://elasticsearch-py.readthedocs.io/en/master/api.html?highlight=health#elasticsearch.client.ClusterClient.health).

It'd be nice to point out that as at the time of writing, I'm yet to successfully run `./load_sample_data.sh` so i don't know if this could be linked to the above problem.



[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-626223763)


*madewithkode* commented on Mon May 11 2020:

>Hi Alden, Progress Report :)

Successfully got the `load_sample_data.sh` to run,  and so far every other thing is working fine. 
I've also set up the 10s response caching on the `/healthcheck` view using redis and also the error logging.

However, I figured out the reason for the unresponsiveness when querying the elastic search `image` index was that it was non-existent and that the whole cluster index was empty too.

Do I need to do a manual population or something?




[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-626749591)


*aldenstpage* commented on Mon May 11 2020:

>Hi again Onyenanu – if the index doesn't exist, the healthcheck should fail. This could happen in situations where we are switching Elasticsearch clusters in production and forgot to index data into the new one (or something went wrong while we were loading data into the new cluster).

In my experience, the ES Python libs can behave in unexpected ways that you sometimes have to work around. Since it seems like querying specifically for the `image` index health hangs when the index doesn't exist, perhaps you could query for healthchecks of every index in the cluster, and fail the healthcheck if `image` is not among them and green?

It sounds like it's coming along nicely!
[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-626920424)


*madewithkode* commented on Tue May 12 2020:

>> Hi again Onyenanu – if the index doesn't exist, the healthcheck should fail. This could happen in situations where we are switching Elasticsearch clusters in production and forgot to index data into the new one (or something went wrong while we were loading data into the new cluster).
> 
> In my experience, the ES Python libs can behave in unexpected ways that you sometimes have to work around. Since it seems like querying specifically for the `image` index health hangs when the index doesn't exist, perhaps you could query for healthchecks of every index in the cluster, and fail the healthcheck if `image` is not among them and green?
> 
> It sounds like it's coming along nicely!

Hey Alden...Many thanks again for coming through with better insights. Suggestion sounds nice, would proceed with it.

And yes, the whole stuff  is getting more interesting, learnt a handful in the few days :)
[source](https://github.com/creativecommons/cccatalog-api/issues/487#issuecomment-626973607)



Discussion:

Resolving patch:
diff --git a/api/catalog/api/views/health_views.py b/api/catalog/api/views/health_views.py
--- a/api/catalog/api/views/health_views.py
+++ b/api/catalog/api/views/health_views.py
@@ -1,10 +1,19 @@
+from django.conf import settings
+from rest_framework import status
+from rest_framework.exceptions import APIException
+from rest_framework.request import Request
 from rest_framework.response import Response
 from rest_framework.views import APIView
 
 
+class ElasticsearchHealthcheckException(APIException):
+    status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+
+
 class HealthCheck(APIView):
     """
-    Returns a "200 OK" response if the server is running normally.
+    Returns a "200 OK" response if the server is running normally. Returns 503
+    otherwise.
 
     This endpoint is used in production to ensure that the server should receive
     traffic. If no response is provided, the server is deregistered from the
@@ -13,5 +22,20 @@ class HealthCheck(APIView):
 
     swagger_schema = None
 
-    def get(self, request, format=None):
+    def _check_es(self) -> Response | None:
+        """
+        Checks Elasticsearch cluster health. Raises an exception if ES is not healthy.
+        """
+        es_health = settings.ES.cluster.health(timeout="5s")
+
+        if es_health["timed_out"]:
+            raise ElasticsearchHealthcheckException("es_timed_out")
+
+        if (status := es_health["status"]) != "green":
+            raise ElasticsearchHealthcheckException(f"es_status_{status}")
+
+    def get(self, request: Request):
+        if "check_es" in request.query_params:
+            self._check_es()
+
         return Response({"status": "200 OK"}, status=200)


Test patch:
diff --git a/api/test/unit/conftest.py b/api/test/unit/conftest.py
new file mode 100644
--- /dev/null
+++ b/api/test/unit/conftest.py
@@ -0,0 +1,8 @@
+from rest_framework.test import APIClient
+
+import pytest
+
+
+@pytest.fixture
+def api_client():
+    return APIClient()
diff --git a/api/test/unit/views/health_views_test.py b/api/test/unit/views/health_views_test.py
new file mode 100644
--- /dev/null
+++ b/api/test/unit/views/health_views_test.py
@@ -0,0 +1,51 @@
+import pook
+import pytest
+
+
+def mock_health_response(status="green", timed_out=False):
+    return (
+        pook.get(pook.regex(r"_cluster\/health"))
+        .times(1)
+        .reply(200)
+        .json(
+            {
+                "status": status if not timed_out else None,
+                "timed_out": timed_out,
+            }
+        )
+    )
+
+
+def test_health_check_plain(api_client):
+    res = api_client.get("/healthcheck/")
+    assert res.status_code == 200
+
+
+def test_health_check_es_timed_out(api_client):
+    mock_health_response(timed_out=True)
+    pook.on()
+    res = api_client.get("/healthcheck/", data={"check_es": True})
+    pook.off()
+
+    assert res.status_code == 503
+    assert res.json()["detail"] == "es_timed_out"
+
+
+@pytest.mark.parametrize("status", ("yellow", "red"))
+def test_health_check_es_status_bad(status, api_client):
+    mock_health_response(status=status)
+    pook.on()
+    res = api_client.get("/healthcheck/", data={"check_es": True})
+    pook.off()
+
+    assert res.status_code == 503
+    assert res.json()["detail"] == f"es_status_{status}"
+
+
+def test_health_check_es_all_good(api_client):
+    mock_health_response(status="green")
+    pook.on()
+    res = api_client.get("/healthcheck/", data={"check_es": True})
+    pook.off()
+
+    assert res.status_code == 200
diff --git a/api/test/unit/views/image_views_test.py b/api/test/unit/views/image_views_test.py
--- a/api/test/unit/views/image_views_test.py
+++ b/api/test/unit/views/image_views_test.py
@@ -4,8 +4,6 @@
 from pathlib import Path
 from test.factory.models.image import ImageFactory
 
-from rest_framework.test import APIClient
-
 import pytest
 from requests import Request, Response
 
@@ -17,11 +15,6 @@
 _MOCK_IMAGE_INFO = json.loads((_MOCK_IMAGE_PATH / "sample-image-info.json").read_text())
 
 
-@pytest.fixture
-def api_client():
-    return APIClient()
-
-
 @dataclass
 class RequestsFixture:
     requests: list[Request]
diff --git a/api/test/unit/views/media_views_test.py b/api/test/unit/views/media_views_test.py
--- a/api/test/unit/views/media_views_test.py
+++ b/api/test/unit/views/media_views_test.py
@@ -7,8 +7,6 @@
 from unittest import mock
 from unittest.mock import patch
 
-from rest_framework.test import APIClient
-
 import pytest
 import requests as requests_lib
 from fakeredis import FakeRedis
@@ -22,11 +20,6 @@
 _MOCK_IMAGE_INFO = json.loads((_MOCK_IMAGE_PATH / "sample-image-info.json").read_text())
 
 
-@pytest.fixture
-def api_client():
-    return APIClient()
-
-
 @dataclass
 class SentRequest:
     request: PreparedRequest