Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Stop the ES client from queueing without a deadline and make the health check's DB check opt-in (#5677)
Dhruv Bhanushalibe9d693dba5f
diff --git a/api/api/utils/es_transport.py b/api/api/utils/es_transport.pynew file mode 100644index 000000000..c08413d25--- /dev/null+++ b/api/api/utils/es_transport.py@@ -0,0 +1,59 @@+"""Elasticsearch transport node that refuses to wait for a socket forever."""++from __future__ import annotations++from elastic_transport import NodeConfig, Urllib3HttpNode+from urllib3.exceptions import EmptyPoolError+++class SearchCapacityExceeded(RuntimeError):+ """+ No pooled Elasticsearch socket became free within the configured wait.++ This deliberately subclasses ``RuntimeError``: ``elastic_transport``+ re-raises builtin exceptions untouched, whereas anything else raised by a+ node is wrapped in ``ConnectionError``, retried and used to mark the node+ dead. None of that is wanted when the node is fine and we are the ones+ saturating it.+ """+++class BoundedWaitUrllib3HttpNode(Urllib3HttpNode):+ """+ ``Urllib3HttpNode`` whose socket pool gives up after ``pool_timeout``.++ Per-task request concurrency is otherwise unbounded (Django's ASGI handler+ runs each request on its own thread), so under a slow cluster the default+ node queued searches for minutes with ``request_timeout`` never engaging.+ """++ pool_timeout: float = 5.0++ def __init__(self, config: NodeConfig):+ super().__init__(config)+ # Wrap the pool the base class built rather than rebuilding it, so its+ # TLS configuration survives. ``urlopen`` already takes the wait+ # deadline as ``pool_timeout``; ``elastic_transport`` just never passes+ # one. The translation must happen outside ``urlopen`` because its+ # cleanup treats ``EmptyPoolError`` specially: raising anything else+ # from the acquisition makes it "release" a connection it never got,+ # which adds a phantom slot to the pool.+ pool = self.pool++ def urlopen_with_deadline(*args, **kwargs):+ kwargs.setdefault("pool_timeout", self.pool_timeout)+ try:+ # Resolved on every call, not captured at start-up, so that+ # class-level patches of ``urlopen`` (pook in the tests) apply.+ return type(pool).urlopen(pool, *args, **kwargs)+ except EmptyPoolError as e:+ raise SearchCapacityExceeded(+ f"No Elasticsearch connection free within {self.pool_timeout} s"+ ) from e++ self.pool.urlopen = urlopen_with_deadline++ @classmethod+ def with_pool_timeout(cls, seconds: float) -> type[BoundedWaitUrllib3HttpNode]:+ """Return a subclass for ``Elasticsearch(node_class=...)``, which takes no instance."""+ return type(cls.__name__, (cls,), {"pool_timeout": seconds})diff --git a/api/api/utils/exceptions.py b/api/api/utils/exceptions.pyindex 128ee39f8..7dce1b457 100644--- a/api/api/utils/exceptions.py+++ b/api/api/utils/exceptions.py@@ -1,6 +1,10 @@+from rest_framework import statusfrom rest_framework.exceptions import ValidationError+from rest_framework.response import Responsefrom rest_framework.views import exception_handler as drf_exception_handler+from api.utils.es_transport import SearchCapacityExceeded+def exception_handler(ex, context):"""@@ -14,6 +18,13 @@ def exception_handler(ex, context)::return: the response to show for the exception""" # noqa: E501+ if isinstance(ex, SearchCapacityExceeded):+ return Response(+ {"detail": "Search is over capacity, please retry shortly."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ headers={"Retry-After": "5"},+ )+res = drf_exception_handler(ex, context)if isinstance(ex, ValidationError):# Wrap validation errors inside a `detail` key for consistencydiff --git a/api/api/views/health_views.py b/api/api/views/health_views.pyindex 556eb5cda..6cd141985 100644--- a/api/api/views/health_views.py+++ b/api/api/views/health_views.py@@ -21,6 +21,14 @@ class HealthCheck(APIView):This endpoint is used in production to ensure that the server should receivetraffic. If no response is provided, the server is deregistered from theload balancer and destroyed.++ The database and Elasticsearch checks are opt-in (``check_db`` and+ ``check_es`` query parameters). The load balancer calls this endpoint+ without them: the DB check needs a pooled connection, so whenever slow+ requests exhausted the pool the check timed out too and the task was+ killed, which only moved the load onto the remaining tasks. A task that+ cannot reach the database never finishes booting anyway, because+ migrations run on startup."""throttle_classes = [HealthcheckAnonRateThrottle, ExemptOAuth2IdRateThrottle]@@ -56,6 +64,7 @@ class HealthCheck(APIView):def get(self, request: Request):if "check_es" in request.query_params:self._check_es()- self._check_db()+ if "check_db" in request.query_params:+ self._check_db()return Response({"status": "200 OK"}, status=200)diff --git a/api/conf/settings/elasticsearch.py b/api/conf/settings/elasticsearch.pyindex 974af1abb..003faf3d0 100644--- a/api/conf/settings/elasticsearch.py+++ b/api/conf/settings/elasticsearch.py@@ -5,6 +5,7 @@ from elasticsearch import Elasticsearchfrom elasticsearch_dsl import connectionsfrom api.constants.media_types import MEDIA_TYPES+from api.utils.es_transport import BoundedWaitUrllib3HttpNodedef _elasticsearch_connect() -> tuple[Elasticsearch, str]:@@ -31,6 +32,18 @@ def _elasticsearch_connect() -> tuple[Elasticsearch, str]:retry_on_timeout=config("ELASTICSEARCH_RETRY_ON_TIMEOUT", default=False, cast=bool),+ # The transport keeps a blocking urllib3 pool of this many sockets per+ # node (default 10). Per-task request concurrency is unbounded, so with+ # a slow cluster the client-side queue grew to minutes while each+ # queued search held a Django thread, and for authenticated requests a+ # pooled DB connection too. The node class below puts a deadline on+ # that wait; see ``api.utils.es_transport``.+ connections_per_node=config(+ "ELASTICSEARCH_CONNECTIONS_PER_NODE", default=32, cast=int+ ),+ node_class=BoundedWaitUrllib3HttpNode.with_pool_timeout(+ config("ELASTICSEARCH_POOL_TIMEOUT", default=5, cast=float)+ ),)_es.info()_es.cluster.health(wait_for_status="yellow")diff --git a/api/env.template b/api/env.templateindex 906541ed2..8978a9a97 100644--- a/api/env.template+++ b/api/env.template@@ -41,6 +41,8 @@ SEMANTIC_VERSION=1.0.0#ELASTICSEARCH_REQUEST_TIMEOUT=8#ELASTICSEARCH_MAX_RETRIES=1#ELASTICSEARCH_RETRY_ON_TIMEOUT=False+#ELASTICSEARCH_CONNECTIONS_PER_NODE=32+#ELASTICSEARCH_POOL_TIMEOUT=5#IMAGE_INDEX_NAME=image#AUDIO_INDEX_NAME=audiodiff --git a/api/test/unit/utils/test_es_transport.py b/api/test/unit/utils/test_es_transport.pynew file mode 100644index 000000000..7fce68596--- /dev/null+++ b/api/test/unit/utils/test_es_transport.py@@ -0,0 +1,45 @@+import time++import pytest+from elastic_transport import NodeConfig+from urllib3 import HTTPSConnectionPool++from api.utils.es_transport import BoundedWaitUrllib3HttpNode, SearchCapacityExceeded+++def _node(pool_timeout=0.05, scheme="http"):+ node_class = BoundedWaitUrllib3HttpNode.with_pool_timeout(pool_timeout)+ return node_class(+ NodeConfig(scheme=scheme, host="127.0.0.1", port=9, connections_per_node=1)+ )+++def test_request_gives_up_when_no_socket_frees_up_in_time():+ node = _node()+ node.pool._get_conn() # the only socket is now busy++ start = time.monotonic()+ with pytest.raises(SearchCapacityExceeded):+ node.perform_request("GET", "/")+ assert time.monotonic() - start < 1+++def test_timed_out_requests_do_not_add_slots_to_the_pool():+ node = _node()+ conn = node.pool._get_conn()++ for _ in range(3):+ with pytest.raises(SearchCapacityExceeded):+ node.perform_request("GET", "/")+ assert node.pool.pool.qsize() == 0++ node.pool._put_conn(conn)+ assert node.pool.pool.qsize() == 1+++def test_wait_uses_the_configured_timeout():+ assert _node(pool_timeout=1.5).pool_timeout == 1.5+++def test_https_pool_is_kept():+ assert isinstance(_node(scheme="https").pool, HTTPSConnectionPool)diff --git a/api/test/unit/views/test_health_views.py b/api/test/unit/views/test_health_views.pyindex 12fde2e1b..93c7f7cf0 100644--- a/api/test/unit/views/test_health_views.py+++ b/api/test/unit/views/test_health_views.py@@ -26,10 +26,17 @@ def test_health_check_plain(api_client):assert res.status_code == 200-def test_health_check_calls__check_db(api_client):+def test_health_check_plain_skips__check_db(api_client):with mock.patch("api.views.health_views.HealthCheck._check_db") as mock_check_db:res = api_client.get("/healthcheck/")assert res.status_code == 200+ mock_check_db.assert_not_called()+++def test_health_check_calls__check_db(api_client):+ with mock.patch("api.views.health_views.HealthCheck._check_db") as mock_check_db:+ res = api_client.get("/healthcheck/", data={"check_db": True})+ assert res.status_code == 200mock_check_db.assert_called_once()@@ -38,7 +45,7 @@ def test_health_check_calls__check_db_with_failure(api_client):"api.views.health_views.connection.ensure_connection") as mock_ensure_connection:mock_ensure_connection.side_effect = OperationalError("Database has gone away")- res = api_client.get("/healthcheck/")+ res = api_client.get("/healthcheck/", data={"check_db": True})assert res.status_code == 503assert res.json() == {"detail": "postgres: Database has gone away"}mock_ensure_connection.assert_called_once()diff --git a/documentation/api/reference/healthcheck.md b/documentation/api/reference/healthcheck.mdindex 1a41a214b..d96187e00 100644--- a/documentation/api/reference/healthcheck.md+++ b/documentation/api/reference/healthcheck.md@@ -3,12 +3,19 @@The Django API healthcheck endpoint checks the following:- Whether the API is accessible at all (i.e., is Django returning responses)-- Whether the Postgres database is accessible to Django, by checking if- connections are available to the database+- Optionally, whether the Postgres database is accessible to Django, by checking+ if connections are available to the database (only when the `check_db` query+ parameter is present)- Optionally, whether Elasticsearch is accessible to Django (only when the`check_es` query parameter is present)- When debugging live healthcheck requests, check the request parameters to- determine whether Elasticsearch health is included+ determine whether the database or Elasticsearch health is included++The load balancer and container health checks pass neither parameter. The+database check needs a connection from the per-task pool, so when slow requests+exhaust the pool the check times out as well and the task is killed, which only+shifts the load onto the remaining tasks. A task that cannot reach the database+never finishes starting anyway, because migrations run on startup.The healthcheck can fail for any of the following reasons:@@ -16,8 +23,9 @@ The healthcheck can fail for any of the following reasons:- The worker meant to service the healthcheck request was aborted, eitherbecause it timed out when serving another or this request, or because theentire task was stopped due to another failure-- The database connection health check failed, either due to a temporary or- persistent database connection issue+- The `check_db` query parameter was passed and the database connection health+ check failed, either due to a temporary or persistent database connection+ issue- The `check_es` query parameter was passed and the worker was unable toestablish a connection to Elasticsearch _or_ Elasticsearch reported clusterhealth as "red"