Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ env:

jobs:
main:
permissions:
contents: read
pull-requests: read

runs-on: ubuntu-latest
timeout-minutes: 55
Expand All @@ -41,10 +44,8 @@ jobs:

steps:
- uses: actions/checkout@v4

- uses: actions/setup-node@v3
with:
node-version: 20.11.0
fetch-depth: 0

# Check if the repository is a fork
- name: Check if repository is a fork
Expand All @@ -63,10 +64,10 @@ jobs:
export AIRFLOW_PSQL_DB_MAIN="${{ secrets.CI_PSQL_DB }}"
fi

- name: Semantic Release Title Check
uses: osl-incubator/semantic-release-pr-title-check@v1.4.1
- name: Lint Commit Messages
uses: wagoid/commitlint-github-action@v6
with:
convention-name: conventionalcommits
configFile: commitlint.config.mjs

- uses: conda-incubator/setup-miniconda@v3
with:
Expand All @@ -89,6 +90,10 @@ jobs:
run: |
make linter

- name: Run Unit Tests
run: |
make test

- name: Create Docker network
run: |
docker network create infodengue-dev_infodengue
Expand Down
17 changes: 16 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ USER root

ARG HOST_UID
ARG HOST_GID
ARG PYSUS_REF=2.11.3

RUN apt-get update \
&& apt-get install -y \
Expand Down Expand Up @@ -71,7 +72,7 @@ ENV PATH "$PATH:/home/airflow/.local/bin"
ENV PATH "$PATH:/usr/bin/dirname"

COPY --chown=airflow scripts/entrypoint.sh /entrypoint.sh
COPY --chown=airflow pyproject.toml README.md scripts/requirements-vegetation-metrics.txt ${AIRFLOW_HOME}/
COPY --chown=airflow pyproject.toml poetry.lock README.md scripts/requirements-vegetation-metrics.txt scripts/requirements-pysus.txt ${AIRFLOW_HOME}/
RUN chmod +x /entrypoint.sh

USER airflow
Expand All @@ -87,4 +88,18 @@ RUN python3.12 -m venv /opt/airflow/envs/geospatial_env \
&& /opt/airflow/envs/geospatial_env/bin/pip install --no-cache-dir --upgrade pip setuptools wheel \
&& /opt/airflow/envs/geospatial_env/bin/pip install --no-cache-dir -r ${AIRFLOW_HOME}/requirements-vegetation-metrics.txt

# PySUS requires Python <3.14, so it lives in its own Python 3.12 interpreter
# (Airflow runs on 3.14). The management check/sync engine is excluded from the
# published wheel, so PySUS is installed from source and the management package
# is overlaid into site-packages afterwards.
RUN git clone --depth 1 --branch ${PYSUS_REF} https://github.com/AlertaDengue/PySUS.git /tmp/pysus-src \
&& python3.12 -m venv /opt/airflow/envs/pysus_env \
&& /opt/airflow/envs/pysus_env/bin/pip install --no-cache-dir --upgrade pip setuptools wheel \
&& /opt/airflow/envs/pysus_env/bin/pip install --no-cache-dir -r ${AIRFLOW_HOME}/requirements-pysus.txt \
&& /opt/airflow/envs/pysus_env/bin/pip install --no-cache-dir /tmp/pysus-src \
&& PYSUS_SITE="$(/opt/airflow/envs/pysus_env/bin/python -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')" \
&& cp -r /tmp/pysus-src/pysus/management "${PYSUS_SITE}/pysus/management" \
&& /opt/airflow/envs/pysus_env/bin/python -c "from pysus.management import SyncEngine; print('pysus management OK:', SyncEngine)" \
&& rm -rf /tmp/pysus-src

ENTRYPOINT [ "/entrypoint.sh" ]
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ env:
linter:
pre-commit run --all-files --verbose

.PHONY: test
test:
poetry run python -m unittest discover -s tests -t . -v

# -- Docker --
build:
set -e
Expand Down
158 changes: 158 additions & 0 deletions alertflow/dags/pysus_update.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
"""Check and update the PySUS S3 database mirrors.

PySUS requires Python <3.14, so it runs in its own interpreter
(``/opt/airflow/envs/pysus_env``) via ``@task.external_python``. The
``pysus.management`` package is excluded from the published wheel, so the
container installs PySUS from source and overlays that package.

The pipeline runs a dry-run ``check`` first and only ``apply`` (download,
convert, upload and catalog) the databases that actually need it. The
``SyncEngine`` is single-writer, so the DAG serialises runs
(``max_active_runs=1``).
"""

from __future__ import annotations

from datetime import datetime, timedelta

from airflow import DAG
from airflow.sdk import Variable, task

PYSUS_PYTHON = "/opt/airflow/envs/pysus_env/bin/python"

default_args = {
"owner": "airflow",
"depends_on_past": False,
"email_on_failure": False,
"email_on_retry": False,
"retries": 2,
"retry_delay": timedelta(minutes=10),
}

with DAG(
dag_id="PYSUS_UPDATE",
description="Check and update every PySUS S3 database mirror",
start_date=datetime(2026, 9, 28, 3, 0),
schedule="0 3 * * 1",
catchup=False,
max_active_runs=1,
tags=["pysus", "s3", "databases"],
default_args=default_args,
) as pysus_dag:

@task
def get_credentials() -> dict:
access = Variable.get("pysus_s3_access_key", deserialize_json=True)
secret = Variable.get("pysus_s3_secret_key", deserialize_json=True)
token = Variable.get("pysus_dadosgov_token", deserialize_json=True)
return {
"access_key": access.get("PYSUS_S3_ACCESS_KEY", ""),
"secret_key": secret.get("PYSUS_S3_SECRET_KEY", ""),
"dadosgov_token": token.get("PYSUS_DADOSGOV_TOKEN", ""),
}

@task.external_python(python=PYSUS_PYTHON, task_id="check_databases")
def check_databases(credentials: dict) -> dict:
"""Dry-run: classify every file as missing/outdated/current."""
import logging

from pysus.api.client import _run_sync
from pysus.management.sync import SyncEngine

log = logging.getLogger("pysus_update.check")

engine = SyncEngine(
access_key=credentials["access_key"],
secret_key=credentials["secret_key"],
dadosgov_token=credentials["dadosgov_token"],
)

async def _run() -> dict:
await engine.__aenter__(lock=False)
try:
checks = await engine.check()
finally:
await engine.__aexit__(None, None, None)
return {ds: check.summary() for ds, check in checks.items()}

summary = _run_sync(_run())

log.info("PySUS check finished for %d database(s)", len(summary))
for dataset in sorted(summary):
stats = summary[dataset]
log.info(
" %-22s missing=%-6d outdated=%-6d current=%-6d%s",
dataset,
stats["missing"],
stats["outdated"],
stats["current"],
" [needs update]" if stats["needs_update"] else "",
)

pending = sorted(ds for ds, s in summary.items() if s["needs_update"])
listing = ", ".join(pending)
log.info("%d database(s) need updating: %s", len(pending), listing)
return summary

@task.external_python(python=PYSUS_PYTHON, task_id="apply_updates")
def apply_updates(credentials: dict, check_summary: dict) -> dict:
"""Download, convert, upload and catalog the pending files."""
import logging

from pysus.api.client import _run_sync
from pysus.management.sync import SyncEngine

log = logging.getLogger("pysus_update.apply")

pending = sorted(
ds
for ds, summary in (check_summary or {}).items()
if summary.get("needs_update")
)
if not pending:
log.info("All PySUS databases are up to date; nothing to apply.")
return {"total": 0, "uploaded": 0, "failed": 0, "datasets": []}

log.info(
"Applying updates to %d database(s): %s",
len(pending),
", ".join(pending),
)

counts: dict[str, int] = {}

def on_outcome(outcome) -> None:
counts[outcome.status] = counts.get(outcome.status, 0) + 1
if outcome.status in ("failed", "needs_token"):
log.warning("[%s] %s", outcome.status, outcome.detail)
processed = sum(counts.values())
if processed % 100 == 0:
breakdown = ", ".join(
f"{key}={value}" for key, value in sorted(counts.items())
)
log.info("progress: %d processed (%s)", processed, breakdown)

engine = SyncEngine(
access_key=credentials["access_key"],
secret_key=credentials["secret_key"],
dadosgov_token=credentials["dadosgov_token"],
)

async def _run() -> dict:
async with engine:
report = await engine.run(
datasets=pending,
workers=8,
ftp_connections=4,
on_outcome=on_outcome,
)
return report.summary()

summary = _run_sync(_run())
summary["datasets"] = pending
log.info("PySUS apply finished: %s", summary)
return summary

credentials = get_credentials()
check_result = check_databases(credentials)
apply_updates(credentials, check_result)
9 changes: 9 additions & 0 deletions commitlint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default {
extends: ["@commitlint/config-conventional"],
// GitHub-generated merge commits are not conventional; skip them.
ignores: [(message) => message.startsWith("Merge ")],
rules: {
// Release/tooling commit bodies can contain long URLs and lines.
"body-max-line-length": [0, "always", 100],
},
};
3 changes: 3 additions & 0 deletions docker-compose.dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ x-airflow-common: &airflow-common
AIRFLOW_HOME: ${AIRFLOW_HOME:-/opt/airflow}
AIRFLOW_VAR_PSQL_MAIN_URI: '{"PSQL_MAIN_URI":"${PSQL_URI_MAIN}"}'
AIRFLOW_VAR_CDSAPI_KEY: '{"CDSAPI_KEY":"${CDSAPI_KEY}"}'
AIRFLOW_VAR_PYSUS_S3_ACCESS_KEY: '{"PYSUS_S3_ACCESS_KEY":"${PYSUS_S3_ACCESS_KEY}"}'
AIRFLOW_VAR_PYSUS_S3_SECRET_KEY: '{"PYSUS_S3_SECRET_KEY":"${PYSUS_S3_SECRET_KEY}"}'
AIRFLOW_VAR_PYSUS_DADOSGOV_TOKEN: '{"PYSUS_DADOSGOV_TOKEN":"${PYSUS_DADOSGOV_TOKEN}"}'
# --
AIRFLOW__SMTP__SMTP_HOST: ${AIRFLOW__SMTP__SMTP_HOST:-''}
AIRFLOW__SMTP__SMTP_STARTTLS: ${AIRFLOW__SMTP__SMTP_STARTTLS:-true}
Expand Down
5 changes: 4 additions & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# AIRFLOW__CORE__FERNET_KEY, AIRFLOW__CORE__INTERNAL_API_SECRET_KEY,
# AIRFLOW__WEBSERVER__SECRET_KEY, AIRFLOW__API_AUTH__JWT_SECRET,
# _AIRFLOW_WWW_USER_USERNAME, _AIRFLOW_WWW_USER_PASSWORD, plus the
# PSQL_*/CDSAPI_KEY values used by the DAGs.
# PSQL_*/CDSAPI_KEY/PYSUS_* values used by the DAGs.
# - In the Coolify UI, set the `airflow-apiserver` service's Domains field to
# https://alertflow.dengue.mat.br:8081 (the suffix is the internal container
# port) and set AIRFLOW__WEBSERVER__BASE_URL=https://alertflow.dengue.mat.br.
Expand All @@ -33,6 +33,9 @@ x-airflow-common: &airflow-common
AIRFLOW_HOME: /opt/airflow
AIRFLOW_VAR_PSQL_MAIN_URI: '{"PSQL_MAIN_URI":"${PSQL_URI_MAIN}"}'
AIRFLOW_VAR_CDSAPI_KEY: '{"CDSAPI_KEY":"${CDSAPI_KEY}"}'
AIRFLOW_VAR_PYSUS_S3_ACCESS_KEY: '{"PYSUS_S3_ACCESS_KEY":"${PYSUS_S3_ACCESS_KEY}"}'
AIRFLOW_VAR_PYSUS_S3_SECRET_KEY: '{"PYSUS_S3_SECRET_KEY":"${PYSUS_S3_SECRET_KEY}"}'
AIRFLOW_VAR_PYSUS_DADOSGOV_TOKEN: '{"PYSUS_DADOSGOV_TOKEN":"${PYSUS_DADOSGOV_TOKEN}"}'
# --
AIRFLOW__SMTP__SMTP_HOST: ${AIRFLOW__SMTP__SMTP_HOST:-''}
AIRFLOW__SMTP__SMTP_STARTTLS: ${AIRFLOW__SMTP__SMTP_STARTTLS:-true}
Expand Down
5 changes: 5 additions & 0 deletions env.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ PSQL_URI_MAIN=postgresql://${PSQL_USER_MAIN}:${PSQL_PASSWORD_MAIN}@${PSQL_HOST_M
# https://cds.climate.copernicus.eu/user/{MY_USER}
CDSAPI_KEY=${CDSAPI_KEY}

# PySUS S3 mirror and dados.gov.br credentials
PYSUS_S3_ACCESS_KEY=${PYSUS_S3_ACCESS_KEY}
PYSUS_S3_SECRET_KEY=${PYSUS_S3_SECRET_KEY}
PYSUS_DADOSGOV_TOKEN=${PYSUS_DADOSGOV_TOKEN}

# Extras
AIRFLOW__CORE__FERNET_KEY=${AIRFLOW__CORE__FERNET_KEY}
AIRFLOW__CORE__INTERNAL_API_SECRET_KEY=${AIRFLOW__CORE__INTERNAL_API_SECRET_KEY}
Expand Down
10 changes: 10 additions & 0 deletions scripts/requirements-pysus.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Runtime dependencies for the PySUS external interpreter (Python 3.12).
#
# PySUS itself is installed from source at the tag defined by the PYSUS_REF
# build arg in the Dockerfile, because the `pysus.management` package (the
# database check/sync engine) is excluded from the published PyPI wheel.
#
# These two packages are what @task.external_python needs to communicate with
# the Airflow task runner; Airflow itself (Python 3.14) cannot host PySUS.
apache-airflow-task-sdk==1.2.1
pendulum==3.2.0
Empty file added tests/__init__.py
Empty file.
Loading
Loading