Skip to content

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

Generate DAGs to recreate popularity calculations using a factory (#507)

Staci Cooper31f461ace7b4
diff --git a/openverse_catalog/dags/common/popularity/operators.py b/openverse_catalog/dags/common/popularity/operators.py
deleted file mode 100644
index 5d4fbe37b..000000000
--- a/openverse_catalog/dags/common/popularity/operators.py
+++ /dev/null
@@ -1,102 +0,0 @@
-import logging
-
-from airflow.operators.python import PythonOperator
-from common.popularity import sql
-
-
-logger = logging.getLogger(__name__)
-
-
-DROP_MEDIA_POPULARITY_RELATIONS_TASK_ID = "drop_media_popularity_relations"
-DROP_MEDIA_POPULARITY_FUNCTIONS_TASK_ID = "drop_media_popularity_functions"
-CREATE_MEDIA_POPULARITY_METRICS_TASK_ID = "create_media_popularity_metrics_table"
-UPDATE_MEDIA_POPULARITY_METRICS_TASK_ID = "update_media_popularity_metrics_table"
-CREATE_MEDIA_POPULARITY_PERCENTILE_TASK_ID = "create_media_popularity_percentile"
-CREATE_MEDIA_POPULARITY_CONSTANTS_TASK_ID = "create_media_popularity_constants_view"
-CREATE_MEDIA_STANDARDIZED_POPULARITY_TASK_ID = "create_media_standardized_popularity"
-CREATE_DB_VIEW_TASK_ID = "create_materialized_popularity_view"
-
-
-def drop_media_popularity_relations(
- postgres_conn_id,
- media_type="image",
-):
- return PythonOperator(
- task_id=DROP_MEDIA_POPULARITY_RELATIONS_TASK_ID,
- python_callable=sql.drop_media_popularity_relations,
- op_args=[postgres_conn_id, media_type],
- )
-
-
-def drop_media_popularity_functions(
- postgres_conn_id,
- media_type="image",
-):
- return PythonOperator(
- task_id=DROP_MEDIA_POPULARITY_FUNCTIONS_TASK_ID,
- python_callable=sql.drop_media_popularity_functions,
- op_args=[postgres_conn_id, media_type],
- )
-
-
-def create_media_popularity_metrics(
- postgres_conn_id,
- media_type="image",
-):
- return PythonOperator(
- task_id=CREATE_MEDIA_POPULARITY_METRICS_TASK_ID,
- python_callable=sql.create_media_popularity_metrics,
- op_args=[postgres_conn_id, media_type],
- )
-
-
-def update_media_popularity_metrics(
- postgres_conn_id,
- media_type="image",
-):
- return PythonOperator(
- task_id=UPDATE_MEDIA_POPULARITY_METRICS_TASK_ID,
- python_callable=sql.update_media_popularity_metrics,
- op_args=[postgres_conn_id, media_type],
- )
-
-
-def create_media_popularity_percentile(
- postgres_conn_id,
- media_type="image",
-):
- return PythonOperator(
- task_id=CREATE_MEDIA_POPULARITY_PERCENTILE_TASK_ID,
- python_callable=sql.create_media_popularity_percentile_function,
- op_args=[postgres_conn_id, media_type],
- )
-
-
-def create_media_popularity_constants(
- postgres_conn_id,
- media_type="image",
-):
- return PythonOperator(
- task_id=CREATE_MEDIA_POPULARITY_CONSTANTS_TASK_ID,
- python_callable=sql.create_media_popularity_constants_view,
- op_args=[postgres_conn_id, media_type],
- )
-
-
-def create_media_standardized_popularity(
- postgres_conn_id,
- media_type="image",
-):
- return PythonOperator(
- task_id=CREATE_MEDIA_STANDARDIZED_POPULARITY_TASK_ID,
- python_callable=sql.create_standardized_media_popularity_function,
- op_args=[postgres_conn_id, media_type],
- )
-
-
-def create_db_view(postgres_conn_id, media_type="image"):
- return PythonOperator(
- task_id=CREATE_DB_VIEW_TASK_ID,
- python_callable=sql.create_media_view,
- op_args=[postgres_conn_id, media_type],
- )
diff --git a/openverse_catalog/dags/data_refresh/data_refresh_types.py b/openverse_catalog/dags/data_refresh/data_refresh_types.py
index b4fce771f..9cc6563a3 100644
--- a/openverse_catalog/dags/data_refresh/data_refresh_types.py
+++ b/openverse_catalog/dags/data_refresh/data_refresh_types.py
@@ -21,20 +21,25 @@ class DataRefresh:
Optional Constructor Arguments:
- default_args: dictionary which is passed to the airflow.dag.DAG
- __init__ method.
- start_date: datetime.datetime giving the
- first valid execution_date of the DAG.
- schedule_interval: string giving the schedule on which the DAG should
- be run. Passed to the airflow.dag.DAG __init__
- method.
- data_refresh_timeout: int giving the amount of time in seconds a given
- data pull may take.
- refresh_metrics_timeout: timedelta expressing amount of time the refresh
- popularity metrics tasks may take.
- refresh_matview_timeout: timedelta expressing amount of time the refresh
- of the popularity matview may take.
- doc_md: str used for the DAG's documentation markdown
+ default_args: dictionary which is passed to the
+ airflow.dag.DAG __init__ method.
+ start_date: datetime.datetime giving the
+ first valid execution_date of the DAG.
+ schedule_interval: string giving the schedule on which the DAG
+ should be run. Passed to the
+ airflow.dag.DAG __init__ method.
+ data_refresh_timeout: int giving the amount of time in seconds a
+ given data pull may take.
+ refresh_metrics_timeout: timedelta expressing amount of time the
+ refresh popularity metrics tasks may take.
+ refresh_matview_timeout: timedelta expressing amount of time the
+ refresh of the popularity matview may take.
+ create_pop_constants_view_timeout: timedelta expressing amount of time the
+ creation of the popularity constants view
+ may take
+ create_materialized_view_timeout: timedelta expressing amount of time the
+ creation of the matview may take
+ doc_md: str used for the DAG's documentation markdown
"""
dag_id: str = field(init=False)
@@ -45,6 +50,8 @@ class DataRefresh:
data_refresh_timeout: int = 24 * 60 * 60 # 1 day
refresh_metrics_timeout: timedelta = timedelta(hours=1)
refresh_matview_timeout: timedelta = timedelta(hours=1)
+ create_pop_constants_view_timeout: timedelta = timedelta(hours=1)
+ create_materialized_view_timeout: timedelta = timedelta(hours=1)
def __post_init__(self):
self.dag_id = f"{self.media_type}_data_refresh"
@@ -56,6 +63,8 @@ DATA_REFRESH_CONFIGS = [
data_refresh_timeout=3 * 24 * 60 * 60, # 3 days,
refresh_metrics_timeout=timedelta(hours=24),
refresh_matview_timeout=timedelta(hours=24),
+ create_pop_constants_view_timeout=timedelta(hours=8),
+ create_materialized_view_timeout=timedelta(hours=5),
),
DataRefresh(media_type="audio"),
]
diff --git a/openverse_catalog/dags/database/recreate_audio_popularity_calculation.py b/openverse_catalog/dags/database/recreate_audio_popularity_calculation.py
deleted file mode 100644
index 3ed8ab9ea..000000000
--- a/openverse_catalog/dags/database/recreate_audio_popularity_calculation.py
+++ /dev/null
@@ -1,97 +0,0 @@
-"""
-This file defines an Apache Airflow DAG that completely wipes out the
-PostgreSQL relations and functions involved in calculating our
-standardized popularity metric. It then recreates relations and
-functions to make the calculation, and performs an initial calculation.
-The results are available in the `image_view` materialized view.
-
-This should only be run when new SQL code is deployed for the calculation.
-"""
-import os
-from datetime import datetime, timedelta
-
-from airflow import DAG
-from common import slack
-from common.popularity import operators
-
-
-DAG_ID = "recreate_audio_popularity_calculation"
-DB_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")
-MAX_ACTIVE_TASKS = 1
-SCHEDULE_CRON = None
-
-DAG_DEFAULT_ARGS = {
- "owner": "data-eng-admin",
- "depends_on_past": False,
- "start_date": datetime(2020, 6, 15),
- "email_on_retry": False,
- "retries": 2,
- "retry_delay": timedelta(seconds=3600),
- "on_failure_callback": slack.on_failure_callback,
-}
-
-
-def create_dag(
- dag_id=DAG_ID,
- args=DAG_DEFAULT_ARGS,
- max_active_tasks=MAX_ACTIVE_TASKS,
- max_active_runs=MAX_ACTIVE_TASKS,
- schedule_cron=SCHEDULE_CRON,
- postgres_conn_id=DB_CONN_ID,
-):
- dag = DAG(
- dag_id=dag_id,
- default_args=args,
- max_active_tasks=max_active_tasks,
- max_active_runs=max_active_runs,
- schedule_interval=schedule_cron,
- catchup=False,
- tags=["database"],
- )
- with dag:
- drop_relations = operators.drop_media_popularity_relations(
- postgres_conn_id,
- "audio",
- )
- drop_functions = operators.drop_media_popularity_functions(
- postgres_conn_id,
- "audio",
- )
- create_metrics = operators.create_media_popularity_metrics(
- postgres_conn_id,
- "audio",
- )
- update_metrics = operators.update_media_popularity_metrics(
- postgres_conn_id,
- "audio",
- )
- create_percentile = operators.create_media_popularity_percentile(
- postgres_conn_id,
- "audio",
- )
- create_constants = operators.create_media_popularity_constants(
- postgres_conn_id,
- "audio",
- )
- create_popularity = operators.create_media_standardized_popularity(
- postgres_conn_id,
- "audio",
- )
- create_db_view = operators.create_db_view(
- postgres_conn_id,
- "audio",
- )
-
- (
- [drop_relations, drop_functions]
- >> create_metrics
- >> [update_metrics, create_percentile]
- >> create_constants
- >> create_popularity
- >> create_db_view
- )
-
- return dag
-
-
-globals()[DAG_ID] = create_dag()
diff --git a/openverse_catalog/dags/database/recreate_image_popularity_calculation.py b/openverse_catalog/dags/database/recreate_image_popularity_calculation.py
deleted file mode 100644
index c8a27943a..000000000
--- a/openverse_catalog/dags/database/recreate_image_popularity_calculation.py
+++ /dev/null
@@ -1,81 +0,0 @@
-"""
-This file defines an Apache Airflow DAG that completely wipes out the
-PostgreSQL relations and functions involved in calculating our
-standardized popularity metric. It then recreates relations and
-functions to make the calculation, and performs an initial calculation.
-The results are available in the `image_view` materialized view.
-
-This should only be run when new SQL code is deployed for the calculation.
-"""
-import os
-from datetime import datetime, timedelta
-
-from airflow import DAG
-from common import slack
-from common.popularity import operators
-
-
-DAG_ID = "recreate_image_popularity_calculation"
-DB_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")
-MAX_ACTIVE_TASKS = 1
-SCHEDULE_CRON = None
-
-DAG_DEFAULT_ARGS = {
- "owner": "data-eng-admin",
- "depends_on_past": False,
- "start_date": datetime(2020, 6, 15),
- "email_on_retry": False,
- "retries": 2,
- "retry_delay": timedelta(seconds=3600),
- "on_failure_callback": slack.on_failure_callback,
-}
-
-
-def create_dag(
- dag_id=DAG_ID,
- args=DAG_DEFAULT_ARGS,
- max_active_tasks=MAX_ACTIVE_TASKS,
- max_active_runs=MAX_ACTIVE_TASKS,
- schedule_cron=SCHEDULE_CRON,
- postgres_conn_id=DB_CONN_ID,
-):
- dag = DAG(
- dag_id=dag_id,
- default_args=args,
- max_active_tasks=max_active_tasks,
- max_active_runs=max_active_runs,
- schedule_interval=schedule_cron,
- catchup=False,
- tags=["database"],
- )
- with dag:
- drop_relations = operators.drop_media_popularity_relations(
- postgres_conn_id,
- )
- drop_functions = operators.drop_media_popularity_functions(
- postgres_conn_id,
- )
- create_metrics = operators.create_media_popularity_metrics(postgres_conn_id)
- update_metrics = operators.update_media_popularity_metrics(postgres_conn_id)
- create_percentile = operators.create_media_popularity_percentile(
- postgres_conn_id
- )
- create_constants = operators.create_media_popularity_constants(postgres_conn_id)
- create_popularity = operators.create_media_standardized_popularity(
- postgres_conn_id
- )
- create_image_view = operators.create_db_view(postgres_conn_id)
-
- (
- [drop_relations, drop_functions]
- >> create_metrics
- >> [update_metrics, create_percentile]
- >> create_constants
- >> create_popularity
- >> create_image_view
- )
-
- return dag
-
-
-globals()[DAG_ID] = create_dag()
diff --git a/openverse_catalog/dags/database/recreate_popularity_calculation_dag_factory.py b/openverse_catalog/dags/database/recreate_popularity_calculation_dag_factory.py
new file mode 100644
index 000000000..2db97c493
--- /dev/null
+++ b/openverse_catalog/dags/database/recreate_popularity_calculation_dag_factory.py
@@ -0,0 +1,152 @@
+"""
+This file generates Apache Airflow DAGs that, for the given media type,
+completely wipe out the PostgreSQL relations and functions involved in
+calculating our standardized popularity metric. It then recreates relations
+and functions to make the calculation, and performs an initial calculation.
+The results are available in the materialized view for that media type.
+
+These DAGs are not on a schedule, and should only be run manually when new
+SQL code is deployed for the calculation.
+"""
+from airflow import DAG
+from airflow.operators.python import PythonOperator
+from common.constants import DAG_DEFAULT_ARGS, POSTGRES_CONN_ID
+from common.popularity import sql
+from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefresh
+
+
+def create_recreate_popularity_calculation_dag(data_refresh: DataRefresh):
+ media_type = data_refresh.media_type
+ default_args = {
+ **DAG_DEFAULT_ARGS,
+ **data_refresh.default_args,
+ }
+
+ dag = DAG(
+ dag_id=f"recreate_{media_type}_popularity_calculation",
+ default_args=default_args,
+ max_active_runs=1,
+ schedule_interval=None,
+ catchup=False,
+ doc_md=__doc__,
+ tags=["database", "data_refresh"],
+ )
+ with dag:
+ drop_relations = PythonOperator(
+ task_id="drop_popularity_relations",
+ python_callable=sql.drop_media_popularity_relations,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
+ doc="Drop the existing popularity views and tables.",
+ )
+
+ drop_functions = PythonOperator(
+ task_id="drop_popularity_functions",
+ python_callable=sql.drop_media_popularity_functions,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
+ doc="Drop the existing popularity functions.",
+ )
+
+ create_metrics_table = PythonOperator(
+ task_id="create_popularity_metrics_table",
+ python_callable=sql.create_media_popularity_metrics,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
+ doc=(
+ "Create the popularity metrics table, which stores popularity "
+ "metrics and target percentiles per provider."
+ ),
+ )
+
+ update_metrics_table = PythonOperator(
+ task_id="update_popularity_metrics_table",
+ python_callable=sql.update_media_popularity_metrics,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
+ doc="Update the popularity metrics table with values for each provider.",
+ )
+
+ create_percentile_function = PythonOperator(
+ task_id="create_popularity_percentile_function",
+ python_callable=sql.create_media_popularity_percentile_function,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
+ doc=(
+ "Create the function for calculating popularity percentile values, "
+ "used for calculating the popularity constants for each provider."
+ ),
+ )
+
+ create_constants_view = PythonOperator(
+ task_id="create_popularity_constants_view",
+ python_callable=sql.create_media_popularity_constants_view,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
+ execution_timeout=data_refresh.create_pop_constants_view_timeout,
+ doc=(
+ "Create the materialized view with popularity constants for each "
+ "provider, using the percentile function."
+ ),
+ )
+
+ create_popularity_function = PythonOperator(
+ task_id="create_standardized_popularity_function",
+ python_callable=sql.create_standardized_media_popularity_function,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
+ doc=(
+ "Create the function that calculates popularity data for a given "
+ "record, standardizing across providers with the generated popularity "
+ "constants."
+ ),
+ )
+
+ create_matview = PythonOperator(
+ task_id="create_materialized_popularity_view",
+ python_callable=sql.create_media_view,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": media_type,
+ },
+ execution_timeout=data_refresh.create_materialized_view_timeout,
+ doc=(
+ "Create the materialized view containing standardized popularity data "
+ "for all records."
+ ),
+ )
+
+ (
+ [drop_relations, drop_functions]
+ >> create_metrics_table
+ >> [update_metrics_table, create_percentile_function]
+ >> create_constants_view
+ >> create_popularity_function
+ >> create_matview
+ )
+
+ return dag
+
+
+# Generate a recreate_popularity_calculation DAG for each DATA_REFRESH_CONFIG.
+for data_refresh in DATA_REFRESH_CONFIGS:
+ recreate_popularity_calculation_dag = create_recreate_popularity_calculation_dag(
+ data_refresh
+ )
+ globals()[
+ recreate_popularity_calculation_dag.dag_id
+ ] = recreate_popularity_calculation_dag
diff --git a/tests/dags/test_dag_parsing.py b/tests/dags/test_dag_parsing.py
index 8d3095083..65b089e1c 100644
--- a/tests/dags/test_dag_parsing.py
+++ b/tests/dags/test_dag_parsing.py
@@ -2,6 +2,7 @@ from pathlib import Path
import pytest
from airflow.models import DagBag
+from common.constants import MEDIA_TYPES
# The path to DAGs *within the container*, though that should mirror the current
@@ -40,14 +41,18 @@ ADDITIONAL_DAGS = [
"commoncrawl/sync_commoncrawl_workflow.py",
"commoncrawl/commoncrawl_etl.py",
"database/loader_workflow.py",
- "database/recreate_image_popularity_calculation.py",
+ "database/recreate_popularity_calculation_dag_factory.py",
+ "data_refresh/dag_factory.py",
"oauth2/authorize_dag.py",
"oauth2/token_refresh_dag.py",
]
# Expected count from the DagBag once a file has been parsed
# (this will likely not need to be edited for new providers)
-EXPECTED_COUNT = {}
+EXPECTED_COUNT = {
+ "database/recreate_popularity_calculation_dag_factory.py": len(MEDIA_TYPES),
+ "data_refresh/dag_factory.py": len(MEDIA_TYPES),
+}
# relative_path represents the path from the DAG folder to the file