Skip to content

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

Add DAG for creating staging indices (#3232)

Staci Mullinsee77ef5fe752
diff --git a/catalog/dags/common/ingestion_server.py b/catalog/dags/common/ingestion_server.py
index 3848724f4..2edb8731e 100644
--- a/catalog/dags/common/ingestion_server.py
+++ b/catalog/dags/common/ingestion_server.py
@@ -93,10 +93,12 @@ def generate_index_suffix(default_suffix: str | None = None) -> str:
return default_suffix or uuid.uuid4().hex
-def get_current_index(target_alias: str) -> SimpleHttpOperator:
+def get_current_index(
+ target_alias: str, http_conn_id: str = "data_refresh"
+) -> SimpleHttpOperator:
return SimpleHttpOperator(
task_id="get_current_index",
- http_conn_id="data_refresh",
+ http_conn_id=http_conn_id,
endpoint=f"stat/{target_alias}",
method="GET",
response_check=lambda response: response.status_code == 200,
@@ -108,6 +110,7 @@ def trigger_task(
action: str,
model: str,
data: dict | None = None,
+ http_conn_id: str = "data_refresh",
) -> SimpleHttpOperator:
data = {
**(data or {}),
@@ -116,7 +119,7 @@ def trigger_task(
}
return SimpleHttpOperator(
task_id=f"trigger_{action.lower()}",
- http_conn_id="data_refresh",
+ http_conn_id=http_conn_id,
endpoint="task",
data=data,
response_check=lambda response: response.status_code == 202,
@@ -129,10 +132,11 @@ def wait_for_task(
task_trigger: SimpleHttpOperator,
timeout: timedelta,
poke_interval: int = REFRESH_POKE_INTERVAL,
+ http_conn_id: str = "data_refresh",
) -> HttpSensor:
return HttpSensor(
task_id=f"wait_for_{action.lower()}",
- http_conn_id="data_refresh",
+ http_conn_id=http_conn_id,
endpoint=XCOM_PULL_TEMPLATE.format(task_trigger.task_id, "return_value"),
method="GET",
response_check=response_check_wait_for_completion,
@@ -148,9 +152,10 @@ def trigger_and_wait_for_task(
timeout: timedelta,
data: dict | None = None,
poke_interval: int = REFRESH_POKE_INTERVAL,
+ http_conn_id: str = "data_refresh",
) -> tuple[SimpleHttpOperator, HttpSensor]:
- trigger = trigger_task(action, model, data)
- waiter = wait_for_task(action, trigger, timeout, poke_interval)
+ trigger = trigger_task(action, model, data, http_conn_id)
+ waiter = wait_for_task(action, trigger, timeout, poke_interval, http_conn_id)
trigger >> waiter
return trigger, waiter
diff --git a/catalog/dags/common/slack.py b/catalog/dags/common/slack.py
index 3c872bf68..4365d003a 100644
--- a/catalog/dags/common/slack.py
+++ b/catalog/dags/common/slack.py
@@ -55,6 +55,7 @@ from collections.abc import Callable
from os.path import basename
from typing import Any
+from airflow.decorators import task
from airflow.exceptions import AirflowNotFoundException
from airflow.models import Variable
from airflow.providers.http.hooks.http import HttpHook
@@ -404,3 +405,18 @@ def on_failure_callback(context: dict) -> None:
task_id=task_id,
username="Airflow DAG Failure",
)
+
+
+@task
+def notify_slack(
+ text: str,
+ dag_id: str,
+ username: str = "Airflow Notification",
+ icon_emoji: str = ":airflow:",
+) -> None:
+ send_message(
+ text,
+ username=username,
+ icon_emoji=icon_emoji,
+ dag_id=dag_id,
+ )
diff --git a/catalog/dags/data_refresh/create_filtered_index_dag.py b/catalog/dags/data_refresh/create_filtered_index_dag.py
index 1cadcbd91..7870b7b7f 100644
--- a/catalog/dags/data_refresh/create_filtered_index_dag.py
+++ b/catalog/dags/data_refresh/create_filtered_index_dag.py
@@ -161,5 +161,5 @@ def create_filtered_index_creation_dag(data_refresh: DataRefresh):
return dag
-for data_refresh in DATA_REFRESH_CONFIGS:
+for data_refresh in DATA_REFRESH_CONFIGS.values():
create_filtered_index_dag = create_filtered_index_creation_dag(data_refresh)
diff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.py
index 88ed8075c..838ab97c8 100644
--- a/catalog/dags/data_refresh/dag_factory.py
+++ b/catalog/dags/data_refresh/dag_factory.py
@@ -135,9 +135,9 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
# Generate a data refresh DAG for each DATA_REFRESH_CONFIG.
-all_data_refresh_dag_ids = {refresh.dag_id for refresh in DATA_REFRESH_CONFIGS}
+all_data_refresh_dag_ids = {refresh.dag_id for refresh in DATA_REFRESH_CONFIGS.values()}
-for data_refresh in DATA_REFRESH_CONFIGS:
+for data_refresh in DATA_REFRESH_CONFIGS.values():
# Construct a set of all data refresh DAG ids other than the current DAG
other_dag_ids = all_data_refresh_dag_ids - {data_refresh.dag_id}
diff --git a/catalog/dags/data_refresh/data_refresh_task_factory.py b/catalog/dags/data_refresh/data_refresh_task_factory.py
index 32ce04977..67d0c36a1 100644
--- a/catalog/dags/data_refresh/data_refresh_task_factory.py
+++ b/catalog/dags/data_refresh/data_refresh_task_factory.py
@@ -46,11 +46,9 @@ https://github.com/WordPress/openverse-catalog/issues/353)
"""
import logging
import os
-import uuid
from collections.abc import Sequence
from airflow.models.baseoperator import chain
-from airflow.operators.python import PythonOperator
from airflow.sensors.external_task import ExternalTaskSensor
from airflow.utils.state import State
from airflow.utils.task_group import TaskGroup
@@ -150,11 +148,9 @@ def create_data_refresh_task_group(
tasks.append(get_current_index)
# Generate a UUID suffix that will be used by the newly created index.
- generate_index_suffix = PythonOperator(
- task_id="generate_index_suffix",
- python_callable=lambda: uuid.uuid4().hex,
+ generate_index_suffix = ingestion_server.generate_index_suffix.override(
trigger_rule=TriggerRule.NONE_FAILED,
- )
+ )()
tasks.append(generate_index_suffix)
# Trigger the 'ingest_upstream' task on the ingestion server and await its
@@ -166,9 +162,7 @@ def create_data_refresh_task_group(
action="ingest_upstream",
model=data_refresh.media_type,
data={
- "index_suffix": XCOM_PULL_TEMPLATE.format(
- generate_index_suffix.task_id, "return_value"
- ),
+ "index_suffix": generate_index_suffix,
},
timeout=data_refresh.data_refresh_timeout,
)
@@ -177,9 +171,7 @@ def create_data_refresh_task_group(
# 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"
- ),
+ index_suffix=generate_index_suffix,
timeout=data_refresh.index_readiness_timeout,
)
tasks.append(index_readiness_check)
@@ -191,14 +183,10 @@ def create_data_refresh_task_group(
promote_filtered_index,
) = create_filtered_index_creation_task_groups(
data_refresh=data_refresh,
- origin_index_suffix=XCOM_PULL_TEMPLATE.format(
- generate_index_suffix.task_id, "return_value"
- ),
+ origin_index_suffix=generate_index_suffix,
# Match origin and destination suffixes so we can tell which
# filtered indexes were created as part of a data refresh.
- destination_index_suffix=XCOM_PULL_TEMPLATE.format(
- generate_index_suffix.task_id, "return_value"
- ),
+ destination_index_suffix=generate_index_suffix,
)
# Add the task group for triggering the filtered index creation and awaiting its
@@ -216,9 +204,7 @@ def create_data_refresh_task_group(
action="promote",
model=data_refresh.media_type,
data={
- "index_suffix": XCOM_PULL_TEMPLATE.format(
- generate_index_suffix.task_id, "return_value"
- ),
+ "index_suffix": generate_index_suffix,
"alias": target_alias,
},
timeout=data_refresh.data_refresh_timeout,
diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.py
index 8648aab18..6791edb69 100644
--- a/catalog/dags/data_refresh/data_refresh_types.py
+++ b/catalog/dags/data_refresh/data_refresh_types.py
@@ -9,7 +9,7 @@ import os
from dataclasses import dataclass, field
from datetime import datetime, timedelta
-from common.constants import REFRESH_POKE_INTERVAL
+from common.constants import AUDIO, IMAGE, REFRESH_POKE_INTERVAL
@dataclass
@@ -71,8 +71,8 @@ class DataRefresh:
self.dag_id = f"{self.media_type}_data_refresh"
-DATA_REFRESH_CONFIGS = [
- DataRefresh(
+DATA_REFRESH_CONFIGS = {
+ IMAGE: DataRefresh(
media_type="image",
data_refresh_timeout=timedelta(days=4),
refresh_metrics_timeout=timedelta(hours=24),
@@ -84,11 +84,11 @@ DATA_REFRESH_CONFIGS = [
os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 30)
),
),
- DataRefresh(
+ AUDIO: DataRefresh(
media_type="audio",
data_refresh_poke_interval=int(
os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 30)
),
filtered_index_poke_interval=int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60)),
),
-]
+}
diff --git a/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py b/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py
index c9f57a4a8..b3062d78a 100644
--- a/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py
+++ b/catalog/dags/database/staging_database_restore/staging_database_restore_dag.py
@@ -28,13 +28,20 @@ from textwrap import dedent as d
from airflow.decorators import dag
from airflow.providers.amazon.aws.operators.rds import RdsDeleteDbInstanceOperator
from airflow.providers.amazon.aws.sensors.rds import RdsSnapshotExistenceSensor
+from airflow.sensors.external_task import ExternalTaskSensor
+from airflow.utils.state import State
from airflow.utils.trigger_rule import TriggerRule
+from es.recreate_staging_index.recreate_full_staging_index import (
+ DAG_ID as RECREATE_STAGING_INDEX_DAG_ID,
+)
from common.constants import (
AWS_RDS_CONN_ID,
DAG_DEFAULT_ARGS,
POSTGRES_API_STAGING_CONN_ID,
+ REFRESH_POKE_INTERVAL,
)
+from common.sensors.utils import get_most_recent_dag_run
from common.sql import PGExecuteQueryOperator
from database.staging_database_restore import constants
from database.staging_database_restore.staging_database_restore import (
@@ -70,9 +77,26 @@ log = logging.getLogger(__name__)
render_template_as_native_obj=True,
)
def restore_staging_database():
+ # If the `recreate_full_staging_index` DAG was manually triggered prior
+ # to the database restoration starting, we should wait for it to
+ # finish.
+ wait_for_recreate_full_staging_index = ExternalTaskSensor(
+ task_id="wait_for_recreate_full_staging_index",
+ external_dag_id=RECREATE_STAGING_INDEX_DAG_ID,
+ # Wait for the whole DAG, not just a part of it
+ external_task_id=None,
+ check_existence=False,
+ poke_interval=REFRESH_POKE_INTERVAL,
+ execution_date_fn=lambda _: get_most_recent_dag_run(
+ RECREATE_STAGING_INDEX_DAG_ID
+ ),
+ mode="reschedule",
+ # Any "finished" state is sufficient for us to continue.
+ allowed_states=[State.SUCCESS, State.FAILED],
+ )
should_skip = skip_restore()
latest_snapshot = get_latest_prod_snapshot()
- should_skip >> latest_snapshot
+ wait_for_recreate_full_staging_index >> should_skip >> latest_snapshot
ensure_snapshot_ready = RdsSnapshotExistenceSensor(
task_id="ensure_snapshot_ready",
diff --git a/catalog/dags/es/recreate_staging_index/recreate_full_staging_index.py b/catalog/dags/es/recreate_staging_index/recreate_full_staging_index.py
new file mode 100644
index 000000000..7033a7c13
--- /dev/null
+++ b/catalog/dags/es/recreate_staging_index/recreate_full_staging_index.py
@@ -0,0 +1,95 @@
+from datetime import timedelta
+
+from airflow.decorators import task, task_group
+from airflow.exceptions import AirflowSensorTimeout
+from airflow.sensors.external_task import ExternalTaskSensor
+from airflow.utils.state import State
+
+from common import ingestion_server
+from common.sensors.utils import get_most_recent_dag_run
+from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS
+from database.staging_database_restore.constants import (
+ DAG_ID as STAGING_DB_RESTORE_DAG_ID,
+)
+
+
+DAG_ID = "recreate_full_staging_index"
+
+
+@task(retries=0)
+def prevent_concurrency_with_staging_database_restore(**context):
+ wait_for_dag = ExternalTaskSensor(
+ task_id="check_for_running_staging_db_restore",
+ external_dag_id=STAGING_DB_RESTORE_DAG_ID,
+ # Set timeout to 0 to prevent retries. If the staging DB restoration is running,
+ # immediately fail the staging index creation DAG.
+ timeout=0,
+ # Wait for the whole DAG, not just a part of it
+ external_task_id=None,
+ check_existence=False,
+ execution_date_fn=lambda _: get_most_recent_dag_run(STAGING_DB_RESTORE_DAG_ID),
+ # Any "finished" state is sufficient for us to continue.
+ allowed_states=[State.SUCCESS, State.FAILED],
+ mode="reschedule",
+ )
+ try:
+ wait_for_dag.execute(context)
+ except AirflowSensorTimeout:
+ raise ValueError(
+ "Concurrency check failed. Staging index creation cannot start"
+ " during staging DB restoration."
+ )
+
+
+@task
+def get_target_alias(media_type: str, target_alias_override: str):
+ return target_alias_override or f"{media_type}-full"
+
+
+def should_delete_index(should_delete: bool, old_index: str):
+ if should_delete and old_index:
+ # We should try to delete the old index only if the param is enabled,
+ # and we were able to find an index with the target_alias in the
+ # preceding task.
+ return "trigger_delete_index"
+ # Skip straight to notifying Slack.
+ return "notify_complete"
+
+
+@task_group(group_id="create_index")
+def create_index(media_type: str, index_suffix: str) -> None:
+ """Create the new elasticsearch index on the staging cluster."""
+
+ # Get the DataRefresh config associated with this media type, in order to get
+ # the reindexing timeout information.
+ config = DATA_REFRESH_CONFIGS.get(media_type)
+ data_refresh_timeout = config.data_refresh_timeout if config else timedelta(days=1)
+
+ ingestion_server.trigger_and_wait_for_task(
+ action="REINDEX",
+ model=media_type,
+ data={"index_suffix": index_suffix},
+ timeout=data_refresh_timeout,
+ http_conn_id="staging_data_refresh",
+ )
+
+
+@task_group(group_id="point_alias")
+def point_alias(media_type: str, target_alias: str, index_suffix: str) -> None:
+ """
+ Alias the index with the given suffix to the target_alias, first removing the
+ target_alias from any other indices to which it is linked.
+ """
+ point_alias_payload = {
+ "alias": target_alias,
+ "index_suffix": index_suffix,
+ }
+
+ ingestion_server.trigger_and_wait_for_task(
+ action="POINT_ALIAS",
+ model=media_type,
+ data=point_alias_payload,
+ timeout=timedelta(hours=12), # matches the ingestion server's wait time
+ http_conn_id="staging_data_refresh",
+ )
diff --git a/catalog/dags/es/recreate_staging_index/recreate_full_staging_index_dag.py b/catalog/dags/es/recreate_staging_index/recreate_full_staging_index_dag.py
new file mode 100644
index 000000000..cf9fd4820
--- /dev/null
+++ b/catalog/dags/es/recreate_staging_index/recreate_full_staging_index_dag.py
@@ -0,0 +1,165 @@
+"""
+# Recreate Full Staging Index DAG
+
+This DAG is used to fully recreate a new staging Elasticsearch index for a
+given `media_type`, using records pulled from the staging API database. It is
+used to decouple the steps of creating a new index from the rest of the
+data refresh process.
+
+Staging index creation is handled by the _staging_ ingestion server. The DAG
+triggers the ingestion server `REINDEX` action to create a new index in the
+staging elasticsearch cluster for the given media type, suffixed by the current
+timestamp. The DAG awaits the completion of the index creation and then points
+the `<media_type>-full` alias to the newly created index.
+
+Required Dagrun Configuration parameters:
+
+* media_type: the media type for which to create a new index.
+
+Optional params:
+
+* target_alias_override: Override the alias that is pointed to the new index. By
+ default this is `<media_type>-full`.
+* delete_old_index: Whether to delete the index previously pointed to by the
+ target alias, if applicable. Defaults to False.
+
+## When this DAG runs
+
+This DAG is on a `None` schedule and is run manually.
+
+## Race conditions
+
+Because this DAG runs on the staging ingestion server and staging elasticsearch
+cluster, it does _not_ interfere with the `data_refresh` or
+`create_filtered_index` DAGs.
+
+However, the DAG will exit immediately if the `staging_database_restore` DAG is
+running, as it operates on the staging API database.
+"""
+from datetime import datetime
+
+from airflow.decorators import dag
+from airflow.models.param import Param
+from airflow.utils.trigger_rule import TriggerRule
+from es.recreate_staging_index.recreate_full_staging_index import (
+ DAG_ID,
+ create_index,
+ get_target_alias,
+ point_alias,
+ prevent_concurrency_with_staging_database_restore,
+ should_delete_index,
+)
+
+from common import ingestion_server, slack
+from common.constants import AUDIO, DAG_DEFAULT_ARGS, MEDIA_TYPES, XCOM_PULL_TEMPLATE
+
+
+@dag(
+ dag_id=DAG_ID,
+ default_args=DAG_DEFAULT_ARGS,
+ schedule=None,
+ start_date=datetime(2023, 4, 1),
+ tags=["database", "elasticsearch"],
+ max_active_runs=1,
+ catchup=False,
+ doc_md=__doc__,
+ params={
+ "media_type": Param(
+ default=AUDIO,
+ enum=MEDIA_TYPES,
+ description="The media type for which to create the index.",
+ ),
+ "target_alias_override": Param(
+ default=None,
+ type=["string", "null"],
+ description=(
+ "Optionally, override the target alias for the newly created index."
+ " The default to `{media_type}-full` using the given media_type."
+ ),
+ ),
+ "delete_old_index": Param(
+ default=False,
+ type="boolean",
+ description=(
+ "Whether to delete the index previously pointed to be the "
+ "`target_alias`, if it is replaced. The index will "
+ "only be deleted if the alias was successfully linked to the "
+ " newly created index."
+ ),
+ ),
+ },
+ render_template_as_native_obj=True,
+)
+def recreate_full_staging_index():
+ prevent_concurrency = prevent_concurrency_with_staging_database_restore()
+
+ target_alias = get_target_alias(
+ media_type="{{ params.media_type }}",
+ target_alias_override="{{ params.target_alias_override }}",
+ )
+
+ # Suffix the index with a current timestamp.
+ new_index_suffix = ingestion_server.generate_index_suffix.override(
+ trigger_rule=TriggerRule.NONE_FAILED
+ )("full-{{ ts_nodash.lower() }}")
+
+ # Get the index currently aliased by the target_alias, in case it must be
+ # deleted later.
+ get_current_index_if_exists = ingestion_server.get_current_index(
+ target_alias, http_conn_id="staging_data_refresh"
+ )
+
+ # Create the new Elasticsearch index
+ do_create_index = create_index(
+ media_type="{{ params.media_type }}", index_suffix=new_index_suffix
+ )
+
+ # Actually point the alias
+ do_point_alias = point_alias(
+ media_type="{{ params.media_type }}",
+ target_alias=target_alias,
+ index_suffix=new_index_suffix,
+ )
+
+ check_if_should_delete_index = should_delete_index(
+ should_delete="{{ params.delete_old_index }}",
+ old_index=XCOM_PULL_TEMPLATE.format(
+ get_current_index_if_exists.task_id, "return_value"
+ ),
+ )
+
+ # Branch only reached if check_if_should_delete_index is True.
+ # Deletes the old index pointed to by the target_alias after the alias has been
+ # unlinked.
+ delete_old_index = ingestion_server.trigger_task(
+ action="DELETE_INDEX",
+ model="{{ params.media_type }}",
+ data={
+ "index_suffix": XCOM_PULL_TEMPLATE.format(
+ get_current_index_if_exists.task_id, "return_value"
+ ),
+ },
+ http_conn_id="staging_data_refresh",
+ )
+
+ notify_complete = slack.notify_slack.override(
+ task_id="notify_complete", trigger_rule=TriggerRule.NONE_FAILED
+ )(
+ text=(
+ "Finished creating full staging index `{{ params.media_type }}-"
+ f"{new_index_suffix}` aliased to `{target_alias}`."
+ ),
+ username="Full Staging Index Creation",
+ dag_id=DAG_ID,
+ )
+
+ # Set up dependencies
+ prevent_concurrency >> target_alias >> get_current_index_if_exists
+ get_current_index_if_exists >> new_index_suffix
+ new_index_suffix >> do_create_index >> do_point_alias
+ do_point_alias >> check_if_should_delete_index
+ check_if_should_delete_index >> [delete_old_index, notify_complete]
+ delete_old_index >> notify_complete
+
+
+recreate_full_staging_index()
diff --git a/catalog/dags/popularity/popularity_refresh_dag_factory.py b/catalog/dags/popularity/popularity_refresh_dag_factory.py
index 567e907d2..ae7a11720 100644
--- a/catalog/dags/popularity/popularity_refresh_dag_factory.py
+++ b/catalog/dags/popularity/popularity_refresh_dag_factory.py
@@ -42,16 +42,6 @@ from database.batched_update.constants import DAG_ID as BATCHED_UPDATE_DAG_ID
logger = logging.getLogger(__name__)
-@task
-def notify_slack(text: str, media_type: str, dag_id: str) -> None:
- slack.send_message(
- text,
- username=f"{media_type.capitalize()} Popularity Refresh",
- icon_emoji=":database:",
- dag_id=dag_id,
- )
-
-
@task
def get_last_updated_time():
"""
@@ -78,6 +68,10 @@ def create_popularity_refresh_dag(popularity_refresh: PopularityRefresh):
popularity_refresh: dataclass containing configuration information for the DAG
"""
+
+ SLACK_USERNAME = f"{popularity_refresh.media_type.capitalize()} Popularity Refresh"
+ SLACK_EMOJI = ":database:"
+
default_args = {
**DAG_DEFAULT_ARGS,
**popularity_refresh.default_args,
@@ -108,12 +102,13 @@ def create_popularity_refresh_dag(popularity_refresh: PopularityRefresh):
" to the metrics table."
)
- update_metrics_status = notify_slack.override(
+ update_metrics_status = slack.notify_slack.override(
task_id="report_update_popularity_metrics_status"
)(
text="Popularity metrics update complete | _Next: popularity"
" constants update_",
- media_type=popularity_refresh.media_type,
+ username=SLACK_USERNAME,
+ icon_emoji=SLACK_EMOJI,
dag_id=popularity_refresh.dag_id,
)
@@ -136,12 +131,13 @@ def create_popularity_refresh_dag(popularity_refresh: PopularityRefresh):
" popularity scores."
)
- update_constants_status = notify_slack.override(
+ update_constants_status = slack.notify_slack.override(
task_id="report_update_popularity_metrics_status"
)(
text="Popularity constants update complete | _Next: refresh"
" popularity scores_",
- media_type=popularity_refresh.media_type,
+ username=SLACK_USERNAME,
+ icon_emoji=SLACK_EMOJI,
dag_id=popularity_refresh.dag_id,
)
@@ -169,12 +165,13 @@ def create_popularity_refresh_dag(popularity_refresh: PopularityRefresh):
)
)
- notify_complete = notify_slack(
+ notify_complete = slack.notify_slack(
text=(
f"{popularity_refresh.media_type.capitalize()} Popularity Refresh"
" Complete"
),
- media_type=popularity_refresh.media_type,
+ username=SLACK_USERNAME,
+ icon_emoji=SLACK_EMOJI,
dag_id=popularity_refresh.dag_id,
)
diff --git a/catalog/env.template b/catalog/env.template
index 2c5812d40..b3b8ac028 100644
--- a/catalog/env.template
+++ b/catalog/env.template
@@ -46,7 +46,7 @@ AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING=postgres://deploy:deploy@upstream_db:54
AIRFLOW_CONN_POSTGRES_OPENLEDGER_API_STAGING=postgres://deploy:deploy@db:5432/openledger
TEST_CONN_ID=postgres_openledger_testing
-# Elasticsearch connections. Change the following line in prod to use the appropriate DB.
+# Elasticsearch connections. Change the following line in prod to use the appropriate URL.
AIRFLOW_CONN_ELASTICSEARCH_HTTP_PRODUCTION=http://es:9200
# API DB connection. Change the following line in prod to use the appropriate DB
@@ -63,6 +63,10 @@ S3_LOCAL_ENDPOINT=http://s3:5000
# Connection to the Ingestion Server, used for managing data refreshes. Default is used to
# connect to your locally running ingestion server.
AIRFLOW_CONN_DATA_REFRESH=http://ingestion_server:8001
+# Connection to the Staging Ingestion Server, used for managing indices on the staging
+# elasticsearch cluster. Default is used to connect to your locally running ingestion
+# server.
+AIRFLOW_CONN_STAGING_DATA_REFRESH=http://ingestion_server:8001
# Django Admin url. Change the following line to use the appropriate environment.
DJANGO_ADMIN_URL="https://localhost:8000/admin"
diff --git a/catalog/tests/dags/test_dag_parsing.py b/catalog/tests/dags/test_dag_parsing.py
index 2b6f131c4..83f1648a0 100644
--- a/catalog/tests/dags/test_dag_parsing.py
+++ b/catalog/tests/dags/test_dag_parsing.py
@@ -24,6 +24,7 @@ DAG_PATHS = [
"popularity/popularity_refresh_dag_factory.py",
"data_refresh/dag_factory.py",
"data_refresh/create_filtered_index_dag.py",
+ "es/recreate_staging_index/recreate_full_staging_index_dag.py",
"oauth2/authorize_dag.py",
"oauth2/token_refresh_dag.py",
"database/delete_records/delete_records_dag.py",
diff --git a/documentation/catalog/reference/DAGs.md b/documentation/catalog/reference/DAGs.md
index cef197962..6e2bbe03c 100644
--- a/documentation/catalog/reference/DAGs.md
+++ b/documentation/catalog/reference/DAGs.md
@@ -46,6 +46,7 @@ The following are DAGs grouped by their primary tag:
| [`batched_update`](#batched_update) | `None` |
| [`delete_records`](#delete_records) | `None` |
| [`recreate_audio_popularity_calculation`](#recreate_audio_popularity_calculation) | `None` |
+| [`recreate_full_staging_index`](#recreate_full_staging_index) | `None` |
| [`recreate_image_popularity_calculation`](#recreate_image_popularity_calculation) | `None` |
| [`report_pending_reported_media`](#report_pending_reported_media) | `@weekly` |
| [`staging_database_restore`](#staging_database_restore) | `@monthly` |
@@ -150,6 +151,7 @@ The following is documentation associated with each DAG (where available):
1. [`pr_review_reminders`](#pr_review_reminders)
1. [`rawpixel_workflow`](#rawpixel_workflow)
1. [`recreate_audio_popularity_calculation`](#recreate_audio_popularity_calculation)
+1. [`recreate_full_staging_index`](#recreate_full_staging_index)
1. [`recreate_image_popularity_calculation`](#recreate_image_popularity_calculation)
1. [`report_pending_reported_media`](#report_pending_reported_media)
1. [`rotate_db_snapshots`](#rotate_db_snapshots)
@@ -802,6 +804,45 @@ popularity constants and standardized popularity scores using the new functions.
These DAGs are not on a schedule, and should only be run manually when new SQL
code is deployed for the calculation.
+### `recreate_full_staging_index`
+
+#### Recreate Full Staging Index DAG
+
+This DAG is used to fully recreate a new staging Elasticsearch index for a given
+`media_type`, using records pulled from the staging API database. It is used to
+decouple the steps of creating a new index from the rest of the data refresh
+process.
+
+Staging index creation is handled by the _staging_ ingestion server. The DAG
+triggers the ingestion server `REINDEX` action to create a new index in the
+staging elasticsearch cluster for the given media type, suffixed by the current
+timestamp. The DAG awaits the completion of the index creation and then points
+the `<media_type>-full` alias to the newly created index.
+
+Required Dagrun Configuration parameters:
+
+- media_type: the media type for which to create a new index.
+
+Optional params:
+
+- target_alias_override: Override the alias that is pointed to the new index. By
+ default this is `<media_type>-full`.
+- delete_old_index: Whether to delete the index previously pointed to by the
+ target alias, if applicable. Defaults to False.
+
+##### When this DAG runs
+
+This DAG is on a `None` schedule and is run manually.
+
+##### Race conditions
+
+Because this DAG runs on the staging ingestion server and staging elasticsearch
+cluster, it does _not_ interfere with the `data_refresh` or
+`create_filtered_index` DAGs.
+
+However, the DAG will exit immediately if the `staging_database_restore` DAG is
+running, as it operates on the staging API database.
+
### `recreate_image_popularity_calculation`
This file generates Apache Airflow DAGs that, for the given media type,
diff --git a/ingestion_server/ingestion_server/distributed_reindex_scheduler.py b/ingestion_server/ingestion_server/distributed_reindex_scheduler.py
index 16effdca9..54d4d0178 100644
--- a/ingestion_server/ingestion_server/distributed_reindex_scheduler.py
+++ b/ingestion_server/ingestion_server/distributed_reindex_scheduler.py
@@ -20,6 +20,7 @@ import requests
from decouple import config
from ingestion_server.state import register_indexing_job
+from ingestion_server.utils.config import get_record_limit
client = boto3.client("ec2", region_name=config("AWS_REGION", default="us-east-1"))
@@ -40,7 +41,10 @@ def _assign_work(db_conn, workers, model_name, table_name, target_index):
with db_conn.cursor() as cur:
cur.execute(est_records_query)
estimated_records = cur.fetchone()[0]
- records_per_worker = math.floor(estimated_records / len(workers))
+
+ records_per_worker = math.floor(
+ min(estimated_records, get_record_limit()) / len(workers)
+ )
worker_url_template = "http://{}:8002"
# Wait for the workers to start.
diff --git a/ingestion_server/ingestion_server/indexer.py b/ingestion_server/ingestion_server/indexer.py
index 1912f818a..cb6e035e3 100644
--- a/ingestion_server/ingestion_server/indexer.py
+++ b/ingestion_server/ingestion_server/indexer.py
@@ -339,7 +339,8 @@ class TableIndexer:
def point_alias(self, model_name: str, index_suffix: str, alias: str, **_):
"""
- Map the given index to the given alias.
+ Map the given index to the given alias. If the alias is in use by another
+ index, it will first be unlinked from that index.
:param model_name: the name of the media type
:param index_suffix: the suffix of the index for which to assign the alias
diff --git a/ingestion_server/ingestion_server/ingest.py b/ingestion_server/ingestion_server/ingest.py
index f491f5ace..ceeb2bdbf 100644
--- a/ingestion_server/ingestion_server/ingest.py
+++ b/ingestion_server/ingestion_server/ingest.py
@@ -33,6 +33,7 @@ from ingestion_server.queries import (
get_fdw_query,
get_go_live_query,
)
+from ingestion_server.utils.config import get_record_limit
UPSTREAM_DB_HOST = config("UPSTREAM_DB_HOST", default="localhost")
@@ -317,12 +318,7 @@ def refresh_api_table(
# Step 4: Import data into a temporary table
log.info("Copying upstream data...")
- environment = config("ENVIRONMENT", default="local").lower()
- limit_default = 100_000
- if environment in {"prod", "production"}:
- # If we're in production, turn off limits unless it's explicitly provided
- limit_default = 0
- limit = config("DATA_REFRESH_LIMIT", cast=int, default=limit_default)
+ limit = get_record_limit()
copy_data = get_copy_data_query(
upstream_table,
downstream_table,
diff --git a/ingestion_server/ingestion_server/state.py b/ingestion_server/ingestion_server/state.py
index 8213c6769..2c24f419b 100644
--- a/ingestion_server/ingestion_server/state.py
+++ b/ingestion_server/ingestion_server/state.py
@@ -37,6 +37,21 @@ class TaskData(NamedTuple):
percent_completed: float
+def is_indexing_in_progress(db):
+ """
+ Determine whether any indexing is in progress, by checking to see if there are any
+ registered workers with the RUNNING status.
+
+ :param db: the Shelf object representing worker state on disk.
+ :return: True if there are any active indexer workers.
+ """
+ if "worker_statuses" in db:
+ for worker in db["worker_statuses"]:
+ if db["worker_statuses"][worker] == WorkerStatus.RUNNING:
+ return True
+ return False
+
+
def register_indexing_job(worker_ips, target_index, task_id):
"""
Track the active indexer workers to prevent concurrent indexing jobs.
@@ -49,13 +64,7 @@ def register_indexing_job(worker_ips, target_index, task_id):
:return: Return True if scheduling succeeds
"""
with FileLock(lock_path), shelve.open(shelf_path, writeback=True) as db:
- # Wipe last job out if it has finished.
- indexing_in_progress = False
- if "worker_statuses" in db:
- for worker in db["worker_statuses"]:
- if db["worker_statuses"][worker] == WorkerStatus.RUNNING:
- indexing_in_progress = True
- if indexing_in_progress:
+ if is_indexing_in_progress(db):
log.error("Failed to schedule indexing job; another one is running.")
return False
@@ -70,6 +79,24 @@ def register_indexing_job(worker_ips, target_index, task_id):
return True
+def has_active_workers_for_task_id(task_id):
+ """
+ Determine whether there are any actively running indexer-worker instances
+ for the given task_id, even if the parent task has completed.
+
+ :param task_id: The id of the data_refresh task to check.
+ :return: Return True if there are any active workers for this task.
+ """
+ with FileLock(lock_path), shelve.open(shelf_path) as db:
+ if "task_id" in db and db["task_id"] == task_id:
+ return is_indexing_in_progress(db)
+
+ # There can only be one indexing job happening at a time, so if the currently
+ # registered `task_id` does not match the one we're looking for, we can
+ # be sure there are no active workers for this task.
+ return False
+
+
def worker_finished(worker_ip, error):
"""
Receive the notifications indicating an indexing worker has finished its task.
diff --git a/ingestion_server/ingestion_server/tasks.py b/ingestion_server/ingestion_server/tasks.py
index f75396fec..513546a3c 100644
--- a/ingestion_server/ingestion_server/tasks.py
+++ b/ingestion_server/ingestion_server/tasks.py
@@ -13,6 +13,7 @@ from ingestion_server.constants.media_types import MediaType
from ingestion_server.es_helpers import elasticsearch_connect
from ingestion_server.indexer import TableIndexer
from ingestion_server.ingest import promote_api_table, refresh_api_table
+from ingestion_server.state import has_active_workers_for_task_id
class TaskTypes(Enum):
@@ -91,7 +92,7 @@ class TaskTracker:
} | kwargs
@staticmethod
- def serialize_task_info(task_info: dict) -> dict:
+ def serialize_task_info(task_id: str, task_info: dict) -> dict:
"""
Generate a response dictionary containing all relevant information about a task.
@@ -111,12 +112,13 @@ class TaskTracker:
return None
return str(datetime.datetime.utcfromtimestamp(timestamp))
- active = task_info["task"].is_alive()
+ active = task_info["task"].is_alive() or has_active_workers_for_task_id(task_id)
start_time = task_info["start_time"]
finish_time = task_info["finish_time"].value
progress = task_info["progress"].value
active_workers = task_info["active_workers"].value
is_bad_request = task_info["is_bad_request"].value
+
return {
"active": active,
"model": task_info["model"],
@@ -127,6 +129,9 @@ class TaskTracker:
"finish_timestamp": finish_time,
"finish_time": _time_fmt(finish_time),
"active_workers": bool(active_workers),
+ # The task is considered to have errored if the task is no longer alive, or
+ # else it does not have any associated active workers, but progress did not
+ # reach 100%.
"error": progress < 100 and not active,
"is_bad_request": bool(is_bad_request),
}
@@ -153,7 +158,7 @@ class TaskTracker:
self._prune_old_tasks()
task_info = self.tasks[task_id]
- return {"task_id": task_id} | self.serialize_task_info(task_info)
+ return {"task_id": task_id} | self.serialize_task_info(task_id, task_info)
def _with_sentry(fn):
diff --git a/ingestion_server/ingestion_server/utils/config.py b/ingestion_server/ingestion_server/utils/config.py
new file mode 100644
index 000000000..45c2aaf58
--- /dev/null
+++ b/ingestion_server/ingestion_server/utils/config.py
@@ -0,0 +1,19 @@
+from decouple import config
+
+
+def get_record_limit():
+ """
+ Check and retrieve the limit of records to ingest for the environment.
+
+ If a limit is explicitly configured, it is always used. Otherwise, production
+ defaults to no limit, and all other environments default to 100,000.
+ """
+ configured_limit = config("DATA_REFRESH_LIMIT", default=None)
+ if configured_limit is not None:
+ return int(configured_limit)
+
+ environment = config("ENVIRONMENT", default="local").lower()
+ if environment in {"prod", "production"}:
+ return 0
+
+ return 100_000