Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Add index readiness check to data refresh (#2209)

Staci Mullins475f464a7f05
diff --git a/catalog/dags/common/constants.py b/catalog/dags/common/constants.py
index dace6d3b2..6cdef64b2 100644
--- a/catalog/dags/common/constants.py
+++ b/catalog/dags/common/constants.py
@@ -36,3 +36,4 @@ POSTGRES_API_STAGING_CONN_ID = os.getenv(
)
AWS_CONN_ID = os.getenv("AWS_CONN_ID", "aws_conn_id")
AWS_RDS_CONN_ID = os.environ.get("AWS_RDS_CONN_ID", AWS_CONN_ID)
+ES_PROD_HTTP_CONN_ID = "elasticsearch_http_production"
diff --git a/catalog/dags/common/ingestion_server.py b/catalog/dags/common/ingestion_server.py
index 07043466d..f3ac3eeff 100644
--- a/catalog/dags/common/ingestion_server.py
+++ b/catalog/dags/common/ingestion_server.py
@@ -8,13 +8,15 @@ from airflow.providers.http.operators.http import SimpleHttpOperator
from airflow.providers.http.sensors.http import HttpSensor
from requests import Response
-from common.constants import XCOM_PULL_TEMPLATE
+from common.constants import ES_PROD_HTTP_CONN_ID, XCOM_PULL_TEMPLATE
logger = logging.getLogger(__name__)
POKE_INTERVAL = int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 15))
+# Minimum number of records we expect to get back from ES when querying an index.
+THRESHOLD_RESULT_COUNT = int(os.getenv("ES_INDEX_READINESS_RECORD_COUNT", 10_000))
def response_filter_stat(response: Response) -> str:
@@ -65,6 +67,22 @@ def response_check_wait_for_completion(response: Response) -> bool:
return True
+def response_check_index_readiness_check(response: Response) -> bool:
+ """
+ Handle the response for `index_readiness_check` Sensor, to await a
+ healthy Elasticsearch cluster. We expect to retrieve a healthy number
+ of results.
+ """
+ data = response.json()
+ hits = data.get("hits", {}).get("total", {}).get("value", 0)
+ logger.info(
+ f"Retrieved {hits} records from Elasticsearch using the new index."
+ f" Checking against threshold of {THRESHOLD_RESULT_COUNT}."
+ )
+
+ return hits >= THRESHOLD_RESULT_COUNT
+
+
def get_current_index(target_alias: str) -> SimpleHttpOperator:
return SimpleHttpOperator(
task_id="get_current_index",
@@ -125,3 +143,25 @@ def trigger_and_wait_for_task(
waiter = wait_for_task(action, trigger, timeout, poke_interval)
trigger >> waiter
return trigger, waiter
+
+
+def index_readiness_check(
+ media_type: str,
+ index_suffix: str,
+ timeout: timedelta = timedelta(days=1),
+ poke_interval: int = POKE_INTERVAL,
+) -> HttpSensor:
+ """
+ Poll the Elasticsearch index, returning true only when results greater
+ than the expected threshold_count are returned.
+ """
+ return HttpSensor(
+ task_id="index_readiness_check",
+ http_conn_id=ES_PROD_HTTP_CONN_ID,
+ endpoint=f"{media_type}-{index_suffix}/_search",
+ method="GET",
+ response_check=response_check_index_readiness_check,
+ mode="reschedule",
+ poke_interval=poke_interval,
+ timeout=timeout.total_seconds(),
+ )
diff --git a/catalog/dags/data_refresh/create_filtered_index_dag.py b/catalog/dags/data_refresh/create_filtered_index_dag.py
index b2978376b..4597540e9 100644
--- a/catalog/dags/data_refresh/create_filtered_index_dag.py
+++ b/catalog/dags/data_refresh/create_filtered_index_dag.py
@@ -206,6 +206,12 @@ def filtered_index_creation_dag_factory(data_refresh: DataRefresh):
destination_index_suffix=destination_index_suffix,
)
+ # Await healthy results from the newly created elasticsearch index.
+ index_readiness_check = ingestion_server.index_readiness_check(
+ media_type=media_type,
+ index_suffix=destination_index_suffix,
+ )
+
do_point_alias = point_alias(destination_index_suffix=destination_index_suffix)
delete_old_index = ingestion_server.trigger_task(
@@ -235,7 +241,7 @@ def filtered_index_creation_dag_factory(data_refresh: DataRefresh):
)
get_current_index_if_exists >> continue_if_no_current_index >> do_create
- await_create >> do_point_alias
+ await_create >> index_readiness_check >> do_point_alias
[get_current_index_if_exists, do_point_alias] >> delete_old_index
diff --git a/catalog/dags/data_refresh/data_refresh_task_factory.py b/catalog/dags/data_refresh/data_refresh_task_factory.py
index abbae1b78..9ac2fa2bf 100644
--- a/catalog/dags/data_refresh/data_refresh_task_factory.py
+++ b/catalog/dags/data_refresh/data_refresh_task_factory.py
@@ -152,25 +152,48 @@ def create_data_refresh_task_group(
)
tasks.append(generate_index_suffix)
- action_data_map: dict[str, dict] = {
- "ingest_upstream": {},
- "promote": {"alias": target_alias},
- }
- for action, action_post_data in action_data_map.items():
- with TaskGroup(group_id=action) as task_group:
- ingestion_server.trigger_and_wait_for_task(
- action=action,
- model=data_refresh.media_type,
- data={
- "index_suffix": XCOM_PULL_TEMPLATE.format(
- generate_index_suffix.task_id, "return_value"
- ),
- }
- | action_post_data,
- timeout=data_refresh.data_refresh_timeout,
- )
-
- tasks.append(task_group)
+ # Trigger the 'ingest_upstream' task on the ingestion server and await its
+ # completion. This task copies the media table for the given model from the
+ # Catalog into the API DB and builds the elasticsearch index. The new table
+ # and index are not promoted until a later step.
+ with TaskGroup(group_id="ingest_upstream") as ingest_upstream_tasks:
+ ingestion_server.trigger_and_wait_for_task(
+ action="ingest_upstream",
+ model=data_refresh.media_type,
+ data={
+ "index_suffix": XCOM_PULL_TEMPLATE.format(
+ generate_index_suffix.task_id, "return_value"
+ ),
+ },
+ timeout=data_refresh.data_refresh_timeout,
+ )
+ tasks.append(ingest_upstream_tasks)
+
+ # Await healthy results from the newly created elasticsearch index.
+ index_readiness_check = ingestion_server.index_readiness_check(
+ media_type=data_refresh.media_type,
+ index_suffix=XCOM_PULL_TEMPLATE.format(
+ generate_index_suffix.task_id, "return_value"
+ ),
+ timeout=data_refresh.index_readiness_timeout,
+ )
+ tasks.append(index_readiness_check)
+
+ # Trigger the `promote` task on the ingestion server and await its completion.
+ # This task promotes the newly created API DB table and elasticsearch index.
+ with TaskGroup(group_id="promote") as promote_tasks:
+ ingestion_server.trigger_and_wait_for_task(
+ action="promote",
+ model=data_refresh.media_type,
+ data={
+ "index_suffix": XCOM_PULL_TEMPLATE.format(
+ generate_index_suffix.task_id, "return_value"
+ ),
+ "alias": target_alias,
+ },
+ timeout=data_refresh.data_refresh_timeout,
+ )
+ tasks.append(promote_tasks)
# Delete the alias' previous target index, now unused.
delete_old_index = ingestion_server.trigger_task(
diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.py
index 4426453ca..f54e7c4d3 100644
--- a/catalog/dags/data_refresh/data_refresh_types.py
+++ b/catalog/dags/data_refresh/data_refresh_types.py
@@ -38,6 +38,8 @@ class DataRefresh:
may take
create_materialized_view_timeout: timedelta expressing amount of time the
creation of the matview may take
+ index_readiness_timeout: timedelta expressing amount of time it may take
+ to await a healthy ES index after reindexing
doc_md: str used for the DAG's documentation markdown
"""
@@ -52,6 +54,7 @@ class DataRefresh:
create_pop_constants_view_timeout: timedelta = timedelta(hours=1)
create_materialized_view_timeout: timedelta = timedelta(hours=1)
create_filtered_index_timeout: timedelta = timedelta(days=1)
+ index_readiness_timeout: timedelta = timedelta(days=1)
def __post_init__(self):
self.dag_id = f"{self.media_type}_data_refresh"
diff --git a/catalog/env.template b/catalog/env.template
index e4edcc90f..35b928264 100644
--- a/catalog/env.template
+++ b/catalog/env.template
@@ -55,6 +55,9 @@ AIRFLOW_CONN_POSTGRES_OPENLEDGER_API_STAGING=postgres://deploy:deploy@db:5432/op
OPENLEDGER_CONN_ID=postgres_openledger_upstream
TEST_CONN_ID=postgres_openledger_testing
+# Elasticsearch connections. Change the following line in prod to use the appropriate DB.
+AIRFLOW_CONN_ELASTICSEARCH_HTTP_PRODUCTION=http://es:9200
+
# API DB connection. Change the following line in prod to use the appropriate DB
AIRFLOW_CONN_POSTGRES_OPENLEDGER_API=postgres://deploy:deploy@db:5432/openledger
OPENLEDGER_API_CONN_ID=postgres_openledger_api
@@ -113,6 +116,9 @@ DATA_REFRESH_POOL=default_pool
DEFAULT_RETRY_COUNT = 2
# Whether to enable catchup for dated DAGs, allowing automatic backfill.
AIRFLOW_VAR_CATCHUP_ENABLED=false
+# Number of records to expect in a healthy ES index. Used during the data refresh to verify that
+# a new index is healthy before promoting.
+ES_INDEX_READINESS_RECORD_COUNT=1000
AIRFLOW_VAR_AIRFLOW_RDS_ARN=unset
AIRFLOW_VAR_AIRFLOW_RDS_SNAPSHOTS_TO_RETAIN=7
diff --git a/catalog/tests/dags/common/test_ingestion_server.py b/catalog/tests/dags/common/test_ingestion_server.py
index 086a0519e..6f78e341d 100644
--- a/catalog/tests/dags/common/test_ingestion_server.py
+++ b/catalog/tests/dags/common/test_ingestion_server.py
@@ -1,11 +1,47 @@
-from unittest.mock import MagicMock
+from datetime import timedelta
+from unittest import mock
import pytest
+import requests
from airflow.exceptions import AirflowSkipException
+from airflow.models import DagRun, TaskInstance
+from airflow.models.dag import DAG
+from airflow.utils.session import create_session
+from airflow.utils.state import DagRunState, TaskInstanceState
+from airflow.utils.timezone import datetime
+from airflow.utils.types import DagRunType
from common import ingestion_server
+TEST_START_DATE = datetime(2022, 2, 1, 0, 0, 0)
+TEST_DAG_ID = "api_healthcheck_test_dag"
+
+
[email protected](autouse=True)
+def clean_db():
+ with create_session() as session:
+ # synchronize_session='fetch' required here to refresh models
+ # https://stackoverflow.com/a/51222378 CC BY-SA 4.0
+ session.query(DagRun).filter(DagRun.dag_id.startswith(TEST_DAG_ID)).delete(
+ synchronize_session="fetch"
+ )
+ session.query(TaskInstance).filter(
+ TaskInstance.dag_id.startswith(TEST_DAG_ID)
+ ).delete(synchronize_session="fetch")
+
+
+def index_readiness_dag():
+ # Create a DAG that just has an index_readiness_check task
+ with DAG(dag_id=TEST_DAG_ID, schedule=None, start_date=TEST_START_DATE) as dag:
+ ingestion_server.index_readiness_check(
+ media_type="image", index_suffix="my_test_suffix", timeout=timedelta(days=1)
+ )
+
+ return dag
+
+
@pytest.mark.parametrize(
"data, expected",
[
@@ -19,7 +55,60 @@ from common import ingestion_server
],
)
def test_response_filter_stat(data, expected):
- response = MagicMock()
+ response = mock.MagicMock()
response.json.return_value = data
actual = ingestion_server.response_filter_stat(response)
assert actual == expected
+
+
+ "response_code, response_json, expected_status",
+ [
+ pytest.param(
+ 200,
+ {"hits": {"total": {"value": 20_000, "relation": "eq"}}},
+ TaskInstanceState.SUCCESS,
+ id="healthy-index",
+ ),
+ pytest.param(
+ 200,
+ {"hits": {"total": {"value": 100, "relation": "eq"}}},
+ TaskInstanceState.UP_FOR_RESCHEDULE,
+ id="not-enough-records",
+ ),
+ pytest.param(
+ 200, {"foo": "bar"}, TaskInstanceState.UP_FOR_RESCHEDULE, id="missing-hits"
+ ),
+ pytest.param(
+ 404,
+ {"error": {"root_cause": [{"type": "index_not_found_exception"}]}},
+ TaskInstanceState.UP_FOR_RESCHEDULE,
+ id="index-not-found-error",
+ ),
+ ],
+)
+def test_index_readiness_check(
+ index_readiness_dag, response_code, response_json, expected_status
+):
+ execution_date = TEST_START_DATE + timedelta(days=1)
+ dagrun = index_readiness_dag.create_dagrun(
+ start_date=execution_date,
+ execution_date=execution_date,
+ data_interval=(execution_date, execution_date),
+ state=DagRunState.RUNNING,
+ run_type=DagRunType.MANUAL,
+ )
+
+ with mock.patch(
+ "airflow.providers.http.hooks.http.requests.Session.send"
+ ) as mock_session_send:
+ r = requests.Response()
+ r.status_code = response_code
+ r.reason = "test"
+ r.json = mock.MagicMock(return_value=response_json)
+ mock_session_send.return_value = r
+
+ ti = dagrun.get_task_instance(task_id="index_readiness_check")
+ ti.task = index_readiness_dag.get_task(task_id="index_readiness_check")
+ ti.run()
+ assert ti.state == expected_status