Skip to content

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

Retire TSV loading workflow (#789)

Madison Swain-Bowden63b0fb7f2afb
diff --git a/DAGs.md b/DAGs.md
index 7d5a93f3d..e369f82a0 100644
--- a/DAGs.md
+++ b/DAGs.md
@@ -48,7 +48,6 @@ The following are DAGs grouped by their primary tag:
| [`recreate_audio_popularity_calculation`](#recreate_audio_popularity_calculation) | `None` |
| [`recreate_image_popularity_calculation`](#recreate_image_popularity_calculation) | `None` |
| [`report_pending_reported_media`](#report_pending_reported_media) | `@weekly` |
-| [`tsv_to_postgres_loader`](#tsv_to_postgres_loader) | `None` |
@@ -131,7 +130,6 @@ The following is documentation associated with each DAG (where available):
1. [`report_pending_reported_media`](#report_pending_reported_media)
1. [`smithsonian_workflow`](#smithsonian_workflow)
1. [`stocksnap_workflow`](#stocksnap_workflow)
- 1. [`tsv_to_postgres_loader`](#tsv_to_postgres_loader)
1. [`wikimedia_commons_workflow`](#wikimedia_commons_workflow)
1. [`wikimedia_reingestion_workflow`](#wikimedia_reingestion_workflow)
1. [`wordpress_workflow`](#wordpress_workflow)
@@ -536,56 +534,6 @@ Notes: https://stocksnap.io/api/load-photos/date/desc/1
API is undocumented.
-## `tsv_to_postgres_loader`
-
-#### Database Loader DAG
-**DB Loader Apache Airflow DAG** (directed acyclic graph) takes the media data saved
-locally in TSV files, cleans it using an intermediate database table, and saves
-the cleaned-up data into the main database (also called upstream or Openledger).
-
-In production,"locally" means on AWS EC2 instance that runs the Apache Airflow
-webserver. Storing too much data there is dangerous, because if ingestion to the
-database breaks down, the disk of this server gets full, and breaks all
-Apache Airflow operations.
-
-As a first step, the DB Loader Apache Airflow DAG saves the data gathered by
-Provider API Scripts to S3 before attempting to load it to PostgreSQL, and delete
- it from disk if saving to S3 succeeds, even if loading to PostgreSQL fails.
-
-This way, we can delete data from the EC2 instance to open up disk space without
- the possibility of losing that data altogether. This will allow us to recover if
- we lose data from the DB somehow, because it will all be living in S3.
-It's also a prerequisite to the long-term plan of saving data only to S3
-(since saving it to the EC2 disk is a source of concern in the first place).
-
-This is one step along the path to avoiding saving data on the local disk at all.
-It should also be faster to load into the DB from S3, since AWS RDS instances
-provide special optimized functionality to load data from S3 into tables in the DB.
-
-Loading the data into the Database is a two-step process: first, data is saved
-to the intermediate table. Any items that don't have the required fields
-(media url, license, foreign landing url and foreign id), and duplicates as
-determined by combination of provider and foreign_id are deleted.
-Then the data from the intermediate table is upserted into the main database.
-If the same item is already present in the database, we update its information
-with newest (non-null) data, and merge any metadata or tags objects to preserve all
-previously downloaded data, and update any data that needs updating
-(eg. popularity metrics).
-
-You can find more background information on the loading process in the following
-issues and related PRs:
-
-- [[Feature] More sophisticated merging of columns in PostgreSQL when upserting](
-https://github.com/creativecommons/cccatalog/issues/378)
-
-- [DB Loader DAG should write to S3 as well as PostgreSQL](
-https://github.com/creativecommons/cccatalog/issues/333)
-
-- [DB Loader should take data from S3, rather than EC2 to load into PostgreSQL](
-https://github.com/creativecommons/cccatalog/issues/334)
-
-
-
## `wikimedia_commons_workflow`
diff --git a/openverse_catalog/dags/common/loader/paths.py b/openverse_catalog/dags/common/loader/paths.py
index 4ac36a9f6..8e76d62cc 100644
--- a/openverse_catalog/dags/common/loader/paths.py
+++ b/openverse_catalog/dags/common/loader/paths.py
@@ -1,140 +1,11 @@
-import logging
-import os
import re
-from datetime import datetime, timedelta
from typing import Optional
-from airflow.exceptions import AirflowSkipException
-from airflow.models import TaskInstance
+from common.constants import MEDIA_TYPES
-FAILURE_SUBDIRECTORY = "db_loader_failures"
-STAGING_SUBDIRECTORY = "db_loader_staging"
-SUPPORTED_MEDIA_TYPES = {"audio", "image"}
LEGACY_TSV_VERSION = "000"
-logger = logging.getLogger(__name__)
-
-
-def stage_oldest_tsv_file(
- output_dir: str,
- identifier: str,
- minimum_file_age_minutes: int,
- ti: TaskInstance,
-) -> bool:
- """
- Selects the oldest tsv file from the output directory.
- If the file hasn't changed in `minimum_file_age_minutes`,
- moves the file to `staging_directory`, and sends an Airflow
- xcom message with file media_type extracted from the filename.
- :param output_dir: Directory where temporary tsv files are
- stored.
- :param identifier: File identifier, usually timestamp with
- the time when ingestion for provider started.
- :param minimum_file_age_minutes: If the file has not been
- updated in this time, it is safe to assume that ingestion
- has finished, and we can save the data to the database.
- :param ti: Airflow Task Instance, used to sent the media_type to
- downstream tasks
- :return: True if tsv file was staged, false otherwise
- """
- 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 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_found
-
-
-def delete_staged_file(output_dir: str, identifier: str) -> None:
- staging_directory = _get_staging_directory(output_dir, identifier)
- staging_directory_files = os.listdir(staging_directory)
- logger.debug(f"Files in staging directory: {staging_directory_files}")
- for file_name in staging_directory_files:
- file_path = os.path.join(staging_directory, file_name)
- logger.info(f"Deleting {file_path}")
- os.remove(file_path)
- logger.info(f"Deleting {staging_directory}")
- os.rmdir(staging_directory)
-
-
-def move_staged_files_to_failure_directory(output_dir: str, identifier: str) -> None:
- staging_directory = _get_staging_directory(output_dir, identifier)
- failure_directory = _get_failure_directory(output_dir, identifier)
- staged_file_list = _get_full_tsv_paths(staging_directory)
- for file_path in staged_file_list:
- _move_file(file_path, failure_directory)
- logger.info(f"Deleting {staging_directory}")
- os.rmdir(staging_directory)
-
-
-def get_staged_file(
- output_dir: str,
- identifier: str,
-) -> str:
- staging_directory = _get_staging_directory(output_dir, identifier)
- path_list = _get_full_tsv_paths(staging_directory)
- assert len(path_list) == 1
- return path_list[0]
-
-
-def _get_staging_directory(
- output_dir: str,
- identifier: str,
- staging_subdirectory: Optional[str] = STAGING_SUBDIRECTORY,
-):
- return os.path.join(output_dir, staging_subdirectory, identifier)
-
-
-def _get_failure_directory(
- output_dir: str,
- identifier: str,
- failure_subdirectory: Optional[str] = FAILURE_SUBDIRECTORY,
-):
- return os.path.join(output_dir, failure_subdirectory, identifier)
-
-
-def _get_oldest_tsv_file(
- directory: str, minimum_file_age_minutes: int
-) -> Optional[str]:
- oldest_file_name = None
- logger.info(f"getting files from {directory}")
- path_list = _get_full_tsv_paths(directory)
- logger.info(f"found files:\n{path_list}")
- tsv_last_modified_list = [(p, os.stat(p).st_mtime) for p in path_list]
- logger.info(f"last_modified_list:\n{tsv_last_modified_list}")
-
- if len(tsv_last_modified_list) == 0:
- return
-
- oldest_file_modified = min(tsv_last_modified_list, key=lambda t: t[1])
- cutoff_time = datetime.now() - timedelta(minutes=minimum_file_age_minutes)
-
- if datetime.fromtimestamp(oldest_file_modified[1]) <= cutoff_time:
- oldest_file_name = oldest_file_modified[0]
- else:
- logger.info(f"no file found older than {minimum_file_age_minutes} minutes.")
-
- return oldest_file_name
-
-
-def _move_file(file_path, new_directory):
- os.makedirs(new_directory, exist_ok=True)
- new_file_path = os.path.join(new_directory, os.path.basename(file_path))
- logger.info(f"Moving {file_path} to {new_file_path}")
- os.rename(file_path, new_file_path)
-
-
-def _get_full_tsv_paths(directory):
- return [
- os.path.join(directory, f) for f in os.listdir(directory) if f[-4:] == ".tsv"
- ]
-
def _extract_media_type(tsv_file_name: Optional[str]) -> str:
"""
@@ -148,7 +19,7 @@ def _extract_media_type(tsv_file_name: Optional[str]) -> str:
"""
try:
media_type = tsv_file_name.split("/")[-1].split("_")[1]
- if media_type not in SUPPORTED_MEDIA_TYPES:
+ if media_type not in MEDIA_TYPES:
media_type = "image"
# None or no underscores
except (AttributeError, IndexError):
@@ -170,4 +41,4 @@ def get_tsv_version(tsv_file_name: str) -> str:
version_pattern = re.compile(r"_v(\d+)_")
if match := re.search(version_pattern, tsv_file_name):
return match.group(1)
- return "000"
+ return LEGACY_TSV_VERSION
diff --git a/openverse_catalog/dags/database/loader_workflow.py b/openverse_catalog/dags/retired/database/loader_workflow.py
similarity index 100%
rename from openverse_catalog/dags/database/loader_workflow.py
rename to openverse_catalog/dags/retired/database/loader_workflow.py
diff --git a/tests/dags/common/loader/test_paths.py b/tests/dags/common/loader/test_paths.py
deleted file mode 100644
index ed2896e42..000000000
--- a/tests/dags/common/loader/test_paths.py
+++ /dev/null
@@ -1,252 +0,0 @@
-import time
-from unittest import mock
-
-import pytest
-from airflow.exceptions import AirflowSkipException
-from airflow.models import TaskInstance
-from common.loader import paths
-
-
-TEST_ID = "testing"
-
-ti = mock.Mock(spec=TaskInstance)
-
-
-def test_stage_oldest_tsv_file_finds_tsv_file(tmpdir):
- tmp_directory = str(tmpdir)
- identifier = TEST_ID
- test_tsv = "test_v002_.tsv"
- path = tmpdir.join(test_tsv)
- path.write("")
- tsv_found = paths.stage_oldest_tsv_file(
- tmp_directory,
- identifier,
- 0,
- ti,
- )
-
- assert tsv_found
-
-
-def test_stage_oldest_tsv_file_stages_tsv_file(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- identifier = TEST_ID
- test_tsv = "test_v002_.tsv"
- path = tmpdir.join(test_tsv)
- path.write("")
- paths.stage_oldest_tsv_file(tmp_directory, identifier, 0, ti)
- staged_path = tmpdir.join(staging_subdirectory, identifier, test_tsv)
-
- assert staged_path.check(file=1)
-
-
-def test_stage_oldest_tsv_file_removes_staged_file_from_output_dir(tmpdir):
- tmp_directory = str(tmpdir)
- identifier = TEST_ID
- test_tsv = "test_v002_.tsv"
- path = tmpdir.join(test_tsv)
- path.write("")
- paths.stage_oldest_tsv_file(tmp_directory, identifier, 0, ti)
-
- assert path.check(file=0)
-
-
-def test_stage_oldest_tsv_file_stages_older_file(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- identifier = TEST_ID
- test_one_tsv = "test1_v001_.tsv"
- test_two_tsv = "test2_v001_.tsv"
- path_one = tmpdir.join(test_one_tsv)
- path_one.write("")
- time.sleep(0.01)
- path_two = tmpdir.join(test_two_tsv)
- path_two.write("")
- paths.stage_oldest_tsv_file(tmp_directory, identifier, 0, ti)
- staged_path = tmpdir.join(staging_subdirectory, identifier, test_one_tsv)
- assert staged_path.check(file=1)
-
-
-def test_stage_oldest_tsv_file_ignores_newer_file(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- identifier = TEST_ID
- test_one_tsv = "test1_v002_.tsv"
- test_two_tsv = "test2_v002_.tsv"
- path_one = tmpdir.join(test_one_tsv)
- path_one.write("")
- time.sleep(0.01)
- path_two = tmpdir.join(test_two_tsv)
- path_two.write("")
- paths.stage_oldest_tsv_file(tmp_directory, identifier, 0, ti)
- staged_path_two = tmpdir.join(staging_subdirectory, identifier, test_two_tsv)
- assert staged_path_two.check(file=0)
- assert path_two.check(file=1)
-
-
-def test_stage_oldest_tsv_file_ignores_non_tsv(tmpdir):
- tmp_directory = str(tmpdir)
- identifier = TEST_ID
- test = "t"
- path = tmpdir.join(test)
- path.write("")
- 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)
- identifier = TEST_ID
- test_tsv = "test_v002_.tsv"
- path = tmpdir.join(test_tsv)
- path.write("")
- with pytest.raises(AirflowSkipException):
- paths.stage_oldest_tsv_file(tmp_directory, identifier, 5, ti)
-
-
-def test_delete_staged_file_deletes_staged_file(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- identifier = TEST_ID
- test_tsv = "test.tsv"
- staged_path = tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_tsv)
- staged_path.write("")
- paths.delete_staged_file(tmp_directory, identifier)
-
- assert staged_path.check(file=0)
-
-
-def test_delete_staged_file_deletes_all_files_from_staging_dir(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- identifier = TEST_ID
- test_tsv = "test.tsv"
- staged_path = tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_tsv)
- test_non_tsv = "test.tsv.backup"
- staged_non_tsv_path = (
- tmpdir.join(staging_subdirectory).join(identifier).join(test_non_tsv)
- )
- staged_path.write("")
- staged_non_tsv_path.write("")
- paths.delete_staged_file(tmp_directory, identifier)
-
- assert staged_path.check(file=0)
- assert staged_non_tsv_path.check(file=0)
-
-
-def test_delete_staged_file_ignores_unidentified_file(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- identifier = TEST_ID
- nonidentifier = "abcd"
- test_tsv = "test.tsv"
- staged_path = tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_tsv)
- staged_path.write("")
- unidentified_path = (
- tmpdir.join(staging_subdirectory).mkdir(nonidentifier).join(test_tsv)
- )
- unidentified_path.write("")
- paths.delete_staged_file(tmp_directory, identifier)
-
- assert unidentified_path.check(file=1)
-
-
-def test_delete_staged_file_ignores_nonstaged_file(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- other_subdirectory = "abcd"
- identifier = TEST_ID
- test_tsv = "test.tsv"
- staged_path = tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_tsv)
- staged_path.write("")
- nonstaged_path = tmpdir.mkdir(other_subdirectory).mkdir(identifier).join(test_tsv)
- nonstaged_path.write("")
- paths.delete_staged_file(tmp_directory, identifier)
-
- assert nonstaged_path.check(file=1)
-
-
-def test_move_staged_files_handles_nonexistent_failure_directory(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- failure_subdirectory = paths.FAILURE_SUBDIRECTORY
- identifier = TEST_ID
- test_tsv = "test.tsv"
- staged_path = tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_tsv)
- staged_path.write("")
- failure_path = tmpdir.join(failure_subdirectory).join(identifier).join(test_tsv)
- paths.move_staged_files_to_failure_directory(tmp_directory, identifier)
-
- assert failure_path.check(file=1)
-
-
-def test_move_staged_files_handles_existing_failure_directory(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- failure_subdirectory = paths.FAILURE_SUBDIRECTORY
- identifier = TEST_ID
- test_tsv = "test.tsv"
- staged_path = tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_tsv)
- staged_path.write("")
- failure_path = tmpdir.mkdir(failure_subdirectory).join(identifier).join(test_tsv)
- paths.move_staged_files_to_failure_directory(tmp_directory, identifier)
-
- assert failure_path.check(file=1)
-
-
-def test_move_staged_files_handles_multiple_staged_files(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- failure_subdirectory = paths.FAILURE_SUBDIRECTORY
- identifier = TEST_ID
- test_one_tsv = "test1.tsv"
- test_two_tsv = "test2.tsv"
- staged_path_one = (
- tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_one_tsv)
- )
- staged_path_one.write("")
- staged_path_two = (
- tmpdir.join(staging_subdirectory).join(identifier).join(test_two_tsv)
- )
- staged_path_two.write("")
- failure_path_one = (
- tmpdir.mkdir(failure_subdirectory).join(identifier).join(test_one_tsv)
- )
- failure_path_two = (
- tmpdir.join(failure_subdirectory).join(identifier).join(test_two_tsv)
- )
- paths.move_staged_files_to_failure_directory(tmp_directory, identifier)
-
- assert failure_path_one.check(file=1)
- assert failure_path_two.check(file=1)
-
-
-def test_get_staged_file_finds_staged_file(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- identifier = TEST_ID
- test_tsv = "test.tsv"
- staged_path = tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_tsv)
- staged_path.write("")
- staged_file = paths.get_staged_file(tmp_directory, identifier)
-
- assert staged_file == str(staged_path)
-
-
-def test_get_staged_file_throws_error_for_multiple_staged_files(tmpdir):
- tmp_directory = str(tmpdir)
- staging_subdirectory = paths.STAGING_SUBDIRECTORY
- identifier = TEST_ID
- test_one_tsv = "test1.tsv"
- test_two_tsv = "test2.tsv"
- staged_path_one = (
- tmpdir.mkdir(staging_subdirectory).mkdir(identifier).join(test_one_tsv)
- )
- staged_path_one.write("")
- staged_path_two = (
- tmpdir.join(staging_subdirectory).join(identifier).join(test_two_tsv)
- )
- staged_path_two.write("")
- with pytest.raises(AssertionError):
- paths.get_staged_file(tmp_directory, identifier)
diff --git a/tests/dags/test_dag_parsing.py b/tests/dags/test_dag_parsing.py
index d6bfcfdaa..3087291a3 100644
--- a/tests/dags/test_dag_parsing.py
+++ b/tests/dags/test_dag_parsing.py
@@ -20,7 +20,6 @@ DAG_PATHS = [
"maintenance/pr_review_reminders/pr_review_reminders_dag.py",
"commoncrawl/sync_commoncrawl_workflow.py",
"commoncrawl/commoncrawl_etl.py",
- "database/loader_workflow.py",
"database/recreate_popularity_calculation_dag_factory.py",
"data_refresh/dag_factory.py",
"oauth2/authorize_dag.py",