Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Reduce TSV loader complexity (#289)
Madison Swain-Bowden7b142c7885aa
diff --git a/openverse_catalog/dags/common/loader/loader.py b/openverse_catalog/dags/common/loader/loader.pyindex a3f01d061..3225a5eaf 100644--- a/openverse_catalog/dags/common/loader/loader.py+++ b/openverse_catalog/dags/common/loader/loader.py@@ -2,19 +2,6 @@ from common.loader import paths, s3, sqlfrom common.loader.paths import _extract_media_type-def load_local_data(output_dir, postgres_conn_id, identifier, ti):- tsv_file_name = paths.get_staged_file(output_dir, identifier)- tsv_version = ti.xcom_pull(task_ids="stage_oldest_tsv_file", key="tsv_version")-- media_type = _extract_media_type(tsv_file_name)- sql.load_local_data_to_intermediate_table(- postgres_conn_id, tsv_file_name, identifier- )- sql.upsert_records_to_db_table(- postgres_conn_id, identifier, media_type=media_type, tsv_version=tsv_version- )--def copy_to_s3(output_dir, bucket, identifier, aws_conn_id):tsv_file_name = paths.get_staged_file(output_dir, identifier)media_type = _extract_media_type(tsv_file_name)diff --git a/openverse_catalog/dags/common/loader/operators.py b/openverse_catalog/dags/common/loader/operators.pyindex d27f7939e..87df97e11 100644--- a/openverse_catalog/dags/common/loader/operators.py+++ b/openverse_catalog/dags/common/loader/operators.py@@ -1,9 +1,7 @@import logging-from airflow.operators.dummy import DummyOperator-from airflow.operators.python import PythonOperator, ShortCircuitOperator-from airflow.utils.trigger_rule import TriggerRule-from common.loader import loader, paths, smithsonian_unit_codes, sql+from airflow.operators.python import PythonOperator+from common.loader import smithsonian_unit_codes, sqllogger = logging.getLogger(__name__)@@ -11,113 +9,6 @@ logger = logging.getLogger(__name__)TIMESTAMP_TEMPLATE = "{{ ts_nodash }}"-def get_file_staging_operator(- output_dir, minimum_file_age_minutes, identifier=TIMESTAMP_TEMPLATE-):- return ShortCircuitOperator(- task_id="stage_oldest_tsv_file",- python_callable=paths.stage_oldest_tsv_file,- op_args=[output_dir, identifier, minimum_file_age_minutes],- )---def get_table_creator_operator(postgres_conn_id, identifier=TIMESTAMP_TEMPLATE):- return PythonOperator(- task_id="create_loading_table",- python_callable=sql.create_loading_table,- op_args=[postgres_conn_id, identifier],- )---def get_load_local_data_operator(- output_dir, postgres_conn_id, identifier=TIMESTAMP_TEMPLATE-):- return PythonOperator(- task_id="load_local_data",- python_callable=loader.load_local_data,- op_args=[output_dir, postgres_conn_id, identifier],- trigger_rule=TriggerRule.ALL_SUCCESS,- )---def get_copy_to_s3_operator(- output_dir, storage_bucket, aws_conn_id, identifier=TIMESTAMP_TEMPLATE-):- return PythonOperator(- task_id="copy_to_s3",- python_callable=loader.copy_to_s3,- op_args=[output_dir, storage_bucket, identifier, aws_conn_id],- )---def get_load_s3_data_operator(- bucket,- aws_conn_id,- postgres_conn_id,- identifier=TIMESTAMP_TEMPLATE,-):- return PythonOperator(- task_id="load_s3_data",- python_callable=loader.load_s3_data,- op_args=[bucket, aws_conn_id, postgres_conn_id, identifier],- )---def get_one_failed_switch(identifier):- return DummyOperator(- task_id=f"one_failed_{identifier}",- trigger_rule=TriggerRule.ONE_FAILED,- )---def get_all_failed_switch(identifier):- return DummyOperator(- task_id=f"all_failed_{identifier}",- trigger_rule=TriggerRule.ALL_FAILED,- )---def get_one_success_switch(identifier):- return DummyOperator(- task_id=f"one_success_{identifier}",- trigger_rule=TriggerRule.ONE_SUCCESS,- )---def get_all_done_switch(identifier):- return DummyOperator(- task_id=f"all_done_{identifier}",- trigger_rule=TriggerRule.ALL_DONE,- )---def get_file_deletion_operator(output_dir, identifier=TIMESTAMP_TEMPLATE):- return PythonOperator(- task_id="delete_staged_file",- python_callable=paths.delete_staged_file,- op_args=[output_dir, identifier],- trigger_rule=TriggerRule.ALL_SUCCESS,- )---def get_drop_table_operator(postgres_conn_id, identifier=TIMESTAMP_TEMPLATE):- return PythonOperator(- task_id="drop_loading_table",- python_callable=sql.drop_load_table,- op_args=[postgres_conn_id, identifier],- trigger_rule=TriggerRule.ALL_DONE,- )---def get_failure_moving_operator(output_dir, identifier=TIMESTAMP_TEMPLATE):- return PythonOperator(- task_id="move_staged_failures",- python_callable=paths.move_staged_files_to_failure_directory,- op_args=[output_dir, identifier],- trigger_rule=TriggerRule.ONE_SUCCESS,- )--def get_smithsonian_unit_code_operator(postgres_conn_id):return PythonOperator(task_id="check_new_smithsonian_unit_codes",diff --git a/openverse_catalog/dags/common/loader/paths.py b/openverse_catalog/dags/common/loader/paths.pyindex 62b03b6f0..7b57da5e6 100644--- a/openverse_catalog/dags/common/loader/paths.py+++ b/openverse_catalog/dags/common/loader/paths.py@@ -4,6 +4,7 @@ import refrom datetime import datetime, timedeltafrom typing import Optional+from airflow.exceptions import AirflowSkipExceptionfrom airflow.models import TaskInstance@@ -40,12 +41,13 @@ def stage_oldest_tsv_file(staging_directory = _get_staging_directory(output_dir, identifier)tsv_file_name = _get_oldest_tsv_file(output_dir, minimum_file_age_minutes)tsv_found = tsv_file_name is not None- if tsv_found:- tsv_version = _get_tsv_version(tsv_file_name)- _move_file(tsv_file_name, staging_directory)- media_type = _extract_media_type(tsv_file_name)- ti.xcom_push(key="media_type", value=media_type)- ti.xcom_push(key="tsv_version", value=tsv_version)+ if not tsv_found:+ raise AirflowSkipException("No files to process")+ tsv_version = _get_tsv_version(tsv_file_name)+ _move_file(tsv_file_name, staging_directory)+ media_type = _extract_media_type(tsv_file_name)+ ti.xcom_push(key="media_type", value=media_type)+ ti.xcom_push(key="tsv_version", value=tsv_version)return tsv_founddiff --git a/openverse_catalog/dags/database/loader_workflow.py b/openverse_catalog/dags/database/loader_workflow.pyindex eaefb9282..0c4377b0a 100644--- a/openverse_catalog/dags/database/loader_workflow.py+++ b/openverse_catalog/dags/database/loader_workflow.py@@ -48,9 +48,12 @@ https://github.com/creativecommons/cccatalog/issues/334)"""import osfrom datetime import datetime, timedelta+from textwrap import dedent as dfrom airflow import DAG-from common.loader import operators+from airflow.operators.python import PythonOperator+from airflow.utils.trigger_rule import TriggerRule+from common.loader import loader, paths, sqlDAG_ID = "tsv_to_postgres_loader"@@ -75,7 +78,7 @@ dag = DAG("retry_delay": timedelta(seconds=15),},concurrency=CONCURRENCY,- max_active_runs=CONCURRENCY,+ max_active_runs=1,schedule_interval="* * * * *",catchup=False,tags=["database"],@@ -83,56 +86,107 @@ dag = DAG()with dag:- stage_oldest_tsv_file = operators.get_file_staging_operator(- OUTPUT_DIR_PATH,- MINIMUM_FILE_AGE_MINUTES,- identifier=TIMESTAMP_TEMPLATE,+ stage_oldest_tsv_file = PythonOperator(+ task_id="stage_oldest_tsv_file",+ python_callable=paths.stage_oldest_tsv_file,+ op_kwargs={+ "output_dir": OUTPUT_DIR_PATH,+ "identifier": TIMESTAMP_TEMPLATE,+ "minimum_file_age_minutes": MINIMUM_FILE_AGE_MINUTES,+ },+ doc_md=d(+ f"""+ Find the oldest TSV in the output directory ({OUTPUT_DIR_PATH}) that hasn't been+ modified in {MINIMUM_FILE_AGE_MINUTES} minutes and transfer it to the staging+ directory. If no files are found matching this criteria, the DAG is skipped.+ """+ ),)- create_loading_table = operators.get_table_creator_operator(- DB_CONN_ID,- identifier=TIMESTAMP_TEMPLATE,+ create_loading_table = PythonOperator(+ task_id="create_loading_table",+ python_callable=sql.create_loading_table,+ op_kwargs={+ "postgres_conn_id": DB_CONN_ID,+ "identifier": TIMESTAMP_TEMPLATE,+ },+ doc_md="Create a temporary loading table for ingesting data from a TSV.",)- copy_to_s3 = operators.get_copy_to_s3_operator(- OUTPUT_DIR_PATH,- OPENVERSE_BUCKET,- AWS_CONN_ID,- identifier=TIMESTAMP_TEMPLATE,+ copy_to_s3 = PythonOperator(+ task_id="copy_to_s3",+ python_callable=loader.copy_to_s3,+ op_kwargs={+ "output_dir": OUTPUT_DIR_PATH,+ "bucket": OPENVERSE_BUCKET,+ "aws_conn_id": AWS_CONN_ID,+ "identifier": TIMESTAMP_TEMPLATE,+ },+ doc_md=d(+ f"""+ Copy the TSV from the local output directory ({OUTPUT_DIR_PATH}) into the S3+ bucket ({OPENVERSE_BUCKET}) for direct loading into the database.+ """+ ),)- load_s3_data = operators.get_load_s3_data_operator(- OPENVERSE_BUCKET,- AWS_CONN_ID,- DB_CONN_ID,- identifier=TIMESTAMP_TEMPLATE,+ load_s3_data = PythonOperator(+ task_id="load_s3_data",+ python_callable=loader.load_s3_data,+ op_kwargs={+ "bucket": OPENVERSE_BUCKET,+ "aws_conn_id": AWS_CONN_ID,+ "postgres_conn_id": DB_CONN_ID,+ "identifier": TIMESTAMP_TEMPLATE,+ },+ doc_md="Load the TSV from S3 into the database.",)- one_failed_s3 = operators.get_one_failed_switch("s3")- load_local_data = operators.get_load_local_data_operator(- OUTPUT_DIR_PATH,- DB_CONN_ID,- identifier=TIMESTAMP_TEMPLATE,+ delete_staged_file = PythonOperator(+ task_id="delete_staged_file",+ python_callable=paths.delete_staged_file,+ op_kwargs={"output_dir": OUTPUT_DIR_PATH, "identifier": TIMESTAMP_TEMPLATE},+ trigger_rule=TriggerRule.ALL_SUCCESS,+ doc_md=d(+ """+ Delete the staged TSV. This step will only be run if the file was _both_ copied+ into S3 and loaded into the database successfully.+ """+ ),)- one_success_save = operators.get_one_success_switch("save")- all_done_save = operators.get_all_done_switch("save")- all_failed_save = operators.get_all_failed_switch("save")- delete_staged_file = operators.get_file_deletion_operator(- OUTPUT_DIR_PATH,- identifier=TIMESTAMP_TEMPLATE,+ drop_loading_table = PythonOperator(+ task_id="drop_loading_table",+ python_callable=sql.drop_load_table,+ op_kwargs={"postgres_conn_id": DB_CONN_ID, "identifier": TIMESTAMP_TEMPLATE},+ trigger_rule=TriggerRule.NONE_SKIPPED,+ doc_md=d(+ """+ Drop the temporary loading table used to store the TSV records. This step will+ always occur after table creation unless the DAG has been skipped in order to+ ensure tables are cleaned up in all cases.+ """+ ),)- one_failed_delete = operators.get_one_failed_switch("delete")- drop_loading_table = operators.get_drop_table_operator(- DB_CONN_ID,- identifier=TIMESTAMP_TEMPLATE,+ move_staged_failures = PythonOperator(+ task_id="move_staged_failures",+ python_callable=paths.move_staged_files_to_failure_directory,+ op_kwargs={+ "output_dir": OUTPUT_DIR_PATH,+ "identifier": TIMESTAMP_TEMPLATE,+ },+ trigger_rule=TriggerRule.ONE_FAILED,+ doc_md=d(+ """+ Move any staged files that have failed to upload into the failed directory.+ This task will run if any of the critical loader tasks fail. This allows+ operators to retry the loading once the problem has been addressed.+ """+ ),)- move_staged_failures = operators.get_failure_moving_operator(- OUTPUT_DIR_PATH,- identifier=TIMESTAMP_TEMPLATE,- )- (stage_oldest_tsv_file >> [create_loading_table, copy_to_s3] >> load_s3_data)- [copy_to_s3, load_s3_data] >> one_failed_s3- [create_loading_table, one_failed_s3] >> load_local_data- [copy_to_s3, load_local_data] >> one_success_save- [copy_to_s3, load_local_data] >> all_done_save- [copy_to_s3, load_local_data] >> all_failed_save- [one_success_save, all_done_save] >> delete_staged_file- [load_s3_data, load_local_data] >> drop_loading_table- delete_staged_file >> one_failed_delete- [one_failed_delete, all_failed_save] >> move_staged_failures++ # If there is a TSV to load, copy it to S3 & create the loading table,+ # then perform the load into Postgres from S3+ stage_oldest_tsv_file >> [copy_to_s3, create_loading_table] >> load_s3_data+ # Should any of these tasks fail, move the TSV to the failed location+ [copy_to_s3, create_loading_table, load_s3_data] >> move_staged_failures+ # If any of the loading steps fail, we don't need the loading table anymore+ [create_loading_table, load_s3_data] >> drop_loading_table+ # Once the data is loaded successfully, delete the staged TSV locally+ # (since it exists in S3)+ load_s3_data >> delete_staged_filediff --git a/tests/dags/common/loader/test_paths.py b/tests/dags/common/loader/test_paths.pyindex 66cf664be..82864014d 100644--- a/tests/dags/common/loader/test_paths.py+++ b/tests/dags/common/loader/test_paths.py@@ -2,6 +2,7 @@ import datetimeimport timeimport pytest+from airflow.exceptions import AirflowSkipExceptionfrom airflow.models import TaskInstancefrom airflow.operators.dummy import DummyOperatorfrom common.loader import paths@@ -90,29 +91,22 @@ def test_stage_oldest_tsv_file_ignores_newer_file(tmpdir):def test_stage_oldest_tsv_file_ignores_non_tsv(tmpdir):tmp_directory = str(tmpdir)- staging_subdirectory = paths.STAGING_SUBDIRECTORYidentifier = TEST_IDtest = "t"path = tmpdir.join(test)path.write("")- paths.stage_oldest_tsv_file(tmp_directory, identifier, 0, ti)- staged_path = tmpdir.join(staging_subdirectory, identifier, test)- assert staged_path.check(file=0)- assert path.check(file=1)+ with pytest.raises(AirflowSkipException):+ paths.stage_oldest_tsv_file(tmp_directory, identifier, 0, ti)def test_stage_oldest_tsv_file_ignores_young_tsv(tmpdir):tmp_directory = str(tmpdir)- staging_subdirectory = paths.STAGING_SUBDIRECTORYidentifier = TEST_IDtest_tsv = "test_v002_.tsv"path = tmpdir.join(test_tsv)path.write("")- paths.stage_oldest_tsv_file(tmp_directory, identifier, 5, ti)- staged_path = tmpdir.join(staging_subdirectory, identifier, test_tsv)-- assert staged_path.check(file=0)- assert path.check(file=1)+ with pytest.raises(AirflowSkipException):+ paths.stage_oldest_tsv_file(tmp_directory, identifier, 5, ti)def test_delete_staged_file_deletes_staged_file(tmpdir):