Skip to content

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

Read DAG and task state through the Task SDK on Airflow 3 (#5814)

Olga Bulat9085f5c0babc
diff --git a/catalog/dags/common/dag_state.py b/catalog/dags/common/dag_state.py
new file mode 100644
index 000000000..9fec094b6
--- /dev/null
+++ b/catalog/dags/common/dag_state.py
@@ -0,0 +1,155 @@
+"""
+Read DAG run and task instance states from inside a running task.
+
+Airflow 2 tasks can query the metadata database directly. Airflow 3 blocks that,
+and tasks ask the API server through the Task SDK methods on the running task
+instance instead. Each function here picks the implementation for the installed
+Airflow version, so the DAGs behave the same on both. The Airflow 2 branches can
+be removed once the catalog runs Airflow 3.
+"""
+
+from urllib.parse import quote
+
+from airflow import __version__ as airflow_version
+from airflow.configuration import conf
+from airflow.exceptions import AirflowException
+from airflow.providers.standard.operators.python import get_current_context
+from airflow.utils.state import DagRunState, TaskInstanceState
+from packaging.version import Version
+
+
+IS_AIRFLOW_3 = Version(airflow_version).major >= 3
+
+ACTIVE_DAG_RUN_STATES = [DagRunState.QUEUED.value, DagRunState.RUNNING.value]
+
+# Run ids are sent to the API server as query parameters, so look them up in
+# batches to keep the request URL short
+RUN_ID_BATCH_SIZE = 20
+
+
+def _task_sdk_ti():
+ return get_current_context()["ti"]
+
+
+def assert_dag_exists(dag_id: str) -> None:
+ """Raise an `AirflowException` if no DAG with `dag_id` is deployed."""
+ if IS_AIRFLOW_3:
+ from airflow.sdk.exceptions import AirflowRuntimeError
+
+ try:
+ _task_sdk_ti().get_dag(dag_id)
+ except AirflowRuntimeError as error:
+ raise AirflowException(
+ f"The external DAG {dag_id} does not exist."
+ ) from error
+ return
+
+ from airflow.models import DagModel
+ from airflow.utils.session import create_session
+
+ with create_session() as session:
+ if not session.query(DagModel).filter(DagModel.dag_id == dag_id).first():
+ raise AirflowException(f"The external DAG {dag_id} does not exist.")
+
+
+def count_active_dag_runs(dag_id: str) -> int:
+ """Return the number of queued or running DAG runs for `dag_id`."""
+ if IS_AIRFLOW_3:
+ return _task_sdk_ti().get_dr_count(dag_id=dag_id, states=ACTIVE_DAG_RUN_STATES)
+
+ from airflow.models import DagRun
+ from airflow.utils.session import create_session
+
+ with create_session() as session:
+ return (
+ session.query(DagRun)
+ .filter(
+ DagRun.dag_id == dag_id,
+ DagRun.state.in_(ACTIVE_DAG_RUN_STATES),
+ )
+ .count()
+ )
+
+
+def count_running_dag_runs_past_task(dag_id: str, task_id: str) -> int:
+ """
+ Return the number of running DAG runs for `dag_id` in which the task `task_id`
+ has already succeeded.
+ """
+ running = DagRunState.RUNNING.value
+ success = TaskInstanceState.SUCCESS.value
+
+ if IS_AIRFLOW_3:
+ ti = _task_sdk_ti()
+ if not ti.get_dr_count(dag_id=dag_id, states=[running]):
+ return 0
+ task_states = ti.get_task_states(dag_id=dag_id, task_ids=[task_id])
+ succeeded_run_ids = [
+ run_id
+ for run_id, states in task_states.items()
+ if states.get(task_id) == success
+ ]
+ return sum(
+ ti.get_dr_count(
+ dag_id=dag_id,
+ run_ids=succeeded_run_ids[i : i + RUN_ID_BATCH_SIZE],
+ states=[running],
+ )
+ for i in range(0, len(succeeded_run_ids), RUN_ID_BATCH_SIZE)
+ )
+
+ from airflow.models import DagRun, TaskInstance
+ from airflow.utils.session import create_session
+
+ with create_session() as session:
+ return (
+ session.query(DagRun)
+ .filter(DagRun.dag_id == dag_id, DagRun.state == running)
+ .join(
+ TaskInstance,
+ (TaskInstance.dag_id == DagRun.dag_id)
+ & (TaskInstance.run_id == DagRun.run_id),
+ )
+ .filter(TaskInstance.task_id == task_id, TaskInstance.state == success)
+ .count()
+ )
+
+
+def get_task_states(dag_run) -> dict[str, str | None]:
+ """
+ Return the state of each task instance in `dag_run`, keyed by task id. Mapped
+ task instances are keyed by `<task_id>_<map_index>`.
+ """
+ if IS_AIRFLOW_3:
+ task_states = _task_sdk_ti().get_task_states(
+ dag_id=dag_run.dag_id, run_ids=[dag_run.run_id]
+ )
+ return task_states.get(dag_run.run_id, {})
+
+ return {
+ (ti.task_id if ti.map_index < 0 else f"{ti.task_id}_{ti.map_index}"): ti.state
+ for ti in dag_run.get_task_instances()
+ }
+
+
+DEFAULT_BASE_URL = "http://localhost:8080"
+
+
+def _base_url() -> str:
+ section = "api" if IS_AIRFLOW_3 else "webserver"
+ # `[api] base_url` has no default in Airflow 3, so `conf.get` raises without one
+ return conf.get(section, "base_url", fallback=DEFAULT_BASE_URL).rstrip("/")
+
+
+def dag_run_url(dag_id: str, run_id: str) -> str:
+ """Return the Airflow UI URL of a DAG run."""
+ if IS_AIRFLOW_3:
+ return f"{_base_url()}/dags/{quote(dag_id)}/runs/{quote(run_id)}"
+ return f"{_base_url()}/dags/{quote(dag_id)}/grid?dag_run_id={quote(run_id)}"
+
+
+def task_log_url(dag_id: str, run_id: str, task_id: str) -> str:
+ """Return the Airflow UI URL of a task instance's logs."""
+ if IS_AIRFLOW_3:
+ return f"{dag_run_url(dag_id, run_id)}/tasks/{quote(task_id)}"
+ return f"{dag_run_url(dag_id, run_id)}&task_id={quote(task_id)}&tab=logs"
diff --git a/catalog/dags/common/operators/http.py b/catalog/dags/common/operators/http.py
deleted file mode 100644
index b68e9ba7f..000000000
--- a/catalog/dags/common/operators/http.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from airflow.providers.http.operators.http import HttpOperator
-
-
-class TemplatedConnectionHttpOperator(HttpOperator):
- """
- Wrapper around the HTTPOperator which allows templating of the conn_id,
- in order to support using a conn_id passed through XCOMs.
- """
-
- # Extended to allow templating of conn_id
- template_fields = HttpOperator.template_fields + ("http_conn_id",)
diff --git a/catalog/dags/common/sensors/constants.py b/catalog/dags/common/sensors/constants.py
index 8d94c9bf3..ec6532954 100644
--- a/catalog/dags/common/sensors/constants.py
+++ b/catalog/dags/common/sensors/constants.py
@@ -17,3 +17,33 @@ ES_CONCURRENCY_TAGS = {
PRODUCTION: PRODUCTION_ES_CONCURRENCY_TAG,
STAGING: STAGING_ES_CONCURRENCY_TAG,
}
+
+# The DAGs that have each concurrency tag. Airflow 3 tasks cannot look tags up in the
+# metadata database, so they are listed here, and the DAG parsing tests check that
+# this matches the tags the DAGs actually have.
+CONCURRENCY_TAG_DAG_IDS = {
+ PRODUCTION_ES_CONCURRENCY_TAG: [
+ "audio_data_refresh",
+ "create_filtered_audio_index",
+ "create_filtered_image_index",
+ "create_new_production_es_index",
+ "image_data_refresh",
+ "point_production_es_alias",
+ "production_audio_data_refresh",
+ "production_image_data_refresh",
+ ],
+ STAGING_ES_CONCURRENCY_TAG: [
+ "create_new_staging_es_index",
+ "create_proportional_by_source_staging_index",
+ "point_staging_es_alias",
+ "recreate_full_staging_index",
+ "staging_audio_data_refresh",
+ "staging_image_data_refresh",
+ ],
+ STAGING_DB_CONCURRENCY_TAG: [
+ "recreate_full_staging_index",
+ "staging_audio_data_refresh",
+ "staging_database_restore",
+ "staging_image_data_refresh",
+ ],
+}
diff --git a/catalog/dags/common/sensors/http.py b/catalog/dags/common/sensors/http.py
deleted file mode 100644
index 0dc2652f7..000000000
--- a/catalog/dags/common/sensors/http.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from airflow.providers.http.sensors.http import HttpSensor
-
-
-class TemplatedConnectionHttpSensor(HttpSensor):
- """
- Wrapper around the HTTPSensor which allows templating of the conn_id,
- in order to support using a conn_id passed through XCOMs.
- """
-
- # Extended to allow templating of conn_id
- template_fields = HttpSensor.template_fields + ("http_conn_id",)
diff --git a/catalog/dags/common/sensors/single_run_external_dags_sensor.py b/catalog/dags/common/sensors/single_run_external_dags_sensor.py
index a6279b6dc..e9092ffff 100644
--- a/catalog/dags/common/sensors/single_run_external_dags_sensor.py
+++ b/catalog/dags/common/sensors/single_run_external_dags_sensor.py
@@ -1,11 +1,8 @@
-import os
from collections.abc import Iterable
-from airflow.exceptions import AirflowException
-from airflow.models import DagBag, DagModel, DagRun, TaskInstance
from airflow.sensors.base import BaseSensorOperator
-from airflow.utils.session import provide_session
-from airflow.utils.state import State
+
+from common.dag_state import assert_dag_exists, count_running_dag_runs_past_task
class SingleRunExternalDAGsSensor(BaseSensorOperator):
@@ -18,9 +15,12 @@ class SingleRunExternalDAGsSensor(BaseSensorOperator):
successfully. It looks for a task with the same `task_id` in each of the
provided external DAGs.
+ The DAG parsing tests check that each external DAG has a task with this sensor's
+ `task_id`.
+
:param external_dag_ids: A list of dag_ids that you want to wait for
- :param check_existence: Set to `True` to check if the external DAGs exist,
- and immediately cease waiting if not (default value: False).
+ :param check_existence: Set to `True` to fail if any of the external DAGs is not
+ deployed. The check runs on every poke (default value: False).
:param allow_concurrent_runs: Used to force the Sensor to pass, even
if there are concurrent runs.
"""
@@ -38,69 +38,30 @@ class SingleRunExternalDAGsSensor(BaseSensorOperator):
self.check_existence = check_existence
self.allow_concurrent_runs = allow_concurrent_runs
- # Used to ensure some checks are only evaluated on the first poke
- self._has_checked_params = False
-
- @provide_session
- def poke(self, context, session=None):
+ def poke(self, context):
self.log.info(
"Poking for DAGs %s ...",
self.external_dag_ids,
)
- if not self._has_checked_params:
- if self.allow_concurrent_runs:
- self.log.info(
- "`allow_concurrent_runs` is enabled. Returning without"
- " checking for running DAGs."
- )
- return True
-
- if self.check_existence:
- self._check_for_existence(session=session)
-
- # Only check DAG existence and `allow_concurrent_runs`
- # on the first execution.
- self._has_checked_params = True
-
- count_running = self.get_count(session)
-
- self.log.info("%s DAGs are in the running state", count_running)
- return count_running == 0
-
- def _check_for_existence(self, session) -> None:
- for dag_id in self.external_dag_ids:
- dag_to_wait = (
- session.query(DagModel).filter(DagModel.dag_id == dag_id).first()
+ if self.allow_concurrent_runs:
+ self.log.info(
+ "`allow_concurrent_runs` is enabled. Returning without"
+ " checking for running DAGs."
)
+ return True
- if not dag_to_wait:
- raise AirflowException(f"The external DAG {dag_id} does not exist.")
+ if self.check_existence:
+ for dag_id in self.external_dag_ids:
+ assert_dag_exists(dag_id)
- if not os.path.exists(dag_to_wait.fileloc):
- raise AirflowException(f"The external DAG {dag_id} was deleted.")
-
- refreshed_dag_info = DagBag(dag_to_wait.fileloc).get_dag(dag_id)
- if not refreshed_dag_info.has_task(self.task_id):
- raise AirflowException(
- f"The external DAG {dag_id} does not have a task "
- f"with id {self.task_id}."
- )
+ # A DAG is considered 'running' if the DAG itself is in the running state,
+ # and if its instance of the Sensor task has completed successfully. Stop
+ # at the first one, since a single running DAG is enough to wait.
+ for dag_id in self.external_dag_ids:
+ if count_running_dag_runs_past_task(dag_id, self.task_id):
+ self.log.info("DAG %s is in the running state", dag_id)
+ return False
- def get_count(self, session) -> int:
- # Get the count of running DAGs. A DAG is considered 'running' if
- # the DAG itself is in the running state, and if its instance of
- # the Sensor task has completed successfully.
- return (
- session.query(DagRun)
- .filter(
- DagRun.dag_id.in_(self.external_dag_ids),
- DagRun.state == State.RUNNING,
- )
- .join(TaskInstance, TaskInstance.run_id == DagRun.run_id)
- .filter(
- TaskInstance.task_id == self.task_id,
- TaskInstance.state == State.SUCCESS,
- )
- .count()
- )
+ self.log.info("None of the DAGs are in the running state")
+ return True
diff --git a/catalog/dags/common/sensors/utils.py b/catalog/dags/common/sensors/utils.py
index d8dee2ba9..d5ee46b3c 100644
--- a/catalog/dags/common/sensors/utils.py
+++ b/catalog/dags/common/sensors/utils.py
@@ -1,54 +1,22 @@
-from datetime import datetime
-
from airflow.decorators import task, task_group
from airflow.exceptions import AirflowSensorTimeout
-from airflow.models import DagModel, DagRun, DagTag
-from airflow.providers.standard.sensors.external_task import ExternalTaskSensor
-from airflow.utils.session import provide_session
-from airflow.utils.state import State
+from airflow.providers.standard.sensors.python import PythonSensor
from common.constants import REFRESH_POKE_INTERVAL
+from common.dag_state import count_active_dag_runs
+from common.sensors.constants import CONCURRENCY_TAG_DAG_IDS
THREE_DAYS = 60 * 60 * 24 * 3
-def _get_most_recent_dag_run(dag_id) -> list[datetime] | datetime:
- """
- Retrieve the most recent DAG run's execution date.
-
- For use as ``execution_date_fn`` argument to ``ExternalTaskSensor``.
-
- Adapted from <https://stackoverflow.com/a/74017474>
- CC BY-SA 4.0 by Stack Overflow user Nahid O.
- """
- dag_runs = DagRun.find(dag_id=dag_id)
- dag_runs.sort(key=lambda x: x.logical_date, reverse=True)
- if dag_runs:
- return dag_runs[0].logical_date
-
- # If there are no DAG runs, return an empty list to indicate that
- # there are no execution dates to check.
- # This works because the sensor waits until the number
- # of runs for the execution dates in the ``allowed_states`` matches the
- # length of the list of execution dates to check. If there are no runs
- # for this DAG, then the only possible number of required states
- # we can have is 0. See ``ExternalTaskSensor::poke`` and
- # ``ExternalTaskSensor::get_count``, especially the handling
- # of ``dttm_filter`` for the relevant implementation details.
- return []
-
-
@task
-def get_dags_with_concurrency_tag(
- tag: str, excluded_dag_ids: list[str], session=None, dag=None
-):
+def get_dags_with_concurrency_tag(tag: str, excluded_dag_ids: list[str], dag=None):
"""
Get a list of DAG ids with the given tag. The id of the running DAG is excluded,
as well as any ids in the `excluded_dag_ids` list.
"""
- dags = session.query(DagModel).filter(DagModel.tags.any(DagTag.name == tag)).all()
- dag_ids = [dag.dag_id for dag in dags]
+ dag_ids = CONCURRENCY_TAG_DAG_IDS.get(tag, [])
running_dag_id = dag.dag_id
if running_dag_id not in dag_ids:
@@ -56,7 +24,8 @@ def get_dags_with_concurrency_tag(
f"The `{running_dag_id}` DAG tried preventing concurrency with the `{tag}`,"
" tag, but does not have the tag itself. To ensure that other DAGs with this"
f" tag will also avoid running concurrently with `{running_dag_id}`, it must"
- f"have the `{tag}` tag applied."
+ f" have the `{tag}` tag applied and be listed under it in"
+ " `CONCURRENCY_TAG_DAG_IDS`."
)
# Return just the ids of DAGs to prevent concurrency with. This excludes the running dag id,
@@ -73,7 +42,7 @@ def wait_for_external_dag(
):
"""
Execute a Sensor task which will wait if the given external DAG is
- running.
+ queued or running.
To fully ensure that the waiting DAG and the external DAG do not run
concurrently, the external DAG should have a `prevent_concurrency_with_dag`
@@ -86,17 +55,12 @@ def wait_for_external_dag(
if not task_id:
task_id = f"wait_for_{external_dag_id}"
- sensor = ExternalTaskSensor(
+ sensor = PythonSensor(
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),
+ # Wait until no run of the external DAG is queued or running
+ python_callable=lambda: count_active_dag_runs(external_dag_id) == 0,
mode="reschedule",
- # Any "finished" state is sufficient for us to continue
- allowed_states=[State.SUCCESS, State.FAILED],
# execution_timeout for the task does not include time that the sensor
# was up for reschedule but not actually running. `timeout` does
timeout=timeout,
@@ -106,17 +70,14 @@ def wait_for_external_dag(
@task_group(group_id="wait_for_external_dags")
-@provide_session
-def wait_for_external_dags_with_tag(
- tag: str, excluded_dag_ids: list[str] = None, session=None
-):
+def wait_for_external_dags_with_tag(tag: str, excluded_dag_ids: list[str] = None):
"""
Wait until all DAGs with the given `tag`, excluding those identified by the
`excluded_dag_ids`, are no longer in the running state before continuing.
"""
external_dag_ids = get_dags_with_concurrency_tag.override(
task_id=f"get_dags_in_{tag}_group"
- )(tag=tag, excluded_dag_ids=excluded_dag_ids or [], session=session)
+ )(tag=tag, excluded_dag_ids=excluded_dag_ids or [])
wait_for_external_dag.expand(external_dag_id=external_dag_ids)
@@ -139,9 +100,8 @@ def prevent_concurrency_with_dag(external_dag_id: str, **context):
@task_group(group_id="prevent_concurrency_with_dags")
-@provide_session
def prevent_concurrency_with_dags_with_tag(
- tag: str, excluded_dag_ids: list[str] = None, session=None
+ tag: str, excluded_dag_ids: list[str] = None
):
"""
Prevent concurrency with any DAGs that have the given `tag`, excluding
@@ -151,7 +111,7 @@ def prevent_concurrency_with_dags_with_tag(
"""
external_dag_ids = get_dags_with_concurrency_tag.override(
task_id=f"get_dags_in_{tag}_group"
- )(tag=tag, excluded_dag_ids=excluded_dag_ids or [], session=session)
+ )(tag=tag, excluded_dag_ids=excluded_dag_ids or [])
prevent_concurrency_with_dag.expand(external_dag_id=external_dag_ids)
diff --git a/catalog/dags/data_refresh/constants.py b/catalog/dags/data_refresh/constants.py
index 6a74f93d8..fef8e227d 100644
--- a/catalog/dags/data_refresh/constants.py
+++ b/catalog/dags/data_refresh/constants.py
@@ -1,8 +1,19 @@
+from datetime import timedelta
+
from common.constants import PRODUCTION, STAGING
INDEXER_WORKER_COUNTS = {STAGING: 2, PRODUCTION: 6}
+INDEXER_WORKER_PORT = 8003
+
+# Seconds to wait for the indexer worker API to respond to a request
+INDEXER_WORKER_REQUEST_TIMEOUT = 60
+
+# Retries for a reindex status check that fails, for example on a dropped connection
+WAIT_FOR_REINDEXING_RETRIES = 3
+WAIT_FOR_REINDEXING_RETRY_DELAY = timedelta(minutes=2)
+
INDEXER_LAUNCH_TEMPLATES = {
STAGING: "indexer-worker-pool-s",
PRODUCTION: "indexer-worker-pool-p",
diff --git a/catalog/dags/data_refresh/distributed_reindex.py b/catalog/dags/data_refresh/distributed_reindex.py
index 48c6276d2..f81d24ba9 100644
--- a/catalog/dags/data_refresh/distributed_reindex.py
+++ b/catalog/dags/data_refresh/distributed_reindex.py
@@ -10,10 +10,9 @@ import math
from textwrap import dedent
from urllib.parse import urlparse
-from airflow import settings
+import requests
from airflow.decorators import task, task_group
from airflow.exceptions import AirflowSkipException
-from airflow.models.connection import Connection
from airflow.providers.amazon.aws.hooks.ec2 import EC2Hook
from airflow.providers.common.sql.hooks.handlers import fetch_one_handler
from airflow.providers.standard.operators.empty import EmptyOperator
@@ -28,10 +27,15 @@ from common.constants import (
PRODUCTION,
Environment,
)
-from common.operators.http import TemplatedConnectionHttpOperator
-from common.sensors.http import TemplatedConnectionHttpSensor
from common.sql import PGExecuteQueryOperator
-from data_refresh.constants import INDEXER_LAUNCH_TEMPLATES, INDEXER_WORKER_COUNTS
+from data_refresh.constants import (
+ INDEXER_LAUNCH_TEMPLATES,
+ INDEXER_WORKER_COUNTS,
+ INDEXER_WORKER_PORT,
+ INDEXER_WORKER_REQUEST_TIMEOUT,
+ WAIT_FOR_REINDEXING_RETRIES,
+ WAIT_FOR_REINDEXING_RETRY_DELAY,
+)
from data_refresh.data_refresh_types import DataRefreshConfig
@@ -245,30 +249,43 @@ def get_instance_ip_address(
return reservations[0].get("Instances", {})[0].get("PrivateIpAddress")
-@task(
- # Instance creation tasks are skipped locally, but we still want this task to run.
- trigger_rule=TriggerRule.NONE_FAILED
-)
-def create_connection(
- environment: str,
- instance_id: str,
- media_type: str,
- server: str,
-):
+# A retry after a timed-out request could start a second reindex of the same range
+@task(retries=0)
+def trigger_reindexing_task(server: str, data: dict) -> str:
"""
- Create an Airflow Connection for the given indexer worker and persist it. It will
- later be dropped in a cleanup task.
+ Start a reindexing task on the indexer worker on `server` and return the URL for
+ checking its status.
"""
- worker_conn_id = f"indexer_worker_{instance_id or media_type}"
+ worker_url = f"http://{server}:{INDEXER_WORKER_PORT}"
+ response = requests.post(
+ f"{worker_url}/task", data=data, timeout=INDEXER_WORKER_REQUEST_TIMEOUT
+ )
+ response.raise_for_status()
+ if response.status_code != 202:
+ raise ValueError(
+ f"The indexer worker responded with {response.status_code} instead of 202."
+ )
+ return f"{worker_url}{response_filter_status_check_endpoint(response)}"
- # Create the Connection
- logger.info(f"Creating connection with id {worker_conn_id}")
- worker_conn = Connection(conn_id=worker_conn_id, uri=f"http://{server}:8003/")
- session = settings.Session()
- session.add(worker_conn)
- session.commit()
- return worker_conn_id
+ mode="reschedule",
+ retries=WAIT_FOR_REINDEXING_RETRIES,
+ retry_delay=WAIT_FOR_REINDEXING_RETRY_DELAY,
+)
+def wait_for_reindexing_task(status_url: str) -> bool:
+ """
+ Wait for the reindexing task on the indexer worker to finish. A failed status
+ request fails the try, and the task's own retries poll again. One dropped
+ request doesn't fail a reindex that takes many hours, but a worker that stays
+ unreachable fails it within minutes instead of at the sensor timeout.
+ """
+ response = requests.get(status_url, timeout=INDEXER_WORKER_REQUEST_TIMEOUT)
+ # The worker may not know about the task yet
+ if response.status_code == 404:
+ return False
+ response.raise_for_status()
+ return response_check_wait_for_completion(response)
@task
@@ -286,24 +303,14 @@ def terminate_indexer_worker(
return ec2_hook.conn.terminate_instances(InstanceIds=[instance_id])
-@task(trigger_rule=TriggerRule.ALL_DONE)
-def drop_connection(worker_conn: str):
- """Drop the Connection to the now terminated instance."""
- conn = Connection.get_connection_from_secrets(worker_conn)
-
- session = settings.Session()
- session.delete(conn)
- session.commit()
-
-
def assert_reindexing_success() -> EmptyOperator:
"""
Fail if the direct upstream tasks, which perform the actual reindexing,
fail. Otherwise simply pass.
This is necessary because we have some tasks after the reindex step
- which always run even on reindexing failure (to drop the connection
- and terminate the worker instance). However in the event of failures,
+ which always run even on reindexing failure (to terminate the worker
+ instance). However in the event of failures,
we still need the last task in the TaskGroup to be marked as `Failed`
or else subsequent tasks (like the promotion steps) will run. It is
not possible to set individual tasks within a TaskGroup as
@@ -347,17 +354,8 @@ def reindex(
environment=environment, instance_id=instance_id
)
- worker_conn = create_connection(
- environment=environment,
- instance_id=instance_id,
- media_type=data_refresh_config.media_type,
+ status_url = trigger_reindexing_task(
server=instance_ip_address,
- )
-
- trigger_reindexing_task = TemplatedConnectionHttpOperator(
- task_id="trigger_reindexing_task",
- http_conn_id=worker_conn,
- endpoint="task",
data={
"model_name": data_refresh_config.media_type,
"table_name": data_refresh_config.table_mapping.temp_table_name,
@@ -365,20 +363,12 @@ def reindex(
"start_id": start_id,
"end_id": end_id,
},
- response_check=lambda response: response.status_code == 202,
- response_filter=response_filter_status_check_endpoint,
)
- wait_for_reindexing_task = TemplatedConnectionHttpSensor(
- task_id="wait_for_reindexing_task",
- http_conn_id=worker_conn,
- endpoint=trigger_reindexing_task.output,
- method="GET",
- response_check=response_check_wait_for_completion,
- mode="reschedule",
+ await_reindexing = wait_for_reindexing_task.override(
poke_interval=data_refresh_config.reindex_poke_interval,
- timeout=data_refresh_config.indexer_worker_timeout,
- )
+ timeout=data_refresh_config.indexer_worker_timeout.total_seconds(),
+ )(status_url=status_url)
terminate_instance = terminate_indexer_worker.override(
# Terminate the instance even if there is an upstream failure
@@ -390,11 +380,8 @@ def reindex(
status = assert_reindexing_success()
- drop_conn = drop_connection(worker_conn=worker_conn)
-
- instance_id >> await_worker >> [instance_ip_address, worker_conn]
- worker_conn >> trigger_reindexing_task >> wait_for_reindexing_task
- wait_for_reindexing_task >> [terminate_instance, drop_conn, status]
+ instance_id >> await_worker >> instance_ip_address
+ await_reindexing >> [terminate_instance, status]
@task_group(
diff --git a/catalog/dags/legacy_data_refresh/data_refresh_task_factory.py b/catalog/dags/legacy_data_refresh/data_refresh_task_factory.py
index b987d9043..111fb9072 100644
--- a/catalog/dags/legacy_data_refresh/data_refresh_task_factory.py
+++ b/catalog/dags/legacy_data_refresh/data_refresh_task_factory.py
@@ -56,7 +56,7 @@ from airflow.utils.state import TaskInstanceState
from airflow.utils.task_group import TaskGroup
from airflow.utils.trigger_rule import TriggerRule
-from common import cloudwatch, ingestion_server
+from common import cloudwatch, dag_state, ingestion_server
from common.constants import (
AUDIO,
DATA_REFRESH_POOL,
@@ -85,7 +85,7 @@ TEMP_TABLES = {
@task(trigger_rule=TriggerRule.ONE_FAILED)
-def drop_temp_tables(media_type: str, ingest_trigger_task_id: str, ti=None):
+def drop_temp_tables(media_type: str, ingest_trigger_task_id: str, dag_run=None):
"""
Drop the API DB temp tables a failed data refresh left behind.
@@ -98,8 +98,8 @@ def drop_temp_tables(media_type: str, ingest_trigger_task_id: str, ti=None):
for example while waiting on other Elasticsearch DAGs, the tables may belong to
a refresh that is still running.
"""
- trigger_ti = ti.get_dagrun().get_task_instance(ingest_trigger_task_id)
- if trigger_ti is None or trigger_ti.state != TaskInstanceState.SUCCESS:
+ trigger_state = dag_state.get_task_states(dag_run).get(ingest_trigger_task_id)
+ if trigger_state != TaskInstanceState.SUCCESS:
raise AirflowSkipException(
"This run did not trigger ingest_upstream, so it created no temp tables."
)
diff --git a/catalog/dags/providers/provider_dag_factory.py b/catalog/dags/providers/provider_dag_factory.py
index 0b6246f4c..4411cd0ae 100644
--- a/catalog/dags/providers/provider_dag_factory.py
+++ b/catalog/dags/providers/provider_dag_factory.py
@@ -66,11 +66,9 @@ https://github.com/creativecommons/cccatalog/issues/334)
import logging
import os
import re
-import urllib.parse
from string import Template
from airflow import DAG
-from airflow.configuration import conf
from airflow.decorators import task
from airflow.exceptions import AirflowSkipException
from airflow.models import Variable
@@ -82,7 +80,7 @@ from airflow.utils.state import State
from airflow.utils.task_group import TaskGroup
from airflow.utils.trigger_rule import TriggerRule
-from common import slack
+from common import dag_state, slack
from common.constants import AWS_CONN_ID, DAG_DEFAULT_ARGS, XCOM_PULL_TEMPLATE
from common.constants import POSTGRES_CONN_ID as DB_CONN_ID
from common.loader import loader, reporting, s3, sql
@@ -585,33 +583,40 @@ def report_aggregate_reingestion_errors(
"""
# Get the list of failed `pull_data` tasks
media_type_name = _get_media_type_descriptor(provider_conf.media_types)
- failed_pull_data_tasks = [
- task
- for task in dag_run.get_task_instances(state=State.FAILED)
- if f"pull_{media_type_name}_data" in task.task_id
- ]
-
- base_url = conf.get("webserver", "BASE_URL")
- dag_run_url = f"{base_url}/dags/{dag_run.dag_id}/grid?dag_run_id={urllib.parse.quote(dag_run.run_id)}"
+ failed_pull_data_task_ids = sorted(
+ (
+ task_id
+ for task_id, state in dag_state.get_task_states(dag_run).items()
+ if state == State.FAILED and f"pull_{media_type_name}_data" in task_id
+ ),
+ # Order by day shift, so that day_shift_2 comes before day_shift_10
+ key=lambda task_id: [
+ int(part) if part.isdigit() else part
+ for part in re.split(r"(\d+)", task_id)
+ ],
+ )
- if not failed_pull_data_tasks:
+ if not failed_pull_data_task_ids:
raise AirflowSkipException
+ dag_run_url = dag_state.dag_run_url(dag_run.dag_id, dag_run.run_id)
+
message = (
(
- f"Ingestion errors were encountered in {len(failed_pull_data_tasks)}"
+ f"Ingestion errors were encountered in {len(failed_pull_data_task_ids)}"
f" ingestion days while running the `{provider_conf.dag_id}` DAG "
f"(<{dag_run_url}|link>). See the"
" logs for details"
)
+ (
" (showing only the first 5):\n"
- if len(failed_pull_data_tasks) > 5
+ if len(failed_pull_data_task_ids) > 5
else ":\n"
)
+ "\n".join(
- f" - <{task.log_url}|{task.task_id}>"
- for task in failed_pull_data_tasks[:5]
+ f" - <{dag_state.task_log_url(dag_run.dag_id, dag_run.run_id, task_id)}"
+ f"|{task_id}>"
+ for task_id in failed_pull_data_task_ids[:5]
)
)
diff --git a/catalog/tests/dags/common/sensors/test_single_run_external_dags_sensor.py b/catalog/tests/dags/common/sensors/test_single_run_external_dags_sensor.py
index a544f92ad..6c28c1b1e 100644
--- a/catalog/tests/dags/common/sensors/test_single_run_external_dags_sensor.py
+++ b/catalog/tests/dags/common/sensors/test_single_run_external_dags_sensor.py
@@ -2,7 +2,7 @@ import logging
import pytest
from airflow.exceptions import AirflowException
-from airflow.models import DagBag, Pool
+from airflow.models import Pool
from airflow.models.dag import DAG
from airflow.utils.state import State
from airflow.utils.timezone import datetime
@@ -13,7 +13,6 @@ from common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGs
DEFAULT_DATE = datetime(2022, 1, 1)
TEST_TASK_ID = "wait_task"
-DEV_NULL = "/dev/null"
def run_sensor(sensor):
@@ -24,7 +23,6 @@ def create_task(dag, task_id, sample_pool_fixture):
return SingleRunExternalDAGsSensor(
task_id=task_id,
external_dag_ids=[],
- check_existence=True,
dag=dag,
pool=sample_pool_fixture,
poke_interval=5,
@@ -70,92 +68,6 @@ def setup_pool(sample_pool_fixture):
)
[email protected]("clean_db")
-# This appears to be coming from Airflow internals during testing as a result of
-# loading the example DAGs:
-# /opt/airflow/.local/lib/python3.10/site-packages/airflow/example_dags/example_subdag_operator.py:43: RemovedInAirflow3Warning # noqa: E501
- "ignore:This class is deprecated. Please use "
- "`airflow.utils.task_group.TaskGroup`.:airflow.exceptions.RemovedInAirflow3Warning"
-)
-# This also appears to be coming from Airflow internals during testing as a result of
-# loading the example bash operator DAG:
-# /home/airflow/.local/lib/python3.10/site-packages/airflow/models/dag.py:3492: RemovedInAirflow3Warning # noqa: E501
- "ignore:Param `schedule_interval` is deprecated and will be removed in a future release. "
- "Please use `schedule` instead.:airflow.exceptions.RemovedInAirflow3Warning"
-)
-def test_fails_if_external_dag_does_not_exist(clean_db, setup_pool):
- with pytest.raises(
- AirflowException,
- match="The external DAG nonexistent_dag_id does not exist.",
- ):
- dag = DAG(
- "test_missing_dag_error",
- schedule=None,
- default_args={
- "owner": "airflow",
- "start_date": DEFAULT_DATE,
- },
- )
- sensor = SingleRunExternalDAGsSensor(
- task_id=TEST_TASK_ID,
- external_dag_ids=[
- "nonexistent_dag_id",
- ],
- check_existence=True,
- poke_interval=5,
- mode="reschedule",
- dag=dag,
- )
-
- run_sensor(sensor)
-
-
- "ignore:This class is deprecated. Please use "
- "`airflow.utils.task_group.TaskGroup`.:airflow.exceptions.RemovedInAirflow3Warning"
-)
-# This also appears to be coming from Airflow internals during testing as a result of
-# loading the example bash operator DAG:
-# /home/airflow/.local/lib/python3.10/site-packages/airflow/models/dag.py:3492: RemovedInAirflow3Warning # noqa: E501
- "ignore:Param `schedule_interval` is deprecated and will be removed in a future release. "
- "Please use `schedule` instead.:airflow.exceptions.RemovedInAirflow3Warning"
-)
-def test_fails_if_external_dag_missing_sensor_task(clean_db, setup_pool):
- # Loads an example DAG which does not have a Sensor task.
- dagbag = DagBag(dag_folder=DEV_NULL, include_examples=True)
- bash_dag = dagbag.dags["example_bash_operator"]
- bash_dag.sync_to_db()
-
- error_msg = (
- "The external DAG example_bash_operator does not have a task"
- f" with id {TEST_TASK_ID}"
- )
- with pytest.raises(AirflowException, match=error_msg):
- dag = DAG(
- "test_missing_task_error",
- schedule=None,
- default_args={
- "owner": "airflow",
- "start_date": DEFAULT_DATE,
- },
- )
- sensor = SingleRunExternalDAGsSensor(
- task_id=TEST_TASK_ID,
- external_dag_ids=[
- "example_bash_operator",
- ],
- check_existence=True,
- poke_interval=5,
- mode="reschedule",
- dag=dag,
- )
-
- run_sensor(sensor)
-
-
@pytest.mark.filterwarnings(
"ignore:This class is deprecated. Please use "
"`airflow.utils.task_group.TaskGroup`.:airflow.exceptions.RemovedInAirflow3Warning"
@@ -205,7 +117,7 @@ def test_succeeds_if_no_running_dags(
"Poking for DAGs ['successful_dag', 'failed_dag', 'queued_dag'] ..."
in caplog.text
)
- assert "0 DAGs are in the running state" in caplog.text
+ assert "None of the DAGs are in the running state" in caplog.text
@pytest.mark.filterwarnings(
@@ -215,7 +127,7 @@ def test_succeeds_if_no_running_dags(
@pytest.mark.parametrize(
"allow_concurrent_runs, expected_message",
[
- (False, "1 DAGs are in the running state"),
+ (False, "DAG {dag_id_prefix}_running_dag is in the running state"),
(
True,
"`allow_concurrent_runs` is enabled. Returning without checking for"
@@ -281,4 +193,20 @@ def test_retries_if_running_dags_with_completed_sensor_task(
f"{sample_dag_id_fixture}_success_dag', '{sample_dag_id_fixture}_running_dag'] ..."
in caplog.text
)
- assert expected_message in caplog.text
+ assert (
+ expected_message.format(dag_id_prefix=sample_dag_id_fixture) in caplog.text
+ )
+
+
+def test_check_existence_fails_for_missing_dag():
+ sensor = SingleRunExternalDAGsSensor(
+ task_id=TEST_TASK_ID,
+ external_dag_ids=["nonexistent_dag_id"],
+ check_existence=True,
+ poke_interval=5,
+ mode="reschedule",
+ )
+ with pytest.raises(
+ AirflowException, match="The external DAG nonexistent_dag_id does not exist."
+ ):
+ sensor.poke(context={})
diff --git a/catalog/tests/dags/common/sensors/test_utils.py b/catalog/tests/dags/common/sensors/test_utils.py
index ff416fd9d..f3e48bf88 100644
--- a/catalog/tests/dags/common/sensors/test_utils.py
+++ b/catalog/tests/dags/common/sensors/test_utils.py
@@ -1,41 +1,30 @@
-from datetime import timedelta
+from unittest import mock
-from airflow.models.dag import DAG
-from airflow.utils.state import State
-from airflow.utils.timezone import datetime
-from airflow.utils.types import DagRunType
+import pytest
-from common.sensors.utils import _get_most_recent_dag_run
+from common.sensors.constants import (
+ PRODUCTION_ES_CONCURRENCY_TAG,
+ STAGING_DB_CONCURRENCY_TAG,
+)
+from common.sensors.utils import get_dags_with_concurrency_tag
-TEST_DAG_ID = "data_refresh_dag_factory_test_dag"
-TEST_DAG = DAG(TEST_DAG_ID, schedule=None, default_args={"owner": "airflow"})
+def test_get_dags_with_concurrency_tag_excludes_running_and_excluded_dags():
+ dag = mock.MagicMock(dag_id="staging_database_restore")
-
-def _create_dagrun(start_date, sample_dag_id_fixture, conf={}):
- return DAG(
- sample_dag_id_fixture, schedule=None, default_args={"owner": "airflow"}
- ).create_dagrun(
- start_date=start_date,
- execution_date=start_date,
- data_interval=(start_date, start_date),
- state=State.SUCCESS,
- run_type=DagRunType.MANUAL,
- conf=conf,
+ actual = get_dags_with_concurrency_tag.function(
+ tag=STAGING_DB_CONCURRENCY_TAG,
+ excluded_dag_ids=["staging_audio_data_refresh"],
+ dag=dag,
)
+ assert actual == ["recreate_full_staging_index", "staging_image_data_refresh"]
-def test_get_most_recent_dag_run_returns_most_recent_execution_date(
- sample_dag_id_fixture, clean_db
-):
- most_recent = datetime(2023, 5, 10)
- for i in range(3):
- _create_dagrun(most_recent - timedelta(days=i), sample_dag_id_fixture)
- assert _get_most_recent_dag_run(sample_dag_id_fixture) == most_recent
+def test_get_dags_with_concurrency_tag_requires_the_running_dag_to_have_the_tag():
+ dag = mock.MagicMock(dag_id="staging_database_restore")
-def test_get_most_recent_dag_run_returns_empty_list_when_no_runs(
- sample_dag_id_fixture, clean_db
-):
- # Relies on ``clean_db`` cleaning up DagRuns from other tests
- assert _get_most_recent_dag_run(sample_dag_id_fixture) == []
+ with pytest.raises(ValueError, match="does not have the tag itself"):
+ get_dags_with_concurrency_tag.function(
+ tag=PRODUCTION_ES_CONCURRENCY_TAG, excluded_dag_ids=[], dag=dag
+ )
diff --git a/catalog/tests/dags/common/test_dag_state.py b/catalog/tests/dags/common/test_dag_state.py
new file mode 100644
index 000000000..3bb3489bc
--- /dev/null
+++ b/catalog/tests/dags/common/test_dag_state.py
@@ -0,0 +1,245 @@
+from datetime import timedelta
+from unittest import mock
+
+import pytest
+from airflow.exceptions import AirflowException
+from airflow.models import DagModel
+from airflow.models.dag import DAG
+from airflow.providers.standard.operators.empty import EmptyOperator
+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 dag_state
+
+
+DEFAULT_DATE = datetime(2022, 1, 1)
+TASK_ID = "wait_task"
+
+
+def airflow_3_ti():
+ ti = mock.MagicMock()
+ with (
+ mock.patch.object(dag_state, "IS_AIRFLOW_3", True),
+ mock.patch.object(dag_state, "_task_sdk_ti", return_value=ti),
+ ):
+ yield ti
+
+
+def airflow_2():
+ with mock.patch.object(dag_state, "IS_AIRFLOW_3", False):
+ yield
+
+
+def _create_dag_run(dag_id, state, run_number=0, task_state=None):
+ with DAG(dag_id, schedule=None, start_date=DEFAULT_DATE) as dag:
+ EmptyOperator(task_id=TASK_ID)
+ logical_date = DEFAULT_DATE + timedelta(days=run_number)
+ dag_run = dag.create_dagrun(
+ run_id=f"{dag_id}_{run_number}",
+ start_date=logical_date,
+ execution_date=logical_date,
+ data_interval=(logical_date, logical_date),
+ state=state,
+ run_type=DagRunType.MANUAL,
+ )
+ if task_state:
+ ti = dag_run.get_task_instance(TASK_ID)
+ ti.set_state(task_state)
+ return dag_run
+
+
[email protected]("airflow_2", "clean_db")
+ "states, expected",
+ [
+ pytest.param([], 0, id="no-runs"),
+ pytest.param([DagRunState.SUCCESS, DagRunState.FAILED], 0, id="finished"),
+ pytest.param([DagRunState.SUCCESS, DagRunState.RUNNING], 1, id="running"),
+ pytest.param([DagRunState.QUEUED, DagRunState.RUNNING], 2, id="queued"),
+ ],
+)
+def test_count_active_dag_runs_on_airflow_2(sample_dag_id_fixture, states, expected):
+ for run_number, state in enumerate(states):
+ _create_dag_run(sample_dag_id_fixture, state, run_number)
+
+ assert dag_state.count_active_dag_runs(sample_dag_id_fixture) == expected
+
+
+def test_count_active_dag_runs_on_airflow_3(airflow_3_ti):
+ airflow_3_ti.get_dr_count.return_value = 2
+
+ assert dag_state.count_active_dag_runs("some_dag") == 2
+ airflow_3_ti.get_dr_count.assert_called_once_with(
+ dag_id="some_dag", states=["queued", "running"]
+ )
+
+
[email protected]("airflow_2", "clean_db")
+ "runs, expected",
+ [
+ pytest.param([], 0, id="no-runs"),
+ pytest.param([(DagRunState.RUNNING, None)], 0, id="task-not-started"),
+ pytest.param(
+ [(DagRunState.RUNNING, TaskInstanceState.RUNNING)], 0, id="task-running"
+ ),
+ pytest.param(
+ [(DagRunState.SUCCESS, TaskInstanceState.SUCCESS)], 0, id="run-finished"
+ ),
+ pytest.param(
+ [
+ (DagRunState.RUNNING, TaskInstanceState.SUCCESS),
+ (DagRunState.SUCCESS, TaskInstanceState.SUCCESS),
+ ],
+ 1,
+ id="task-succeeded-in-running-run",
+ ),
+ ],
+)
+def test_count_running_dag_runs_past_task_on_airflow_2(
+ sample_dag_id_fixture, runs, expected
+):
+ for run_number, (state, task_state) in enumerate(runs):
+ _create_dag_run(sample_dag_id_fixture, state, run_number, task_state)
+
+ assert (
+ dag_state.count_running_dag_runs_past_task(sample_dag_id_fixture, TASK_ID)
+ == expected
+ )
+
+
+def test_count_running_dag_runs_past_task_on_airflow_3_skips_idle_dags(airflow_3_ti):
+ airflow_3_ti.get_dr_count.return_value = 0
+
+ assert dag_state.count_running_dag_runs_past_task("some_dag", TASK_ID) == 0
+ airflow_3_ti.get_task_states.assert_not_called()
+
+
+def test_count_running_dag_runs_past_task_on_airflow_3(airflow_3_ti):
+ succeeded_run_ids = [f"run_{i}" for i in range(dag_state.RUN_ID_BATCH_SIZE + 1)]
+ airflow_3_ti.get_task_states.return_value = {
+ **{run_id: {TASK_ID: "success"} for run_id in succeeded_run_ids},
+ "running_task": {TASK_ID: "running"},
+ "other_task": {"other": "success"},
+ }
+ # One running DAG run, then one per batch of succeeded run ids
+ airflow_3_ti.get_dr_count.side_effect = [1, 1, 0]
+
+ assert dag_state.count_running_dag_runs_past_task("some_dag", TASK_ID) == 1
+ airflow_3_ti.get_task_states.assert_called_once_with(
+ dag_id="some_dag", task_ids=[TASK_ID]
+ )
+ assert airflow_3_ti.get_dr_count.call_args_list == [
+ mock.call(dag_id="some_dag", states=["running"]),
+ mock.call(
+ dag_id="some_dag",
+ run_ids=succeeded_run_ids[: dag_state.RUN_ID_BATCH_SIZE],
+ states=["running"],
+ ),
+ mock.call(
+ dag_id="some_dag",
+ run_ids=succeeded_run_ids[dag_state.RUN_ID_BATCH_SIZE :],
+ states=["running"],
+ ),
+ ]
+
+
[email protected]("airflow_2", "clean_db")
+def test_get_task_states_on_airflow_2(sample_dag_id_fixture):
+ dag_run = _create_dag_run(
+ sample_dag_id_fixture, DagRunState.RUNNING, task_state=TaskInstanceState.FAILED
+ )
+
+ assert dag_state.get_task_states(dag_run) == {TASK_ID: "failed"}
+
+
+def test_get_task_states_on_airflow_3(airflow_3_ti):
+ dag_run = mock.MagicMock(dag_id="some_dag", run_id="some_run")
+ airflow_3_ti.get_task_states.return_value = {"some_run": {TASK_ID: "failed"}}
+
+ assert dag_state.get_task_states(dag_run) == {TASK_ID: "failed"}
+ airflow_3_ti.get_task_states.assert_called_once_with(
+ dag_id="some_dag", run_ids=["some_run"]
+ )
+
+
+ "is_airflow_3, section, expected_run_url, expected_log_url",
+ [
+ pytest.param(
+ False,
+ "webserver",
+ "https://airflow.test/dags/some_dag/grid?dag_run_id=manual__2022-01-01T00%3A00%3A00",
+ "https://airflow.test/dags/some_dag/grid?dag_run_id=manual__2022-01-01T00%3A00%3A00"
+ "&task_id=group.task&tab=logs",
+ id="airflow-2",
+ ),
+ pytest.param(
+ True,
+ "api",
+ "https://airflow.test/dags/some_dag/runs/manual__2022-01-01T00%3A00%3A00",
+ "https://airflow.test/dags/some_dag/runs/manual__2022-01-01T00%3A00%3A00"
+ "/tasks/group.task",
+ id="airflow-3",
+ ),
+ ],
+)
+def test_ui_urls(is_airflow_3, section, expected_run_url, expected_log_url):
+ run_id = "manual__2022-01-01T00:00:00"
+
+ def get_conf(conf_section, key, fallback=None):
+ assert (conf_section, key) == (section, "base_url")
+ return "https://airflow.test/"
+
+ with (
+ mock.patch.object(dag_state, "IS_AIRFLOW_3", is_airflow_3),
+ mock.patch.object(dag_state.conf, "get", side_effect=get_conf),
+ ):
+ assert dag_state.dag_run_url("some_dag", run_id) == expected_run_url
+ assert (
+ dag_state.task_log_url("some_dag", run_id, "group.task") == expected_log_url
+ )
+
+
[email protected]("is_airflow_3", [False, True])
+def test_ui_urls_fall_back_without_base_url(is_airflow_3):
+ def get_unset_conf(section, key, fallback=None):
+ return fallback
+
+ with (
+ mock.patch.object(dag_state, "IS_AIRFLOW_3", is_airflow_3),
+ mock.patch.object(dag_state.conf, "get", side_effect=get_unset_conf),
+ ):
+ assert dag_state.dag_run_url("some_dag", "run").startswith(
+ "http://localhost:8080/dags/some_dag/"
+ )
+
+
[email protected]("airflow_2", "clean_db")
+def test_assert_dag_exists_on_airflow_2(sample_dag_id_fixture):
+ with pytest.raises(AirflowException, match="does not exist"):
+ dag_state.assert_dag_exists(sample_dag_id_fixture)
+
+ with create_session() as session:
+ session.add(DagModel(dag_id=sample_dag_id_fixture))
+ try:
+ dag_state.assert_dag_exists(sample_dag_id_fixture)
+ finally:
+ with create_session() as session:
+ session.query(DagModel).filter(
+ DagModel.dag_id == sample_dag_id_fixture
+ ).delete()
+
+
+def test_assert_dag_exists_on_airflow_3(airflow_3_ti):
+ sdk_exceptions = pytest.importorskip("airflow.sdk.exceptions")
+ airflow_3_ti.get_dag.side_effect = sdk_exceptions.AirflowRuntimeError(
+ mock.MagicMock()
+ )
+
+ with pytest.raises(AirflowException, match="does not exist"):
+ dag_state.assert_dag_exists("missing_dag")
diff --git a/catalog/tests/dags/data_refresh/test_distributed_reindex.py b/catalog/tests/dags/data_refresh/test_distributed_reindex.py
index c00869fa9..67d192c19 100644
--- a/catalog/tests/dags/data_refresh/test_distributed_reindex.py
+++ b/catalog/tests/dags/data_refresh/test_distributed_reindex.py
@@ -2,10 +2,21 @@ import logging
from unittest import mock
import pytest
+import requests
+from airflow.models.dag import DAG
from airflow.providers.amazon.aws.hooks.ec2 import EC2Hook
+from airflow.utils.timezone import datetime
from common.constants import PRODUCTION
-from data_refresh.distributed_reindex import wait_for_worker
+from data_refresh.constants import (
+ INDEXER_WORKER_REQUEST_TIMEOUT,
+ WAIT_FOR_REINDEXING_RETRIES,
+)
+from data_refresh.distributed_reindex import (
+ trigger_reindexing_task,
+ wait_for_reindexing_task,
+ wait_for_worker,
+)
logger = logging.getLogger(__name__)
@@ -132,3 +143,104 @@ def test_wait_for_worker(instance_status_response, should_pass, mock_ec2_hook):
)
assert poke_return_value.is_done == should_pass
+
+
+WORKER_URL = "http://10.0.0.1:8003"
+
+
+def _response(status_code, json_body=None):
+ response = mock.MagicMock(status_code=status_code)
+ response.json.return_value = json_body
+ if status_code >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(str(status_code))
+ return response
+
+
+def test_trigger_reindexing_task_returns_status_url():
+ data = {"model_name": "image", "start_id": 0, "end_id": 10}
+ response = _response(202, {"status_check": "http://localhost:8003/task/abc-123"})
+ with mock.patch("requests.post", return_value=response) as post:
+ actual = trigger_reindexing_task.function(server="10.0.0.1", data=data)
+
+ post.assert_called_once_with(
+ f"{WORKER_URL}/task", data=data, timeout=INDEXER_WORKER_REQUEST_TIMEOUT
+ )
+ assert actual == f"{WORKER_URL}/task/abc-123"
+
+
+ "status_code, error",
+ [
+ pytest.param(200, ValueError, id="not-accepted"),
+ pytest.param(500, requests.HTTPError, id="server-error"),
+ ],
+)
+def test_trigger_reindexing_task_fails_unless_accepted(status_code, error):
+ with mock.patch("requests.post", return_value=_response(status_code)):
+ with pytest.raises(error):
+ trigger_reindexing_task.function(server="10.0.0.1", data={})
+
+
+ "response, expected",
+ [
+ pytest.param(_response(404), False, id="task-not-found-yet"),
+ pytest.param(
+ _response(200, {"active": True, "error": False, "progress": 50}),
+ False,
+ id="active",
+ ),
+ pytest.param(
+ _response(200, {"active": False, "error": False, "progress": 100}),
+ True,
+ id="done",
+ ),
+ ],
+)
+def test_wait_for_reindexing_task(response, expected):
+ status_url = f"{WORKER_URL}/task/abc-123"
+ with mock.patch("requests.get", return_value=response) as get:
+ assert wait_for_reindexing_task.function(status_url=status_url) is expected
+
+ get.assert_called_once_with(status_url, timeout=INDEXER_WORKER_REQUEST_TIMEOUT)
+
+
+ "response, error",
+ [
+ pytest.param(
+ _response(200, {"active": False, "error": True, "progress": 10}),
+ ValueError,
+ id="reindex-error",
+ ),
+ pytest.param(_response(403), requests.HTTPError, id="client-error"),
+ pytest.param(_response(502), requests.HTTPError, id="server-error"),
+ ],
+)
+def test_wait_for_reindexing_task_raises_on_errors(response, error):
+ with mock.patch("requests.get", return_value=response):
+ with pytest.raises(error):
+ wait_for_reindexing_task.function(status_url=f"{WORKER_URL}/task/abc")
+
+
+ "error",
+ [
+ pytest.param(requests.ConnectionError("reset"), id="connection-error"),
+ pytest.param(requests.Timeout("timed out"), id="timeout"),
+ pytest.param(requests.exceptions.ChunkedEncodingError(), id="truncated"),
+ ],
+)
+def test_wait_for_reindexing_task_raises_on_network_errors(error):
+ with mock.patch("requests.get", side_effect=error):
+ with pytest.raises(type(error)):
+ wait_for_reindexing_task.function(status_url=f"{WORKER_URL}/task/abc")
+
+
+def test_reindexing_tasks_retry_only_the_status_check():
+ with DAG("test_reindexing_retries", schedule=None, start_date=datetime(2024, 1, 1)):
+ status_url = trigger_reindexing_task(server="10.0.0.1", data={})
+ wait = wait_for_reindexing_task(status_url=status_url)
+
+ assert status_url.operator.retries == 0
+ assert wait.operator.retries == WAIT_FOR_REINDEXING_RETRIES
diff --git a/catalog/tests/dags/legacy_data_refresh/test_data_refresh_task_factory.py b/catalog/tests/dags/legacy_data_refresh/test_data_refresh_task_factory.py
index 0e0f7cee3..7073aa72a 100644
--- a/catalog/tests/dags/legacy_data_refresh/test_data_refresh_task_factory.py
+++ b/catalog/tests/dags/legacy_data_refresh/test_data_refresh_task_factory.py
@@ -11,11 +11,12 @@ from legacy_data_refresh.data_refresh_task_factory import drop_temp_tables
TRIGGER_TASK_ID = "data_refresh.ingest_upstream.trigger_ingest_upstream"
-def _ti_with_trigger_state(state):
- ti = mock.MagicMock()
- trigger_ti = None if state is None else mock.MagicMock(state=state)
- ti.get_dagrun.return_value.get_task_instance.return_value = trigger_ti
- return ti
+def _patch_trigger_state(state):
+ task_states = {} if state is None else {TRIGGER_TASK_ID: state}
+ return mock.patch(
+ "legacy_data_refresh.data_refresh_task_factory.dag_state.get_task_states",
+ return_value=task_states,
+ )
@pytest.mark.parametrize(
@@ -34,16 +35,17 @@ def _ti_with_trigger_state(state):
def test_drop_temp_tables_drops_tables_after_ingest_was_triggered(
media_type, expected_statements
):
- ti = _ti_with_trigger_state(TaskInstanceState.SUCCESS)
+ dag_run = mock.MagicMock()
- with mock.patch(
- "legacy_data_refresh.data_refresh_task_factory.PostgresHook"
- ) as hook_cls:
- drop_temp_tables.function(media_type, TRIGGER_TASK_ID, ti=ti)
+ with (
+ _patch_trigger_state("success") as get_task_states,
+ mock.patch(
+ "legacy_data_refresh.data_refresh_task_factory.PostgresHook"
+ ) as hook_cls,
+ ):
+ drop_temp_tables.function(media_type, TRIGGER_TASK_ID, dag_run=dag_run)
- ti.get_dagrun.return_value.get_task_instance.assert_called_once_with(
- TRIGGER_TASK_ID
- )
+ get_task_states.assert_called_once_with(dag_run)
hook_cls.assert_called_once_with(postgres_conn_id=OPENLEDGER_API_CONN_ID)
hook_cls.return_value.run.assert_called_once_with(expected_statements)
@@ -54,15 +56,19 @@ def test_drop_temp_tables_drops_tables_after_ingest_was_triggered(
pytest.param(None, id="trigger-task-missing"),
pytest.param(TaskInstanceState.UPSTREAM_FAILED, id="upstream-failed"),
pytest.param(TaskInstanceState.FAILED, id="trigger-failed"),
+ pytest.param("running", id="trigger-running"),
],
)
def test_drop_temp_tables_skips_when_ingest_was_not_triggered(trigger_state):
- ti = _ti_with_trigger_state(trigger_state)
-
- with mock.patch(
- "legacy_data_refresh.data_refresh_task_factory.PostgresHook"
- ) as hook_cls:
+ with (
+ _patch_trigger_state(trigger_state),
+ mock.patch(
+ "legacy_data_refresh.data_refresh_task_factory.PostgresHook"
+ ) as hook_cls,
+ ):
with pytest.raises(AirflowSkipException):
- drop_temp_tables.function("image", TRIGGER_TASK_ID, ti=ti)
+ drop_temp_tables.function(
+ "image", TRIGGER_TASK_ID, dag_run=mock.MagicMock()
+ )
hook_cls.assert_not_called()
diff --git a/catalog/tests/dags/providers/test_provider_dag_factory.py b/catalog/tests/dags/providers/test_provider_dag_factory.py
index 05fe3217b..b1dd037c7 100644
--- a/catalog/tests/dags/providers/test_provider_dag_factory.py
+++ b/catalog/tests/dags/providers/test_provider_dag_factory.py
@@ -245,3 +245,79 @@ def test_create_report_load_completion_for_reingestion_dag():
assert "date_range_start" not in report_task.op_kwargs
assert "date_range_end" not in report_task.op_kwargs
+
+
+def reingestion_conf():
+ return ProviderReingestionWorkflow(
+ ingester_class=MockImageOnlyProviderDataIngester,
+ )
+
+
+def test_report_aggregate_reingestion_errors_skips_without_failures(
+ reingestion_conf,
+):
+ dag_run = mock.MagicMock(dag_id="some_dag", run_id="some_run")
+ task_states = {
+ "ingest_data.pull_image_data": "success",
+ "ingest_data_day_shift_1.load_image_data": "failed",
+ }
+ with (
+ mock.patch.object(
+ provider_dag_factory.dag_state,
+ "get_task_states",
+ return_value=task_states,
+ ),
+ mock.patch.object(provider_dag_factory.slack, "send_alert") as send_alert,
+ ):
+ with pytest.raises(AirflowSkipException):
+ provider_dag_factory.report_aggregate_reingestion_errors.function(
+ reingestion_conf, dag_run=dag_run
+ )
+
+ send_alert.assert_not_called()
+
+
+def test_report_aggregate_reingestion_errors_reports_failed_pull_tasks(
+ reingestion_conf,
+):
+ dag_run = mock.MagicMock(dag_id="some_dag", run_id="some_run")
+ task_states = {
+ f"ingest_data_day_shift_{day}.pull_image_data_day_shift_{day}": "failed"
+ for day in range(12, 0, -1)
+ }
+ task_states["ingest_data.pull_image_data"] = "success"
+ with (
+ mock.patch.object(
+ provider_dag_factory.dag_state,
+ "get_task_states",
+ return_value=task_states,
+ ),
+ mock.patch.object(
+ provider_dag_factory.dag_state,
+ "dag_run_url",
+ return_value="https://airflow.test/run",
+ ),
+ mock.patch.object(
+ provider_dag_factory.dag_state,
+ "task_log_url",
+ side_effect=lambda dag_id, run_id, task_id: (
+ f"https://airflow.test/{task_id}"
+ ),
+ ),
+ mock.patch.object(provider_dag_factory.slack, "send_alert") as send_alert,
+ ):
+ provider_dag_factory.report_aggregate_reingestion_errors.function(
+ reingestion_conf, dag_run=dag_run
+ )
+
+ message = send_alert.call_args.args[0]
+ assert "encountered in 12 ingestion days" in message
+ assert "<https://airflow.test/run|link>" in message
+ assert "(showing only the first 5)" in message
+ listed_days = [
+ line.rsplit("_", 1)[-1].rstrip(">")
+ for line in message.splitlines()
+ if line.startswith(" - <")
+ ]
+ assert listed_days == ["1", "2", "3", "4", "5"]
diff --git a/catalog/tests/dags/test_dag_parsing.py b/catalog/tests/dags/test_dag_parsing.py
index b21bef2f0..9deced119 100644
--- a/catalog/tests/dags/test_dag_parsing.py
+++ b/catalog/tests/dags/test_dag_parsing.py
@@ -4,6 +4,8 @@ import pytest
from airflow.models import DagBag
from common.constants import ENVIRONMENTS, MEDIA_TYPES
+from common.sensors.constants import CONCURRENCY_TAG_DAG_IDS
+from common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGsSensor
from providers.provider_reingestion_workflows import (
PROVIDER_REINGESTION_WORKFLOWS as REINGESTION_WORKFLOW_CONFIGS,
)
@@ -118,3 +120,54 @@ def test_dag_uses_default_args():
assert not failures, (
f"The following DAGs do not have DAG_DEFAULT_ARGS defined: {failures}"
)
+
+
[email protected](scope="module")
+def all_dags():
+ return DagBag(dag_folder=DAG_FOLDER, include_examples=False).dags
+
+
+def test_concurrency_tag_dag_ids_match_dag_tags(all_dags):
+ # Concurrency checks read `CONCURRENCY_TAG_DAG_IDS` instead of the DAG tags, so
+ # the two must stay in sync
+ for tag, dag_ids in CONCURRENCY_TAG_DAG_IDS.items():
+ tagged = sorted(dag_id for dag_id, dag in all_dags.items() if tag in dag.tags)
+ assert sorted(dag_ids) == tagged, (
+ f"Update `CONCURRENCY_TAG_DAG_IDS[{tag!r}]` to match the DAGs with the tag"
+ )
+
+ all_tags = {tag for dag in all_dags.values() for tag in dag.tags}
+ unlisted = {tag for tag in all_tags if tag.endswith("_concurrency")} - set(
+ CONCURRENCY_TAG_DAG_IDS
+ )
+ assert not unlisted, f"Add these tags to `CONCURRENCY_TAG_DAG_IDS`: {unlisted}"
+
+
+def test_single_run_sensors_wait_on_existing_tasks(all_dags):
+ # The sensor looks for a task with its own task id in each external DAG
+ sensors = [
+ (dag_id, task)
+ for dag_id, dag in all_dags.items()
+ for task in dag.tasks
+ if isinstance(task, SingleRunExternalDAGsSensor)
+ ]
+ assert sensors
+
+ for dag_id, sensor in sensors:
+ for external_dag_id in sensor.external_dag_ids:
+ assert external_dag_id in all_dags, (
+ f"{dag_id}.{sensor.task_id} waits on a missing DAG {external_dag_id}"
+ )
+ assert all_dags[external_dag_id].has_task(sensor.task_id), (
+ f"{external_dag_id} has no {sensor.task_id} task for {dag_id} to wait on"
+ )
+
+
+def test_concurrency_tagged_dags_have_one_active_run(all_dags):
+ # The concurrency sensors wait while any run of a tagged DAG is active, which
+ # matches waiting on its latest run only while each DAG runs one at a time
+ tagged_dag_ids = {
+ dag_id for dag_ids in CONCURRENCY_TAG_DAG_IDS.values() for dag_id in dag_ids
+ }
+ for dag_id in tagged_dag_ids:
+ assert all_dags[dag_id].max_active_runs == 1, dag_id