Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add Airflow variable used to configure overrides for task timeouts (#976)
Staci Mullins63cfe8abec7c
diff --git a/openverse_catalog/dags/providers/provider_dag_factory.py b/openverse_catalog/dags/providers/provider_dag_factory.pyindex b13e12881..fbfe8ff4a 100644--- a/openverse_catalog/dags/providers/provider_dag_factory.py+++ b/openverse_catalog/dags/providers/provider_dag_factory.py@@ -64,9 +64,11 @@ https://github.com/creativecommons/cccatalog/issues/334)"""import loggingimport os+import refrom string import Templatefrom airflow import DAG+from airflow.models.mappedoperator import MappedOperatorfrom airflow.models.param import Paramfrom airflow.operators.empty import EmptyOperatorfrom airflow.operators.python import PythonOperator@@ -76,7 +78,11 @@ from common.constants import DAG_DEFAULT_ARGS, XCOM_PULL_TEMPLATEfrom common.loader import loader, reporting, s3, sqlfrom providers.factory_utils import date_partition_for_prefix, pull_media_wrapperfrom providers.provider_reingestion_workflows import ProviderReingestionWorkflow-from providers.provider_workflows import ProviderWorkflow+from providers.provider_workflows import (+ ProviderWorkflow,+ TaskOverride,+ get_time_override,+)logger = logging.getLogger(__name__)@@ -93,6 +99,44 @@ DATE_PARTITION_ARG_TEMPLATE = Template()+def _apply_configuration_overrides(dag: DAG, overrides: list[TaskOverride]):+ """+ For each task in the given DAG, check if any overrides are configured and,+ if so, apply them.+ """+ if not overrides:+ return++ for task in dag.tasks:+ if (task_overrides := _get_overrides_for_task(task.task_id, overrides)) is None:+ continue++ # Format timeout override and apply+ timeout_override = get_time_override(task_overrides.get("timeout"))+ if timeout_override:+ # If the task is a MappedOperator, apply the timeout to partial+ # kwargs to ensure it is set on each mapped task.+ if isinstance(task, MappedOperator):+ task.partial_kwargs["execution_timeout"] = timeout_override+ else:+ task.execution_timeout = timeout_override+++def _get_overrides_for_task(+ task_id: str, overrides: list[TaskOverride]+) -> TaskOverride | None:+ """+ Return any configured TaskOverride whose task_id_pattern matches the+ id of the given task.+ """+ for override in overrides:+ if re.search(override["task_id_pattern"], task_id):+ return override++ # No overrides were found for this task.+ return None++def create_ingestion_workflow(conf: ProviderWorkflow, day_shift: int = 0, is_reingestion: bool = False):@@ -339,6 +383,9 @@ def create_provider_api_workflow_dag(conf: ProviderWorkflow):ingest_data >> report_load_completion+ # Apply any overrides from the DAG configuration+ _apply_configuration_overrides(dag, conf.overrides)+return dag@@ -493,4 +540,7 @@ def create_day_partitioned_reingestion_dag(# final list.partitioned_ingest_workflows[-1] >> report_load_completion+ # Apply any overrides from the DAG configuration+ _apply_configuration_overrides(dag, conf.overrides)+return dagdiff --git a/openverse_catalog/dags/providers/provider_reingestion_workflows.py b/openverse_catalog/dags/providers/provider_reingestion_workflows.pyindex 150a4a1e5..cb76c8920 100644--- a/openverse_catalog/dags/providers/provider_reingestion_workflows.py+++ b/openverse_catalog/dags/providers/provider_reingestion_workflows.py@@ -49,11 +49,8 @@ class ProviderReingestionWorkflow(ProviderWorkflow):def __post_init__(self):if not self.dag_id:- # Call super() first to initialize the provider_name- super().__post_init__()- # Override the dag_id- self.dag_id = f"{self.provider_name}_reingestion_workflow"- return+ _, provider_name = self._get_module_info()+ self.dag_id = f"{provider_name}_reingestion_workflow"super().__post_init__()diff --git a/openverse_catalog/dags/providers/provider_workflows.py b/openverse_catalog/dags/providers/provider_workflows.pyindex c0d699fec..f61e1362e 100644--- a/openverse_catalog/dags/providers/provider_workflows.py+++ b/openverse_catalog/dags/providers/provider_workflows.py@@ -1,8 +1,11 @@import inspect+import logging+import refrom collections.abc import Callable, Sequencefrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta+from airflow.models import Variablefrom providers.provider_api_scripts.brooklyn_museum import BrooklynMuseumDataIngesterfrom providers.provider_api_scripts.cleveland_museum import ClevelandDataIngesterfrom providers.provider_api_scripts.europeana import EuropeanaDataIngester@@ -26,6 +29,69 @@ from providers.provider_api_scripts.wikimedia_commons import (WikimediaCommonsDataIngester,)from providers.provider_api_scripts.wordpress import WordPressDataIngester+from typing_extensions import NotRequired, TypedDict+++logger = logging.getLogger(__name__)+++class TaskOverride(TypedDict):+ """+ Describes available options for overriding a task's properties.++ Required Arguments:++ task_id: A regex pattern that matches the task_id of the task+ to be modified.++ Optional Arguments:++ timeout: str in "%d:%H:%M:%S" format giving the amount of time the+ task may take+ """++ task_id_pattern: str+ timeout: NotRequired[str | None]+++def get_time_override(time_str: str | None) -> timedelta | None:+ """+ Convert a string in the format:+ "{days}d:{hours}h:{minutes}m:{seconds}s" to a timedelta. Each+ component is optional.+ Return None if the string is improperly formatted.++ Examples:+ * "5d:10h:20m:30s" -> 5 days, 10 hours, 20 minutes, 30 seconds+ * "10d" -> 10 days+ * "90s" -> 90 seconds+ * "1h:30m" -> 1 hour, 30 minutes+ """+ if time_str is None:+ return None++ days = hours = minutes = seconds = 0++ ts = time_str.split(":")+ for t in ts:+ if not (match := re.match(r"(\d+)([d,h,m,s])$", t)):+ # Incorrectly formatted time string. Do not apply. We don't raise+ # an error in order to avoid breaking DAGs.+ logger.error(f"{t} could not be parsed.")+ return None++ count, unit = match.groups()+ match unit:+ case "d":+ days = int(count)+ case "h":+ hours = int(count)+ case "m":+ minutes = int(count)+ case "s":+ seconds = int(count)++ return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)@dataclass@@ -76,6 +142,7 @@ class ProviderWorkflow:to run any necessary post-ingestion tasks, such as dropping dataloaded during pre-ingestiontags: list of any additional tags to apply to the generated DAG+ overrides: list of TaskOverrides to apply to the generated DAG"""ingester_class: type[ProviderDataIngester]@@ -93,11 +160,18 @@ class ProviderWorkflow:create_preingestion_tasks: Callable | None = Nonecreate_postingestion_tasks: Callable | None = Nonetags: list[str] = field(default_factory=list)+ overrides: list[TaskOverride] = field(default_factory=list)- def __post_init__(self):+ def _get_module_info(self):# Get the module the ProviderDataIngester was defined inprovider_script = inspect.getmodule(self.ingester_class)- self.provider_name = provider_script.__name__.split(".")[-1]+ # Parse out the provider name+ provider_name = provider_script.__name__.split(".")[-1]++ return provider_script, provider_name++ def __post_init__(self):+ provider_script, self.provider_name = self._get_module_info()if not self.dag_id:self.dag_id = f"{self.provider_name}_workflow"@@ -108,6 +182,12 @@ class ProviderWorkflow:if not self.doc_md:self.doc_md = provider_script.__doc__+ # Check for custom configuration overrides, which will be applied when+ # the DAG is generated.+ self.overrides = Variable.get(+ "CONFIGURATION_OVERRIDES", default_var={}, deserialize_json=True+ ).get(self.dag_id, [])+PROVIDER_WORKFLOWS = [ProviderWorkflow(diff --git a/tests/dags/providers/test_provider_dag_factory.py b/tests/dags/providers/test_provider_dag_factory.pyindex adeffcda3..c9a3f398e 100644--- a/tests/dags/providers/test_provider_dag_factory.py+++ b/tests/dags/providers/test_provider_dag_factory.py@@ -1,9 +1,12 @@+from datetime import datetime, timedeltafrom unittest import mockimport pytest+from airflow import DAGfrom airflow.exceptions import AirflowSkipException, BackfillUnfinishedfrom airflow.executors.debug_executor import DebugExecutorfrom airflow.models import DagRun, TaskInstance+from airflow.operators.empty import EmptyOperatorfrom airflow.utils.session import create_sessionfrom pendulum import nowfrom providers import provider_dag_factory@@ -116,3 +119,89 @@ def test_create_day_partitioned_ingestion_dag_with_multi_layer_dependencies():assert ingest4_task.upstream_task_ids == {gather1_id}ingest5_task = dag.get_task(ingest5_id)assert ingest5_task.upstream_task_ids == {gather1_id}+++def test_apply_configuration_overrides():+ # Create a mock DAG+ dag = DAG(+ dag_id="test_dag",+ start_date=datetime(1970, 1, 1),+ default_args={"execution_timeout": timedelta(hours=1)},+ )+ with dag:+ task_with_no_overrides_and_default = EmptyOperator(+ task_id="task_with_no_overrides_and_default"+ )+ task_with_no_overrides = EmptyOperator(+ task_id="task_with_no_overrides", execution_timeout=timedelta(hours=2)+ )+ task_with_override_but_no_timeout = EmptyOperator(+ task_id="task_with_override_but_no_timeout",+ execution_timeout=timedelta(hours=2),+ )+ task_with_override_but_improper_timeout = EmptyOperator(+ task_id="task_with_override_but_improper_timeout",+ execution_timeout=timedelta(hours=2),+ )+ task_with_override = EmptyOperator(+ task_id="task_with_proper_override", execution_timeout=timedelta(hours=2)+ )+ mapped_task_with_override = EmptyOperator.partial(+ task_id="mapped_task_with_override",+ ).expand_kwargs([{"foo": 1}, {"foo": 2}])++ overrides = [+ {"task_id_pattern": "task_with_override_but_no_timeout", "timeout": None},+ {+ "task_id_pattern": "task_with_override_but_improper_timeout",+ "timeout": "foo", # Improperly formatted timeout should not be applied+ },+ {"task_id_pattern": "task_with_proper_override", "timeout": "1d:0h:0m:0s"},+ {"task_id_pattern": "mapped_task_with_override", "timeout": "4m:0s"},+ {"task_id_pattern": "some_task_that_does_not_exist", "timeout": "1d:2h:3m:4s"},+ ]++ # Apply the overrides to the DAG+ provider_dag_factory._apply_configuration_overrides(dag, overrides)++ # Assert that the overrides were applied+ assert task_with_no_overrides_and_default.execution_timeout == timedelta(hours=1)+ assert task_with_no_overrides.execution_timeout == timedelta(hours=2)+ assert task_with_override_but_no_timeout.execution_timeout == timedelta(hours=2)+ assert task_with_override_but_improper_timeout.execution_timeout == timedelta(+ hours=2+ )+ assert task_with_override.execution_timeout == timedelta(days=1)+ assert mapped_task_with_override.execution_timeout == timedelta(minutes=4)+++ "task_id, expected_overrides",+ [+ # Fully match the task id+ ("task_baz", {"task_id_pattern": "task_baz", "timeout": "3:3:3:3"}),+ # Partial match+ (+ "task_bar_plus_suffix",+ {"task_id_pattern": "task_bar", "timeout": "2:2:2:2"},+ ),+ # Partial match for a task that is part of a TaskGroup+ (+ "task_group_id.task_foo_plus_suffix",+ {"task_id_pattern": "task_foo", "timeout": "1:1:1:1"},+ ),+ # No match+ ("task_oops", None),+ ],+)+def test_get_overrides_for_task(task_id, expected_overrides):+ overrides = [+ {"task_id_pattern": "task_foo", "timeout": "1:1:1:1"},+ {"task_id_pattern": "task_bar", "timeout": "2:2:2:2"},+ {"task_id_pattern": "task_baz", "timeout": "3:3:3:3"},+ ]++ actual_task_overrides = provider_dag_factory._get_overrides_for_task(+ task_id, overrides+ )+ assert actual_task_overrides == expected_overridesdiff --git a/tests/dags/providers/test_provider_workflows.py b/tests/dags/providers/test_provider_workflows.pynew file mode 100644index 000000000..bb6472e42--- /dev/null+++ b/tests/dags/providers/test_provider_workflows.py@@ -0,0 +1,129 @@+from datetime import timedelta+from unittest import mock++import pytest+from providers.provider_workflows import ProviderWorkflow, get_time_override++from tests.dags.providers.provider_api_scripts.resources.provider_data_ingester.mock_provider_data_ingester import (+ MockAudioOnlyProviderDataIngester,+ MockImageOnlyProviderDataIngester,+ MockProviderDataIngester,+)+++ "provider_workflow, expected_dag_id",+ [+ # If the ProviderWorkflow defines dag_id, this should be used+ (+ ProviderWorkflow(+ ingester_class=MockProviderDataIngester, dag_id="my_dag_id_override"+ ),+ "my_dag_id_override",+ ),+ # If no dag_id is defined, it should build a default using the module+ # name of the ingester class+ (+ ProviderWorkflow(ingester_class=MockProviderDataIngester),+ "mock_provider_data_ingester_workflow",+ ),+ ],+)+def test_dag_id(provider_workflow, expected_dag_id):+ assert provider_workflow.dag_id == expected_dag_id+++ "ingester_class, expected_media_types",+ [+ (+ MockAudioOnlyProviderDataIngester,+ [+ "audio",+ ],+ ),+ (+ MockImageOnlyProviderDataIngester,+ [+ "image",+ ],+ ),+ (MockProviderDataIngester, ["audio", "image"]),+ ],+)+def test_sets_media_types(ingester_class, expected_media_types):+ provider_workflow = ProviderWorkflow(ingester_class=ingester_class)++ assert provider_workflow.media_types == expected_media_types+++ "configuration_overrides, expected_overrides",+ [+ # No overrides configured+ ({}, []),+ # Overrides configured, but not for this dag_id+ (+ {+ "some_other_dag_id": [+ {"task_id_pattern": "some_task_id", "timeout": "1:0:0:0"}+ ]+ },+ [],+ ),+ # Configured overrides+ (+ {+ "some_other_dag_id": [+ {"task_id_pattern": "some_task_id", "timeout": "1:0:0:0"},+ ],+ "my_dag_id": [+ {"task_id_pattern": "my_dag_id", "timeout": "1:2:3:4"},+ ],+ },+ [+ {"task_id_pattern": "my_dag_id", "timeout": "1:2:3:4"},+ ],+ ),+ ],+)+def test_overrides(configuration_overrides, expected_overrides):+ with mock.patch("providers.provider_workflows.Variable") as MockVariable:+ MockVariable.get.side_effect = [+ configuration_overrides,+ ]+ test_workflow = ProviderWorkflow(+ dag_id="my_dag_id",+ ingester_class=MockProviderDataIngester,+ pull_timeout=timedelta(days=1),+ upsert_timeout=timedelta(hours=1),+ )++ assert test_workflow.overrides == expected_overrides+++ "time_str, expected_timedelta",+ [+ ("0d:0h:0m:10s", timedelta(seconds=10)),+ ("30d:10h:57m:45s", timedelta(days=30, hours=10, minutes=57, seconds=45)),+ ("0d:6h:0m:0s", timedelta(hours=6)),+ ("0d:36h:0m:0s", timedelta(days=1, hours=12)),+ # Strings that do not provide all four parts+ ("0d:1h:2m", timedelta(hours=1, minutes=2)),+ ("2h", timedelta(hours=2)),+ ("10s", timedelta(seconds=10)),+ ("1d:1s", timedelta(days=1, seconds=1)),+ ("36h", timedelta(days=1, hours=12)),+ ("4s:3m:2h:1d", timedelta(days=1, hours=2, minutes=3, seconds=4)),+ # Incorrectly formatted strings returns None+ ("1d:2h:3m:4ss", None),+ ("10b", None),+ ("oned:2h:3m:4s", None),+ ("foo", None),+ (None, None),+ ],+)+def test_get_timedelta(time_str, expected_timedelta):+ actual_timedelta = get_time_override(time_str)+ assert actual_timedelta == expected_timedelta