Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Update Smithsonian Unit code checker DAG to alert to Slack (#452)
Staci Cooper4738e3f7b844
diff --git a/openverse_catalog/dags/common/loader/provider_details.py b/openverse_catalog/dags/common/loader/provider_details.pyindex 5af4e5180..4d478ee11 100644--- a/openverse_catalog/dags/common/loader/provider_details.py+++ b/openverse_catalog/dags/common/loader/provider_details.py@@ -63,7 +63,6 @@ EUROPEANA_SUB_PROVIDERS = {"wellcome_collection": "Wellcome Collection"}# Smithsonian parametersSMITHSONIAN_SUB_PROVIDERS = {"smithsonian_national_museum_of_natural_history": {- "NMNHANTHRO", # NMNH - Paleobiology Dept."NMNHBIRDS", # NMNH - Vertebrate Zoology - Birds Division"NMNHBOTANY", # NMNH - Botany Dept."NMNHEDUCATION", # NMNH - Education & Outreach@@ -88,9 +87,6 @@ SMITHSONIAN_SUB_PROVIDERS = {"OFEO-SG", # Office of Facilities Engineering and Operations},"smithsonian_hirshhorn_museum": {"HMSG"}, # Hirshhorn Museum and Sculpture Garden- "smithsonian_anthropological_archives": {- "NAA" # National Anthropological Archives- },"smithsonian_air_and_space_museum": {"NASM"}, # National Air and Space Museum"smithsonian_african_american_history_museum": {"NMAAHC" # National Museum of African American History and Culturediff --git a/openverse_catalog/dags/common/loader/smithsonian_unit_codes.py b/openverse_catalog/dags/common/loader/smithsonian_unit_codes.pydeleted file mode 100644index 331c51cf2..000000000--- a/openverse_catalog/dags/common/loader/smithsonian_unit_codes.py+++ /dev/null@@ -1,134 +0,0 @@-"""-This program helps identify smithsonian unit codes which are not yet added to-the smithsonian sub-provider dictionary-"""--import logging-from textwrap import dedent--import requests-from airflow.providers.postgres.hooks.postgres import PostgresHook-from common.loader import provider_details as prov-from providers.provider_api_scripts import smithsonian---logger = logging.getLogger(__name__)--DELAY = smithsonian.DELAY-API_KEY = smithsonian.API_KEY-API_ROOT = smithsonian.API_ROOT-UNITS_ENDPOINT = smithsonian.UNITS_ENDPOINT-PARAMS = {"api_key": API_KEY, "q": "online_media_type:Images"}-SUB_PROVIDERS = prov.SMITHSONIAN_SUB_PROVIDERS-SI_UNIT_CODE_TABLE = "smithsonian_new_unit_codes"---def initialise_unit_code_table(postgres_conn_id, unit_code_table):- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)-- """- Create table to store new unit codes if it does not exist- """- postgres.run(- dedent(- f"""- CREATE TABLE IF NOT EXISTS public.{unit_code_table} (- new_unit_code character varying(80),- action character varying(40)- );- """- )- )-- """- Delete old unit code entries- """- postgres.run(- dedent(- f"""- DELETE FROM public.{unit_code_table};- """- )- )---def get_new_and_outdated_unit_codes(unit_code_set, sub_prov_dict=SUB_PROVIDERS):- sub_provider_unit_code_set = set()-- for sub_prov, unit_code_sub_set in sub_prov_dict.items():- sub_provider_unit_code_set = sub_provider_unit_code_set.union(unit_code_sub_set)-- new_unit_codes = unit_code_set - sub_provider_unit_code_set- outdated_unit_codes = sub_provider_unit_code_set - unit_code_set-- if bool(new_unit_codes):- logger.info(- f"The new unit codes {new_unit_codes} must be added to "- f"the SMITHSONIAN_SUB_PROVIDERS dictionary"- )-- if bool(outdated_unit_codes):- logger.info(- f"The outdated unit codes {outdated_unit_codes} must be "- f"deleted from the SMITHSONIAN_SUB_PROVIDERS dictionary"- )-- return new_unit_codes, outdated_unit_codes---def alert_unit_codes_from_api(- postgres_conn_id,- unit_code_table="smithsonian_new_unit_codes",- units_endpoint=UNITS_ENDPOINT,- query_params=PARAMS,-):- response = requests.get(units_endpoint, params=query_params)- unit_code_set = set(response.json().get("response", {}).get("terms", []))- new_unit_codes, outdated_unit_codes = get_new_and_outdated_unit_codes(unit_code_set)-- initialise_unit_code_table(postgres_conn_id, unit_code_table)-- postgres = PostgresHook(postgres_conn_id=postgres_conn_id)-- """- Populate the table with new unit codes- """- for new_unit_code in new_unit_codes:- postgres.run(- dedent(- f"""- INSERT INTO public.{unit_code_table}- (new_unit_code, action)- VALUES (- '{new_unit_code}', 'add'- );- """- )- )-- """- Populate the table with outdated unit codes- """- for outdated_unit_code in outdated_unit_codes:- postgres.run(- dedent(- f"""- INSERT INTO public.{unit_code_table}- (new_unit_code, action)- VALUES (- '{outdated_unit_code}', 'delete'- );- """- )- )-- """- Raise exception if human intervention is needed to update the- SMITHSONIAN_SUB_PROVIDERS dictionary by checking the entries in the- smithsonian_new_unit_codes table- """- if bool(new_unit_codes) or bool(outdated_unit_codes):- raise Exception(- "Please check the smithsonian_new_unit_codes table for necessary "- "updates to the SMITHSONIAN_SUB_PROVIDERS dictionary"- )diff --git a/openverse_catalog/dags/providers/check_new_smithsonian_unit_codes_workflow.py b/openverse_catalog/dags/providers/check_new_smithsonian_unit_codes_workflow.pydeleted file mode 100644index ae242c408..000000000--- a/openverse_catalog/dags/providers/check_new_smithsonian_unit_codes_workflow.py+++ /dev/null@@ -1,57 +0,0 @@-"""-This file configures the Apache Airflow DAG to alert regarding new-smithsonian unit codes which are not seen in the SMITHSONIAN_SUB_PROVIDERS-dictionary-"""--import os-from datetime import datetime, timedelta--from airflow import DAG-from airflow.operators.python import PythonOperator-from common.loader import smithsonian_unit_codes---DAG_ID = "check_new_smithsonian_unit_codes_workflow"-DB_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")-MAX_ACTIVE_TASKS = 5--DAG_DEFAULT_ARGS = {- "owner": "data-eng-admin",- "depends_on_past": False,- "start_date": datetime(2020, 1, 15),- "email_on_retry": False,- "retries": 2,- "retry_delay": timedelta(seconds=15),- "schedule_interval": None,-}---def create_dag(- dag_id=DAG_ID,- args=DAG_DEFAULT_ARGS,- max_active_tasks=MAX_ACTIVE_TASKS,- max_active_runs=MAX_ACTIVE_TASKS,- postgres_conn_id=DB_CONN_ID,-):- dag = DAG(- dag_id=dag_id,- default_args=args,- max_active_tasks=max_active_tasks,- max_active_runs=max_active_runs,- catchup=False,- schedule_interval=None,- tags=["provider-metadata"],- )-- with dag:- PythonOperator(- task_id="check_new_smithsonian_unit_codes",- python_callable=smithsonian_unit_codes.alert_unit_codes_from_api,- op_args=[postgres_conn_id],- )-- return dag---globals()[DAG_ID] = create_dag()diff --git a/openverse_catalog/dags/providers/provider_api_scripts/smithsonian.py b/openverse_catalog/dags/providers/provider_api_scripts/smithsonian.pyindex 498a1680c..c82cb8a6d 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/smithsonian.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/smithsonian.py@@ -12,7 +12,9 @@ import jsonimport loggingimport osfrom datetime import datetime+from typing import Tuple+from airflow.exceptions import AirflowExceptionfrom airflow.models import Variablefrom common.licenses import LicenseInfofrom common.loader import provider_details as prov@@ -124,7 +126,10 @@ def main():defined as a search query that finds all objects whose hash IDstarts with some string of hexits of a specified length (e.g.,'0a2*' is a hash prefix of length 3).++ It fails early if the unit codes are not configured correctly."""+ validate_unit_codes_from_api()for hash_prefix in _get_hash_prefixes(HASH_PREFIX_LENGTH):total_rows = _process_hash_prefix(hash_prefix)logger.info(f"Total rows for {hash_prefix}: {total_rows}")@@ -186,6 +191,49 @@ def _gather_unit_sample(unit, sample_dir, retries=RETRIES, endpoint=SEARCH_ENDPObreak+def get_new_and_outdated_unit_codes(+ unit_codes_from_api: set, sub_providers: dict = SUB_PROVIDERS+) -> Tuple[set, set]:+ current_unit_codes = set().union(*sub_providers.values())++ new_unit_codes = unit_codes_from_api - current_unit_codes+ outdated_unit_codes = current_unit_codes - unit_codes_from_api++ return new_unit_codes, outdated_unit_codes+++def validate_unit_codes_from_api(units_endpoint: str = UNITS_ENDPOINT) -> None:+ """+ Validates the SMITHSONIAN_SUB_PROVIDERS dictionary, and raises an exception if+ human intervention is needed to add or remove unit codes.+ """+ query_params = {"api_key": API_KEY, "q": "online_media_type:Images"}+ response_json = delayed_requester.get_response_json(+ units_endpoint, query_params=query_params+ )+ unit_codes_from_api = set(response_json.get("response", {}).get("terms", []))+ new_unit_codes, outdated_unit_codes = get_new_and_outdated_unit_codes(+ unit_codes_from_api+ )++ if bool(new_unit_codes) or bool(outdated_unit_codes):+ message = "\n*Updates needed to the SMITHSONIAN_SUB_PROVIDERS dictionary*:\n\n"++ if bool(new_unit_codes):+ codes_string = "\n".join(f" - `{code}`" for code in new_unit_codes)+ message += "New unit codes must be added:\n"+ message += codes_string+ message += "\n"++ if bool(outdated_unit_codes):+ codes_string = "\n".join(f" - `{code}`" for code in outdated_unit_codes)+ message += "Outdated unit codes must be deleted:\n"+ message += codes_string++ logger.info(message)+ raise AirflowException(message)++def _get_hash_prefixes(prefix_length):max_prefix = "f" * prefix_lengthformat_string = f"0{prefix_length}x"diff --git a/tests/dags/common/loader/test_smithsonian_unit_codes.py b/tests/dags/common/loader/test_smithsonian_unit_codes.pydeleted file mode 100644index 71f0d0f7b..000000000--- a/tests/dags/common/loader/test_smithsonian_unit_codes.py+++ /dev/null@@ -1,77 +0,0 @@-import os-from collections import namedtuple-from unittest.mock import Mock, patch--import psycopg2-import pytest-from common.loader import smithsonian_unit_codes as si---POSTGRES_TEST_URI = os.getenv("AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING")-POSTGRES_CONN_ID = os.getenv("TEST_CONN_ID")-SI_UNIT_CODE_TABLE = "test_unit_code_table"---CREATE_TABLE_QUERY = (- f"CREATE TABLE IF NOT EXISTS public.{SI_UNIT_CODE_TABLE} ("- f"new_unit_code character varying(80),"- f"action character varying(40));"-)---def postgres_with_test_unit_code_table():- Postgres = namedtuple("Postgres", ["cursor", "connection"])- conn = psycopg2.connect(POSTGRES_TEST_URI)- cur = conn.cursor()- drop_command = f"DROP TABLE IF EXISTS {SI_UNIT_CODE_TABLE}"- cur.execute(drop_command)- conn.commit()- create_command = CREATE_TABLE_QUERY- cur.execute(create_command)- conn.commit()-- yield Postgres(cursor=cur, connection=conn)-- cur.execute(drop_command)- cur.close()- conn.commit()- conn.close()---def test_alert_new_unit_codes():- unit_code_set = {"a", "b", "c", "d"}- sub_prov_dict = {"sub_prov1": {"a", "c"}, "sub_prov2": {"b"}, "sub_prov3": {"e"}}-- assert si.get_new_and_outdated_unit_codes(unit_code_set, sub_prov_dict) == (- {"d"},- {"e"},- )---def test_alert_unit_codes_from_api(postgres_with_test_unit_code_table):- postgres_conn_id = POSTGRES_CONN_ID- unit_code_table = SI_UNIT_CODE_TABLE- response_mock = Mock()- response_mock.json.return_value = {}-- with patch.object(- si, "get_new_and_outdated_unit_codes", return_value=({"d"}, {"e"})- ) as mock_get_unit_codes, patch.object(- si.requests, "get", return_value=response_mock- ):- with pytest.raises(Exception):- si.alert_unit_codes_from_api(postgres_conn_id, unit_code_table)-- mock_get_unit_codes.assert_called()-- postgres_with_test_unit_code_table.cursor.execute(- f"SELECT * FROM {unit_code_table};"- )-- actual_rows = postgres_with_test_unit_code_table.cursor.fetchall()- postgres_with_test_unit_code_table.connection.commit()-- assert len(actual_rows) == 2- assert ("d", "add") in actual_rows- assert ("e", "delete") in actual_rowsdiff --git a/tests/dags/providers/provider_api_scripts/test_smithsonian.py b/tests/dags/providers/provider_api_scripts/test_smithsonian.pyindex d77d25666..dd32610b0 100644--- a/tests/dags/providers/provider_api_scripts/test_smithsonian.py+++ b/tests/dags/providers/provider_api_scripts/test_smithsonian.py@@ -4,6 +4,7 @@ import osfrom unittest.mock import call, patchimport pytest+from airflow.exceptions import AirflowExceptionfrom common.licenses import LicenseInfofrom providers.provider_api_scripts import smithsonian as si@@ -48,6 +49,47 @@ def test_get_hash_prefixes_with_len_one():assert actual_prefix_list == expect_prefix_list+def test_alert_new_unit_codes():+ unit_code_set = {"a", "b", "c", "d"}+ sub_prov_dict = {"sub_prov1": {"a", "c"}, "sub_prov2": {"b"}, "sub_prov3": {"e"}}++ assert si.get_new_and_outdated_unit_codes(unit_code_set, sub_prov_dict) == (+ {"d"},+ {"e"},+ )+++ "new_unit_codes, outdated_unit_codes",+ [+ ({"d"}, {"e"}),+ ({"d"}, set()),+ (set(), {"e"}),+ ],+)+def test_validate_unit_codes_from_api_raises_exception(+ new_unit_codes, outdated_unit_codes+):+ with patch.object(si.delayed_requester, "get_response_json"), patch.object(+ si,+ "get_new_and_outdated_unit_codes",+ return_value=(new_unit_codes, outdated_unit_codes),+ ):+ with pytest.raises(+ AirflowException,+ match="^\n\\*Updates needed to the SMITHSONIAN_SUB_PROVIDERS dictionary\\**",+ ):+ si.validate_unit_codes_from_api()+++def test_validate_unit_codes_from_api():+ with patch.object(si.delayed_requester, "get_response_json"), patch.object(+ si, "get_new_and_outdated_unit_codes", return_value=(set(), set())+ ):+ # Validation should run without raising an exception+ si.validate_unit_codes_from_api()++@pytest.mark.parametrize("input_int,expect_len,expect_first,expect_last",[diff --git a/tests/dags/test_dag_parsing.py b/tests/dags/test_dag_parsing.pyindex fad249c7c..28a9dbe1d 100644--- a/tests/dags/test_dag_parsing.py+++ b/tests/dags/test_dag_parsing.py@@ -14,7 +14,6 @@ PROVIDER_WORKFLOWS = [DAG_FOLDER / "providers" / workflowfor workflow in ["brooklyn_museum_workflow.py",- "check_new_smithsonian_unit_codes_workflow.py","cleveland_museum_workflow.py","europeana_ingestion_workflow.py","europeana_workflow.py",