Skip to content

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

Use Airflow base Docker image (#874)

Madison Swain-Bowdenf42555b19ea2
diff --git a/README.md b/README.md
index 25722aa75..3aca71b5f 100644
--- a/README.md
+++ b/README.md
@@ -142,9 +142,9 @@ and some networking setup so that they can communicate. Note:
databases and tables to emulate the production environment. It also provides a
database for Airflow to store its running state.
- The directory containing all modules files (including DAGs, dependencies, and other
- tooling) will be mounted to the directory `/usr/local/airflow/openverse_catalog`
+ tooling) will be mounted to the directory `/opt/airflow/openverse_catalog`
in the container `openverse_catalog_webserver_1`. On production, only the DAGs folder
- will be mounted, e.g. `/usr/local/airflow/openverse_catalog/dags`.
+ will be mounted, e.g. `/opt/airflow/openverse_catalog/dags`.
The various services can be accessed using these links:
@@ -208,6 +208,12 @@ To fully recreate everything from the ground up, you can use:
just recreate
```
+> **Note**:
+> Any recipes or scripts which output files to the container's mounted volumes will
+> need to be run as the root user. This can be done with the `DC_USER=root`
+> environment variable for `just` recipes. For example, see the
+> [generate-dag-docs recipe](https://github.com/WordPress/openverse-catalog/blob/c9be67e483e49e9eda7cd21b52bcde8857cd3922/justfile#L126).
+
[justfile]: justfile
[dockercompose]: docker-compose.yml
[cc_airflow]: openverse_catalog/
diff --git a/docker-compose.override.yml b/docker-compose.override.yml
index e2da3531b..2a64d87f0 100644
--- a/docker-compose.override.yml
+++ b/docker-compose.override.yml
@@ -1,5 +1,23 @@
version: "3"
+# Common build configuration for Airflow
+# Extension field, see https://docs.docker.com/compose/compose-file/compose-file-v3/#extension-fields
+x-airflow-common: &airflow-common
+ restart: on-failure
+ depends_on:
+ - postgres
+ - s3
+ build:
+ context: .
+ args:
+ - REQUIREMENTS_FILE=requirements_dev.txt
+ - PROJECT_PY_VERSION=${PROJECT_PY_VERSION}
+ - PROJECT_AIRFLOW_VERSION=${PROJECT_AIRFLOW_VERSION}
+ dockerfile: docker/airflow/Dockerfile
+ volumes:
+ - ./openverse_catalog:/opt/airflow/openverse_catalog
+ - ipython:/home/airflow/.ipython
+
services:
# Services only needed for local development
postgres:
@@ -76,26 +94,29 @@ services:
exit 0;
"
+ # Dev changes for the scheduler
+ scheduler:
+ <<: *airflow-common
+ depends_on:
+ - postgres
+ - s3
+ environment:
+ _AIRFLOW_WWW_USER_CREATE: "true"
+ _AIRFLOW_WWW_USER_USERNAME: airflow
+ _AIRFLOW_WWW_USER_PASSWORD: airflow
+ _AIRFLOW_WWW_USER_FIRSTNAME: Air
+ _AIRFLOW_WWW_USER_LASTNAME: Flow
+ _AIRFLOW_WWW_USER_EMAIL: [email protected]
+
# Dev changes for the webserver container
webserver:
+ <<: *airflow-common
depends_on:
- postgres
- s3
- build:
- context: .
- args:
- - REQUIREMENTS_FILE=requirements_dev.txt
- - PROJECT_PY_VERSION=${PROJECT_PY_VERSION}
- - PROJECT_AIRFLOW_VERSION=${PROJECT_AIRFLOW_VERSION}
- dockerfile: docker/airflow/Dockerfile
- restart: on-failure
- # This command ensures an admin account is created on startup
- command: init
- volumes:
- - ./openverse_catalog:/usr/local/airflow/openverse_catalog
- stdin_open: true
- tty: true
+ - scheduler
volumes:
postgres:
minio:
+ ipython:
diff --git a/docker-compose.yml b/docker-compose.yml
index c0885e646..9abaef5a3 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,15 +1,31 @@
version: "3"
services:
+ scheduler:
+ image: ghcr.io/wordpress/openverse-catalog:${DOCKER_IMAGE_TAG:-latest}
+ env_file: .env
+ restart: always
+ environment:
+ # Upgrade the DB on startup
+ _AIRFLOW_DB_UPGRADE: "true"
+ command: scheduler
+ expose:
+ - "8793" # Used for fetching logs
+ volumes:
+ - airflow:/var/workflow_output
+ - ./openverse_catalog/dags:/opt/airflow/openverse_catalog/dags
+
webserver:
image: ghcr.io/wordpress/openverse-catalog:${DOCKER_IMAGE_TAG:-latest}
+ depends_on:
+ - scheduler
env_file: .env
restart: always
+ command: webserver
ports:
- "${AIRFLOW_PORT}:8080"
volumes:
- - airflow:/var/workflow_output
- - ./openverse_catalog/dags:/usr/local/airflow/openverse_catalog/dags
+ - ./openverse_catalog/dags:/opt/airflow/openverse_catalog/dags
volumes:
airflow:
diff --git a/docker/airflow/Dockerfile b/docker/airflow/Dockerfile
index 2a4200dc9..f10ee3540 100644
--- a/docker/airflow/Dockerfile
+++ b/docker/airflow/Dockerfile
@@ -1,17 +1,18 @@
# Cannot use $PYTHON_VERSION because that is overwritten by the base image
# with the patch version (we only care about major and minor version)
ARG PROJECT_PY_VERSION
+ARG PROJECT_AIRFLOW_VERSION
-FROM python:${PROJECT_PY_VERSION}-slim
+FROM apache/airflow:slim-${PROJECT_AIRFLOW_VERSION}-python${PROJECT_PY_VERSION}
# Build-time arguments, with sensible defaults
ARG REQUIREMENTS_FILE=requirements_prod.txt
# Path configurations
-ENV AIRFLOW_HOME=/usr/local/airflow
+ENV AIRFLOW_HOME=/opt/airflow
ENV DAGS_FOLDER=${AIRFLOW_HOME}/openverse_catalog/dags
ENV PYTHONPATH=${DAGS_FOLDER}
-ENV PATH=/usr/local/airflow/.local/bin:$PATH
+ENV PATH=${AIRFLOW_HOME}/.local/bin:$PATH
# Container optimizations
ENV PIPNOCACHEDIR=1
@@ -33,21 +34,25 @@ ENV AIRFLOW__LOGGING__REMOTE_LOG_CONN_ID=aws_default
ENV AIRFLOW__LOGGING__REMOTE_BASE_LOG_FOLDER=s3://openverse-airflow-logs
-RUN apt-get update && apt-get -yqq upgrade && apt-get -yqq install \
+USER root
+RUN apt-get update && apt-get -yqq install \
build-essential \
libpq-dev \
libffi-dev \
&& apt-get autoremove -y \
&& rm -rf /var/lib/apt/lists/*
-RUN useradd -m -d ${AIRFLOW_HOME} airflow && \
- mkdir -p ${OUTPUT_DIR} && \
- chown airflow:airflow ${OUTPUT_DIR}
+
+# Create and set the ownership of directories so airflow user can write to them
+# The .ipython directories are not needed in production but it's easier to perform
+# this step here while we're doing it for the output directory
+RUN mkdir -p ${OUTPUT_DIR} /home/airflow/.ipython && \
+ chown airflow ${OUTPUT_DIR} /home/airflow/.ipython
+
USER airflow
WORKDIR ${AIRFLOW_HOME}
# Always add the prod req because the dev reqs depend on it for deduplication
COPY ${REQUIREMENTS_FILE} requirements_prod.txt ${AIRFLOW_HOME}/
-COPY docker/airflow/wait_for_db.py /opt/airflow/
# args go out of scope when a new build stage starts so it must be redeclared here
ARG PROJECT_PY_VERSION
@@ -60,5 +65,4 @@ RUN pip install --user -r ${REQUIREMENTS_FILE} -c ${CONSTRAINTS_FILE}
COPY docker/airflow/entrypoint.sh /opt/airflow/entrypoint.sh
-ENTRYPOINT ["/opt/airflow/entrypoint.sh"]
-CMD ["server"]
+ENTRYPOINT ["/usr/bin/dumb-init", "--", "/opt/airflow/entrypoint.sh"]
diff --git a/docker/airflow/entrypoint.sh b/docker/airflow/entrypoint.sh
index 742134beb..2e66cb8dc 100755
--- a/docker/airflow/entrypoint.sh
+++ b/docker/airflow/entrypoint.sh
@@ -11,14 +11,17 @@ function help_text() {
\ / | | | | |/ | | \ . ) |
`-' ' `--' ' ' ' `--' ' ' `-' `--'
-Docker entrypoint script for Openverse Airflow. Unless specified, all commands
-will wait for the database to be ready and will upgrade the Airflow schema.
+Docker entrypoint script for Openverse Airflow. This uses the upstream Airflow
+entrypoint under the hood. For help running commands, see
+https://airflow.apache.org/docs/docker-stack/entrypoint.html#executing-commands
+Unless specified, all commands will wait for the database to be ready and
+will upgrade the Airflow schema.
Usage:
help - print this help text and exit
- init - create an admin user account before starting the scheduler+webserver
- server - start the scheduler+webserver
- (anything else) - run the command provided
+ bash [...] - drop into a bash shell or run a bash command/script
+ python [ ... ] - drop into a python shell or run a python command/script
+ (anything else) - interpreted as an argument to "airflow [ argument ]"
END
}
@@ -58,27 +61,4 @@ while read -r var_string; do
# only include airflow connections with http somewhere in the string
done < <(env | grep "^AIRFLOW_CONN[A-Z_]\+=http.*$")
-# Wait for postgres
-header "WAITING FOR POSTGRES"
-python /opt/airflow/wait_for_db.py
-# Upgrade the database -- command is idempotent.
-header "MIGRATING DATABASE"
-airflow db upgrade
-if [[ "$1" == "init" ]]; then
- header "CREATING ADMIN USER"
- airflow users create -r Admin -u airflow -f Air -l Flow -p airflow --email [email protected]
-fi
-
-case "$1" in
- init|server|"")
- # Start scheduler and webserver in same container
- header "STARTING AIRFLOW"
- airflow scheduler &
- exec airflow webserver
- ;;
- *)
- # The command is something like bash, not an airflow subcommand. Just run it in the right environment.
- header "RUNNING \"$*\""
- exec "$@"
- ;;
-esac
+exec /entrypoint "$@"
diff --git a/docker/airflow/wait_for_db.py b/docker/airflow/wait_for_db.py
deleted file mode 100644
index e7f61fbc9..000000000
--- a/docker/airflow/wait_for_db.py
+++ /dev/null
@@ -1,50 +0,0 @@
-import logging
-import os
-import sys
-import time
-
-import sqlalchemy as db
-
-
-logging.basicConfig(
- format="%(asctime)s - %(name)s - %(levelname)s: %(message)s", level=logging.INFO
-)
-
-logger = logging.getLogger(__file__)
-
-TRIES = 10
-CONN_ID = os.getenv("AIRFLOW__DATABASE__SQL_ALCHEMY_CONN")
-
-
-def main():
- db_available = _wait_for_db()
- if not db_available:
- logger.error(f"Could not connect to DB using conn_id {CONN_ID}")
- sys.exit(1)
- else:
- sys.exit(0)
-
-
-def _wait_for_db(tries=TRIES, conn_id=CONN_ID):
- if not conn_id:
- raise ValueError("MetaDB connection ID not provided")
- engine = db.create_engine(conn_id)
- success = False
- logger.info(f"Testing DB connection {conn_id}")
- for i in range(1, tries + 1):
- try:
- connection = engine.connect()
- connection.close()
- success = True
- break
- except db.exc.OperationalError as oe:
- logger.info("DB not yet available")
- logger.debug(f"Error was: {oe}")
- logger.info(f"Waiting {i} seconds...")
- # Back off with each loop to give the DB a chance to appear.
- time.sleep(i)
- return success
-
-
-if __name__ == "__main__":
- main()
diff --git a/env.template b/env.template
index 48e107306..aa83106ab 100644
--- a/env.template
+++ b/env.template
@@ -15,6 +15,8 @@ AIRFLOW__CORE__HIDE_SENSITIVE_VAR_CONN_FIELDS=False
# Use the following python code to generate a fernet key for production
# python -c "import base64, os; print(base64.urlsafe_b64encode(os.urandom(32)).decode())"
# AIRFLOW__CORE__FERNET_KEY=
+# CSRF key https://airflow.apache.org/docs/apache-airflow/stable/configurations-ref.html#secret-key
+AIRFLOW__WEBSERVER__SECRET_KEY=sample-secret-key=
# Executor to use
AIRFLOW__CORE__EXECUTOR=LocalExecutor
# Environment this instance is being run in
diff --git a/justfile b/justfile
index 24ccc7dd7..5a2035ce6 100644
--- a/justfile
+++ b/justfile
@@ -8,7 +8,8 @@ IS_PROD := env_var_or_default("IS_PROD", "")
DOCKER_FILES := "--file=docker-compose.yml" + (
if IS_PROD != "true" {" --file=docker-compose.override.yml"} else {""}
)
-SERVICE := "webserver"
+SERVICE := env_var_or_default("SERVICE", "scheduler")
+DC_USER := env_var_or_default("DC_USER", "airflow")
export PROJECT_PY_VERSION := `grep '# PYTHON' requirements_prod.txt | awk -F= '{print $2}'`
export PROJECT_AIRFLOW_VERSION := `grep '^apache-airflow' requirements_prod.txt | awk -F= '{print $3}'`
@@ -40,17 +41,21 @@ install: check-py-version
dotenv:
@([ ! -f .env ] && cp env.template .env) || true
+# Run docker compose with the specified command
+_dc *args:
+ docker-compose {{ DOCKER_FILES }} {{ args }}
+
# Build all (or specified) container(s)
build service="": dotenv
- docker-compose {{ DOCKER_FILES }} build {{ service }}
+ @just _dc build {{ service }}
# Bring all Docker services up
up flags="": dotenv
- docker-compose {{ DOCKER_FILES }} up -d {{ flags }}
+ @just _dc up -d {{ flags }}
# Take all Docker services down
down flags="":
- docker-compose {{ DOCKER_FILES }} down {{ flags }}
+ @just _dc down {{ flags }}
# Recreate all volumes and containers from scratch
recreate: dotenv
@@ -59,13 +64,12 @@ recreate: dotenv
# Show logs of all, or named, Docker services
logs service="": up
- docker-compose {{ DOCKER_FILES }} logs -f {{ service }}
+ @just _dc logs -f {{ service }}
# Pull, build, and deploy all services
deploy:
- @just down
-git pull
- @just build
+ @just pull
@just up
# Run pre-commit on all files
@@ -79,11 +83,11 @@ _deps:
# Mount the tests directory and run a particular command
@_mount-tests command: _deps
# The test directory is mounted into the container only during testing
- docker-compose {{ DOCKER_FILES }} run \
+ @just _dc run \
-e AIRFLOW_VAR_INGESTION_LIMIT=1000000 \
- -v {{ justfile_directory() }}/tests:/usr/local/airflow/tests/ \
- -v {{ justfile_directory() }}/docker:/usr/local/airflow/docker/ \
- -v {{ justfile_directory() }}/pytest.ini:/usr/local/airflow/pytest.ini \
+ -v {{ justfile_directory() }}/tests:/opt/airflow/tests/ \
+ -v {{ justfile_directory() }}/pytest.ini:/opt/airflow/pytest.ini \
+ -v {{ justfile_directory() }}/docker:/opt/airflow/docker/ \
--rm \
{{ SERVICE }} \
{{ command }}
@@ -94,34 +98,33 @@ test-session:
# Run pytest using the webserver image
test *pytestargs:
- @just _mount-tests "/usr/local/airflow/.local/bin/pytest {{ pytestargs }}"
+ @just _mount-tests "bash -c \'pytest {{ pytestargs }}\'"
# Open a shell into the webserver container
-shell: up
- docker-compose {{ DOCKER_FILES }} exec {{ SERVICE }} /bin/bash
+shell user="airflow": up
+ @just _dc exec -u {{ user }} {{ SERVICE }} /bin/bash
# Launch an IPython REPL using the webserver image
ipython: _deps
- docker-compose {{ DOCKER_FILES }} run \
+ @just _dc run \
--rm \
- -w /usr/local/airflow/openverse_catalog/dags \
- -v {{ justfile_directory() }}/.ipython:/usr/local/airflow/.ipython:z \
+ -w /opt/airflow/openverse_catalog/dags \
{{ SERVICE }} \
- /usr/local/airflow/.local/bin/ipython
+ bash -c \'ipython\'
-# Run a given command using the webserver image
+# Run a given command in bash using the scheduler image
run *args: _deps
- docker-compose {{ DOCKER_FILES }} run --rm {{ SERVICE }} {{ args }}
+ @just _dc run --rm -u {{ DC_USER }} {{ SERVICE }} bash -c \'{{ args }}\'
# Launch a pgcli shell on the postgres container (defaults to openledger) use "airflow" for airflow metastore
db-shell args="openledger": up
- docker-compose {{ DOCKER_FILES }} exec postgres pgcli {{ args }}
+ @just _dc 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
+ DC_USER=root just run 'python openverse_catalog/utilities/dag_doc_gen/dag_doc_generation.py \&\& chmod 666 /opt/airflow/openverse_catalog/utilities/dag_doc_gen/DAGs.md'
# 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
diff --git a/openverse_catalog/templates/create_provider_ingester.py b/openverse_catalog/templates/create_provider_ingester.py
index 74f8e61a1..f37f1ee05 100644
--- a/openverse_catalog/templates/create_provider_ingester.py
+++ b/openverse_catalog/templates/create_provider_ingester.py
@@ -55,19 +55,26 @@ def _render_file(
endpoint: str,
media_types: list[str],
name: str,
+ repo_path: Path,
):
with target.open("w", encoding="utf-8") as target_file:
filled_template = _get_filled_template(
template_path, provider, endpoint, media_types
)
target_file.write(filled_template)
- print(f"{name + ':':<18} {target.relative_to(REPO_PATH)}")
+ print(f"{name + ':':<18} {target.relative_to(repo_path)}")
-def fill_template(provider, endpoint, media_types):
+def fill_template(
+ provider: str,
+ endpoint: str,
+ media_types: list[str],
+ project_path: Path = PROJECT_PATH,
+ repo_path: Path = REPO_PATH,
+):
print(f"Creating files in {REPO_PATH}")
- dags_path = PROJECT_PATH / "dags" / "providers"
+ dags_path = project_path / "dags" / "providers"
api_path = dags_path / "provider_api_scripts"
filename = inflection.underscore(provider)
@@ -81,11 +88,12 @@ def fill_template(provider, endpoint, media_types):
endpoint,
media_types,
"API script",
+ repo_path,
)
# Render the tests
script_template_path = TEMPLATES_PATH / "template_test.py_template"
- tests_path = REPO_PATH / "tests"
+ tests_path = repo_path / "tests"
# Mirror the directory structure, but under the "tests" top level directory
test_script_path = tests_path.joinpath(*api_path.parts[-3:]) / f"test_{filename}.py"
@@ -96,6 +104,7 @@ def fill_template(provider, endpoint, media_types):
endpoint,
media_types,
"API script test",
+ repo_path,
)
print(
diff --git a/pytest.ini b/pytest.ini
index bf9d961c3..7263d4702 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -24,7 +24,7 @@ addopts =
# Subdag
# This appears to be coming from Airflow internals during testing as a result of
# loading the example DAGs:
-# /usr/local/airflow/.local/lib/python3.10/site-packages/airflow/example_dags/example_subdag_operator.py:43: RemovedInAirflow3Warning
+# /opt/airflow/.local/lib/python3.10/site-packages/airflow/example_dags/example_subdag_operator.py:43: RemovedInAirflow3Warning
# distutils
# Warning in dependency, nothing we can do
# flask
diff --git a/tests/templates/test_create_provider_ingester.py b/tests/templates/test_create_provider_ingester.py
index 1d0c03635..af45caedd 100644
--- a/tests/templates/test_create_provider_ingester.py
+++ b/tests/templates/test_create_provider_ingester.py
@@ -1,5 +1,3 @@
-from pathlib import Path
-
import pytest
from openverse_catalog.templates import create_provider_ingester
@@ -50,22 +48,33 @@ def test_sanitize_provider(provider, expected_result):
assert actual_result == expected_result
-def test_files_created():
+def test_files_created(tmp_path):
+ # Make temporary output directorys for testing
+ dags_path = tmp_path / "openverse_catalog" / "dags" / "providers"
+ (dags_path / "provider_api_scripts").mkdir(parents=True)
+ test_path = tmp_path / "tests"
+ (test_path / "dags" / "providers" / "provider_api_scripts").mkdir(parents=True)
+
provider = "foobar_industries"
endpoint = "https://myfakeapi/v1"
- media_type = "image"
+ media_types = ["image"]
- dags_path = create_provider_ingester.TEMPLATES_PATH.parent / "dags" / "providers"
expected_provider = dags_path / "provider_api_scripts" / "foobar_industries.py"
expected_test = (
- Path(__file__).parents[1]
+ test_path
/ "dags"
/ "providers"
/ "provider_api_scripts"
/ "test_foobar_industries.py"
)
try:
- create_provider_ingester.fill_template(provider, endpoint, media_type)
+ create_provider_ingester.fill_template(
+ provider,
+ endpoint,
+ media_types,
+ project_path=(tmp_path / "openverse_catalog"),
+ repo_path=tmp_path,
+ )
assert expected_provider.exists()
assert expected_test.exists()
finally: