Skip to content

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

Retire update workflows, refactor operators (#266)

Madison Swain-Bowdendc1df6b0032d
diff --git a/openverse_catalog/dags/.airflowignore b/openverse_catalog/dags/.airflowignore
index 3e358e4b5..5886069f6 100644
--- a/openverse_catalog/dags/.airflowignore
+++ b/openverse_catalog/dags/.airflowignore
@@ -4,3 +4,4 @@ commoncrawl_scripts
provider_api_scripts
storage
util
+retired
diff --git a/openverse_catalog/dags/common_api_workflows.py b/openverse_catalog/dags/common_api_workflows.py
index 9ba59f664..2309a0037 100644
--- a/openverse_catalog/dags/common_api_workflows.py
+++ b/openverse_catalog/dags/common_api_workflows.py
@@ -3,8 +3,8 @@ import os
import util.config as conf
from airflow import DAG
+from airflow.operators.bash import BashOperator
from croniter import croniter
-from util.operator_util import get_runner_operator
logging.basicConfig(
@@ -52,7 +52,10 @@ def create_dag(
)
with dag:
- get_runner_operator(source, script_location)
+ BashOperator(
+ task_id=f"get_{source}_images",
+ bash_command=f"python {script_location} --mode default",
+ )
return dag
diff --git a/openverse_catalog/dags/retired/README.md b/openverse_catalog/dags/retired/README.md
new file mode 100644
index 000000000..d2a0c4fef
--- /dev/null
+++ b/openverse_catalog/dags/retired/README.md
@@ -0,0 +1,4 @@
+# Retired DAGs
+
+This folder contains DAGs that were either one-offs or are no longer relevant to current processes, but are useful to keep around for potential future use-cases.
+DAGs in this folder are excluded from Airflow's DAG parsing and will not be shown in the UI.
diff --git a/openverse_catalog/dags/retired/__init__.py b/openverse_catalog/dags/retired/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/openverse_catalog/dags/retired/update_workflows/__init__.py b/openverse_catalog/dags/retired/update_workflows/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/openverse_catalog/dags/europeana_sub_provider_update_workflow.py b/openverse_catalog/dags/retired/update_workflows/europeana_sub_provider_update_workflow.py
similarity index 80%
rename from openverse_catalog/dags/europeana_sub_provider_update_workflow.py
rename to openverse_catalog/dags/retired/update_workflows/europeana_sub_provider_update_workflow.py
index c051d0ab2..203a40f9c 100644
--- a/openverse_catalog/dags/europeana_sub_provider_update_workflow.py
+++ b/openverse_catalog/dags/retired/update_workflows/europeana_sub_provider_update_workflow.py
@@ -9,7 +9,8 @@ import os
from datetime import datetime, timedelta
from airflow import DAG
-from util.loader import operators
+from airflow.operators.python import PythonOperator
+from retired.update_workflows import update_sql
logging.basicConfig(
@@ -50,7 +51,11 @@ def create_dag(
)
with dag:
- operators.get_europeana_sub_provider_update_operator(postgres_conn_id)
+ PythonOperator(
+ task_id="update_europeana_sub_providers",
+ python_callable=update_sql.update_europeana_sub_providers,
+ op_args=[postgres_conn_id],
+ )
return dag
diff --git a/openverse_catalog/dags/flickr_sub_provider_update_workflow.py b/openverse_catalog/dags/retired/update_workflows/flickr_sub_provider_update_workflow.py
similarity index 80%
rename from openverse_catalog/dags/flickr_sub_provider_update_workflow.py
rename to openverse_catalog/dags/retired/update_workflows/flickr_sub_provider_update_workflow.py
index f53c8d090..968b11c4d 100644
--- a/openverse_catalog/dags/flickr_sub_provider_update_workflow.py
+++ b/openverse_catalog/dags/retired/update_workflows/flickr_sub_provider_update_workflow.py
@@ -9,7 +9,8 @@ import os
from datetime import datetime, timedelta
from airflow import DAG
-from util.loader import operators
+from airflow.operators.python import PythonOperator
+from retired.update_workflows import update_sql
logging.basicConfig(
@@ -50,7 +51,11 @@ def create_dag(
)
with dag:
- operators.get_flickr_sub_provider_update_operator(postgres_conn_id)
+ PythonOperator(
+ task_id="update_flickr_sub_providers",
+ python_callable=update_sql.update_flickr_sub_providers,
+ op_args=[postgres_conn_id],
+ )
return dag
diff --git a/openverse_catalog/dags/smithsonian_sub_provider_update_workflow.py b/openverse_catalog/dags/retired/update_workflows/smithsonian_sub_provider_update_workflow.py
similarity index 80%
rename from openverse_catalog/dags/smithsonian_sub_provider_update_workflow.py
rename to openverse_catalog/dags/retired/update_workflows/smithsonian_sub_provider_update_workflow.py
index 44fcc9068..1f5899914 100644
--- a/openverse_catalog/dags/smithsonian_sub_provider_update_workflow.py
+++ b/openverse_catalog/dags/retired/update_workflows/smithsonian_sub_provider_update_workflow.py
@@ -8,7 +8,8 @@ import os
from datetime import datetime, timedelta
from airflow import DAG
-from util.loader import operators
+from airflow.operators.python import PythonOperator
+from retired.update_workflows import update_sql
logging.basicConfig(
@@ -49,7 +50,11 @@ def create_dag(
)
with dag:
- operators.get_smithsonian_sub_provider_update_operator(postgres_conn_id)
+ PythonOperator(
+ task_id="update_smithsonian_sub_providers",
+ python_callable=update_sql.update_smithsonian_sub_providers,
+ op_args=[postgres_conn_id],
+ )
return dag
diff --git a/openverse_catalog/dags/retired/update_workflows/update_sql.py b/openverse_catalog/dags/retired/update_workflows/update_sql.py
new file mode 100644
index 000000000..4ed0a0b6c
--- /dev/null
+++ b/openverse_catalog/dags/retired/update_workflows/update_sql.py
@@ -0,0 +1,270 @@
+import json
+from textwrap import dedent
+
+from airflow.providers.postgres.hooks.postgres import PostgresHook
+from storage import columns as col
+from util.constants import IMAGE
+from util.loader import provider_details as prov
+from util.loader.sql import DB_USER_NAME, TABLE_NAMES, logger
+
+
+def _create_temp_flickr_sub_prov_table(
+ postgres_conn_id, temp_table="temp_flickr_sub_prov_table"
+):
+ """
+ Drop the temporary table if it already exists
+ """
+ postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres.run(f"DROP TABLE IF EXISTS public.{temp_table};")
+
+ """
+ Create intermediary table for sub provider migration
+ """
+ postgres.run(
+ dedent(
+ f"""
+ CREATE TABLE public.{temp_table} (
+ {col.CREATOR_URL.db_name} character varying(2000),
+ sub_provider character varying(80)
+ );
+ """
+ )
+ )
+
+ postgres.run(f"ALTER TABLE public.{temp_table} OWNER TO {DB_USER_NAME};")
+
+ """
+ Populate the intermediary table with the sub providers of interest
+ """
+ for sub_prov, user_id_set in prov.FLICKR_SUB_PROVIDERS.items():
+ for user_id in user_id_set:
+ creator_url = prov.FLICKR_PHOTO_URL_BASE + user_id
+ postgres.run(
+ dedent(
+ f"""
+ INSERT INTO public.{temp_table} (
+ {col.CREATOR_URL.db_name},
+ sub_provider
+ )
+ VALUES (
+ '{creator_url}',
+ '{sub_prov}'
+ );
+ """
+ )
+ )
+
+ return temp_table
+
+
+def update_flickr_sub_providers(
+ postgres_conn_id,
+ image_table=TABLE_NAMES[IMAGE],
+ default_provider=prov.FLICKR_DEFAULT_PROVIDER,
+):
+ postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ temp_table = _create_temp_flickr_sub_prov_table(postgres_conn_id)
+
+ select_query = dedent(
+ f"""
+ SELECT
+ {col.FOREIGN_ID.db_name} AS foreign_id,
+ public.{temp_table}.sub_provider AS sub_provider
+ FROM {image_table}
+ INNER JOIN public.{temp_table}
+ ON
+ {image_table}.{col.CREATOR_URL.db_name} = public.{temp_table}.{
+ col.CREATOR_URL.db_name}
+ AND
+ {image_table}.{col.PROVIDER.db_name} = '{default_provider}';
+ """
+ )
+
+ selected_records = postgres.get_records(select_query)
+ logger.info(f"Updating {len(selected_records)} records")
+
+ for row in selected_records:
+ foreign_id = row[0]
+ sub_provider = row[1]
+ postgres.run(
+ dedent(
+ f"""
+ UPDATE {image_table}
+ SET {col.SOURCE.db_name} = '{sub_provider}'
+ WHERE
+ {image_table}.{col.PROVIDER.db_name} = '{default_provider}'
+ AND
+ MD5({image_table}.{col.FOREIGN_ID.db_name}) = MD5('{foreign_id}');
+ """
+ )
+ )
+
+ """
+ Drop the temporary table
+ """
+ postgres.run(f"DROP TABLE public.{temp_table};")
+
+
+def _create_temp_europeana_sub_prov_table(
+ postgres_conn_id, temp_table="temp_eur_sub_prov_table"
+):
+ """
+ Drop the temporary table if it already exists
+ """
+ postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ postgres.run(f"DROP TABLE IF EXISTS public.{temp_table};")
+
+ """
+ Create intermediary table for sub provider migration
+ """
+ postgres.run(
+ dedent(
+ f"""
+ CREATE TABLE public.{temp_table} (
+ data_provider character varying(120),
+ sub_provider character varying(80)
+ );
+ """
+ )
+ )
+
+ postgres.run(f"ALTER TABLE public.{temp_table} OWNER TO {DB_USER_NAME};")
+
+ """
+ Populate the intermediary table with the sub providers of interest
+ """
+ for sub_prov, data_provider in prov.EUROPEANA_SUB_PROVIDERS.items():
+ postgres.run(
+ dedent(
+ f"""
+ INSERT INTO public.{temp_table} (
+ data_provider,
+ sub_provider
+ )
+ VALUES (
+ '{data_provider}',
+ '{sub_prov}'
+ );
+ """
+ )
+ )
+
+ return temp_table
+
+
+def update_europeana_sub_providers(
+ postgres_conn_id,
+ image_table=TABLE_NAMES[IMAGE],
+ default_provider=prov.EUROPEANA_DEFAULT_PROVIDER,
+ sub_providers=prov.EUROPEANA_SUB_PROVIDERS,
+):
+ postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+ temp_table = _create_temp_europeana_sub_prov_table(postgres_conn_id)
+
+ select_query = dedent(
+ f"""
+ SELECT L.foreign_id, L.data_providers, R.sub_provider
+ FROM(
+ SELECT
+ {col.FOREIGN_ID.db_name} AS foreign_id,
+ {col.META_DATA.db_name} ->> 'dataProvider' AS data_providers,
+ {col.META_DATA.db_name}
+ FROM {image_table}
+ WHERE {col.PROVIDER.db_name} = '{default_provider}'
+ ) L INNER JOIN
+ {temp_table} R ON
+ L.{col.META_DATA.db_name} ->'dataProvider' ? R.data_provider;
+ """
+ )
+
+ selected_records = postgres.get_records(select_query)
+
+ """
+ Update each selected row if it corresponds to only one sub-provider.
+ Otherwise an exception is thrown
+ """
+ for row in selected_records:
+ foreign_id = row[0]
+ data_providers = json.loads(row[1])
+ sub_provider = row[2]
+
+ eligible_sub_providers = {
+ s for s in sub_providers if sub_providers[s] in data_providers
+ }
+ if len(eligible_sub_providers) > 1:
+ raise Exception(
+ f"More than one sub-provider identified for the "
+ f"image with foreign ID {foreign_id}"
+ )
+
+ assert len(eligible_sub_providers) == 1
+ assert eligible_sub_providers.pop() == sub_provider
+
+ postgres.run(
+ dedent(
+ f"""
+ UPDATE {image_table}
+ SET {col.SOURCE.db_name} = '{sub_provider}'
+ WHERE
+ {image_table}.{col.PROVIDER.db_name} = '{default_provider}'
+ AND
+ MD5({image_table}.{col.FOREIGN_ID.db_name}) = MD5('{foreign_id}');
+ """
+ )
+ )
+
+ """
+ Drop the temporary table
+ """
+ postgres.run(f"DROP TABLE public.{temp_table};")
+
+
+def update_smithsonian_sub_providers(
+ postgres_conn_id,
+ image_table=TABLE_NAMES[IMAGE],
+ default_provider=prov.SMITHSONIAN_DEFAULT_PROVIDER,
+ sub_providers=prov.SMITHSONIAN_SUB_PROVIDERS,
+):
+ postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
+
+ """
+ Select all records where the source value is not yet updated
+ """
+ select_query = dedent(
+ f"""
+ SELECT {col.FOREIGN_ID.db_name},
+ {col.META_DATA.db_name} ->> 'unit_code' AS unit_code
+ FROM {image_table}
+ WHERE
+ {col.PROVIDER.db_name} = '{default_provider}'
+ AND
+ {col.SOURCE.db_name} = '{default_provider}';
+ """
+ )
+
+ selected_records = postgres.get_records(select_query)
+
+ """
+ Set the source value of each selected row to the sub-provider value
+ corresponding to unit code. If the unit code is unknown, an error is thrown
+ """
+ for row in selected_records:
+ foreign_id = row[0]
+ unit_code = row[1]
+
+ source = next((s for s in sub_providers if unit_code in sub_providers[s]), None)
+ if source is None:
+ raise Exception(f"An unknown unit code value {unit_code} encountered ")
+
+ postgres.run(
+ dedent(
+ f"""
+ UPDATE {image_table}
+ SET {col.SOURCE.db_name} = '{source}'
+ WHERE
+ {image_table}.{col.PROVIDER.db_name} = '{default_provider}'
+ AND
+ MD5({image_table}.{col.FOREIGN_ID.db_name}) = MD5('{foreign_id}');
+ """
+ )
+ )
diff --git a/openverse_catalog/dags/util/dag_factory.py b/openverse_catalog/dags/util/dag_factory.py
index 8fd852bbd..fded6950b 100644
--- a/openverse_catalog/dags/util/dag_factory.py
+++ b/openverse_catalog/dags/util/dag_factory.py
@@ -3,14 +3,32 @@ from copy import deepcopy
from datetime import datetime, timedelta
import util.config as conf
-import util.operator_util as ops
from airflow import DAG
from airflow.models.baseoperator import cross_downstream
+from airflow.operators.dummy import DummyOperator
+from airflow.operators.python import PythonOperator
+from airflow.utils.trigger_rule import TriggerRule
logger = logging.getLogger(__name__)
+def get_dated_main_runner_operator(
+ main_function,
+ execution_timeout,
+ day_shift=0,
+ task_id="pull_image_data",
+):
+ args_str = f"{{{{ macros.ds_add(ds, -{day_shift}) }}}}"
+ return PythonOperator(
+ task_id=task_id,
+ python_callable=main_function,
+ op_args=[args_str],
+ execution_timeout=execution_timeout,
+ depends_on_past=False,
+ )
+
+
def create_provider_api_workflow(
dag_id,
main_function,
@@ -74,11 +92,15 @@ def create_provider_api_workflow(
with dag:
if dated:
- ops.get_dated_main_runner_operator(
+ get_dated_main_runner_operator(
main_function, dagrun_timeout, day_shift=day_shift
)
else:
- ops.get_main_runner_operator(main_function)
+ PythonOperator(
+ task_id="pull_image_data",
+ python_callable=main_function,
+ depends_on_past=False,
+ )
return dag
@@ -183,7 +205,9 @@ def create_day_partitioned_ingestion_dag(
reingestion_day_list_list, main_function, ingestion_task_timeout
)
for i in range(len(ingest_operator_list_list) - 1):
- wait_operator = ops.get_wait_till_done_operator(f"wait_L{i}")
+ wait_operator = DummyOperator(
+ task_id=f"wait_L{i}", trigger_rule=TriggerRule.ALL_DONE
+ )
cross_downstream(ingest_operator_list_list[i], [wait_operator])
wait_operator >> ingest_operator_list_list[i + 1]
ingest_operator_list_list[-1]
@@ -198,7 +222,7 @@ def _build_ingest_operator_list_list(
reingestion_day_list_list = [[0]] + reingestion_day_list_list
return [
[
- ops.get_dated_main_runner_operator(
+ get_dated_main_runner_operator(
main_function,
ingestion_task_timeout,
day_shift=d,
diff --git a/openverse_catalog/dags/util/loader/operators.py b/openverse_catalog/dags/util/loader/operators.py
index 78436e1df..d72965b72 100644
--- a/openverse_catalog/dags/util/loader/operators.py
+++ b/openverse_catalog/dags/util/loader/operators.py
@@ -121,30 +121,6 @@ def get_failure_moving_operator(output_dir, identifier=TIMESTAMP_TEMPLATE):
)
-def get_flickr_sub_provider_update_operator(postgres_conn_id):
- return PythonOperator(
- task_id="update_flickr_sub_providers",
- python_callable=sql.update_flickr_sub_providers,
- op_args=[postgres_conn_id],
- )
-
-
-def get_europeana_sub_provider_update_operator(postgres_conn_id):
- return PythonOperator(
- task_id="update_europeana_sub_providers",
- python_callable=sql.update_europeana_sub_providers,
- op_args=[postgres_conn_id],
- )
-
-
-def get_smithsonian_sub_provider_update_operator(postgres_conn_id):
- return PythonOperator(
- task_id="update_smithsonian_sub_providers",
- python_callable=sql.update_smithsonian_sub_providers,
- op_args=[postgres_conn_id],
- )
-
-
def get_smithsonian_unit_code_operator(postgres_conn_id):
return PythonOperator(
task_id="check_new_smithsonian_unit_codes",
diff --git a/openverse_catalog/dags/util/loader/sql.py b/openverse_catalog/dags/util/loader/sql.py
index 24cab9569..f12b1148f 100644
--- a/openverse_catalog/dags/util/loader/sql.py
+++ b/openverse_catalog/dags/util/loader/sql.py
@@ -1,4 +1,3 @@
-import json
import logging
from textwrap import dedent
from typing import List
@@ -335,268 +334,6 @@ def _delete_malformed_row_in_file(tsv_file_name, line_number):
write_obj.write(line)
-def _create_temp_flickr_sub_prov_table(
- postgres_conn_id, temp_table="temp_flickr_sub_prov_table"
-):
- """
- Drop the temporary table if it already exists
- """
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
- postgres.run(f"DROP TABLE IF EXISTS public.{temp_table};")
-
- """
- Create intermediary table for sub provider migration
- """
- postgres.run(
- dedent(
- f"""
- CREATE TABLE public.{temp_table} (
- {col.CREATOR_URL.db_name} character varying(2000),
- sub_provider character varying(80)
- );
- """
- )
- )
-
- postgres.run(f"ALTER TABLE public.{temp_table} OWNER TO {DB_USER_NAME};")
-
- """
- Populate the intermediary table with the sub providers of interest
- """
- for sub_prov, user_id_set in prov.FLICKR_SUB_PROVIDERS.items():
- for user_id in user_id_set:
- creator_url = prov.FLICKR_PHOTO_URL_BASE + user_id
- postgres.run(
- dedent(
- f"""
- INSERT INTO public.{temp_table} (
- {col.CREATOR_URL.db_name},
- sub_provider
- )
- VALUES (
- '{creator_url}',
- '{sub_prov}'
- );
- """
- )
- )
-
- return temp_table
-
-
-def update_flickr_sub_providers(
- postgres_conn_id,
- image_table=TABLE_NAMES[IMAGE],
- default_provider=prov.FLICKR_DEFAULT_PROVIDER,
-):
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
- temp_table = _create_temp_flickr_sub_prov_table(postgres_conn_id)
-
- select_query = dedent(
- f"""
- SELECT
- {col.FOREIGN_ID.db_name} AS foreign_id,
- public.{temp_table}.sub_provider AS sub_provider
- FROM {image_table}
- INNER JOIN public.{temp_table}
- ON
- {image_table}.{col.CREATOR_URL.db_name} = public.{temp_table}.{
- col.CREATOR_URL.db_name}
- AND
- {image_table}.{col.PROVIDER.db_name} = '{default_provider}';
- """
- )
-
- selected_records = postgres.get_records(select_query)
- logger.info(f"Updating {len(selected_records)} records")
-
- for row in selected_records:
- foreign_id = row[0]
- sub_provider = row[1]
- postgres.run(
- dedent(
- f"""
- UPDATE {image_table}
- SET {col.SOURCE.db_name} = '{sub_provider}'
- WHERE
- {image_table}.{col.PROVIDER.db_name} = '{default_provider}'
- AND
- MD5({image_table}.{col.FOREIGN_ID.db_name}) = MD5('{foreign_id}');
- """
- )
- )
-
- """
- Drop the temporary table
- """
- postgres.run(f"DROP TABLE public.{temp_table};")
-
-
-def _create_temp_europeana_sub_prov_table(
- postgres_conn_id, temp_table="temp_eur_sub_prov_table"
-):
- """
- Drop the temporary table if it already exists
- """
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
- postgres.run(f"DROP TABLE IF EXISTS public.{temp_table};")
-
- """
- Create intermediary table for sub provider migration
- """
- postgres.run(
- dedent(
- f"""
- CREATE TABLE public.{temp_table} (
- data_provider character varying(120),
- sub_provider character varying(80)
- );
- """
- )
- )
-
- postgres.run(f"ALTER TABLE public.{temp_table} OWNER TO {DB_USER_NAME};")
-
- """
- Populate the intermediary table with the sub providers of interest
- """
- for sub_prov, data_provider in prov.EUROPEANA_SUB_PROVIDERS.items():
- postgres.run(
- dedent(
- f"""
- INSERT INTO public.{temp_table} (
- data_provider,
- sub_provider
- )
- VALUES (
- '{data_provider}',
- '{sub_prov}'
- );
- """
- )
- )
-
- return temp_table
-
-
-def update_europeana_sub_providers(
- postgres_conn_id,
- image_table=TABLE_NAMES[IMAGE],
- default_provider=prov.EUROPEANA_DEFAULT_PROVIDER,
- sub_providers=prov.EUROPEANA_SUB_PROVIDERS,
-):
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
- temp_table = _create_temp_europeana_sub_prov_table(postgres_conn_id)
-
- select_query = dedent(
- f"""
- SELECT L.foreign_id, L.data_providers, R.sub_provider
- FROM(
- SELECT
- {col.FOREIGN_ID.db_name} AS foreign_id,
- {col.META_DATA.db_name} ->> 'dataProvider' AS data_providers,
- {col.META_DATA.db_name}
- FROM {image_table}
- WHERE {col.PROVIDER.db_name} = '{default_provider}'
- ) L INNER JOIN
- {temp_table} R ON
- L.{col.META_DATA.db_name} ->'dataProvider' ? R.data_provider;
- """
- )
-
- selected_records = postgres.get_records(select_query)
-
- """
- Update each selected row if it corresponds to only one sub-provider.
- Otherwise an exception is thrown
- """
- for row in selected_records:
- foreign_id = row[0]
- data_providers = json.loads(row[1])
- sub_provider = row[2]
-
- eligible_sub_providers = {
- s for s in sub_providers if sub_providers[s] in data_providers
- }
- if len(eligible_sub_providers) > 1:
- raise Exception(
- f"More than one sub-provider identified for the "
- f"image with foreign ID {foreign_id}"
- )
-
- assert len(eligible_sub_providers) == 1
- assert eligible_sub_providers.pop() == sub_provider
-
- postgres.run(
- dedent(
- f"""
- UPDATE {image_table}
- SET {col.SOURCE.db_name} = '{sub_provider}'
- WHERE
- {image_table}.{col.PROVIDER.db_name} = '{default_provider}'
- AND
- MD5({image_table}.{col.FOREIGN_ID.db_name}) = MD5('{foreign_id}');
- """
- )
- )
-
- """
- Drop the temporary table
- """
- postgres.run(f"DROP TABLE public.{temp_table};")
-
-
-def update_smithsonian_sub_providers(
- postgres_conn_id,
- image_table=TABLE_NAMES[IMAGE],
- default_provider=prov.SMITHSONIAN_DEFAULT_PROVIDER,
- sub_providers=prov.SMITHSONIAN_SUB_PROVIDERS,
-):
- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
-
- """
- Select all records where the source value is not yet updated
- """
- select_query = dedent(
- f"""
- SELECT {col.FOREIGN_ID.db_name},
- {col.META_DATA.db_name} ->> 'unit_code' AS unit_code
- FROM {image_table}
- WHERE
- {col.PROVIDER.db_name} = '{default_provider}'
- AND
- {col.SOURCE.db_name} = '{default_provider}';
- """
- )
-
- selected_records = postgres.get_records(select_query)
-
- """
- Set the source value of each selected row to the sub-provider value
- corresponding to unit code. If the unit code is unknown, an error is thrown
- """
- for row in selected_records:
- foreign_id = row[0]
- unit_code = row[1]
-
- source = next((s for s in sub_providers if unit_code in sub_providers[s]), None)
- if source is None:
- raise Exception(f"An unknown unit code value {unit_code} encountered ")
-
- postgres.run(
- dedent(
- f"""
- UPDATE {image_table}
- SET {col.SOURCE.db_name} = '{source}'
- WHERE
- {image_table}.{col.PROVIDER.db_name} = '{default_provider}'
- AND
- MD5({image_table}.{col.FOREIGN_ID.db_name}) = MD5('{foreign_id}');
- """
- )
- )
-
-
def expire_old_images(postgres_conn_id, provider, image_table=TABLE_NAMES[IMAGE]):
postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
diff --git a/openverse_catalog/dags/util/operator_util.py b/openverse_catalog/dags/util/operator_util.py
deleted file mode 100644
index 94fde5cac..000000000
--- a/openverse_catalog/dags/util/operator_util.py
+++ /dev/null
@@ -1,39 +0,0 @@
-from airflow.operators.bash import BashOperator
-from airflow.operators.dummy import DummyOperator
-from airflow.operators.python import PythonOperator
-from airflow.utils.trigger_rule import TriggerRule
-
-
-def get_runner_operator(source, script_location):
- return BashOperator(
- task_id=f"get_{source}_images",
- bash_command=f"python {script_location} --mode default",
- )
-
-
-def get_dated_main_runner_operator(
- main_function,
- execution_timeout,
- day_shift=0,
- task_id="pull_image_data",
-):
- args_str = f"{{{{ macros.ds_add(ds, -{day_shift}) }}}}"
- return PythonOperator(
- task_id=task_id,
- python_callable=main_function,
- op_args=[args_str],
- execution_timeout=execution_timeout,
- depends_on_past=False,
- )
-
-
-def get_main_runner_operator(main_function):
- return PythonOperator(
- task_id="pull_image_data",
- python_callable=main_function,
- depends_on_past=False,
- )
-
-
-def get_wait_till_done_operator(task_id):
- return DummyOperator(task_id=task_id, trigger_rule=TriggerRule.ALL_DONE)
diff --git a/tests/dags/test_common_api_workflows.py b/tests/dags/test_common_api_workflows.py
index fb1cef041..61a3d1c73 100644
--- a/tests/dags/test_common_api_workflows.py
+++ b/tests/dags/test_common_api_workflows.py
@@ -1,8 +1,11 @@
import os
+from datetime import datetime, timedelta, timezone
import common_api_workflows as caw
import util.config as conf
-from airflow.models import DagBag
+import util.dag_factory
+from airflow import DAG
+from airflow.models import DagBag, TaskInstance
SCRIPT = conf.SCRIPT
@@ -10,6 +13,48 @@ CRONTAB_STR = conf.CRONTAB_STR
FILE_DIR = os.path.abspath(os.path.dirname(__file__))
+def dated(dag_date):
+ print(dag_date)
+
+
+def test_get_dated_main_runner_handles_zero_shift(capsys):
+ dag = DAG(dag_id="test_dag", start_date=datetime.strptime("2019-01-01", "%Y-%m-%d"))
+ execution_date = datetime.strptime("2019-01-01", "%Y-%m-%d").replace(
+ tzinfo=timezone.utc
+ )
+ main_func = dated
+ with dag:
+ runner = util.dag_factory.get_dated_main_runner_operator(
+ main_func, timedelta(minutes=1)
+ )
+ ti = TaskInstance(runner, execution_date)
+ ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True)
+ # main_func.assert_called_with('2019-01-01')
+ # Mocking main_func causes errors because Airflow JSON-encodes it,
+ # and MagicMock is not JSON-serializable.
+ captured = capsys.readouterr()
+ assert captured.out == "2019-01-01\n"
+
+
+def test_get_dated_main_runner_handles_day_shift(capsys):
+ dag = DAG(dag_id="test_dag", start_date=datetime.strptime("2019-01-01", "%Y-%m-%d"))
+ execution_date = datetime.strptime("2019-01-01", "%Y-%m-%d").replace(
+ tzinfo=timezone.utc
+ )
+ main_func = dated
+ with dag:
+ runner = util.dag_factory.get_dated_main_runner_operator(
+ main_func, timedelta(minutes=1), day_shift=1
+ )
+ ti = TaskInstance(runner, execution_date)
+ ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True)
+ # main_func.assert_called_with('2018-12-31')
+ # Mocking main_func causes errors because Airflow JSON-encodes it,
+ # and MagicMock is not JSON-serializable.
+ captured = capsys.readouterr()
+ assert captured.out == "2018-12-31\n"
+
+
def test_dags_load_with_no_errors(tmpdir):
tmp_directory = str(tmpdir)
dag_bag = DagBag(dag_folder=tmp_directory, include_examples=False)
diff --git a/tests/dags/test_dag_parsing.py b/tests/dags/test_dag_parsing.py
index 1a96e8a8f..811224481 100644
--- a/tests/dags/test_dag_parsing.py
+++ b/tests/dags/test_dag_parsing.py
@@ -16,11 +16,9 @@ WORKFLOWS = [
"cleaner_workflow.py",
"cleveland_museum_workflow.py",
"europeana_ingestion_workflow.py",
- "europeana_sub_provider_update_workflow.py",
"europeana_workflow.py",
"finnish_museums_workflow.py",
"flickr_ingestion_workflow.py",
- "flickr_sub_provider_update_workflow.py",
"flickr_workflow.py",
"loader_workflow.py",
"metropolitan_museum_workflow.py",
@@ -29,7 +27,6 @@ WORKFLOWS = [
"phylopic_workflow.py",
"rawpixel_workflow.py",
"science_museum_workflow.py",
- "smithsonian_sub_provider_update_workflow.py",
"smithsonian_workflow.py",
"statens_museum_workflow.py",
"sync_commoncrawl_workflow.py",
diff --git a/tests/dags/util/loader/test_sql.py b/tests/dags/util/loader/test_sql.py
index c35b176d4..e989b2d86 100644
--- a/tests/dags/util/loader/test_sql.py
+++ b/tests/dags/util/loader/test_sql.py
@@ -1258,209 +1258,6 @@ def test_drop_load_table_drops_table(postgres_with_load_table):
assert not check_result
-def test_update_flickr_sub_providers(postgres_with_load_and_image_table):
- postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
-
- FID_A = "a"
- FID_B = "b"
- IMG_URL_A = "https://images.com/a/img.jpg"
- IMG_URL_B = "https://images.com/b/img.jpg"
- CREATOR_URL_A = "https://www.flickr.com/photos/29988733@N04"
- CREATOR_URL_B = "https://www.flickr.com/photos/other_user"
- PROVIDER = "flickr"
- LICENSE = "by"
- TAGS = [
- {"name": "tagone", "provider": "test"},
- {"name": "tagtwo", "provider": "test"},
- ]
-
- insert_data_query = f"""INSERT INTO {load_table} VALUES
- ({create_query_values({
- col.FOREIGN_ID.db_name: FID_A,
- col.DIRECT_URL.db_name: IMG_URL_A,
- col.LICENSE.db_name: LICENSE,
- col.CREATOR_URL.db_name: CREATOR_URL_A,
- col.TAGS.db_name: json.dumps(TAGS),
- col.PROVIDER.db_name: PROVIDER,
- col.SOURCE.db_name: PROVIDER,
- })}),
- ({create_query_values({
- col.FOREIGN_ID.db_name: FID_B,
- col.DIRECT_URL.db_name: IMG_URL_B,
- col.LICENSE.db_name: LICENSE,
- col.CREATOR_URL.db_name: CREATOR_URL_B,
- col.TAGS.db_name: json.dumps(TAGS),
- col.PROVIDER.db_name: PROVIDER,
- col.SOURCE.db_name: PROVIDER,
- })});"""
-
- postgres_with_load_and_image_table.cursor.execute(insert_data_query)
- postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
- postgres_with_load_and_image_table.connection.commit()
- postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
- postgres_with_load_and_image_table.connection.commit()
-
- sql.update_flickr_sub_providers(postgres_conn_id, image_table)
- postgres_with_load_and_image_table.connection.commit()
- postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
- actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
- assert len(actual_rows) == 2
-
- for actual_row in actual_rows:
- if actual_row[fid_idx] == "a":
- assert actual_row[source_idx] == "nasa"
- else:
- assert actual_row[fid_idx] == "b" and actual_row[source_idx] == "flickr"
-
-
-def test_update_europeana_sub_providers(postgres_with_load_and_image_table):
- postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
-
- FID_A = "a"
- FID_B = "b"
- IMG_URL_A = "https://images.com/a/img.jpg"
- IMG_URL_B = "https://images.com/b/img.jpg"
- PROVIDER = "europeana"
- LICENSE = "by-nc-nd"
- META_DATA_A = {
- "country": ["Sweden"],
- "dataProvider": ["Wellcome Collection"],
- "description": "A",
- "license_url": "http://creativecommons.org/licenses/by-nc-nd/4.0/",
- }
- META_DATA_B = {
- "country": ["Sweden"],
- "dataProvider": ["Other Collection"],
- "description": "B",
- "license_url": "http://creativecommons.org/licenses/by-nc-nd/4.0/",
- }
-
- query_values = [
- create_query_values(
- {
- col.FOREIGN_ID.db_name: FID_A,
- col.DIRECT_URL.db_name: IMG_URL_A,
- col.LICENSE.db_name: LICENSE,
- col.META_DATA.db_name: json.dumps(META_DATA_A),
- col.PROVIDER.db_name: PROVIDER,
- col.SOURCE.db_name: PROVIDER,
- }
- ),
- create_query_values(
- {
- col.FOREIGN_ID.db_name: FID_B,
- col.DIRECT_URL.db_name: IMG_URL_B,
- col.LICENSE.db_name: LICENSE,
- col.META_DATA.db_name: json.dumps(META_DATA_B),
- col.PROVIDER.db_name: PROVIDER,
- col.SOURCE.db_name: PROVIDER,
- }
- ),
- ]
- insert_data_query = f"""INSERT INTO {load_table} VALUES
- ({query_values[0]}),
- ({query_values[1]}
- );"""
-
- postgres_with_load_and_image_table.cursor.execute(insert_data_query)
- postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
- postgres_with_load_and_image_table.connection.commit()
- postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
- postgres_with_load_and_image_table.connection.commit()
-
- sql.update_europeana_sub_providers(postgres_conn_id, image_table)
- postgres_with_load_and_image_table.connection.commit()
- postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
- actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
- assert len(actual_rows) == 2
-
- for actual_row in actual_rows:
- if actual_row[fid_idx] == "a":
- assert actual_row[source_idx] == "wellcome_collection"
- else:
- assert actual_row[fid_idx] == "b" and actual_row[source_idx] == "europeana"
-
-
-def test_update_smithsonian_sub_providers(postgres_with_load_and_image_table):
- postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
-
- FID_A = "a"
- FID_B = "b"
- IMG_URL_A = "https://images.com/a/img.jpg"
- IMG_URL_B = "https://images.com/b/img.jpg"
- PROVIDER = "smithsonian"
- LICENSE = "by-nc-nd"
- META_DATA_A = {
- "unit_code": "SIA",
- "data_source": "Smithsonian Institution Archives",
- }
- META_DATA_B = {
- "unit_code": "NMNHBIRDS",
- "data_source": "NMNH - Vertebrate Zoology - Birds Division",
- }
-
- query_values = [
- create_query_values(
- {
- col.FOREIGN_ID.db_name: FID_A,
- col.DIRECT_URL.db_name: IMG_URL_A,
- col.LICENSE.db_name: LICENSE,
- col.META_DATA.db_name: json.dumps(META_DATA_A),
- col.PROVIDER.db_name: PROVIDER,
- col.SOURCE.db_name: PROVIDER,
- }
- ),
- create_query_values(
- {
- col.FOREIGN_ID.db_name: FID_B,
- col.DIRECT_URL.db_name: IMG_URL_B,
- col.LICENSE.db_name: LICENSE,
- col.META_DATA.db_name: json.dumps(META_DATA_B),
- col.PROVIDER.db_name: PROVIDER,
- col.SOURCE.db_name: PROVIDER,
- }
- ),
- ]
- insert_data_query = f"""INSERT INTO {load_table} VALUES
- ({query_values[0]}),
- ({query_values[1]}
- );"""
-
- postgres_with_load_and_image_table.cursor.execute(insert_data_query)
- postgres_with_load_and_image_table.connection.commit()
- sql.upsert_records_to_db_table(postgres_conn_id, identifier, db_table=image_table)
- postgres_with_load_and_image_table.connection.commit()
- postgres_with_load_and_image_table.cursor.execute(f"DELETE FROM {load_table};")
- postgres_with_load_and_image_table.connection.commit()
-
- sql.update_smithsonian_sub_providers(postgres_conn_id, image_table)
- postgres_with_load_and_image_table.connection.commit()
- postgres_with_load_and_image_table.cursor.execute(f"SELECT * FROM {image_table};")
- actual_rows = postgres_with_load_and_image_table.cursor.fetchall()
- assert len(actual_rows) == 2
-
- for actual_row in actual_rows:
- if actual_row[fid_idx] == "a":
- assert actual_row[source_idx] == "smithsonian_institution_archives"
- else:
- assert (
- actual_row[fid_idx] == "b"
- and actual_row[source_idx]
- == "smithsonian_national_museum_of_natural_history"
- )
-
-
def test_image_expiration(postgres_with_load_and_image_table):
postgres_conn_id = POSTGRES_CONN_ID
load_table = TEST_LOAD_TABLE
diff --git a/tests/dags/util/test_operator_util.py b/tests/dags/util/test_operator_util.py
deleted file mode 100644
index b6f9f6651..000000000
--- a/tests/dags/util/test_operator_util.py
+++ /dev/null
@@ -1,51 +0,0 @@
-from datetime import datetime, timedelta, timezone
-
-import util.operator_util as op_util
-from airflow import DAG
-from airflow.models.taskinstance import TaskInstance
-
-
-def dated(dag_date):
- print(dag_date)
-
-
-def test_get_runner_operator_creates_valid_string():
- runner = op_util.get_runner_operator("test_source", "/test/script/location.py")
- expected_command = "python /test/script/location.py --mode default"
- assert runner.bash_command == expected_command
-
-
-def test_get_dated_main_runner_handles_zero_shift(capsys):
- dag = DAG(dag_id="test_dag", start_date=datetime.strptime("2019-01-01", "%Y-%m-%d"))
- execution_date = datetime.strptime("2019-01-01", "%Y-%m-%d").replace(
- tzinfo=timezone.utc
- )
- main_func = dated
- with dag:
- runner = op_util.get_dated_main_runner_operator(main_func, timedelta(minutes=1))
- ti = TaskInstance(runner, execution_date)
- ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True)
- # main_func.assert_called_with('2019-01-01')
- # Mocking main_func causes errors because Airflow JSON-encodes it,
- # and MagicMock is not JSON-serializable.
- captured = capsys.readouterr()
- assert captured.out == "2019-01-01\n"
-
-
-def test_get_dated_main_runner_handles_day_shift(capsys):
- dag = DAG(dag_id="test_dag", start_date=datetime.strptime("2019-01-01", "%Y-%m-%d"))
- execution_date = datetime.strptime("2019-01-01", "%Y-%m-%d").replace(
- tzinfo=timezone.utc
- )
- main_func = dated
- with dag:
- runner = op_util.get_dated_main_runner_operator(
- main_func, timedelta(minutes=1), day_shift=1
- )
- ti = TaskInstance(runner, execution_date)
- ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True)
- # main_func.assert_called_with('2018-12-31')
- # Mocking main_func causes errors because Airflow JSON-encodes it,
- # and MagicMock is not JSON-serializable.
- captured = capsys.readouterr()
- assert captured.out == "2018-12-31\n"