al-devops-kit 0.4.0__tar.gz → 0.5.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- al_devops_kit-0.5.0/PKG-INFO +130 -0
- al_devops_kit-0.5.0/README.md +113 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/pyproject.toml +2 -2
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit/dags_installer.py +9 -0
- al_devops_kit-0.5.0/src/al_devops_kit/deploy_steps.py +393 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit/templates/v3.0.0/_airflow_installer_dag.py +1 -1
- al_devops_kit-0.5.0/src/al_devops_kit/templates/v4.0.0/_airflow_deploy_dag.py +405 -0
- al_devops_kit-0.5.0/src/al_devops_kit.egg-info/PKG-INFO +130 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit.egg-info/SOURCES.txt +5 -1
- al_devops_kit-0.5.0/tests/test_airflow_deploy_dag.py +336 -0
- al_devops_kit-0.5.0/tests/test_deploy_steps.py +332 -0
- al_devops_kit-0.4.0/PKG-INFO +0 -85
- al_devops_kit-0.4.0/README.md +0 -68
- al_devops_kit-0.4.0/src/al_devops_kit.egg-info/PKG-INFO +0 -85
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/LICENSE +0 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/setup.cfg +0 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit/__init__.py +0 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit/__main__.py +0 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit.egg-info/dependency_links.txt +0 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit.egg-info/entry_points.txt +0 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit.egg-info/requires.txt +0 -0
- {al_devops_kit-0.4.0 → al_devops_kit-0.5.0}/src/al_devops_kit.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: al-devops-kit
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Airflow deploy DAG and CLI: sync repos, install requirements and run each repo's deploy steps on a running Airflow.
|
|
5
|
+
Author-email: AL Data Labs <pypi@aldatalabs.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://aldatalabs.com
|
|
8
|
+
Keywords: airflow,devops,dags,deployment,ubuntu
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
11
|
+
Classifier: Topic :: System :: Installation/Setup
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: al-data-utils>=0.3.2
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# al-devops-kit
|
|
19
|
+
|
|
20
|
+
Airflow bootstrap tooling: a versioned deploy DAG plus a CLI that installs it.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install al-devops-kit
|
|
26
|
+
al-devops-kit copy-dags /opt/airflow/dags
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Python 3.10+. Install into the Airflow virtualenv. `al-data-utils` is pulled in
|
|
30
|
+
automatically; `apache-airflow` 3.x is expected from the host environment.
|
|
31
|
+
|
|
32
|
+
## CLI
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
al-devops-kit copy-dags <dags_dir> [--version vX.Y.Z] [--force]
|
|
36
|
+
al-devops-kit list-versions
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`copy-dags` copies the deploy DAG template into the given dags folder.
|
|
40
|
+
Existing files are overwritten only when their content differs.
|
|
41
|
+
|
|
42
|
+
## Deploy DAG
|
|
43
|
+
|
|
44
|
+
`_airflow_deploy_dag.py` deploys the repos listed in `/opt/airflow/.repos/repos.yml`:
|
|
45
|
+
|
|
46
|
+
| Task | What it does |
|
|
47
|
+
|---|---|
|
|
48
|
+
| `load_config` | reads `repos.yml` |
|
|
49
|
+
| `sync_repos` | `git fetch`, then checks out the head of each repo's branch (detached, by SHA) |
|
|
50
|
+
| `install_requirements` | merges the repos' `requirements.txt`, pip-installs into the Airflow venv |
|
|
51
|
+
| `run_deploy_steps` | runs each repo's deploy steps, in the order written |
|
|
52
|
+
|
|
53
|
+
`repos.yml`:
|
|
54
|
+
|
|
55
|
+
```yaml
|
|
56
|
+
venv_pip: /opt/airflow/.venv/bin/pip
|
|
57
|
+
schedule: '@daily' # optional; without it the DAG runs only by hand
|
|
58
|
+
repos:
|
|
59
|
+
- name: my-dags
|
|
60
|
+
url: git@github.com:<org>/<repo>.git # SSH + read-only deploy key, no token in the URL
|
|
61
|
+
branch: main
|
|
62
|
+
dags_path: dags/
|
|
63
|
+
requirements: requirements.txt
|
|
64
|
+
require_confirm_sha: false # true: a run needs the param confirm_sha
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
- A scheduled run skips a repo whose branch head is already deployed, and a head
|
|
68
|
+
that failed before. A manual run always deploys.
|
|
69
|
+
- `require_confirm_sha: true`: the run param `confirm_sha` must be the first 8+
|
|
70
|
+
characters of the branch head. It is checked before anything is checked out
|
|
71
|
+
or installed.
|
|
72
|
+
|
|
73
|
+
### Deploy steps
|
|
74
|
+
|
|
75
|
+
`airflow_deploy.yaml` in the repo root (optional):
|
|
76
|
+
|
|
77
|
+
```yaml
|
|
78
|
+
deploy_steps:
|
|
79
|
+
- name: deploy_database # any shell command, cwd = repo root
|
|
80
|
+
run: python -m deploy apply
|
|
81
|
+
timeout: 7200 # seconds, optional (default 3600)
|
|
82
|
+
- name: copy_package_dags
|
|
83
|
+
run: python -m al_data_core copy-dags $AIRFLOW_DAGS_DIR
|
|
84
|
+
- name: sync_repo_dags # repo dags_path -> Airflow dags folder
|
|
85
|
+
deploy_dags:
|
|
86
|
+
keep_files: # not from this repo; never deleted
|
|
87
|
+
- data_core_dag.py
|
|
88
|
+
- data_core_config_engine_dag.py
|
|
89
|
+
- name: finish_deploy
|
|
90
|
+
run: python -m deploy finish
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- Steps run in the order written. A failed step stops the deploy: later steps do not run.
|
|
94
|
+
- `name`: `[a-z0-9_]+`, unique. Exactly one `deploy_dags` step.
|
|
95
|
+
- `run`: on timeout the whole process group gets SIGTERM, then SIGKILL after 30 s.
|
|
96
|
+
- `deploy_dags` makes the dags folder equal to the repo: copies new and changed
|
|
97
|
+
files, deletes every other file. Not deleted: `keep_files` of any repo in `repos.yml`
|
|
98
|
+
(a file, or a folder with everything under it), files of the other repos, the
|
|
99
|
+
deploy DAG itself, `.configs/`. Nothing to keep: `deploy_dags: true`.
|
|
100
|
+
- A DAG file from a package that is not in `keep_files` is deleted by the step.
|
|
101
|
+
- Without the file the deploy is a single `deploy_dags` step.
|
|
102
|
+
|
|
103
|
+
Environment of a `run` step:
|
|
104
|
+
|
|
105
|
+
| Variable | Value |
|
|
106
|
+
|---|---|
|
|
107
|
+
| `AIRFLOW_DAGS_DIR` | Airflow dags folder |
|
|
108
|
+
| `DEPLOY_REPO_NAME`, `DEPLOY_REPO_DIR`, `DEPLOY_BRANCH` | the repo being deployed |
|
|
109
|
+
| `DEPLOY_SHA`, `DEPLOY_PREVIOUS_SHA` | commit being deployed; last successfully deployed commit |
|
|
110
|
+
| `DEPLOY_CONFIRM_SHA` | run param `confirm_sha` |
|
|
111
|
+
| `DEPLOY_RUN_TYPE` | `manual` or `scheduled` |
|
|
112
|
+
| `DEPLOY_DAG_ID` | `_airflow_deploy_dag` |
|
|
113
|
+
| `DEPLOY_OPT_<KEY>` | one per entry of the run param `options` |
|
|
114
|
+
|
|
115
|
+
The Airflow venv `bin` is first in `PATH`, so `python` is the Airflow Python.
|
|
116
|
+
|
|
117
|
+
### Legacy
|
|
118
|
+
|
|
119
|
+
`requirements_post_install.yaml` with `package_dags:` still works when
|
|
120
|
+
`airflow_deploy.yaml` is absent: the listed packages copy their DAGs first, then
|
|
121
|
+
the repo DAGs are deployed. New repos should use `airflow_deploy.yaml`.
|
|
122
|
+
|
|
123
|
+
## Repository extras
|
|
124
|
+
|
|
125
|
+
The source repository also contains an Ansible playbook for a single-VM
|
|
126
|
+
Airflow install on Ubuntu. It is not part of the PyPI package.
|
|
127
|
+
|
|
128
|
+
## Changelog
|
|
129
|
+
|
|
130
|
+
See `CHANGELOG.md` in the repository for release notes.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# al-devops-kit
|
|
2
|
+
|
|
3
|
+
Airflow bootstrap tooling: a versioned deploy DAG plus a CLI that installs it.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install al-devops-kit
|
|
9
|
+
al-devops-kit copy-dags /opt/airflow/dags
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Python 3.10+. Install into the Airflow virtualenv. `al-data-utils` is pulled in
|
|
13
|
+
automatically; `apache-airflow` 3.x is expected from the host environment.
|
|
14
|
+
|
|
15
|
+
## CLI
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
al-devops-kit copy-dags <dags_dir> [--version vX.Y.Z] [--force]
|
|
19
|
+
al-devops-kit list-versions
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`copy-dags` copies the deploy DAG template into the given dags folder.
|
|
23
|
+
Existing files are overwritten only when their content differs.
|
|
24
|
+
|
|
25
|
+
## Deploy DAG
|
|
26
|
+
|
|
27
|
+
`_airflow_deploy_dag.py` deploys the repos listed in `/opt/airflow/.repos/repos.yml`:
|
|
28
|
+
|
|
29
|
+
| Task | What it does |
|
|
30
|
+
|---|---|
|
|
31
|
+
| `load_config` | reads `repos.yml` |
|
|
32
|
+
| `sync_repos` | `git fetch`, then checks out the head of each repo's branch (detached, by SHA) |
|
|
33
|
+
| `install_requirements` | merges the repos' `requirements.txt`, pip-installs into the Airflow venv |
|
|
34
|
+
| `run_deploy_steps` | runs each repo's deploy steps, in the order written |
|
|
35
|
+
|
|
36
|
+
`repos.yml`:
|
|
37
|
+
|
|
38
|
+
```yaml
|
|
39
|
+
venv_pip: /opt/airflow/.venv/bin/pip
|
|
40
|
+
schedule: '@daily' # optional; without it the DAG runs only by hand
|
|
41
|
+
repos:
|
|
42
|
+
- name: my-dags
|
|
43
|
+
url: git@github.com:<org>/<repo>.git # SSH + read-only deploy key, no token in the URL
|
|
44
|
+
branch: main
|
|
45
|
+
dags_path: dags/
|
|
46
|
+
requirements: requirements.txt
|
|
47
|
+
require_confirm_sha: false # true: a run needs the param confirm_sha
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
- A scheduled run skips a repo whose branch head is already deployed, and a head
|
|
51
|
+
that failed before. A manual run always deploys.
|
|
52
|
+
- `require_confirm_sha: true`: the run param `confirm_sha` must be the first 8+
|
|
53
|
+
characters of the branch head. It is checked before anything is checked out
|
|
54
|
+
or installed.
|
|
55
|
+
|
|
56
|
+
### Deploy steps
|
|
57
|
+
|
|
58
|
+
`airflow_deploy.yaml` in the repo root (optional):
|
|
59
|
+
|
|
60
|
+
```yaml
|
|
61
|
+
deploy_steps:
|
|
62
|
+
- name: deploy_database # any shell command, cwd = repo root
|
|
63
|
+
run: python -m deploy apply
|
|
64
|
+
timeout: 7200 # seconds, optional (default 3600)
|
|
65
|
+
- name: copy_package_dags
|
|
66
|
+
run: python -m al_data_core copy-dags $AIRFLOW_DAGS_DIR
|
|
67
|
+
- name: sync_repo_dags # repo dags_path -> Airflow dags folder
|
|
68
|
+
deploy_dags:
|
|
69
|
+
keep_files: # not from this repo; never deleted
|
|
70
|
+
- data_core_dag.py
|
|
71
|
+
- data_core_config_engine_dag.py
|
|
72
|
+
- name: finish_deploy
|
|
73
|
+
run: python -m deploy finish
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
- Steps run in the order written. A failed step stops the deploy: later steps do not run.
|
|
77
|
+
- `name`: `[a-z0-9_]+`, unique. Exactly one `deploy_dags` step.
|
|
78
|
+
- `run`: on timeout the whole process group gets SIGTERM, then SIGKILL after 30 s.
|
|
79
|
+
- `deploy_dags` makes the dags folder equal to the repo: copies new and changed
|
|
80
|
+
files, deletes every other file. Not deleted: `keep_files` of any repo in `repos.yml`
|
|
81
|
+
(a file, or a folder with everything under it), files of the other repos, the
|
|
82
|
+
deploy DAG itself, `.configs/`. Nothing to keep: `deploy_dags: true`.
|
|
83
|
+
- A DAG file from a package that is not in `keep_files` is deleted by the step.
|
|
84
|
+
- Without the file the deploy is a single `deploy_dags` step.
|
|
85
|
+
|
|
86
|
+
Environment of a `run` step:
|
|
87
|
+
|
|
88
|
+
| Variable | Value |
|
|
89
|
+
|---|---|
|
|
90
|
+
| `AIRFLOW_DAGS_DIR` | Airflow dags folder |
|
|
91
|
+
| `DEPLOY_REPO_NAME`, `DEPLOY_REPO_DIR`, `DEPLOY_BRANCH` | the repo being deployed |
|
|
92
|
+
| `DEPLOY_SHA`, `DEPLOY_PREVIOUS_SHA` | commit being deployed; last successfully deployed commit |
|
|
93
|
+
| `DEPLOY_CONFIRM_SHA` | run param `confirm_sha` |
|
|
94
|
+
| `DEPLOY_RUN_TYPE` | `manual` or `scheduled` |
|
|
95
|
+
| `DEPLOY_DAG_ID` | `_airflow_deploy_dag` |
|
|
96
|
+
| `DEPLOY_OPT_<KEY>` | one per entry of the run param `options` |
|
|
97
|
+
|
|
98
|
+
The Airflow venv `bin` is first in `PATH`, so `python` is the Airflow Python.
|
|
99
|
+
|
|
100
|
+
### Legacy
|
|
101
|
+
|
|
102
|
+
`requirements_post_install.yaml` with `package_dags:` still works when
|
|
103
|
+
`airflow_deploy.yaml` is absent: the listed packages copy their DAGs first, then
|
|
104
|
+
the repo DAGs are deployed. New repos should use `airflow_deploy.yaml`.
|
|
105
|
+
|
|
106
|
+
## Repository extras
|
|
107
|
+
|
|
108
|
+
The source repository also contains an Ansible playbook for a single-VM
|
|
109
|
+
Airflow install on Ubuntu. It is not part of the PyPI package.
|
|
110
|
+
|
|
111
|
+
## Changelog
|
|
112
|
+
|
|
113
|
+
See `CHANGELOG.md` in the repository for release notes.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "al-devops-kit"
|
|
3
|
-
version = "0.
|
|
4
|
-
description = "Airflow
|
|
3
|
+
version = "0.5.0"
|
|
4
|
+
description = "Airflow deploy DAG and CLI: sync repos, install requirements and run each repo's deploy steps on a running Airflow."
|
|
5
5
|
authors = [{ name = "AL Data Labs", email = "pypi@aldatalabs.com" }]
|
|
6
6
|
license = "MIT"
|
|
7
7
|
license-files = ["LICENSE"]
|
|
@@ -19,6 +19,9 @@ import os
|
|
|
19
19
|
import shutil
|
|
20
20
|
from pathlib import Path
|
|
21
21
|
|
|
22
|
+
# DAG files of older template versions that a newer version replaces.
|
|
23
|
+
_RETIRED_FILES = ('_airflow_installer_dag.py',)
|
|
24
|
+
|
|
22
25
|
|
|
23
26
|
def _templates_dir() -> Path:
|
|
24
27
|
return Path(__file__).parent / 'templates'
|
|
@@ -73,6 +76,12 @@ def _copy_dags(target: str, version: str | None, force: bool = False) -> None:
|
|
|
73
76
|
print(f' copy {src.name} -> {dest}')
|
|
74
77
|
copied += 1
|
|
75
78
|
|
|
79
|
+
for name in _RETIRED_FILES:
|
|
80
|
+
retired = dest_dir / name
|
|
81
|
+
if retired.exists() and not (src_dir / name).exists():
|
|
82
|
+
retired.unlink()
|
|
83
|
+
print(f' remove {name} (replaced in {ver})')
|
|
84
|
+
|
|
76
85
|
print(f'\nDone. {copied} copied, {updated} updated, {skipped} skipped.')
|
|
77
86
|
|
|
78
87
|
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Deploy steps of one repo, used by the `_airflow_deploy_dag` template.
|
|
3
|
+
|
|
4
|
+
A repo describes its deploy in `airflow_deploy.yaml` (repo root):
|
|
5
|
+
|
|
6
|
+
deploy_steps:
|
|
7
|
+
- name: deploy_database # any shell command, cwd = repo root
|
|
8
|
+
run: python -m deploy apply
|
|
9
|
+
timeout: 7200 # seconds, optional (default 3600)
|
|
10
|
+
- name: sync_repo_dags # repo dags_path -> Airflow dags folder
|
|
11
|
+
deploy_dags:
|
|
12
|
+
keep_files: # not from this repo; never deleted
|
|
13
|
+
- some_package_dag.py
|
|
14
|
+
|
|
15
|
+
Steps run in the order written. A failed step stops the deploy: later steps do
|
|
16
|
+
not run. Exactly one `deploy_dags` step is required (`deploy_dags: true` when
|
|
17
|
+
there is nothing to keep).
|
|
18
|
+
|
|
19
|
+
`deploy_dags` makes the dags folder equal to the repo: files that are neither in
|
|
20
|
+
a configured repo nor in `keep_files` are deleted.
|
|
21
|
+
|
|
22
|
+
Without the file the deploy is a single `deploy_dags` step. The legacy file
|
|
23
|
+
`requirements_post_install.yaml` (`package_dags:`) still works: its packages are
|
|
24
|
+
copied first, then the repo DAGs; the packages' `files:` are kept.
|
|
25
|
+
|
|
26
|
+
This module has no Airflow imports, so it can be tested on its own.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import filecmp
|
|
32
|
+
import importlib
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import re
|
|
36
|
+
import shutil
|
|
37
|
+
import signal
|
|
38
|
+
import subprocess
|
|
39
|
+
from dataclasses import dataclass
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
|
|
42
|
+
DEPLOY_FILE = 'airflow_deploy.yaml'
|
|
43
|
+
LEGACY_FILE = 'requirements_post_install.yaml'
|
|
44
|
+
DEFAULT_TIMEOUT = 3600
|
|
45
|
+
KILL_GRACE_SECONDS = 30
|
|
46
|
+
|
|
47
|
+
_NAME_RE = re.compile(r'^[a-z0-9_]+$')
|
|
48
|
+
_PACKAGE_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
|
|
49
|
+
_SHA_PREFIX_RE = re.compile(r'^[0-9a-f]{8,40}$')
|
|
50
|
+
_OPTION_KEY_RE = re.compile(r'^[a-z][a-z0-9_]*$')
|
|
51
|
+
|
|
52
|
+
_SKIP_DIRS = {'__pycache__', '.git'}
|
|
53
|
+
_SKIP_FILES = {'.gitignore', '.gitkeep'}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class DeployConfigError(ValueError):
|
|
57
|
+
"""The deploy file of a repo is not valid."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class DeployStepError(RuntimeError):
|
|
61
|
+
"""A deploy step failed."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Step:
|
|
66
|
+
name: str
|
|
67
|
+
kind: str # 'run' | 'deploy_dags' | 'package_dags' (legacy only)
|
|
68
|
+
run: str | None = None
|
|
69
|
+
timeout: int = DEFAULT_TIMEOUT
|
|
70
|
+
package: str | None = None
|
|
71
|
+
version: str | None = None
|
|
72
|
+
keep_files: tuple[str, ...] = () # deploy_dags only
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class RepoState:
|
|
77
|
+
"""What the last deploys of one repo left behind. One JSON file per repo."""
|
|
78
|
+
|
|
79
|
+
last_success_sha: str | None = None
|
|
80
|
+
last_failed_sha: str | None = None
|
|
81
|
+
|
|
82
|
+
@classmethod
|
|
83
|
+
def load(cls, path: Path) -> RepoState:
|
|
84
|
+
if not path.exists():
|
|
85
|
+
return cls()
|
|
86
|
+
raw = json.loads(path.read_text(encoding='utf-8'))
|
|
87
|
+
return cls(
|
|
88
|
+
last_success_sha=raw.get('last_success_sha'),
|
|
89
|
+
last_failed_sha=raw.get('last_failed_sha'),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def save(self, path: Path) -> None:
|
|
93
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
tmp = path.with_suffix('.tmp')
|
|
95
|
+
tmp.write_text(json.dumps(self.__dict__, indent=2) + '\n', encoding='utf-8')
|
|
96
|
+
os.replace(tmp, path)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ── Config ───────────────────────────────────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _load_yaml(path: Path) -> dict:
|
|
103
|
+
import yaml
|
|
104
|
+
|
|
105
|
+
data = yaml.safe_load(path.read_text(encoding='utf-8')) or {}
|
|
106
|
+
if not isinstance(data, dict):
|
|
107
|
+
raise DeployConfigError(f'{path.name}: expected a mapping at the top level')
|
|
108
|
+
return data
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _keep_files(value: object, where: str) -> tuple[str, ...]:
|
|
112
|
+
"""Validate a keep_files list: paths relative to the dags folder."""
|
|
113
|
+
if not isinstance(value, list):
|
|
114
|
+
raise DeployConfigError(f'{where}: `keep_files` must be a list')
|
|
115
|
+
keep: list[str] = []
|
|
116
|
+
for item in value:
|
|
117
|
+
if not isinstance(item, str):
|
|
118
|
+
raise DeployConfigError(f'{where}: bad keep_files entry {item!r}')
|
|
119
|
+
path = item.strip().rstrip('/')
|
|
120
|
+
parts = path.split('/')
|
|
121
|
+
if (
|
|
122
|
+
not path
|
|
123
|
+
or '\\' in path
|
|
124
|
+
or ':' in path
|
|
125
|
+
or any(p in ('', '.', '..') for p in parts)
|
|
126
|
+
):
|
|
127
|
+
raise DeployConfigError(
|
|
128
|
+
f'{where}: keep_files entry {item!r} must be a path inside '
|
|
129
|
+
'the dags folder'
|
|
130
|
+
)
|
|
131
|
+
keep.append(path)
|
|
132
|
+
return tuple(keep)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _legacy_steps(cfg: dict, source: str) -> list[Step]:
|
|
136
|
+
steps: list[Step] = []
|
|
137
|
+
keep: list[str] = []
|
|
138
|
+
for raw in cfg.get('package_dags') or []:
|
|
139
|
+
package = str((raw or {}).get('name', ''))
|
|
140
|
+
if not _PACKAGE_RE.match(package):
|
|
141
|
+
raise DeployConfigError(f'{source}: bad package name {package!r}')
|
|
142
|
+
version = raw.get('version')
|
|
143
|
+
keep.extend(_keep_files(raw.get('files') or [], f'{source} ({package})'))
|
|
144
|
+
steps.append(
|
|
145
|
+
Step(
|
|
146
|
+
name=f'copy_{package.lower()}_dags',
|
|
147
|
+
kind='package_dags',
|
|
148
|
+
package=package,
|
|
149
|
+
version=None if version in (None, 'latest') else str(version),
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
steps.append(Step(name='deploy_dags', kind='deploy_dags', keep_files=tuple(keep)))
|
|
153
|
+
return steps
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def load_steps(repo_dir: Path) -> list[Step]:
|
|
157
|
+
"""Read and validate the deploy steps of a repo. Raises DeployConfigError."""
|
|
158
|
+
path = repo_dir / DEPLOY_FILE
|
|
159
|
+
legacy = repo_dir / LEGACY_FILE
|
|
160
|
+
if not path.exists():
|
|
161
|
+
if legacy.exists():
|
|
162
|
+
return _legacy_steps(_load_yaml(legacy), LEGACY_FILE)
|
|
163
|
+
return [Step(name='deploy_dags', kind='deploy_dags')]
|
|
164
|
+
|
|
165
|
+
cfg = _load_yaml(path)
|
|
166
|
+
if 'deploy_steps' not in cfg:
|
|
167
|
+
if 'package_dags' in cfg:
|
|
168
|
+
return _legacy_steps(cfg, DEPLOY_FILE)
|
|
169
|
+
raise DeployConfigError(f'{DEPLOY_FILE}: `deploy_steps` is missing')
|
|
170
|
+
unknown = set(cfg) - {'deploy_steps'}
|
|
171
|
+
if unknown:
|
|
172
|
+
raise DeployConfigError(f'{DEPLOY_FILE}: unknown keys {sorted(unknown)}')
|
|
173
|
+
raw_steps = cfg['deploy_steps']
|
|
174
|
+
if not isinstance(raw_steps, list) or not raw_steps:
|
|
175
|
+
raise DeployConfigError(f'{DEPLOY_FILE}: `deploy_steps` must be a list')
|
|
176
|
+
|
|
177
|
+
steps: list[Step] = []
|
|
178
|
+
seen: set[str] = set()
|
|
179
|
+
for i, raw in enumerate(raw_steps, start=1):
|
|
180
|
+
where = f'{DEPLOY_FILE}: step {i}'
|
|
181
|
+
if not isinstance(raw, dict):
|
|
182
|
+
raise DeployConfigError(f'{where}: expected a mapping')
|
|
183
|
+
name = raw.get('name')
|
|
184
|
+
if not isinstance(name, str) or not _NAME_RE.match(name):
|
|
185
|
+
raise DeployConfigError(f'{where}: `name` must match [a-z0-9_]+')
|
|
186
|
+
if name in seen:
|
|
187
|
+
raise DeployConfigError(f'{where}: duplicate name {name!r}')
|
|
188
|
+
seen.add(name)
|
|
189
|
+
unknown = set(raw) - {'name', 'run', 'deploy_dags', 'timeout'}
|
|
190
|
+
if unknown:
|
|
191
|
+
raise DeployConfigError(f'{where} ({name}): unknown keys {sorted(unknown)}')
|
|
192
|
+
has_run = 'run' in raw
|
|
193
|
+
has_dags = 'deploy_dags' in raw
|
|
194
|
+
if has_run == has_dags:
|
|
195
|
+
raise DeployConfigError(
|
|
196
|
+
f'{where} ({name}): exactly one of `run` or `deploy_dags` is required'
|
|
197
|
+
)
|
|
198
|
+
timeout = raw.get('timeout', DEFAULT_TIMEOUT)
|
|
199
|
+
if isinstance(timeout, bool) or not isinstance(timeout, int) or timeout <= 0:
|
|
200
|
+
raise DeployConfigError(f'{where} ({name}): `timeout` must be seconds > 0')
|
|
201
|
+
if has_run:
|
|
202
|
+
command = raw['run']
|
|
203
|
+
if not isinstance(command, str) or not command.strip():
|
|
204
|
+
raise DeployConfigError(f'{where} ({name}): `run` must be a command')
|
|
205
|
+
steps.append(Step(name=name, kind='run', run=command, timeout=timeout))
|
|
206
|
+
else:
|
|
207
|
+
options = raw['deploy_dags']
|
|
208
|
+
if options is True:
|
|
209
|
+
options = {}
|
|
210
|
+
if not isinstance(options, dict) or set(options) - {'keep_files'}:
|
|
211
|
+
raise DeployConfigError(
|
|
212
|
+
f'{where} ({name}): use `deploy_dags: true` or '
|
|
213
|
+
'`deploy_dags: {keep_files: [...]}`'
|
|
214
|
+
)
|
|
215
|
+
keep = _keep_files(options.get('keep_files') or [], f'{where} ({name})')
|
|
216
|
+
steps.append(
|
|
217
|
+
Step(name=name, kind='deploy_dags', timeout=timeout, keep_files=keep)
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
if sum(1 for s in steps if s.kind == 'deploy_dags') != 1:
|
|
221
|
+
raise DeployConfigError(
|
|
222
|
+
f'{DEPLOY_FILE}: exactly one `deploy_dags` step is required'
|
|
223
|
+
)
|
|
224
|
+
return steps
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def check_confirm_sha(confirm: str | None, sha: str) -> None:
|
|
228
|
+
"""The operator typed 8+ characters of the commit being deployed."""
|
|
229
|
+
value = (confirm or '').strip().lower()
|
|
230
|
+
if not _SHA_PREFIX_RE.match(value):
|
|
231
|
+
raise DeployStepError(
|
|
232
|
+
f'confirm_sha must be the first 8+ hex characters of {sha[:12]}'
|
|
233
|
+
)
|
|
234
|
+
if not sha.startswith(value):
|
|
235
|
+
raise DeployStepError(
|
|
236
|
+
f'confirm_sha {value} does not match the branch head {sha[:12]}'
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def options_env(options: dict | None) -> dict[str, str]:
|
|
241
|
+
"""Run options -> DEPLOY_OPT_<KEY> environment variables (never into a shell)."""
|
|
242
|
+
env: dict[str, str] = {}
|
|
243
|
+
for key, value in (options or {}).items():
|
|
244
|
+
if not isinstance(key, str) or not _OPTION_KEY_RE.match(key):
|
|
245
|
+
raise DeployConfigError(f'option name {key!r} must match [a-z][a-z0-9_]*')
|
|
246
|
+
if isinstance(value, (dict, list)):
|
|
247
|
+
raise DeployConfigError(f'option {key}: must be a plain value')
|
|
248
|
+
if value is None or value == '':
|
|
249
|
+
continue
|
|
250
|
+
env[f'DEPLOY_OPT_{key.upper()}'] = str(value)
|
|
251
|
+
return env
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
# ── Steps ────────────────────────────────────────────────────────────────────
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def run_command(step: Step, cwd: Path, env: dict[str, str]) -> None:
|
|
258
|
+
"""Run a shell command in its own process group; on timeout stop the group."""
|
|
259
|
+
proc = subprocess.Popen(
|
|
260
|
+
step.run, shell=True, cwd=str(cwd), env=env, start_new_session=True
|
|
261
|
+
)
|
|
262
|
+
try:
|
|
263
|
+
code = proc.wait(timeout=step.timeout)
|
|
264
|
+
except subprocess.TimeoutExpired:
|
|
265
|
+
_stop_group(proc)
|
|
266
|
+
raise DeployStepError(
|
|
267
|
+
f'step {step.name}: timed out after {step.timeout} s'
|
|
268
|
+
) from None
|
|
269
|
+
if code != 0:
|
|
270
|
+
raise DeployStepError(f'step {step.name}: exit code {code}')
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _stop_group(proc: subprocess.Popen) -> None:
|
|
274
|
+
"""SIGTERM the group, so the command can clean up; SIGKILL after a grace."""
|
|
275
|
+
try:
|
|
276
|
+
os.killpg(proc.pid, signal.SIGTERM)
|
|
277
|
+
except (ProcessLookupError, AttributeError):
|
|
278
|
+
proc.terminate()
|
|
279
|
+
try:
|
|
280
|
+
proc.wait(timeout=KILL_GRACE_SECONDS)
|
|
281
|
+
return
|
|
282
|
+
except subprocess.TimeoutExpired:
|
|
283
|
+
pass
|
|
284
|
+
try:
|
|
285
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
286
|
+
except (ProcessLookupError, AttributeError):
|
|
287
|
+
proc.kill()
|
|
288
|
+
proc.wait()
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def copy_package_dags(step: Step, dags_dir: Path) -> None:
|
|
292
|
+
"""Legacy `package_dags`: the package copies its own DAG templates."""
|
|
293
|
+
try:
|
|
294
|
+
module = importlib.import_module(f'{step.package}.dags_installer')
|
|
295
|
+
except ImportError as exc:
|
|
296
|
+
raise DeployStepError(
|
|
297
|
+
f'step {step.name}: package {step.package} is not installed: {exc}'
|
|
298
|
+
) from exc
|
|
299
|
+
module._copy_dags(str(dags_dir), step.version, False)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _source_files(source: Path) -> list[str]:
|
|
303
|
+
files: list[str] = []
|
|
304
|
+
for root, dirs, names in os.walk(source):
|
|
305
|
+
dirs[:] = sorted(d for d in dirs if d not in _SKIP_DIRS)
|
|
306
|
+
for name in sorted(names):
|
|
307
|
+
if name in _SKIP_FILES or name.endswith(('.pyc', '.pyo')):
|
|
308
|
+
continue
|
|
309
|
+
files.append((Path(root) / name).relative_to(source).as_posix())
|
|
310
|
+
return files
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def source_files(source: Path) -> list[str]:
|
|
314
|
+
"""Files a repo ships to the dags folder (relative, POSIX); [] if no folder."""
|
|
315
|
+
return _source_files(source) if source.is_dir() else []
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _is_kept(rel: str, keep: set[str]) -> bool:
|
|
319
|
+
"""`rel` is a kept path or lies under a kept folder."""
|
|
320
|
+
parts = rel.split('/')
|
|
321
|
+
return any('/'.join(parts[:i]) in keep for i in range(1, len(parts) + 1))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def deploy_dags(
|
|
325
|
+
source: Path,
|
|
326
|
+
dags_dir: Path,
|
|
327
|
+
keep_files: tuple[str, ...] | list[str] = (),
|
|
328
|
+
other_repos: dict[str, str] | None = None,
|
|
329
|
+
) -> dict[str, int]:
|
|
330
|
+
"""
|
|
331
|
+
Make the dags folder equal to `source`.
|
|
332
|
+
|
|
333
|
+
Copies new and changed files, then deletes every other file in the folder,
|
|
334
|
+
except: `keep_files` (a file, or a folder with everything under it) and the
|
|
335
|
+
files of the other configured repos (`other_repos`: file -> repo name).
|
|
336
|
+
Bytecode caches are left alone. A file shipped by two repos is an error.
|
|
337
|
+
"""
|
|
338
|
+
if not source.is_dir():
|
|
339
|
+
raise DeployStepError(f'dags path not found: {source}')
|
|
340
|
+
others = other_repos or {}
|
|
341
|
+
keep = set(keep_files)
|
|
342
|
+
files = _source_files(source)
|
|
343
|
+
clashes = sorted(f for f in files if f in others)
|
|
344
|
+
if clashes:
|
|
345
|
+
raise DeployStepError(
|
|
346
|
+
'DAG files also shipped by another repo: '
|
|
347
|
+
+ ', '.join(f'{f} ({others[f]})' for f in clashes[:10])
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
summary = {'copied': 0, 'updated': 0, 'deleted': 0, 'same': 0, 'kept': 0}
|
|
351
|
+
dags_dir.mkdir(parents=True, exist_ok=True)
|
|
352
|
+
for rel in files:
|
|
353
|
+
src = source / rel
|
|
354
|
+
dst = dags_dir / rel
|
|
355
|
+
if dst.is_file() and filecmp.cmp(src, dst, shallow=False):
|
|
356
|
+
summary['same'] += 1
|
|
357
|
+
continue
|
|
358
|
+
key = 'updated' if dst.exists() else 'copied'
|
|
359
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
360
|
+
tmp = dst.with_name(dst.name + '.deploy_tmp')
|
|
361
|
+
shutil.copyfile(src, tmp)
|
|
362
|
+
os.replace(tmp, dst) # readers never see a half-written file
|
|
363
|
+
summary[key] += 1
|
|
364
|
+
print(f' [{key.upper()}] {rel}')
|
|
365
|
+
|
|
366
|
+
current = set(files)
|
|
367
|
+
emptied: list[Path] = []
|
|
368
|
+
for root, dirs, names in os.walk(dags_dir):
|
|
369
|
+
base = Path(root)
|
|
370
|
+
dirs[:] = sorted(d for d in dirs if d != '__pycache__')
|
|
371
|
+
for name in sorted(names):
|
|
372
|
+
rel = (base / name).relative_to(dags_dir).as_posix()
|
|
373
|
+
if rel in current or rel in others or name.endswith(('.pyc', '.pyo')):
|
|
374
|
+
continue
|
|
375
|
+
if _is_kept(rel, keep):
|
|
376
|
+
summary['kept'] += 1
|
|
377
|
+
continue
|
|
378
|
+
(base / name).unlink()
|
|
379
|
+
summary['deleted'] += 1
|
|
380
|
+
print(f' [DELETE] {rel}')
|
|
381
|
+
emptied.append(base)
|
|
382
|
+
|
|
383
|
+
for folder in sorted(set(emptied), key=lambda p: len(p.parts), reverse=True):
|
|
384
|
+
while folder != dags_dir:
|
|
385
|
+
rel = folder.relative_to(dags_dir).as_posix()
|
|
386
|
+
if _is_kept(rel, keep) or not folder.is_dir():
|
|
387
|
+
break
|
|
388
|
+
left = [p for p in folder.iterdir() if p.name != '__pycache__']
|
|
389
|
+
if left:
|
|
390
|
+
break
|
|
391
|
+
shutil.rmtree(folder)
|
|
392
|
+
folder = folder.parent
|
|
393
|
+
return summary
|
|
@@ -19,7 +19,7 @@ Setup:
|
|
|
19
19
|
venv_pip: /opt/airflow/.venv/bin/pip
|
|
20
20
|
repos:
|
|
21
21
|
- name: my-dags
|
|
22
|
-
url:
|
|
22
|
+
url: git@github.com:<org>/<repo>.git # SSH, read-only deploy key
|
|
23
23
|
branch: main
|
|
24
24
|
dags_path: dags/
|
|
25
25
|
requirements: requirements.txt
|