Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add external dag sensor utilities (#3482)
Staci Mullinsfa1c2e87837e
diff --git a/catalog/dags/common/sensors/utils.py b/catalog/dags/common/sensors/utils.pyindex 3cd3d72f3..083e47598 100644--- a/catalog/dags/common/sensors/utils.py+++ b/catalog/dags/common/sensors/utils.py@@ -1,6 +1,12 @@from datetime import datetime+from airflow.decorators import task+from airflow.exceptions import AirflowSensorTimeoutfrom airflow.models import DagRun+from airflow.sensors.external_task import ExternalTaskSensor+from airflow.utils.state import State++from common.constants import REFRESH_POKE_INTERVALdef get_most_recent_dag_run(dag_id) -> list[datetime] | datetime:@@ -27,3 +33,43 @@ def get_most_recent_dag_run(dag_id) -> list[datetime] | datetime:# ``ExternalTaskSensor::get_count``, especially the handling# of ``dttm_filter`` for the relevant implementation details.return []+++def wait_for_external_dag(external_dag_id: str, task_id: str | None = None):+ """+ Return a Sensor task which will wait if the given external DAG is+ running.+ """+ if not task_id:+ task_id = f"wait_for_{external_dag_id}"++ return ExternalTaskSensor(+ task_id=task_id,+ poke_interval=REFRESH_POKE_INTERVAL,+ external_dag_id=external_dag_id,+ # 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(external_dag_id),+ mode="reschedule",+ # Any "finished" state is sufficient for us to continue+ allowed_states=[State.SUCCESS, State.FAILED],+ )+++@task(retries=0)+def prevent_concurrency_with_dag(external_dag_id: str, **context):+ """+ Prevent concurrency with the given external DAG, by failing+ immediately if that DAG is running.+ """++ wait_for_dag = wait_for_external_dag(+ external_dag_id=external_dag_id,+ task_id=f"check_for_running_{external_dag_id}",+ )+ wait_for_dag.timeout = 0+ try:+ wait_for_dag.execute(context)+ except AirflowSensorTimeout:+ raise ValueError(f"Concurrency check with {external_dag_id} failed.")diff --git a/catalog/dags/data_refresh/create_filtered_index_dag.py b/catalog/dags/data_refresh/create_filtered_index_dag.pyindex 7870b7b7f..72ce39313 100644--- a/catalog/dags/data_refresh/create_filtered_index_dag.py+++ b/catalog/dags/data_refresh/create_filtered_index_dag.py@@ -53,13 +53,10 @@ critical for the creation of the filtered indexes.from datetime import datetimefrom airflow import DAG-from airflow.decorators import task-from airflow.exceptions import AirflowSensorTimeoutfrom airflow.models.param import Param-from airflow.sensors.external_task import ExternalTaskSensorfrom common.constants import DAG_DEFAULT_ARGS-from common.sensors.utils import get_most_recent_dag_run+from common.sensors.utils import prevent_concurrency_with_dagfrom data_refresh.create_filtered_index import (create_filtered_index_creation_task_groups,)@@ -82,31 +79,6 @@ def create_filtered_index_creation_dag(data_refresh: DataRefresh):"""media_type = data_refresh.media_type- @task(- task_id=f"prevent_concurrency_with_{media_type}_data_refresh",- )- def prevent_concurrency_with_data_refresh(**context):- data_refresh_dag_id = f"{media_type}_data_refresh"- wait_for_filtered_index_creation = ExternalTaskSensor(- task_id="check_for_running_data_refresh",- external_dag_id=data_refresh_dag_id,- # Set timeout to 0 to prevent retries. If the data refresh DAG is running,- # immediately fail the filtered 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(data_refresh_dag_id),- mode="reschedule",- )- try:- wait_for_filtered_index_creation.execute(context)- except AirflowSensorTimeout:- raise ValueError(- f"{media_type} data refresh concurrency check failed. "- "Filtered index creation cannot start during a data refresh."- )-with DAG(dag_id=f"create_filtered_{media_type}_index",default_args=DAG_DEFAULT_ARGS,@@ -141,9 +113,10 @@ def create_filtered_index_creation_dag(data_refresh: DataRefresh):},render_template_as_native_obj=True,) as dag:- prevent_concurrency = prevent_concurrency_with_data_refresh.override(- retries=0- )()+ # Immediately fail if the associated data refresh is running.+ prevent_concurrency = prevent_concurrency_with_dag.override(+ task_id=f"prevent_concurrency_with_{media_type}_data_refresh"+ )(external_dag_id=f"{media_type}_data_refresh")# Once the concurrency check has passed, actually create the filtered# index.diff --git a/catalog/dags/data_refresh/data_refresh_task_factory.py b/catalog/dags/data_refresh/data_refresh_task_factory.pyindex adbfe5c54..1328e82b3 100644--- a/catalog/dags/data_refresh/data_refresh_task_factory.py+++ b/catalog/dags/data_refresh/data_refresh_task_factory.py@@ -49,15 +49,13 @@ import osfrom collections.abc import Sequencefrom airflow.models.baseoperator import chain-from airflow.sensors.external_task import ExternalTaskSensor-from airflow.utils.state import Statefrom airflow.utils.task_group import TaskGroupfrom airflow.utils.trigger_rule import TriggerRulefrom common import ingestion_serverfrom common.constants import XCOM_PULL_TEMPLATEfrom common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGsSensor-from common.sensors.utils import get_most_recent_dag_run+from common.sensors.utils import wait_for_external_dagfrom data_refresh.create_filtered_index import (create_filtered_index_creation_task_groups,)@@ -120,27 +118,9 @@ def create_data_refresh_task_group(# filtered index creation process, even if it was triggered immediately after# filtered index creation. However, it is safer to avoid the possibility# of the race condition altogether.- # ``execution_date_fn`` is used to find the most recent run because- # the filtered index creation DAGs are unscheduled so we can't derive- # anything from the execution date of the current data refresh DAG.- create_filtered_index_dag_id = (- f"create_filtered_{data_refresh.media_type}_index"+ wait_for_filtered_index_creation = wait_for_external_dag(+ external_dag_id=f"create_filtered_{data_refresh.media_type}_index",)- wait_for_filtered_index_creation = ExternalTaskSensor(- task_id="wait_for_create_and_populate_filtered_index",- external_dag_id=create_filtered_index_dag_id,- # Wait for the whole DAG, not just a part of it- external_task_id=None,- check_existence=False,- poke_interval=data_refresh.filtered_index_poke_interval,- execution_date_fn=lambda _: get_most_recent_dag_run(- create_filtered_index_dag_id- ),- mode="reschedule",- # Any "finished" state is sufficient for us to continue.- allowed_states=[State.SUCCESS, State.FAILED],- )-tasks.append([wait_for_data_refresh, wait_for_filtered_index_creation])# Get the index currently mapped to our target alias, to delete later.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.pyindex b3062d78a..942bf1b80 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,8 +28,6 @@ from textwrap import dedent as dfrom airflow.decorators import dagfrom airflow.providers.amazon.aws.operators.rds import RdsDeleteDbInstanceOperatorfrom airflow.providers.amazon.aws.sensors.rds import RdsSnapshotExistenceSensor-from airflow.sensors.external_task import ExternalTaskSensor-from airflow.utils.state import Statefrom airflow.utils.trigger_rule import TriggerRulefrom es.recreate_staging_index.recreate_full_staging_index import (DAG_ID as RECREATE_STAGING_INDEX_DAG_ID,@@ -39,9 +37,8 @@ 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.sensors.utils import wait_for_external_dagfrom common.sql import PGExecuteQueryOperatorfrom database.staging_database_restore import constantsfrom database.staging_database_restore.staging_database_restore import (@@ -80,19 +77,8 @@ 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",+ wait_for_recreate_full_staging_index = wait_for_external_dag(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()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.pyindex 7033a7c13..c72ef2000 100644--- a/catalog/dags/es/recreate_staging_index/recreate_full_staging_index.py+++ b/catalog/dags/es/recreate_staging_index/recreate_full_staging_index.py@@ -1,46 +1,14 @@from datetime import timedeltafrom airflow.decorators import task, task_group-from airflow.exceptions import AirflowSensorTimeout-from airflow.sensors.external_task import ExternalTaskSensor-from airflow.utils.state import Statefrom common import ingestion_server-from common.sensors.utils import get_most_recent_dag_runfrom 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."- )--@taskdef get_target_alias(media_type: str, target_alias_override: str):return target_alias_override or f"{media_type}-full"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.pyindex cf9fd4820..55f0a60ea 100644--- 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@@ -46,12 +46,15 @@ from es.recreate_staging_index.recreate_full_staging_index import (create_index,get_target_alias,point_alias,- prevent_concurrency_with_staging_database_restore,should_delete_index,)from common import ingestion_server, slackfrom common.constants import AUDIO, DAG_DEFAULT_ARGS, MEDIA_TYPES, XCOM_PULL_TEMPLATE+from common.sensors.utils import prevent_concurrency_with_dag+from database.staging_database_restore.constants import (+ DAG_ID as STAGING_DB_RESTORE_DAG_ID,+)@dag(@@ -91,7 +94,10 @@ from common.constants import AUDIO, DAG_DEFAULT_ARGS, MEDIA_TYPES, XCOM_PULL_TEMrender_template_as_native_obj=True,)def recreate_full_staging_index():- prevent_concurrency = prevent_concurrency_with_staging_database_restore()+ # Fail early if the staging_db_restore DAG is running+ prevent_concurrency = prevent_concurrency_with_dag.override(+ task_id="prevent_concurrency_with_staging_db_restore"+ )(external_dag_id=STAGING_DB_RESTORE_DAG_ID)target_alias = get_target_alias(media_type="{{ params.media_type }}",