Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Automatic DAG documentation generation (#649)
Madison Swain-Bowden0f5847542705
diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.ymlindex c33511ea8..be26648ff 100644--- a/.github/workflows/ci_cd.yml+++ b/.github/workflows/ci_cd.yml@@ -74,12 +74,16 @@ jobs:- name: Change permissions for Docker stepsrun: chmod -R 777 openverse_catalog/ tests/- - name: Test+ - name: Build dev container# The containers must be rebuilt here because we need the dev dependencies# rather than the production ones- run: |- just build- just test --extended+ run: just build++ - name: Check DAG documentation+ run: just generate-dag-docs true++ - name: Test+ run: just test --extendedpush:name: Publish Docker imagesdiff --git a/DAGs.md b/DAGs.mdnew file mode 100644index 000000000..fc48f9777--- /dev/null+++ b/DAGs.md@@ -0,0 +1,572 @@+# DAGs++_Note: this document is auto-generated and should not be manually edited_++This document describes the DAGs available along with pertinent DAG information and+the DAG's documentation.++The DAGs are shown in two forms:++ - [DAGs by Type](#dags-by-type)+ - [Individual DAG documentation](#dag-documentation)++# DAGs by Type++The following are DAGs grouped by their primary tag:++ 1. [Commoncrawl](#commoncrawl)+ 1. [Data Refresh](#data_refresh)+ 1. [Database](#database)+ 1. [Maintenance](#maintenance)+ 1. [Oauth](#oauth)+ 1. [Provider](#provider)+ 1. [Provider Reingestion](#provider-reingestion)++## Commoncrawl++| DAG ID | Schedule Interval |+| --- | --- |+| `commoncrawl_etl_workflow` | `0 0 * * 1` |+| `sync_commoncrawl_workflow` | `0 16 15 * *` |++++## Data Refresh++| DAG ID | Schedule Interval |+| --- | --- |+| [`audio_data_refresh`](#audio_data_refresh) | `@weekly` |+| [`image_data_refresh`](#image_data_refresh) | `@weekly` |++++## Database++| DAG ID | Schedule Interval |+| --- | --- |+| `image_expiration_workflow` | `None` |+| [`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` |++++## Maintenance++| DAG ID | Schedule Interval |+| --- | --- |+| [`airflow_log_cleanup`](#airflow_log_cleanup) | `@weekly` |+| [`check_silenced_dags`](#check_silenced_dags) | `@weekly` |+| [`pr_review_reminders`](#pr_review_reminders) | `0 0 * * 1-5` |++++## Oauth++| DAG ID | Schedule Interval |+| --- | --- |+| [`oauth2_authorization`](#oauth2_authorization) | `None` |+| [`oauth2_token_refresh`](#oauth2_token_refresh) | `0 */12 * * *` |++++## Provider++| DAG ID | Schedule Interval | Dated | Media Type(s) |+| --- | --- | --- | --- |+| `brooklyn_museum_workflow` | `@monthly` | `False` | image |+| `cleveland_museum_workflow` | `@monthly` | `False` | image |+| [`europeana_workflow`](#europeana_workflow) | `@daily` | `True` | image |+| `finnish_museums_workflow` | `@monthly` | `False` | image |+| [`flickr_workflow`](#flickr_workflow) | `@daily` | `True` | image |+| [`freesound_workflow`](#freesound_workflow) | `@monthly` | `False` | audio |+| [`jamendo_workflow`](#jamendo_workflow) | `@monthly` | `False` | audio |+| [`metropolitan_museum_workflow`](#metropolitan_museum_workflow) | `@daily` | `True` | image |+| `museum_victoria_workflow` | `@monthly` | `False` | image |+| `nypl_workflow` | `@monthly` | `False` | image |+| [`phylopic_workflow`](#phylopic_workflow) | `@weekly` | `True` | image |+| `rawpixel_workflow` | `@monthly` | `False` | image |+| `science_museum_workflow` | `@monthly` | `False` | image |+| [`smithsonian_workflow`](#smithsonian_workflow) | `@weekly` | `False` | image |+| `smk_workflow` | `@monthly` | `False` | image |+| [`stocksnap_workflow`](#stocksnap_workflow) | `@monthly` | `False` | image |+| [`walters_workflow`](#walters_workflow) | `@monthly` | `False` | image |+| [`wikimedia_commons_workflow`](#wikimedia_commons_workflow) | `@daily` | `True` | image, audio |+| [`wordpress_workflow`](#wordpress_workflow) | `@monthly` | `False` | image |++++## Provider Reingestion++| DAG ID | Schedule Interval |+| --- | --- |+| `europeana_ingestion_workflow` | `@daily` |+| `flickr_ingestion_workflow` | `@daily` |+| `wikimedia_ingestion_workflow` | `@daily` |+++# DAG documentation++The following is documentation associated with each DAG (where available):++ 1. [`airflow_log_cleanup`](#airflow_log_cleanup)+ 1. [`audio_data_refresh`](#audio_data_refresh)+ 1. [`check_silenced_dags`](#check_silenced_dags)+ 1. [`europeana_workflow`](#europeana_workflow)+ 1. [`flickr_workflow`](#flickr_workflow)+ 1. [`freesound_workflow`](#freesound_workflow)+ 1. [`image_data_refresh`](#image_data_refresh)+ 1. [`jamendo_workflow`](#jamendo_workflow)+ 1. [`metropolitan_museum_workflow`](#metropolitan_museum_workflow)+ 1. [`oauth2_authorization`](#oauth2_authorization)+ 1. [`oauth2_token_refresh`](#oauth2_token_refresh)+ 1. [`phylopic_workflow`](#phylopic_workflow)+ 1. [`pr_review_reminders`](#pr_review_reminders)+ 1. [`recreate_audio_popularity_calculation`](#recreate_audio_popularity_calculation)+ 1. [`recreate_image_popularity_calculation`](#recreate_image_popularity_calculation)+ 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. [`walters_workflow`](#walters_workflow)+ 1. [`wikimedia_commons_workflow`](#wikimedia_commons_workflow)+ 1. [`wordpress_workflow`](#wordpress_workflow)+++## `airflow_log_cleanup`+++A maintenance workflow that you can deploy into Airflow to periodically clean+out the task logs to avoid those getting too big. By default, this will also+clean child process logs from the 'scheduler' directory.++Can remove all log files by setting "maxLogAgeInDays" to -1.+If you want to test the DAG in the Airflow Web UI, you can also set+enableDelete to `false`, and then you will see a list of log folders+that can be deleted, but will not actually delete them.++This should all go on one line:+```+airflow dags trigger --conf+'{"maxLogAgeInDays":-1, "enableDelete": "false"}' airflow_log_cleanup+```+`--conf` options:+- maxLogAgeInDays:<INT> - Optional+- enableDelete:<BOOLEAN> - Optional++++## `audio_data_refresh`++### Data Refresh DAG Factory+This file generates our data refresh DAGs using a factory function.+For the given media type these DAGs will first refresh the popularity data,+then initiate a data refresh on the data refresh server and await the+success or failure of that task.++Popularity data for each media type is collated in a materialized view. Before+initiating a data refresh, the DAG will first refresh the view in order to+update popularity data for records that have been ingested since the last refresh.+On the first run of the month, the DAG will also refresh the underlying tables,+including the percentile values and any new popularity metrics. The DAG can also+be run with the `force_refresh_metrics` option to run this refresh after the first+of the month.++Once this step is complete, the data refresh can be initiated. A data refresh+occurs on the data refresh server in the openverse-api project. This is a task+which imports data from the upstream Catalog database into the API, copies contents+to a new Elasticsearch index, and finally makes the index "live". This process is+necessary to make new content added to the Catalog by our provider DAGs available+to the API. You can read more in the [README](+https://github.com/WordPress/openverse-api/blob/main/ingestion_server/README.md+) Importantly, the data refresh TaskGroup is also configured to handle concurrency+requirements of the data refresh server.++You can find more background information on this process in the following+issues and related PRs:++- [[Feature] Data refresh orchestration DAG](+https://github.com/WordPress/openverse-catalog/issues/353)+- [[Feature] Merge popularity calculations and data refresh into a single DAG](+https://github.com/WordPress/openverse-catalog/issues/453)+++## `check_silenced_dags`+++Checks for DAGs that have silenced Slack alerts which may need to be turned back+on.++When a DAG has known failures, it can be ommitted from Slack error reporting by adding+an entry to the `silenced_slack_alerts` Airflow variable. This is a dictionary where the+key is the `dag_id` of the affected DAG, and the value is the URL of a GitHub issue+tracking the error.++The `check_silenced_alert` DAG iterates over the entries in the `silenced_slack_alerts`+configuration and verifies that the associated GitHub issues are still open. If an issue+has been closed, it is assumed that the DAG should have Slack reporting reenabled, and+an alert is sent to prompt manual update of the configuration. This prevents developers+from forgetting to reenable Slack reporting after the issue has been resolved.++The DAG runs weekly.++++## `europeana_workflow`+++Content Provider: Europeana++ETL Process: Use the API to identify all CC licensed images.++Output: TSV file containing the images and the+ respective meta-data.++Notes: https://www.europeana.eu/api/v2/search.json++++## `flickr_workflow`+++Content Provider: Flickr++ETL Process: Use the API to identify all CC licensed images.++Output: TSV file containing the images and the+ respective meta-data.++Notes: https://www.flickr.com/help/terms/api+ Rate limit: 3600 requests per hour.++++## `freesound_workflow`+++Content Provider: Freesound++ETL Process: Use the API to identify all CC-licensed images.++Output: TSV file containing the image, the respective+ meta-data.++Notes: https://freesound.org/apiv2/search/text'+ No rate limit specified.++++## `image_data_refresh`++### Data Refresh DAG Factory+This file generates our data refresh DAGs using a factory function.+For the given media type these DAGs will first refresh the popularity data,+then initiate a data refresh on the data refresh server and await the+success or failure of that task.++Popularity data for each media type is collated in a materialized view. Before+initiating a data refresh, the DAG will first refresh the view in order to+update popularity data for records that have been ingested since the last refresh.+On the first run of the month, the DAG will also refresh the underlying tables,+including the percentile values and any new popularity metrics. The DAG can also+be run with the `force_refresh_metrics` option to run this refresh after the first+of the month.++Once this step is complete, the data refresh can be initiated. A data refresh+occurs on the data refresh server in the openverse-api project. This is a task+which imports data from the upstream Catalog database into the API, copies contents+to a new Elasticsearch index, and finally makes the index "live". This process is+necessary to make new content added to the Catalog by our provider DAGs available+to the API. You can read more in the [README](+https://github.com/WordPress/openverse-api/blob/main/ingestion_server/README.md+) Importantly, the data refresh TaskGroup is also configured to handle concurrency+requirements of the data refresh server.++You can find more background information on this process in the following+issues and related PRs:++- [[Feature] Data refresh orchestration DAG](+https://github.com/WordPress/openverse-catalog/issues/353)+- [[Feature] Merge popularity calculations and data refresh into a single DAG](+https://github.com/WordPress/openverse-catalog/issues/453)+++## `jamendo_workflow`+++Content Provider: Jamendo++ETL Process: Use the API to identify all CC-licensed audio.++Output: TSV file containing the audio meta-data.++Notes: https://api.jamendo.com/v3.0/tracks/+ 35,000 requests per month for non-commercial apps+ Jamendo Music has more than 500,000 tracks shared by+ 40,000 artists from over 150 countries all over+ the world.+ Audio quality: uploaded as WAV/ FLAC/ AIFF+ bit depth: 16/24+ sample rate: 44.1 or 48 kHz+ channels: 1/2++++## `metropolitan_museum_workflow`+++Content Provider: Metropolitan Museum of Art++ETL Process: Use the API to identify all CC0 artworks.++Output: TSV file containing the image, their respective+ meta-data.++Notes: https://metmuseum.github.io/+ No rate limit specified.++++## `oauth2_authorization`++### OAuth Provider Authorization++**Author**: Madison Swain-Bowden++**Created**: 2021-10-13++++Iterates through all the OAuth2 providers and attempts to authorize them using tokens+found in the in the `OAUTH2_AUTH_KEYS` Variable. Once authorization has been+completed successfully, the auth token is removed from that Variable. The authorization+will create an access/refresh token pair in the `OAUTH2_ACCESS_TOKENS` Variable.++**Current Providers**:++- Freesound+++## `oauth2_token_refresh`++### OAuth Provider Token Refresh++**Author**: Madison Swain-Bowden++**Created**: 2021-10-13+++Iterates through all OAuth2 providers and attempts to refresh the access token using+the refresh token stored in the `OAUTH2_ACCESS_TOKENS` Variable. This DAG will+update the tokens stored in the Variable upon successful refresh.++**Current Providers**:++- Freesound+++## `phylopic_workflow`+++Content Provider: PhyloPic++ETL Process: Use the API to identify all CC licensed images.++Output: TSV file containing the image,+ their respective meta-data.++Notes: http://phylopic.org/api/+ No rate limit specified.++++## `pr_review_reminders`+++Iterates through open PRs in our repositories and pings assigned reviewers+who have not yet approved the PR or explicitly requested changes.++This DAG runs daily and pings on the following schedule based on priority label:++| priority | days |+| --- | --- |+| critical | 1 day |+| high | >2 days |+| medium | >4 days |+| low | >7 days |++The DAG does not ping on Saturday and Sunday and accounts for weekend days+when determining how much time has passed since the review.++Unfortunately the DAG does not know when someone is on vacation. It is up to the+author of the PR to re-assign review if one of the randomly selected reviewers+is unavailable for the time period during which the PR should be reviewed.++++## `recreate_audio_popularity_calculation`+++This file generates Apache Airflow DAGs that, for the given media type,+completely wipe out the PostgreSQL relations and functions involved in+calculating our standardized popularity metric. It then recreates relations+and functions to make the calculation, and performs an initial calculation.+The results are available in the materialized view for that media type.++These DAGs are not on a schedule, and should only be run manually when new+SQL code is deployed for the calculation.++++## `recreate_image_popularity_calculation`+++This file generates Apache Airflow DAGs that, for the given media type,+completely wipe out the PostgreSQL relations and functions involved in+calculating our standardized popularity metric. It then recreates relations+and functions to make the calculation, and performs an initial calculation.+The results are available in the materialized view for that media type.++These DAGs are not on a schedule, and should only be run manually when new+SQL code is deployed for the calculation.++++## `report_pending_reported_media`++### Report Pending Reported Media DAG+This DAG checks for any user-reported media pending manual review, and alerts+via Slack.++Media may be reported for mature content or copyright infringement, for+example. Once reported, these require manual review through the Django Admin to+determine whether further action (such as deindexing the record) needs to be+taken. If a record has been reported multiple times, it only needs to be+reviewed once and so is only counted once in the reporting by this DAG.+++## `smithsonian_workflow`+++Content Provider: Smithsonian++ETL Process: Use the API to identify all CC licensed images.++Output: TSV file containing the images and the respective+ meta-data.++Notes: None++++## `stocksnap_workflow`+++Content Provider: StockSnap++ETL Process: Use the API to identify all CC-licensed images.++Output: TSV file containing the image, the respective meta-data.++Notes: https://stocksnap.io/api/load-photos/date/desc/1+ https://stocksnap.io/faq+ All images are licensed under CC0.+ No rate limits or authorization required.+ 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)+++++## `walters_workflow`+++Content Provider: Walters Art Museum++ETL Process: Use the API to identify all CC licensed images.++Output: TSV file containing the images and the+ respective meta-data.++Notes: http://api.thewalters.org/+ Rate limit: 250000 Per Day Per Key++++## `wikimedia_commons_workflow`+++Content Provider: Wikimedia Commons++ETL Process: Use the API to identify all CC-licensed images.++Output: TSV file containing the image, the respective+ meta-data.++Notes: https://commons.wikimedia.org/wiki/API:Main_page+ No rate limit specified.++++## `wordpress_workflow`+++Content Provider: WordPress Photo Directory++ETL Process: Use the API to identify all openly licensed media.++Output: TSV file containing the media metadata.++Notes: https://wordpress.org/photos/wp-json/wp/v2+ Provide photos, media, users and more related resources.+ No rate limit specified.diff --git a/README.md b/README.mdindex 0f92931c7..7bfae23c0 100644--- a/README.md+++ b/README.md@@ -58,39 +58,8 @@ the internet.### API Workflows-Our API-based workflows run at different schedules: some daily, others monthly. Please consider which to use whenever a new DAG is written, and add your new script to one of these schedules.--#### Daily--Workflows that have a `schedule_string='@daily'` parameter are run daily. The DAG-workflows run `provider_api_scripts` to load and extract media data from the APIs. The following provider scripts are run daily:--- [Flickr](openverse_catalog/dags/providers/provider_api_scripts/flickr.py)-- [Met Museum](openverse_catalog/dags/providers/provider_api_scripts/metropolitan_museum_of_art.py)-- [PhyloPic](openverse_catalog/dags/providers/provider_api_scripts/phylopic.py)-- [Wikimedia Commons](openverse_catalog/dags/providers/provider_api_scripts/wikimedia_commons.py)--#### Monthly--Some API ingestion workflows are scheduled to run on the 15th day of each-month at 16:00 UTC. These workflows are reserved for long-running jobs or-APIs that do not have date filtering capabilities, so the data is reprocessed-monthly to keep the catalog updated. The following provider scripts are run monthly:--- [Brooklyn Museum](openverse_catalog/dags/providers/provider_api_scripts/brooklyn_museum.py)-- [Cleveland Museum of Art](openverse_catalog/dags/providers/provider_api_scripts/cleveland_museum_of_art.py)-- [Common Crawl Syncer](openverse_catalog/dags/commoncrawl/commoncrawl_scripts/commoncrawl_s3_syncer/SyncImageProviders.py)-- [NYPL](openverse_catalog/dags/providers/provider_api_scripts/nypl.py)-- [RawPixel](openverse_catalog/dags/providers/provider_api_scripts/raw_pixel.py)-- [StockSnap](openverse_catalog/dags/providers/provider_api_scripts/stocksnap.py)--### TSV to Postgres Loader--The Airflow DAG defined in [`loader_workflow.py`][db_loader] runs every minute,-and loads the oldest file which has not been modified in the last 15 minutes-into the upstream database. It includes some data preprocessing steps.--[db_loader]: openverse_catalog/dags/database/loader_workflow.py+To view more information about all the available workflows (DAGs) within the project,+see [DAGs.md](DAGs.md).See each provider API script's notes in their respective [handbook][ov-handbook] entry.diff --git a/justfile b/justfileindex 012c328cc..e239f3a7d 100644--- a/justfile+++ b/justfile@@ -90,3 +90,19 @@ run *args: (up "postgres s3")# Launch a pgcli shell on the postgres container (defaults to openledger) use "airflow" for airflow metastoredb-shell args="openledger": updocker-compose {{ DOCKER_FILES }} exec postgres pgcli {{ args }}++# Generate the DAG documentation+generate-dag-docs fail_on_diff="false":+ #!/bin/bash+ set -e+ just run python openverse_catalog/utilities/dag_doc_gen/dag_doc_generation.py+ # Move the file to the top level, since that level is not mounted into the container+ mv openverse_catalog/utilities/dag_doc_gen/DAGs.md DAGs.md+ if {{ fail_on_diff }}; then+ set +e+ git diff --exit-code DAGs.md+ if [ $? -ne 0 ]; then+ printf "\n\n\e[31m!! Changes found in DAG documentation, please run 'just generate-dag-docs' locally and commit difference !!\n\n"+ exit 1+ fi+ fidiff --git a/openverse_catalog/dags/maintenance/airflow_log_cleanup_workflow.py b/openverse_catalog/dags/maintenance/airflow_log_cleanup_workflow.pyindex de0833b5b..063e22804 100644--- a/openverse_catalog/dags/maintenance/airflow_log_cleanup_workflow.py+++ b/openverse_catalog/dags/maintenance/airflow_log_cleanup_workflow.py@@ -9,11 +9,13 @@ enableDelete to `false`, and then you will see a list of log foldersthat can be deleted, but will not actually delete them.This should all go on one line:-```airflow dags trigger --conf-'{"maxLogAgeInDays":-1, "enableDelete": "false"}' airflow_log_cleanup```---conf options:- maxLogAgeInDays:<INT> - Optional- enableDelete:<BOOLEAN> - Optional+```+airflow dags trigger --conf+'{"maxLogAgeInDays":-1, "enableDelete": "false"}' airflow_log_cleanup+```+`--conf` options:+- maxLogAgeInDays:<INT> - Optional+- enableDelete:<BOOLEAN> - Optional"""from datetime import datetime, timedeltadiff --git a/openverse_catalog/utilities/README.md b/openverse_catalog/utilities/README.mdnew file mode 100644index 000000000..2ce663418--- /dev/null+++ b/openverse_catalog/utilities/README.md@@ -0,0 +1,4 @@+# Utilities++This folder contains utilities that may be run in the dev environment (e.g. devex utilities, documentation generation, etc.).+This folder is not mounted into the container in production and thus will not be available or accessible in that environment.diff --git a/openverse_catalog/utilities/__init__.py b/openverse_catalog/utilities/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/openverse_catalog/utilities/dag_doc_gen/__init__.py b/openverse_catalog/utilities/dag_doc_gen/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/openverse_catalog/utilities/dag_doc_gen/dag_doc_generation.py b/openverse_catalog/utilities/dag_doc_gen/dag_doc_generation.pynew file mode 100644index 000000000..674e10f8f--- /dev/null+++ b/openverse_catalog/utilities/dag_doc_gen/dag_doc_generation.py@@ -0,0 +1,231 @@+"""+This script generates a markdown documentation file which aggregates various pieces+of information about all of our DAGs. The generated document has two sections: "DAGs+by type" and "individual DAG documentation". Both sections have a small table of+contents.++The DAGs-by-type section shows DAG ID and schedule interval for all DAGS, and also shows+dated & media type info for provider DAGs. Where possible, the DAG IDs link to+individual documentation subsections further in the document.++The individual DAG documentation section pulls the DAG's `doc_md` blurb and renders+it within the document.+"""+import logging+from collections import defaultdict+from pathlib import Path+from typing import NamedTuple++from airflow.models import DAG, DagBag+from providers.provider_workflows import PROVIDER_WORKFLOWS, ProviderWorkflow+++log = logging.getLogger(__name__)+# Silence noisy modules+logging.getLogger("common.storage.media").setLevel(logging.WARNING)++# Constants+DAG_MD_PATH = Path(__file__).parent / "DAGs.md"+DAG_FOLDER = Path(__file__).parents[2] / "dags"+PREAMBLE = """\+# DAGs++_Note: this document is auto-generated and should not be manually edited_++This document describes the DAGs available along with pertinent DAG information and+the DAG's documentation.++The DAGs are shown in two forms:++ - [DAGs by Type](#dags-by-type)+ - [Individual DAG documentation](#dag-documentation)++# DAGs by Type++The following are DAGs grouped by their primary tag:++"""+MIDAMBLE = """+# DAG documentation++The following is documentation associated with each DAG (where available):++"""++# Typing+DagMapping = dict[str, DAG]+++class DagInfo(NamedTuple):+ dag_id: str+ schedule: str | None+ doc: str | None+ type_: str+ dated: bool+ provider_workflow: ProviderWorkflow | None+++def load_dags(dag_folder: str) -> DagMapping:+ """+ Load and return the DAGs in the provided dag folder. Execution will stop if any DAGs+ could not be imported.+ """+ dag_bag = DagBag(dag_folder=dag_folder, include_examples=False)+ if dag_bag.import_errors:+ raise ValueError(+ "DagBag could not load properly due to errors with the following DAGs: "+ f"{set(dag_bag.import_errors.keys())}"+ )+ return dag_bag.dags+++def get_provider_workflows() -> dict[str, ProviderWorkflow]:+ """+ Extract the provider workflows from the PROVIDER_WORKFLOWS list and create a mapping+ from DAG ID to workflow.+ """+ return {workflow.dag_id: workflow for workflow in PROVIDER_WORKFLOWS}+++def get_dags_info(dags: DagMapping) -> list[DagInfo]:+ """+ Convert the provided DAG ID -> DAG mapping into a list of DagInfo instances.+ Provider information is added where available.+ """+ dags_info = []+ provider_workflows = get_provider_workflows()+ for dag_id, dag in dags.items():+ doc = dag.doc_md+ # Convert the initial H1 header level to H3 if it exists, for better formatting+ # within the document+ if doc and doc.strip().startswith("# "):+ doc = "### " + doc.strip()[2:]+ dated = dag.catchup+ # Infer dag type from the first available tag+ type_ = dag.tags[0] if dag.tags else "other"+ dags_info.append(+ DagInfo(+ dag_id=dag_id,+ schedule=dag.schedule_interval,+ doc=doc,+ type_=type_,+ dated=dated,+ provider_workflow=provider_workflows.get(dag_id),+ )+ )++ return dags_info+++def generate_type_subsection(+ name: str, dags_info: list[DagInfo], is_provider: bool+) -> str:+ """+ Generate the documentation for a "DAGs by type" subsection.+ """+ log.info(f"Building subsection for '{name}'")+ text = f"## {name}\n\n"+ # Columns for all DAGs+ header = "| DAG ID | Schedule Interval |"+ # Conditionally add the other columns for the provider-specific DAGs+ if is_provider:+ header += " Dated | Media Type(s) |"++ # In order to create a table of the appropriate width, we need the number of columns+ # to complete the second row of the header (the "---" columns). There are+ # columns + 1 pipe characters, so stripping the pipes on both ends then splitting+ # gives us the appropriate number of columns.+ column_count = len(header.strip("|").split("|"))+ log.info(f"Total columns: {column_count}")+ text += header + "\n"+ text += "| " + " | ".join(["---"] * column_count) + " |"++ for dag in dags_info:+ dag_id = f"`{dag.dag_id}`"+ # If we have documentation for the DAG, we'll want to link to it within the+ # markdown, so we reference it using the heading text (the DAG ID)+ if dag.doc:+ dag_id = f"[{dag_id}](#{dag.dag_id})"+ text += f"\n| {dag_id} | `{dag.schedule}` |"+ if is_provider:+ text += f" `{dag.dated}` | {', '.join(dag.provider_workflow.media_types)} |"++ text += "\n\n"++ return text+++def generate_single_documentation(dag: DagInfo) -> str:+ """+ Generate the documentation for a single DAG.+ """+ return f"""+## `{dag.dag_id}`++{dag.doc}++"""+++def generate_dag_doc(dag_folder: Path = DAG_FOLDER) -> str:+ """+ Generate the DAG documentation markdown file using the DAGs available in the+ folder provided.+ """+ text = PREAMBLE+ dags = load_dags(str(dag_folder))+ # DAGs come out of the DagBag in seemingly random order, so sort them by DAG ID+ # before any operations are run on them.+ dags_info = sorted(get_dags_info(dags), key=lambda x: x.dag_id)++ dag_types = []++ # Group DAGs them into sub-lists by DAG "type", which is determined by the first+ # available DAG tag.+ dags_by_type: dict[str, list[DagInfo]] = defaultdict(list)+ for dag in dags_info:+ dags_by_type[dag.type_].append(dag)++ for type_, dags in sorted(dags_by_type.items()):+ # Create a more human-readable name+ name = type_.replace("_", " ").replace("-", " ").title()+ # Special case for provider tables since they have extra information+ is_provider = type_ == "provider"+ # For each type we generate a sub-list of DAGs. We add a link to each generated+ # sub-list as part of a table of contents, but defer adding the sub-lists until+ # all are generated.+ text += f" 1. [{name}](#{type_})\n"+ dag_types.append(generate_type_subsection(name, dags, is_provider))++ text += "\n" + "\n\n".join(dag_types)++ text += MIDAMBLE+ dag_docs = []+ for dag in sorted(dags_info, key=lambda d: d.dag_id):+ # This section only contains subsections for DAGs where we have documentation+ if not dag.doc:+ continue+ # Similar to the DAGs-by-type section, we add the reference to a table of+ # contents first, and then defer adding all the generated individual docs until+ # the very end.+ text += f" 1. [`{dag.dag_id}`](#{dag.dag_id})\n"+ dag_docs.append(generate_single_documentation(dag))++ text += "\n" + "".join(dag_docs)++ # Normalize the newlines at the end of the file and add one more to make sure+ # our pre-commit checks are happy!+ return text.strip() + "\n"+++def write_dag_doc(path: Path = DAG_MD_PATH) -> None:+ """+ Generate the DAG documentation and write it to a file.+ """+ doc_text = generate_dag_doc()+ log.info(f"Writing DAG doc to {path}")+ path.write_text(doc_text)+++if __name__ == "__main__":+ write_dag_doc()diff --git a/tests/utilities/dag_doc_gen/test_dag_doc_generation.py b/tests/utilities/dag_doc_gen/test_dag_doc_generation.pynew file mode 100644index 000000000..32beb61af--- /dev/null+++ b/tests/utilities/dag_doc_gen/test_dag_doc_generation.py@@ -0,0 +1,164 @@+from typing import NamedTuple+from unittest import mock++import pytest++from openverse_catalog.utilities.dag_doc_gen import dag_doc_generation+from openverse_catalog.utilities.dag_doc_gen.dag_doc_generation import DagInfo+++class DagMock(NamedTuple):+ schedule_interval: str | None+ doc_md: str | None+ catchup: bool+ tags: list[str]+++DAG_ID = "sample_dag_123"+SAMPLE_MEDIA_TYPES = ("m1", "m2")+PROVIDER_WORKFLOW_INSTANCE = mock.MagicMock()+PROVIDER_WORKFLOW_INSTANCE.media_types = SAMPLE_MEDIA_TYPES+_MODULE = "openverse_catalog.utilities.dag_doc_gen.dag_doc_generation"++[email protected]("schedule_interval", ["@daily", None])+ "doc, expected_doc",+ [+ (None, None),+ ("Sample simple doc", "Sample simple doc"),+ ("# Big header", "### Big header"),+ ],+)[email protected]("catchup", [True, False])+ "tags, type_",+ [+ (None, "other"),+ ([], "other"),+ (["foo"], "foo"),+ (["foo", "bar"], "foo"),+ ],+)[email protected]("provider_workflow", ["foo_bar", None])+def test_get_dags_info(+ schedule_interval, doc, expected_doc, catchup, tags, type_, provider_workflow+):+ dag = DagMock(+ schedule_interval=schedule_interval, doc_md=doc, catchup=catchup, tags=tags+ )+ expected = DagInfo(+ dag_id=DAG_ID,+ schedule=schedule_interval,+ doc=expected_doc,+ dated=catchup,+ type_=type_,+ provider_workflow=provider_workflow,+ )+ with mock.patch(f"{_MODULE}.get_provider_workflows") as provider_workflow_mock:+ provider_workflow_mock.return_value.get.return_value = provider_workflow+ actual = dag_doc_generation.get_dags_info({DAG_ID: dag})[0]+ assert actual == expected+++ "dag_info, is_provider, expected",+ [+ # Most info missing+ (+ DagInfo(+ dag_id=DAG_ID,+ schedule=None,+ doc=None,+ type_="",+ dated=False,+ provider_workflow=None,+ ),+ False,+ """+## Special Name++| DAG ID | Schedule Interval |+| --- | --- |+| `sample_dag_123` | `None` |+""",+ ),+ # Most info present+ (+ DagInfo(+ dag_id=DAG_ID,+ schedule="@daily",+ doc="A doc does exist here",+ type_="",+ dated=False,+ provider_workflow=None,+ ),+ False,+ """+## Special Name++| DAG ID | Schedule Interval |+| --- | --- |+| [`sample_dag_123`](#sample_dag_123) | `@daily` |+""",+ ),+ # Provider workflow with most+ (+ DagInfo(+ dag_id=DAG_ID,+ schedule="@daily",+ doc="A doc does exist here",+ type_="",+ dated=False,+ provider_workflow=PROVIDER_WORKFLOW_INSTANCE,+ ),+ True,+ """+## Special Name++| DAG ID | Schedule Interval | Dated | Media Type(s) |+| --- | --- | --- | --- |+| [`sample_dag_123`](#sample_dag_123) | `@daily` | `False` | m1, m2 |+""",+ ),+ ],+)+def test_generate_type_subsection(dag_info, is_provider, expected):+ actual = dag_doc_generation.generate_type_subsection(+ "Special Name", [dag_info], is_provider+ )+ assert actual.strip() == expected.strip()+++def test_generate_dag_doc():+ expected = (+ dag_doc_generation.PREAMBLE+ + """\+ 1. [T1](#t1)++## T1++| DAG ID | Schedule Interval |+| --- | --- |+| `a` | `None` |+| [`b`](#b) | `None` |++"""+ + dag_doc_generation.MIDAMBLE+ + """\+ 1. [`b`](#b)+++## `b`++this one has a doc+"""+ )+ with (mock.patch(f"{_MODULE}.get_dags_info") as get_dags_info_mock,):+ # Return in reverse order to ensure they show up in the correct order+ get_dags_info_mock.return_value = [+ DagInfo("b", None, "this one has a doc", "t1", False, None),+ DagInfo("a", None, None, "t1", False, None),+ ]+ actual = dag_doc_generation.generate_dag_doc()+ assert actual == expected