Skip to content

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

Trigger TSV loading immediately after workflow (#357)

Madison Swain-Bowdenada025d832fd
diff --git a/openverse_catalog/dags/common/dag_factory.py b/openverse_catalog/dags/common/dag_factory.py
index a81ac889e..76e9f216a 100644
--- a/openverse_catalog/dags/common/dag_factory.py
+++ b/openverse_catalog/dags/common/dag_factory.py
@@ -1,17 +1,80 @@
+"""
+# Provider DAG Factory
+This file contains two factory functions which generate the bulk of our
+provider workflow DAGs. These DAGs pull data in from a particular provider,
+and produce one or several TSVs of the results.
+
+The "simple" (non-partitioned) DAG also loads the TSVs into the catalog database.
+
+The loading step 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 loader portion of the 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)
+"""
+import inspect
import logging
+import os
from datetime import datetime, timedelta
+from typing import Callable, Dict, List, Optional, Sequence
from airflow import DAG
+from airflow.models import TaskInstance
from airflow.models.baseoperator import cross_downstream
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import PythonOperator
+from airflow.utils.task_group import TaskGroup
from airflow.utils.trigger_rule import TriggerRule
from common import slack
+from common.loader import loader, s3, sql
logger = logging.getLogger(__name__)
+DB_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")
+AWS_CONN_ID = os.getenv("AWS_CONN_ID", "no_aws_conn_id")
+OPENVERSE_BUCKET = os.getenv("OPENVERSE_BUCKET")
+OUTPUT_DIR_PATH = os.path.realpath(os.getenv("OUTPUT_DIR", "/tmp/"))
DAG_DEFAULT_ARGS = {
"owner": "data-eng-admin",
"depends_on_past": False,
@@ -21,20 +84,65 @@ DAG_DEFAULT_ARGS = {
"retry_delay": timedelta(minutes=15),
"on_failure_callback": slack.on_failure_callback,
}
-DATE_RANGE_ARG_TEMPLATE = "{{ macros.ds_add(ds, -%s) }}"
+DATE_RANGE_ARG_TEMPLATE = "{{{{ macros.ds_add(ds, -{}) }}}}"
+XCOM_PULL_TEMPLATE = "{{{{ ti.xcom_pull(task_ids='{}', key='{}') }}}}"
+
+
+def _push_output_paths_wrapper(
+ func: Callable,
+ media_types: List[str],
+ ti: TaskInstance,
+ args: Sequence = None,
+):
+ """
+ Run the provided callable after pushing the calculated output directories
+ for each media store to XComs. Output locations are pushed under keys with
+ the format `<media-type>_tsv`. This is a temporary workaround due to the nature
+ of the current provider scripts. Once
+ https://github.com/WordPress/openverse-catalog/issues/229 is addressed and the
+ provider scripts are refactored into classes, this wrapper can either be updated
+ or the XCom pushing can be moved into the provider initialization.
+ """
+ args = args or []
+ logger.info("Pushing available store paths to XComs")
+ module = inspect.getmodule(func)
+ stores = {}
+
+ # Stores exist at the module level, so in order to retrieve the output values we
+ # must first pull the stores from the module.
+ for media_type in media_types:
+ if not (store := getattr(module, f"{media_type}_store", None)):
+ continue
+ stores[media_type] = store
+
+ if len(stores) != len(media_types):
+ raise ValueError(
+ f"Expected stores in {module.__name__} were missing: "
+ f"{list(set(media_types) - set(stores))}"
+ )
+
+ for media_type, store in stores.items():
+ logger.info(f"{media_type.capitalize()} store location: {store.output_path}")
+ ti.xcom_push(key=f"{media_type}_tsv", value=store.output_path)
+
+ logger.info("Running provider function")
+ # Not passing kwargs here because Airflow throws a bunch of stuff in there that none
+ # of our provider scripts are expecting.
+ return func(*args)
def create_provider_api_workflow(
- dag_id,
- main_function,
- default_args=None,
- start_date=datetime(1970, 1, 1),
- max_active_tasks=1,
- schedule_string="@daily",
- dated=True,
- day_shift=0,
- dagrun_timeout=timedelta(hours=12),
- doc_md="",
+ dag_id: str,
+ main_function: Callable,
+ default_args: Optional[Dict] = None,
+ start_date: datetime = datetime(1970, 1, 1),
+ max_active_tasks: int = 1,
+ schedule_string: str = "@daily",
+ dated: bool = True,
+ day_shift: int = 0,
+ dagrun_timeout: timedelta = timedelta(hours=12),
+ doc_md: str = "",
+ media_types: Sequence[str] = ("image",),
):
"""
This factory method instantiates a DAG that will run the given
@@ -71,8 +179,15 @@ def create_provider_api_workflow(
be run (if `dated=True`).
dagrun_timeout: datetime.timedelta giving the total amount of time
a given dagrun may take.
+ doc_md: string which should be used for the DAG's documentation markdown
+ media_types: list describing the media type(s) that this provider handles
+ (e.g. `["audio"]`, `["image", "audio"]`, etc.)
"""
default_args = default_args or DAG_DEFAULT_ARGS
+ media_type_name = "mixed" if len(media_types) > 1 else media_types[0]
+ provider_name = dag_id.replace("_workflow", "")
+ identifier = f"{provider_name}_{{{{ ts_nodash }}}}"
+
dag = DAG(
dag_id=dag_id,
default_args={**default_args, "start_date": start_date},
@@ -87,20 +202,72 @@ def create_provider_api_workflow(
)
with dag:
+ pull_kwargs = {"func": main_function, "media_types": media_types}
if dated:
- PythonOperator(
- task_id="pull_image_data",
- python_callable=main_function,
- op_args=[DATE_RANGE_ARG_TEMPLATE % day_shift],
- execution_timeout=dagrun_timeout,
- depends_on_past=False,
- )
- else:
- PythonOperator(
- task_id="pull_image_data",
- python_callable=main_function,
- depends_on_past=False,
- )
+ pull_kwargs["args"] = [DATE_RANGE_ARG_TEMPLATE.format(day_shift)]
+
+ pull_data = PythonOperator(
+ task_id=f"pull_{media_type_name}_data",
+ python_callable=_push_output_paths_wrapper,
+ op_kwargs=pull_kwargs,
+ depends_on_past=False,
+ execution_timeout=dagrun_timeout if dated else None,
+ )
+
+ for media_type in media_types:
+ with TaskGroup(group_id=f"load_{media_type}_data") as load_data:
+ create_loading_table = PythonOperator(
+ task_id="create_loading_table",
+ python_callable=sql.create_loading_table,
+ op_kwargs={
+ "postgres_conn_id": DB_CONN_ID,
+ "identifier": identifier,
+ "media_type": media_type,
+ },
+ trigger_rule=TriggerRule.NONE_SKIPPED,
+ doc_md="Create a temporary loading table for "
+ f"ingesting {media_type} data from a TSV",
+ )
+ copy_to_s3 = PythonOperator(
+ task_id="copy_to_s3",
+ python_callable=s3.copy_file_to_s3,
+ op_kwargs={
+ "tsv_file_path": XCOM_PULL_TEMPLATE.format(
+ pull_data.task_id, f"{media_type}_tsv"
+ ),
+ "s3_bucket": OPENVERSE_BUCKET,
+ "s3_prefix": f"{media_type}/{provider_name}",
+ "aws_conn_id": AWS_CONN_ID,
+ },
+ trigger_rule=TriggerRule.NONE_SKIPPED,
+ )
+ load_from_s3 = PythonOperator(
+ task_id="load_from_s3",
+ python_callable=loader.load_from_s3,
+ op_kwargs={
+ "bucket": OPENVERSE_BUCKET,
+ "key": XCOM_PULL_TEMPLATE.format(copy_to_s3.task_id, "s3_key"),
+ "postgres_conn_id": DB_CONN_ID,
+ "media_type": media_type,
+ "tsv_version": XCOM_PULL_TEMPLATE.format(
+ copy_to_s3.task_id, "tsv_version"
+ ),
+ "identifier": identifier,
+ },
+ )
+ drop_loading_table = PythonOperator(
+ task_id="drop_loading_table",
+ python_callable=sql.drop_load_table,
+ op_kwargs={
+ "postgres_conn_id": DB_CONN_ID,
+ "identifier": identifier,
+ "media_type": media_type,
+ },
+ trigger_rule=TriggerRule.ALL_DONE,
+ )
+ [create_loading_table, copy_to_s3] >> load_from_s3 >> drop_loading_table
+
+ pull_data >> load_data
return dag
@@ -225,7 +392,7 @@ def _build_ingest_operator_list_list(
PythonOperator(
task_id=f"ingest_{d}",
python_callable=main_function,
- op_args=[DATE_RANGE_ARG_TEMPLATE % d],
+ op_args=[DATE_RANGE_ARG_TEMPLATE.format(d)],
execution_timeout=ingestion_task_timeout,
depends_on_past=False,
)
diff --git a/openverse_catalog/dags/common/loader/loader.py b/openverse_catalog/dags/common/loader/loader.py
index 3225a5eaf..5c33d845d 100644
--- a/openverse_catalog/dags/common/loader/loader.py
+++ b/openverse_catalog/dags/common/loader/loader.py
@@ -31,3 +31,19 @@ def load_s3_data(
sql.upsert_records_to_db_table(
postgres_conn_id, identifier, media_type=media_type, tsv_version=tsv_version
)
+
+
+def load_from_s3(
+ bucket,
+ key,
+ postgres_conn_id,
+ media_type,
+ tsv_version,
+ identifier,
+):
+ sql.load_s3_data_to_intermediate_table(
+ postgres_conn_id, bucket, key, identifier, media_type
+ )
+ sql.upsert_records_to_db_table(
+ postgres_conn_id, identifier, media_type=media_type, tsv_version=tsv_version
+ )
diff --git a/openverse_catalog/dags/common/loader/paths.py b/openverse_catalog/dags/common/loader/paths.py
index 7b57da5e6..4ac36a9f6 100644
--- a/openverse_catalog/dags/common/loader/paths.py
+++ b/openverse_catalog/dags/common/loader/paths.py
@@ -43,7 +43,7 @@ def stage_oldest_tsv_file(
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)
+ 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)
@@ -156,14 +156,14 @@ def _extract_media_type(tsv_file_name: Optional[str]) -> str:
return media_type
-def _get_tsv_version(tsv_file_name: str) -> str:
+def get_tsv_version(tsv_file_name: str) -> str:
"""TSV file version can be deducted from the filename
v0: without _vN_ in the filename
v1+: has a _vN in the filename
- >>>_get_tsv_version('/behance_image_20210906130355.tsv')
+ >>>get_tsv_version('/behance_image_20210906130355.tsv')
'000'
- >>> _get_tsv_version('/jamendo_audio_v005_20210906130355.tsv')
+ >>> get_tsv_version('/jamendo_audio_v005_20210906130355.tsv')
'005'
"""
diff --git a/openverse_catalog/dags/common/loader/s3.py b/openverse_catalog/dags/common/loader/s3.py
index b2a8108f8..509b85850 100644
--- a/openverse_catalog/dags/common/loader/s3.py
+++ b/openverse_catalog/dags/common/loader/s3.py
@@ -1,7 +1,10 @@
import logging
import os
+from pathlib import Path
+from airflow.exceptions import AirflowSkipException
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
+from common.loader import paths
logger = logging.getLogger(__name__)
@@ -18,6 +21,10 @@ def copy_file_to_s3_staging(
media_prefix=DEFAULT_MEDIA_PREFIX,
staging_prefix=STAGING_PREFIX,
):
+ """
+ Copy a media file from the staging directory, using a media, staging,
+ and identifiers to construct the S3 key.
+ """
logger.info(f"Creating staging object in s3_bucket: {s3_bucket}")
s3 = S3Hook(aws_conn_id=aws_conn_id)
file_name = os.path.split(tsv_file_path)[1]
@@ -28,6 +35,34 @@ def copy_file_to_s3_staging(
s3.load_file(tsv_file_path, staging_key, bucket_name=s3_bucket)
+def copy_file_to_s3(
+ tsv_file_path,
+ s3_bucket,
+ s3_prefix,
+ aws_conn_id,
+ ti,
+):
+ """
+ Copy a TSV file to S3 with the given prefix.
+ The TSV's version is pushed to the `tsv_version` XCom, and the constructed
+ S3 key is pushed to the `s3_key` XCom.
+ The TSV is removed after the upload is complete.
+ """
+ if tsv_file_path is None:
+ raise FileNotFoundError("No TSV file path was provided")
+ tsv_file = Path(tsv_file_path)
+ if not tsv_file.exists():
+ raise AirflowSkipException(f"TSV file {tsv_file} does not exist.")
+ tsv_version = paths.get_tsv_version(tsv_file_path)
+ s3_key = f"{s3_prefix}/{tsv_file.name}"
+ logger.info(f"Uploading {tsv_file_path} to {s3_bucket}:{s3_key}")
+ s3 = S3Hook(aws_conn_id=aws_conn_id)
+ s3.load_file(tsv_file_path, s3_key, bucket_name=s3_bucket)
+ ti.xcom_push(key="tsv_version", value=tsv_version)
+ ti.xcom_push(key="s3_key", value=s3_key)
+ tsv_file.unlink()
+
+
def get_staged_s3_object(
identifier,
s3_bucket,
diff --git a/openverse_catalog/dags/common/loader/sql.py b/openverse_catalog/dags/common/loader/sql.py
index 918d22ed6..f8a3d137f 100644
--- a/openverse_catalog/dags/common/loader/sql.py
+++ b/openverse_catalog/dags/common/loader/sql.py
@@ -58,17 +58,13 @@ def create_column_definitions(table_columns: List[Column], is_loading=True):
def create_loading_table(
- postgres_conn_id,
- identifier,
- ti,
+ postgres_conn_id: str,
+ identifier: str,
+ media_type: str = IMAGE,
):
"""
Create intermediary table and indices if they do not exist
"""
- media_type = ti.xcom_pull(task_ids="stage_oldest_tsv_file", key="media_type")
- if media_type is None:
- media_type = IMAGE
-
load_table = _get_load_table_name(identifier, media_type=media_type)
postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
loading_table_columns = TSV_COLUMNS[media_type]
@@ -261,10 +257,11 @@ def upsert_records_to_db_table(
postgres.run(upsert_query)
-def drop_load_table(postgres_conn_id, identifier, ti):
- media_type = ti.xcom_pull(task_ids="stage_oldest_tsv_file", key="media_type")
- if media_type is None:
- media_type = IMAGE
+def drop_load_table(
+ postgres_conn_id,
+ identifier,
+ media_type: str = IMAGE,
+):
load_table = _get_load_table_name(identifier, media_type=media_type)
postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
postgres.run(f"DROP TABLE {load_table};")
diff --git a/openverse_catalog/dags/common/storage/media.py b/openverse_catalog/dags/common/storage/media.py
index bdf60e918..b34065f82 100644
--- a/openverse_catalog/dags/common/storage/media.py
+++ b/openverse_catalog/dags/common/storage/media.py
@@ -60,17 +60,16 @@ class MediaStore(metaclass=abc.ABCMeta):
):
logger.info(f"Initialized {media_type} MediaStore with provider {provider}")
self.media_type = media_type
- self._media_buffer = []
- self._total_items = 0
- self._PROVIDER = provider
- self._BUFFER_LENGTH = buffer_length
- self._NOW = datetime.now()
- self._OUTPUT_PATH = self._initialize_output_path(
+ self.provider = provider
+ self.buffer_length = buffer_length
+ self.output_path = self._initialize_output_path(
output_dir,
output_file,
provider,
)
self.columns = None
+ self._media_buffer = []
+ self._total_items = 0
def save_item(self, media) -> None:
"""
@@ -84,7 +83,7 @@ class MediaStore(metaclass=abc.ABCMeta):
if tsv_row:
self._media_buffer.append(tsv_row)
self._total_items += 1
- if len(self._media_buffer) >= self._BUFFER_LENGTH:
+ if len(self._media_buffer) >= self.buffer_length:
self._flush_buffer()
@abc.abstractmethod
@@ -116,7 +115,7 @@ class MediaStore(metaclass=abc.ABCMeta):
):
logger.debug("Discarding media due to invalid license")
return None
- media_data["source"] = util.get_source(media_data.get("source"), self._PROVIDER)
+ media_data["source"] = util.get_source(media_data.get("source"), self.provider)
# Add ingestion_type column value based on `source`.
# The implementation is based on `ingestion_column`
if media_data.get("ingestion_type") is None:
@@ -135,7 +134,7 @@ class MediaStore(metaclass=abc.ABCMeta):
media_data["license_version"] = media_data["license_info"].version
media_data.pop("license_info", None)
- media_data["provider"] = self._PROVIDER
+ media_data["provider"] = self.provider
return media_data
def commit(self):
@@ -171,7 +170,7 @@ class MediaStore(metaclass=abc.ABCMeta):
if output_file is not None:
output_file = str(output_file)
else:
- datetime_string = datetime.strftime(self._NOW, "%Y%m%d%H%M%S")
+ datetime_string = datetime.now().strftime("%Y%m%d%H%M%S")
output_file = (
f"{provider}_{self.media_type}_v{version}_{datetime_string}.tsv"
)
@@ -205,7 +204,7 @@ class MediaStore(metaclass=abc.ABCMeta):
buffer_length = len(self._media_buffer)
if buffer_length > 0:
logger.info(f"Writing {buffer_length} lines from buffer to disk.")
- with open(self._OUTPUT_PATH, "a") as f:
+ with open(self.output_path, "a") as f:
f.writelines(self._media_buffer)
self._media_buffer = []
logger.debug(
@@ -276,4 +275,4 @@ class MediaStore(metaclass=abc.ABCMeta):
return tag
else:
logger.debug(f"Enriching tag: {tag}")
- return {"name": tag, "provider": self._PROVIDER}
+ return {"name": tag, "provider": self.provider}
diff --git a/openverse_catalog/dags/database/loader_workflow.py b/openverse_catalog/dags/database/loader_workflow.py
index 8b11c8833..ba0226225 100644
--- a/openverse_catalog/dags/database/loader_workflow.py
+++ b/openverse_catalog/dags/database/loader_workflow.py
@@ -104,12 +104,16 @@ with dag:
"""
),
)
+
+ media_type_xcom = f"{{{{ ti.xcom_pull(task_ids='{stage_oldest_tsv_file.task_id}', key='media_type') }}}}" # noqa: E501
+
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,
+ "media_type": media_type_xcom,
},
doc_md="Create a temporary loading table for ingesting data from a TSV.",
)
@@ -155,7 +159,11 @@ with dag:
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},
+ op_kwargs={
+ "postgres_conn_id": DB_CONN_ID,
+ "identifier": TIMESTAMP_TEMPLATE,
+ "media_type": media_type_xcom,
+ },
trigger_rule=TriggerRule.NONE_SKIPPED,
doc_md=d(
"""
diff --git a/openverse_catalog/dags/providers/freesound_workflow.py b/openverse_catalog/dags/providers/freesound_workflow.py
index efb31ed9b..5a9b44d33 100644
--- a/openverse_catalog/dags/providers/freesound_workflow.py
+++ b/openverse_catalog/dags/providers/freesound_workflow.py
@@ -21,4 +21,5 @@ globals()[DAG_ID] = create_provider_api_workflow(
schedule_string="@monthly",
dated=False,
doc_md=freesound.__doc__,
+ media_types=["audio"],
)
diff --git a/openverse_catalog/dags/providers/jamendo_workflow.py b/openverse_catalog/dags/providers/jamendo_workflow.py
index 51cc09966..896a67394 100644
--- a/openverse_catalog/dags/providers/jamendo_workflow.py
+++ b/openverse_catalog/dags/providers/jamendo_workflow.py
@@ -18,4 +18,5 @@ globals()[DAG_ID] = create_provider_api_workflow(
schedule_string="@monthly",
dated=False,
dagrun_timeout=DAGRUN_TIMEOUT,
+ media_types=["audio"],
)
diff --git a/openverse_catalog/dags/providers/wikimedia_workflow.py b/openverse_catalog/dags/providers/wikimedia_workflow.py
index 95aa062c8..5ad70c671 100644
--- a/openverse_catalog/dags/providers/wikimedia_workflow.py
+++ b/openverse_catalog/dags/providers/wikimedia_workflow.py
@@ -22,4 +22,5 @@ globals()[DAG_ID] = create_provider_api_workflow(
max_active_tasks=1,
schedule_string="@monthly",
dated=True,
+ media_types=["image", "audio"],
)
diff --git a/tests/dags/common/loader/test_s3.py b/tests/dags/common/loader/test_s3.py
index 40fca64fa..9c22f287b 100644
--- a/tests/dags/common/loader/test_s3.py
+++ b/tests/dags/common/loader/test_s3.py
@@ -1,58 +1,63 @@
import os
-from unittest.mock import patch
+from unittest import mock
import pytest
+from airflow.exceptions import AirflowSkipException
+from airflow.models import TaskInstance
from common.loader import s3
TEST_ID = "testing"
TEST_MEDIA_PREFIX = "media"
TEST_STAGING_PREFIX = "test_staging"
-AWS_CONN_ID = os.getenv("AWS_CONN_ID")
+AWS_CONN_ID = os.getenv("AWS_CONN_ID", "test_conn_id")
S3_LOCAL_ENDPOINT = os.getenv("S3_LOCAL_ENDPOINT")
S3_TEST_BUCKET = f"cccatalog-storage-{TEST_ID}"
ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
SECRET_KEY = os.getenv("AWS_SECRET_KEY")
+def mock_s3_load_file():
+ with mock.patch.object(s3.S3Hook, "load_file") as load_file_mock:
+ yield load_file_mock
+
+
def test_copy_file_to_s3_staging_uses_connection_id():
identifier = TEST_ID
media_prefix = TEST_MEDIA_PREFIX
staging_prefix = TEST_STAGING_PREFIX
tsv_file_path = "/test/file/path/to/data.tsv"
- aws_conn_id = "test_conn_id"
test_bucket_name = "test-bucket"
- with patch.object(s3, "S3Hook") as mock_s3:
+ with mock.patch.object(s3, "S3Hook") as mock_s3:
s3.copy_file_to_s3_staging(
identifier,
tsv_file_path,
test_bucket_name,
- aws_conn_id,
+ AWS_CONN_ID,
media_prefix=media_prefix,
staging_prefix=staging_prefix,
)
- mock_s3.assert_called_once_with(aws_conn_id=aws_conn_id)
+ mock_s3.assert_called_once_with(aws_conn_id=AWS_CONN_ID)
-def test_copy_file_to_s3_staging_uses_bucket_environ(monkeypatch):
+def test_copy_file_to_s3_staging_uses_bucket_environ(monkeypatch, mock_s3_load_file):
identifier = TEST_ID
media_prefix = TEST_MEDIA_PREFIX
staging_prefix = TEST_STAGING_PREFIX
tsv_file_path = "/test/file/path/to/data.tsv"
- aws_conn_id = "test_conn_id"
test_bucket_name = "test-bucket"
monkeypatch.setenv("OPENVERSE_BUCKET", test_bucket_name)
- with patch.object(s3.S3Hook, "load_file") as mock_s3_load_file:
- s3.copy_file_to_s3_staging(
- identifier,
- tsv_file_path,
- test_bucket_name,
- aws_conn_id,
- media_prefix=media_prefix,
- staging_prefix=staging_prefix,
- )
+ s3.copy_file_to_s3_staging(
+ identifier,
+ tsv_file_path,
+ test_bucket_name,
+ AWS_CONN_ID,
+ media_prefix=media_prefix,
+ staging_prefix=staging_prefix,
+ )
mock_s3_load_file.assert_called_once_with(
tsv_file_path,
f"{media_prefix}/{staging_prefix}/{identifier}/data.tsv",
@@ -65,20 +70,17 @@ def test_copy_file_to_s3_staging_given_bucket_name():
media_prefix = TEST_MEDIA_PREFIX
staging_prefix = TEST_STAGING_PREFIX
tsv_file_path = "/test/file/path/to/data.tsv"
- aws_conn_id = "test_conn_id"
test_bucket_name = "test-bucket-given"
- with patch.object(s3.S3Hook, "load_file") as mock_s3_load_file:
+ with mock.patch.object(s3.S3Hook, "load_file") as mock_s3_load_file:
s3.copy_file_to_s3_staging(
identifier,
tsv_file_path,
test_bucket_name,
- aws_conn_id,
+ AWS_CONN_ID,
media_prefix=media_prefix,
staging_prefix=staging_prefix,
)
- print(mock_s3_load_file.mock_calls)
- print(mock_s3_load_file.method_calls)
mock_s3_load_file.assert_called_once_with(
tsv_file_path,
f"{media_prefix}/{staging_prefix}/{identifier}/data.tsv",
@@ -132,3 +134,27 @@ def test_get_staged_s3_object_complains_with_multiple_keys(empty_s3_bucket):
media_prefix=media_prefix,
staging_prefix=staging_prefix,
)
+
+
+def test_copy_file_to_s3_no_path():
+ with pytest.raises(FileNotFoundError):
+ s3.copy_file_to_s3(None, "foo", "bar", "baz", None)
+
+
+def test_copy_file_to_s3_no_actual_file():
+ with pytest.raises(AirflowSkipException):
+ s3.copy_file_to_s3("does_not_exist", "foo", "bar", "baz", None)
+
+
+def test_copy_file_to_s3(tmp_path, mock_s3_load_file, empty_s3_bucket):
+ tsv = tmp_path / "random_media_file.tsv"
+ tsv.touch()
+ version = "9000"
+ ti_mock = mock.MagicMock(spec=TaskInstance)
+ with mock.patch.object(s3.paths, "get_tsv_version", return_value=version):
+ s3.copy_file_to_s3(tsv, empty_s3_bucket, "fake-prefix", AWS_CONN_ID, ti_mock)
+ assert not tsv.exists()
+ assert ti_mock.xcom_push.call_args_list == [
+ mock.call(key="tsv_version", value=version),
+ mock.call(key="s3_key", value="fake-prefix/random_media_file.tsv"),
+ ]
diff --git a/tests/dags/common/loader/test_sql.py b/tests/dags/common/loader/test_sql.py
index b5170f6b0..3dcb10424 100644
--- a/tests/dags/common/loader/test_sql.py
+++ b/tests/dags/common/loader/test_sql.py
@@ -181,7 +181,7 @@ def _load_s3_tsv(tmpdir, bucket, tsv_file_name, identifier):
def test_create_loading_table_creates_table(postgres, load_table, identifier):
postgres_conn_id = POSTGRES_CONN_ID
- sql.create_loading_table(postgres_conn_id, identifier, ti)
+ sql.create_loading_table(postgres_conn_id, identifier)
check_query = (
f"SELECT EXISTS (SELECT FROM pg_tables WHERE tablename='{load_table}');"
@@ -193,9 +193,9 @@ def test_create_loading_table_creates_table(postgres, load_table, identifier):
def test_create_loading_table_errors_if_run_twice_with_same_id(postgres, identifier):
postgres_conn_id = POSTGRES_CONN_ID
- sql.create_loading_table(postgres_conn_id, identifier, ti)
+ sql.create_loading_table(postgres_conn_id, identifier)
with pytest.raises(Exception):
- sql.create_loading_table(postgres_conn_id, identifier, ti)
+ sql.create_loading_table(postgres_conn_id, identifier)
@flaky
@@ -1066,7 +1066,7 @@ def test_upsert_records_replaces_null_tags(
def test_drop_load_table_drops_table(postgres_with_load_table, load_table, identifier):
postgres_conn_id = POSTGRES_CONN_ID
- sql.drop_load_table(postgres_conn_id, identifier, ti)
+ sql.drop_load_table(postgres_conn_id, identifier)
check_query = (
f"SELECT EXISTS (" f"SELECT FROM pg_tables WHERE tablename='{load_table}');"
)
diff --git a/tests/dags/common/storage/test_audio.py b/tests/dags/common/storage/test_audio.py
index 063c093ad..a1942c5f5 100644
--- a/tests/dags/common/storage/test_audio.py
+++ b/tests/dags/common/storage/test_audio.py
@@ -54,8 +54,8 @@ def setup_env(monkeypatch):
def test_AudioStore_includes_provider_in_output_file_string():
audio_store = audio.AudioStore("test_provider")
- assert type(audio_store._OUTPUT_PATH) == str
- assert "test_provider" in audio_store._OUTPUT_PATH
+ assert type(audio_store.output_path) == str
+ assert "test_provider" in audio_store.output_path
def test_AudioStore_add_item_adds_realistic_audio_to_buffer():
diff --git a/tests/dags/common/storage/test_media.py b/tests/dags/common/storage/test_media.py
index d1a204503..a356743bf 100644
--- a/tests/dags/common/storage/test_media.py
+++ b/tests/dags/common/storage/test_media.py
@@ -37,7 +37,7 @@ def test_MediaStore_uses_OUTPUT_DIR_variable(
testing_output_dir = "/my_output_dir"
monkeypatch.setenv("OUTPUT_DIR", testing_output_dir)
image_store = image.ImageStore()
- assert testing_output_dir in image_store._OUTPUT_PATH
+ assert testing_output_dir in image_store.output_path
def test_MediaStore_falls_back_to_tmp_output_dir_variable(
@@ -46,19 +46,19 @@ def test_MediaStore_falls_back_to_tmp_output_dir_variable(
):
monkeypatch.delenv("OUTPUT_DIR")
image_store = image.ImageStore()
- assert "/tmp" in image_store._OUTPUT_PATH
+ assert "/tmp" in image_store.output_path
def test_MediaStore_includes_provider_in_output_file_string():
image_store = image.ImageStore("test_provider")
- assert type(image_store._OUTPUT_PATH) == str
- assert "test_provider" in image_store._OUTPUT_PATH
+ assert type(image_store.output_path) == str
+ assert "test_provider" in image_store.output_path
def test_MediaStore_includes_media_type_in_output_file_string():
image_store = image.ImageStore("test_provider")
- assert type(image_store._OUTPUT_PATH) == str
- assert "image" in image_store._OUTPUT_PATH
+ assert type(image_store.output_path) == str
+ assert "image" in image_store.output_path
def test_MediaStore_add_item_flushes_buffer(tmpdir):
diff --git a/tests/dags/common/test_dag_factory.py b/tests/dags/common/test_dag_factory.py
index 618825789..bec7b6bd1 100644
--- a/tests/dags/common/test_dag_factory.py
+++ b/tests/dags/common/test_dag_factory.py
@@ -1,8 +1,63 @@
-import common.dag_factory as df
+from unittest import mock
+
+import pytest
+import requests
+from airflow.models import TaskInstance
+from common import dag_factory
+
+from tests.dags.common.test_resources import fake_provider_module
+
+
+ "func, media_types, stores",
+ [
+ # Happy path
+ (fake_provider_module.main, ["image"], [fake_provider_module.image_store]),
+ # Empty case, no media types provided
+ (fake_provider_module.main, [], []),
+ # Provided function doesn't have a store at the module level
+ pytest.param(
+ requests.get,
+ ["image"],
+ [None],
+ marks=pytest.mark.raises(
+ exception=ValueError, match="Expected stores in .*? were missing.*"
+ ),
+ ),
+ # Provided function doesn't have all specified stores
+ pytest.param(
+ fake_provider_module.main,
+ ["image", "other"],
+ [None, None],
+ marks=pytest.mark.raises(
+ exception=ValueError, match="Expected stores in .*? were missing.*"
+ ),
+ ),
+ ],
+)
+def test_push_output_paths_wrapper(func, media_types, stores):
+ ti_mock = mock.MagicMock(spec=TaskInstance)
+ # This mock, along with the value, get handed into the provided function.
+ # For fake_provider_module.main, the mock will be called with the provided value.
+ func_mock = mock.MagicMock()
+ value = 42
+ dag_factory._push_output_paths_wrapper(
+ func,
+ media_types,
+ ti_mock,
+ args=[func_mock, value],
+ )
+ assert ti_mock.xcom_push.call_count == len(
+ media_types
+ ), "# of output paths didn't match # of stores expected"
+ for args, store in zip(ti_mock.xcom_push.calls, stores):
+ assert args.kwargs["value"] == store.output_path
+ # Check that the function itself was called with the provided args
+ func_mock.assert_called_once_with(value)
def test_create_day_partitioned_ingestion_dag_with_single_layer_dependencies():
- dag = df.create_day_partitioned_ingestion_dag(
+ dag = dag_factory.create_day_partitioned_ingestion_dag(
"test_dag",
print,
[[1, 2]],
@@ -13,15 +68,15 @@ def test_create_day_partitioned_ingestion_dag_with_single_layer_dependencies():
ingest2_id = "ingest_2"
today_task = dag.get_task(today_id)
assert today_task.upstream_task_ids == set()
- assert today_task.downstream_task_ids == set([wait0_id])
+ assert today_task.downstream_task_ids == {wait0_id}
ingest1_task = dag.get_task(ingest1_id)
- assert ingest1_task.upstream_task_ids == set([wait0_id])
+ assert ingest1_task.upstream_task_ids == {wait0_id}
ingest2_task = dag.get_task(ingest2_id)
- assert ingest2_task.upstream_task_ids == set([wait0_id])
+ assert ingest2_task.upstream_task_ids == {wait0_id}
def test_create_day_partitioned_ingestion_dag_with_multi_layer_dependencies():
- dag = df.create_day_partitioned_ingestion_dag(
+ dag = dag_factory.create_day_partitioned_ingestion_dag(
"test_dag",
print,
[[1, 2], [3, 4, 5]],
@@ -37,12 +92,12 @@ def test_create_day_partitioned_ingestion_dag_with_multi_layer_dependencies():
today_task = dag.get_task(today_id)
assert today_task.upstream_task_ids == set()
ingest1_task = dag.get_task(ingest1_id)
- assert ingest1_task.upstream_task_ids == set([wait0_id])
+ assert ingest1_task.upstream_task_ids == {wait0_id}
ingest2_task = dag.get_task(ingest2_id)
- assert ingest2_task.upstream_task_ids == set([wait0_id])
+ assert ingest2_task.upstream_task_ids == {wait0_id}
ingest3_task = dag.get_task(ingest3_id)
- assert ingest3_task.upstream_task_ids == set([wait1_id])
+ assert ingest3_task.upstream_task_ids == {wait1_id}
ingest4_task = dag.get_task(ingest4_id)
- assert ingest4_task.upstream_task_ids == set([wait1_id])
+ assert ingest4_task.upstream_task_ids == {wait1_id}
ingest5_task = dag.get_task(ingest5_id)
- assert ingest5_task.upstream_task_ids == set([wait1_id])
+ assert ingest5_task.upstream_task_ids == {wait1_id}
diff --git a/tests/dags/common/test_resources/fake_provider_module.py b/tests/dags/common/test_resources/fake_provider_module.py
new file mode 100644
index 000000000..761c180b3
--- /dev/null
+++ b/tests/dags/common/test_resources/fake_provider_module.py
@@ -0,0 +1,12 @@
+"""
+This is a fake provider module used in test_dag_factory.
+It is used to check that the output path acquisition logic is correct.
+"""
+from common.storage.image import ImageStore
+
+
+image_store = ImageStore()
+
+
+def main(mock, value):
+ mock(value)