datadouble 0.0.3__py3-none-any.whl
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.
- datadouble/__init__.py +10 -0
- datadouble/announce.py +380 -0
- datadouble/anonymize.py +165 -0
- datadouble/api.py +1159 -0
- datadouble/boundary.py +47 -0
- datadouble/catalog.py +677 -0
- datadouble/channels.py +62 -0
- datadouble/ci.py +1357 -0
- datadouble/cli.py +940 -0
- datadouble/closure.py +712 -0
- datadouble/engine.py +435 -0
- datadouble/files.py +78 -0
- datadouble/images.py +265 -0
- datadouble/jailer.py +403 -0
- datadouble/names.py +114 -0
- datadouble/notify.py +262 -0
- datadouble/objects.py +195 -0
- datadouble/outcome.py +27 -0
- datadouble/pii.py +109 -0
- datadouble/planner.py +1492 -0
- datadouble/programs.py +68 -0
- datadouble/promote.py +190 -0
- datadouble/prune.py +258 -0
- datadouble/py.typed +0 -0
- datadouble/redaction.py +131 -0
- datadouble/registry.py +128 -0
- datadouble/replicate.py +562 -0
- datadouble/resolve.py +201 -0
- datadouble/run.py +1075 -0
- datadouble/runtime.py +154 -0
- datadouble/secrets.py +57 -0
- datadouble/settings.py +81 -0
- datadouble/signing.py +98 -0
- datadouble/spec.py +1590 -0
- datadouble/staging.py +346 -0
- datadouble/storage.py +222 -0
- datadouble/strict.py +498 -0
- datadouble/subset.py +406 -0
- datadouble/verify.py +171 -0
- datadouble/versions.py +25 -0
- datadouble-0.0.3.dist-info/METADATA +36 -0
- datadouble-0.0.3.dist-info/RECORD +45 -0
- datadouble-0.0.3.dist-info/WHEEL +4 -0
- datadouble-0.0.3.dist-info/entry_points.txt +12 -0
- datadouble-0.0.3.dist-info/licenses/LICENSE +21 -0
datadouble/ci.py
ADDED
|
@@ -0,0 +1,1357 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""CI/CD adapters: generating jobs, and bridging a run to the CI system.
|
|
5
|
+
|
|
6
|
+
A CI/CD adapter contains no pipeline logic. The core decides what each job
|
|
7
|
+
runs (:func:`pipeline`): its ``datadouble`` command lines, triggers,
|
|
8
|
+
schedules and run-time parameters, the secrets it reads by name, and the
|
|
9
|
+
host paths its container needs. The adapter only renders that in its
|
|
10
|
+
system's own configuration, and at run time maps a response onto the
|
|
11
|
+
system's outputs, summary, outcome and log masking.
|
|
12
|
+
|
|
13
|
+
CI/CD adapters register under ``datadouble.ci``; the entry point names a
|
|
14
|
+
callable that returns a :class:`CiAdapter`.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import posixpath
|
|
18
|
+
import re
|
|
19
|
+
import textwrap
|
|
20
|
+
from collections.abc import Callable, Generator, Iterable, Iterator, Mapping
|
|
21
|
+
from contextlib import contextmanager
|
|
22
|
+
from contextvars import ContextVar
|
|
23
|
+
from dataclasses import dataclass, field, replace
|
|
24
|
+
from enum import StrEnum
|
|
25
|
+
from pathlib import Path, PurePosixPath
|
|
26
|
+
from typing import Annotated, Literal, Protocol, assert_never
|
|
27
|
+
from urllib.parse import urlsplit
|
|
28
|
+
|
|
29
|
+
from pydantic import BaseModel, ConfigDict, Discriminator, Field, JsonValue, Tag, field_validator
|
|
30
|
+
|
|
31
|
+
from datadouble.names import SpecName
|
|
32
|
+
from datadouble.outcome import ExitCode, Outcome
|
|
33
|
+
from datadouble.settings import SettingKey
|
|
34
|
+
from datadouble.spec import FILES, AdapterSettings, Notify, ReplicateMode, Spec
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class CiError(Exception):
|
|
38
|
+
"""Jobs that cannot be generated as asked."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class JobKind(StrEnum):
|
|
42
|
+
"""The jobs the lifecycle splits into."""
|
|
43
|
+
|
|
44
|
+
BUILD = "build"
|
|
45
|
+
PROMOTE = "promote"
|
|
46
|
+
FETCH = "fetch"
|
|
47
|
+
PROVISION = "provision"
|
|
48
|
+
RELEASE = "release"
|
|
49
|
+
PRUNE = "prune"
|
|
50
|
+
ACTIVATE = "activate"
|
|
51
|
+
LOCK = "lock"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Side(StrEnum):
|
|
55
|
+
"""Which side of the production boundary jobs run on."""
|
|
56
|
+
|
|
57
|
+
PRODUCTION = "production"
|
|
58
|
+
NON_PRODUCTION = "non-production"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Agent(StrEnum):
|
|
62
|
+
"""Where a system's jobs run Datadouble."""
|
|
63
|
+
|
|
64
|
+
DOCKER = "docker"
|
|
65
|
+
"""On a runner with Docker, which runs the pinned image (decision 100)."""
|
|
66
|
+
KUBERNETES = "kubernetes"
|
|
67
|
+
"""In a pod of the pinned image, beside the engine pods of the ``kubernetes`` runtime."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Trigger(StrEnum):
|
|
71
|
+
"""What starts a job."""
|
|
72
|
+
|
|
73
|
+
SCHEDULE = "schedule"
|
|
74
|
+
AFTER = "after"
|
|
75
|
+
"""Another job of the same spec finishing successfully."""
|
|
76
|
+
REQUEST_OPENED = "request-opened"
|
|
77
|
+
"""A pull or merge request opened: on-demand copies are made for it."""
|
|
78
|
+
REQUEST_CLOSED = "request-closed"
|
|
79
|
+
MANUAL = "manual"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Placeholder(StrEnum):
|
|
83
|
+
"""A command-line argument only the CI system knows when the job runs."""
|
|
84
|
+
|
|
85
|
+
RUN = "run"
|
|
86
|
+
"""The CI system's ID for this run, the same when a run is retried."""
|
|
87
|
+
OWNER = "owner"
|
|
88
|
+
"""Who on-demand copies are for: the pull or merge request."""
|
|
89
|
+
GENERATION = "generation"
|
|
90
|
+
"""A generation the person starting the job chooses."""
|
|
91
|
+
DRY_RUN = "dry-run"
|
|
92
|
+
"""``--dry-run`` when the person starting the job asks for it; otherwise nothing."""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
type Argument = str | Placeholder
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class SpecSourceKind(StrEnum):
|
|
99
|
+
"""Where a job finds the spec's directory: the spec, the specs it extends, and its lock."""
|
|
100
|
+
|
|
101
|
+
CHECKOUT = "checkout"
|
|
102
|
+
"""The CI system's checkout of the repository the pipeline's configuration lives in."""
|
|
103
|
+
MOUNTED = "mounted"
|
|
104
|
+
"""A directory already at an absolute path in the job, which someone else manages."""
|
|
105
|
+
GIT = "git"
|
|
106
|
+
"""A directory in another repository, which the job clones before Datadouble runs."""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
SPEC_CLONE = ".datadouble-spec"
|
|
110
|
+
"""Where a job clones a ``git`` spec source, in its workspace."""
|
|
111
|
+
_CREDENTIAL = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class _Settings(BaseModel):
|
|
115
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class MountedSettings(_Settings):
|
|
119
|
+
"""A spec directory already in the job, at an absolute path."""
|
|
120
|
+
|
|
121
|
+
path: PurePosixPath
|
|
122
|
+
"""The directory, an absolute path inside the job. On a Docker agent it is a path on the
|
|
123
|
+
runner, mounted into the job at the same path."""
|
|
124
|
+
config_map: str | None = Field(
|
|
125
|
+
default=None, max_length=253, pattern=r"^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$"
|
|
126
|
+
)
|
|
127
|
+
"""On Kubernetes agents, the ConfigMap holding the directory's files, which someone else
|
|
128
|
+
manages; the job's pod mounts it at ``path``. A Kubernetes object name: lower-case
|
|
129
|
+
letters, digits, ``-`` and ``.``, at most 253 characters."""
|
|
130
|
+
|
|
131
|
+
@field_validator("path")
|
|
132
|
+
@classmethod
|
|
133
|
+
def _absolute(cls, path: PurePosixPath) -> PurePosixPath:
|
|
134
|
+
if not _HOST_PATH.fullmatch(str(path)) or str(path) == "/" or ".." in path.parts:
|
|
135
|
+
message = (
|
|
136
|
+
"must be an absolute directory other than /, without `..`, spaces, `:` or globs"
|
|
137
|
+
)
|
|
138
|
+
raise ValueError(message)
|
|
139
|
+
return path
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class GitSettings(_Settings):
|
|
143
|
+
"""A spec directory in another repository, which the job clones."""
|
|
144
|
+
|
|
145
|
+
url: str = Field(min_length=1)
|
|
146
|
+
"""The repository's URL, without a password."""
|
|
147
|
+
ref: str = Field(min_length=1)
|
|
148
|
+
"""What to check out: a branch by its name (``main``), a tag as ``refs/tags/<tag>``, or
|
|
149
|
+
a commit by its full SHA. A short SHA fails, and so does a ref starting with ``-``."""
|
|
150
|
+
path: PurePosixPath = PurePosixPath()
|
|
151
|
+
"""The spec's directory inside the repository; its root by default."""
|
|
152
|
+
credential: str = Field(min_length=1)
|
|
153
|
+
"""The CI system's secret, by name, that can read the repository: a GitHub secret, a
|
|
154
|
+
GitLab CI/CD variable or a Jenkins credential ID."""
|
|
155
|
+
|
|
156
|
+
@field_validator("url")
|
|
157
|
+
@classmethod
|
|
158
|
+
def _no_password(cls, url: str) -> str:
|
|
159
|
+
if urlsplit(url).password is not None:
|
|
160
|
+
message = "must not hold a password; the credential names the secret instead"
|
|
161
|
+
raise ValueError(message)
|
|
162
|
+
return url
|
|
163
|
+
|
|
164
|
+
@field_validator("ref")
|
|
165
|
+
@classmethod
|
|
166
|
+
def _not_an_option(cls, ref: str) -> str:
|
|
167
|
+
if ref.startswith("-"):
|
|
168
|
+
message = "must not start with `-`, which git would read as an option"
|
|
169
|
+
raise ValueError(message)
|
|
170
|
+
return ref
|
|
171
|
+
|
|
172
|
+
@field_validator("path")
|
|
173
|
+
@classmethod
|
|
174
|
+
def _relative(cls, path: PurePosixPath) -> PurePosixPath:
|
|
175
|
+
if path.is_absolute() or ".." in path.parts:
|
|
176
|
+
message = "must be a directory inside the repository, without `..`"
|
|
177
|
+
raise ValueError(message)
|
|
178
|
+
return path
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class MountedSource(_Settings):
|
|
182
|
+
"""``{"mounted": {...}}``."""
|
|
183
|
+
|
|
184
|
+
mounted: MountedSettings
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class GitSource(_Settings):
|
|
188
|
+
"""``{"git": {...}}``."""
|
|
189
|
+
|
|
190
|
+
git: GitSettings
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
_SOURCES: tuple[tuple[SpecSourceKind, type[BaseModel]], ...] = (
|
|
194
|
+
(SpecSourceKind.MOUNTED, MountedSource),
|
|
195
|
+
(SpecSourceKind.GIT, GitSource),
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _source_tag(value: object) -> str | None:
|
|
200
|
+
"""Which spec source a value is: its string, or the one key of its object."""
|
|
201
|
+
if isinstance(value, str):
|
|
202
|
+
return value
|
|
203
|
+
for kind, model in _SOURCES:
|
|
204
|
+
if isinstance(value, model) or (isinstance(value, dict) and kind.value in value):
|
|
205
|
+
return kind
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
type SpecSource = Annotated[
|
|
210
|
+
Annotated[Literal[SpecSourceKind.CHECKOUT], Tag(SpecSourceKind.CHECKOUT)]
|
|
211
|
+
| Annotated[MountedSource, Tag(SpecSourceKind.MOUNTED)]
|
|
212
|
+
| Annotated[GitSource, Tag(SpecSourceKind.GIT)],
|
|
213
|
+
Discriminator(_source_tag),
|
|
214
|
+
]
|
|
215
|
+
"""``checkout``, ``{"mounted": {...}}`` or ``{"git": {...}}``."""
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def spec_path(source: SpecSource, spec: Path, root: Path) -> str:
|
|
219
|
+
"""The path jobs pass as ``--spec``: ``<their spec directory>/<the spec's file name>``.
|
|
220
|
+
|
|
221
|
+
With ``checkout`` that is the spec's path from the repository root,
|
|
222
|
+
``root``, so the spec must be inside it. A linked spec keeps its own
|
|
223
|
+
name, since its parents and lock are found beside the link.
|
|
224
|
+
"""
|
|
225
|
+
match source:
|
|
226
|
+
case MountedSource(mounted=mounted):
|
|
227
|
+
return (mounted.path / spec.name).as_posix()
|
|
228
|
+
case GitSource(git=git):
|
|
229
|
+
return (PurePosixPath(SPEC_CLONE) / git.path / spec.name).as_posix()
|
|
230
|
+
case _:
|
|
231
|
+
try:
|
|
232
|
+
return (spec.parent.resolve() / spec.name).relative_to(root.resolve()).as_posix()
|
|
233
|
+
except ValueError:
|
|
234
|
+
message = f"the spec {spec} is not inside {root}, the repository root"
|
|
235
|
+
raise CiError(message) from None
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def credential_name(git: GitSettings, system: str) -> str:
|
|
239
|
+
"""The git credential, checked as a name ``system`` can give a secret: an identifier."""
|
|
240
|
+
if not _CREDENTIAL.fullmatch(git.credential):
|
|
241
|
+
message = (
|
|
242
|
+
f"{system} names secrets with letters, digits and underscores, not starting with a"
|
|
243
|
+
f" digit; {git.credential!r} cannot be one"
|
|
244
|
+
)
|
|
245
|
+
raise CiError(message)
|
|
246
|
+
return git.credential
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@dataclass(frozen=True, slots=True)
|
|
250
|
+
class Invocation:
|
|
251
|
+
"""One ``datadouble`` command line a job runs, after the global options."""
|
|
252
|
+
|
|
253
|
+
arguments: tuple[Argument, ...]
|
|
254
|
+
when: tuple[Trigger, ...] = ()
|
|
255
|
+
"""The triggers it runs for; every trigger when empty."""
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@dataclass(frozen=True, slots=True)
|
|
259
|
+
class Job:
|
|
260
|
+
"""One job: what starts it and what it runs."""
|
|
261
|
+
|
|
262
|
+
kind: JobKind
|
|
263
|
+
triggers: tuple[Trigger, ...]
|
|
264
|
+
invocations: tuple[Invocation, ...]
|
|
265
|
+
schedule: str | None = None
|
|
266
|
+
"""A cron expression, in UTC."""
|
|
267
|
+
after: JobKind | None = None
|
|
268
|
+
parameters: tuple[Placeholder, ...] = ()
|
|
269
|
+
"""Values the person starting the job by hand gives."""
|
|
270
|
+
timeout_minutes: int = 60
|
|
271
|
+
mounts: tuple[str, ...] = ()
|
|
272
|
+
"""Host paths the job's container sees at the same path."""
|
|
273
|
+
environment: tuple[str, ...] = ()
|
|
274
|
+
"""Environment variables the job reads secrets from, by name."""
|
|
275
|
+
artifacts: str | None = None
|
|
276
|
+
"""A directory, relative to the workspace, the job writes files into for the CI system
|
|
277
|
+
to publish as the job's artifact. The adapter makes it writable by the job's user and
|
|
278
|
+
publishes it; the job never commits anything."""
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
@dataclass(frozen=True, slots=True)
|
|
282
|
+
class Pipeline:
|
|
283
|
+
"""Everything a CI/CD adapter needs to write one side's jobs for a spec."""
|
|
284
|
+
|
|
285
|
+
spec: str
|
|
286
|
+
"""The path jobs pass as ``--spec``: from the repository root with the ``checkout``
|
|
287
|
+
spec source, otherwise in the spec directory the source gives."""
|
|
288
|
+
name: SpecName
|
|
289
|
+
side: Side
|
|
290
|
+
jobs: tuple[Job, ...]
|
|
291
|
+
runner: str | None
|
|
292
|
+
"""The runner (label, tag, agent label) jobs run on; None for the system's default."""
|
|
293
|
+
image: str
|
|
294
|
+
"""The pinned Datadouble image the jobs run."""
|
|
295
|
+
version: str
|
|
296
|
+
user: str
|
|
297
|
+
"""The ``uid:gid`` Datadouble runs as: the engine's owner (decision 86)."""
|
|
298
|
+
identity_token: bool = False
|
|
299
|
+
"""Whether jobs need the CI system's identity token, for keyless signing in ``build``."""
|
|
300
|
+
spec_files: tuple[tuple[str, str], ...] = ()
|
|
301
|
+
"""Every file the spec is read from, as its path from the spec's directory and its
|
|
302
|
+
text, the spec's own file last, for systems whose configuration carries them (Argo CD)."""
|
|
303
|
+
lock_text: str = ""
|
|
304
|
+
"""The spec's catalog lock's text, empty when there is none."""
|
|
305
|
+
notify: Notify | None = None
|
|
306
|
+
"""The spec's ``notify`` section: Datadouble posts its webhooks itself, and the
|
|
307
|
+
adapter writes its email in the system's own form, or explains the setup."""
|
|
308
|
+
docker: str | None = None
|
|
309
|
+
"""The Docker command native steps run the image with; None leaves the runner's
|
|
310
|
+
``DATADOUBLE_DOCKER``, or ``docker``."""
|
|
311
|
+
docker_socket: str | None = None
|
|
312
|
+
"""The Docker daemon's socket native steps mount; None leaves the runner's
|
|
313
|
+
``DATADOUBLE_DOCKER_SOCKET``, or ``/var/run/docker.sock``."""
|
|
314
|
+
agent: Agent = Agent.DOCKER
|
|
315
|
+
"""Where the jobs run Datadouble."""
|
|
316
|
+
cloud: str | None = None
|
|
317
|
+
"""The Kubernetes cloud Kubernetes agents' pods start in; None for the system's default."""
|
|
318
|
+
runtime: Mapping[str, JsonValue] | None = None
|
|
319
|
+
"""The spec's ``runtime`` section, for systems whose jobs run beside its pods."""
|
|
320
|
+
spec_source: SpecSource = SpecSourceKind.CHECKOUT
|
|
321
|
+
"""Where jobs find the spec's directory."""
|
|
322
|
+
manual: bool = False
|
|
323
|
+
"""Whether the jobs were generated without schedules or follow-on triggers
|
|
324
|
+
(:func:`manual_note`)."""
|
|
325
|
+
library_remote: str | None = None
|
|
326
|
+
"""A Git URL of a mirror of this repository, which jobs load Datadouble's own CI code
|
|
327
|
+
from at run time (the Jenkins library, the Argo CD chart); None for the public one."""
|
|
328
|
+
|
|
329
|
+
def environment(self) -> tuple[str, ...]:
|
|
330
|
+
"""Every secret the jobs read by name.
|
|
331
|
+
|
|
332
|
+
That is their environment variables, and the credential a ``git`` spec
|
|
333
|
+
source clones with.
|
|
334
|
+
"""
|
|
335
|
+
names = {name for job in self.jobs for name in job.environment}
|
|
336
|
+
git = self.git()
|
|
337
|
+
if git is not None:
|
|
338
|
+
names.add(git.credential)
|
|
339
|
+
return tuple(sorted(names))
|
|
340
|
+
|
|
341
|
+
def mounted(self) -> MountedSettings | None:
|
|
342
|
+
"""The ``mounted`` spec source's settings, if that is the source."""
|
|
343
|
+
return self.spec_source.mounted if isinstance(self.spec_source, MountedSource) else None
|
|
344
|
+
|
|
345
|
+
def git(self) -> GitSettings | None:
|
|
346
|
+
"""The ``git`` spec source's settings, if that is the source."""
|
|
347
|
+
return self.spec_source.git if isinstance(self.spec_source, GitSource) else None
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
class GeneratedFile(BaseModel):
|
|
351
|
+
"""A configuration file an adapter generated, relative to the repository root."""
|
|
352
|
+
|
|
353
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
354
|
+
|
|
355
|
+
path: PurePosixPath
|
|
356
|
+
content: str
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
class CiBridge(BaseModel):
|
|
360
|
+
"""A request's CI system: whose outputs, summary and masking to use."""
|
|
361
|
+
|
|
362
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
363
|
+
|
|
364
|
+
system: str
|
|
365
|
+
directory: Path | None = None
|
|
366
|
+
"""Where the adapter writes outputs and the summary for the native step to pick up."""
|
|
367
|
+
job: JobKind | None = None
|
|
368
|
+
"""The generated job the request runs for: its spec's ``notify`` section applies."""
|
|
369
|
+
record: Path | None = None
|
|
370
|
+
"""The file the generated job records its last outcome in, so a success after
|
|
371
|
+
anything else is a recovery (decision 142); ``ci init`` names it."""
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
class Report(BaseModel):
|
|
375
|
+
"""What a CI system is told about a response. Never holds data values."""
|
|
376
|
+
|
|
377
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
378
|
+
|
|
379
|
+
command: str
|
|
380
|
+
outcome: Outcome
|
|
381
|
+
outputs: dict[str, str]
|
|
382
|
+
summary: str
|
|
383
|
+
"""For people, as the CLI prints it."""
|
|
384
|
+
message: str | None = None
|
|
385
|
+
"""Why a request failed."""
|
|
386
|
+
warnings: tuple[str, ...] = ()
|
|
387
|
+
files: tuple[Path, ...] = ()
|
|
388
|
+
"""Files the command wrote for the job's artifact (the ``lock`` job's lock and changes),
|
|
389
|
+
for systems whose generated configuration cannot publish them (Argo CD prints them)."""
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
class CiAdapter(Protocol):
|
|
393
|
+
"""A CI/CD system."""
|
|
394
|
+
|
|
395
|
+
@property
|
|
396
|
+
def name(self) -> str:
|
|
397
|
+
"""The name requests use for this system."""
|
|
398
|
+
...
|
|
399
|
+
|
|
400
|
+
@property
|
|
401
|
+
def agents(self) -> tuple[Agent, ...]:
|
|
402
|
+
"""Where the system's jobs can run Datadouble, its default first."""
|
|
403
|
+
...
|
|
404
|
+
|
|
405
|
+
@property
|
|
406
|
+
def identity_token(self) -> bool:
|
|
407
|
+
"""Whether ``build`` jobs get the system's identity token, for keyless signing."""
|
|
408
|
+
...
|
|
409
|
+
|
|
410
|
+
def generate(self, pipeline: Pipeline) -> tuple[GeneratedFile, ...]:
|
|
411
|
+
"""The system's configuration for the pipeline's jobs."""
|
|
412
|
+
...
|
|
413
|
+
|
|
414
|
+
def instructions(self, pipeline: Pipeline) -> tuple[str, ...]:
|
|
415
|
+
"""Setup the system's configuration cannot hold, such as GitLab's pipeline schedules."""
|
|
416
|
+
...
|
|
417
|
+
|
|
418
|
+
def vendor_hosted(self, environ: Mapping[str, str]) -> str | None:
|
|
419
|
+
"""A description of the runner, if ``environ`` shows the vendor hosts it."""
|
|
420
|
+
...
|
|
421
|
+
|
|
422
|
+
def run_url(self, environ: Mapping[str, str]) -> str | None:
|
|
423
|
+
"""The web page of the running job, from the system's variables in ``environ``."""
|
|
424
|
+
...
|
|
425
|
+
|
|
426
|
+
def mask(self, value: str) -> None:
|
|
427
|
+
"""Have the system hide a resolved secret value in its logs."""
|
|
428
|
+
...
|
|
429
|
+
|
|
430
|
+
def report(self, report: Report, directory: Path | None) -> ExitCode:
|
|
431
|
+
"""Write outputs, the summary and annotations; return the exit code to use."""
|
|
432
|
+
...
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
type CiFactory = Callable[[], CiAdapter]
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
# Log masking
|
|
439
|
+
|
|
440
|
+
_MASK: ContextVar[Callable[[str], None] | None] = ContextVar("datadouble_mask", default=None)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
@contextmanager
|
|
444
|
+
def masking(mask: Callable[[str], None]) -> Generator[None]:
|
|
445
|
+
"""Pass every secret value resolved inside the block to ``mask``."""
|
|
446
|
+
token = _MASK.set(mask)
|
|
447
|
+
try:
|
|
448
|
+
yield
|
|
449
|
+
finally:
|
|
450
|
+
_MASK.reset(token)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def mask(value: str) -> None:
|
|
454
|
+
"""Hand a resolved secret value to the CI system's log masking, if there is one."""
|
|
455
|
+
callback = _MASK.get()
|
|
456
|
+
if callback is not None:
|
|
457
|
+
callback(value)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
# Jobs
|
|
461
|
+
|
|
462
|
+
IMAGE = "ghcr.io/datadouble/datadouble"
|
|
463
|
+
"""Where release images are published; tagged ``v<version>``."""
|
|
464
|
+
PRODUCTION_JOBS = frozenset({JobKind.BUILD, JobKind.PROMOTE, JobKind.LOCK})
|
|
465
|
+
NON_PRODUCTION_JOBS = frozenset(
|
|
466
|
+
{JobKind.FETCH, JobKind.PROVISION, JobKind.RELEASE, JobKind.ACTIVATE}
|
|
467
|
+
)
|
|
468
|
+
_SECTIONS: dict[tuple[JobKind, Side], tuple[str, ...]] = {
|
|
469
|
+
(JobKind.BUILD, Side.PRODUCTION): (
|
|
470
|
+
"sources",
|
|
471
|
+
"files",
|
|
472
|
+
"package",
|
|
473
|
+
"store",
|
|
474
|
+
"signing",
|
|
475
|
+
"secrets",
|
|
476
|
+
"runtime",
|
|
477
|
+
"notify",
|
|
478
|
+
),
|
|
479
|
+
(JobKind.PROMOTE, Side.PRODUCTION): ("store", "promote", "trust", "notify"),
|
|
480
|
+
(JobKind.LOCK, Side.PRODUCTION): ("sources", "notify"),
|
|
481
|
+
(JobKind.PRUNE, Side.PRODUCTION): ("store", "promote", "notify"),
|
|
482
|
+
(JobKind.FETCH, Side.NON_PRODUCTION): ("fetch", "trust", "notify"),
|
|
483
|
+
(JobKind.PROVISION, Side.NON_PRODUCTION): (
|
|
484
|
+
"fetch",
|
|
485
|
+
"replicate",
|
|
486
|
+
"announce",
|
|
487
|
+
"runtime",
|
|
488
|
+
"notify",
|
|
489
|
+
),
|
|
490
|
+
(JobKind.RELEASE, Side.NON_PRODUCTION): ("fetch", "replicate", "announce", "runtime", "notify"),
|
|
491
|
+
(JobKind.PRUNE, Side.NON_PRODUCTION): ("fetch", "replicate", "notify"),
|
|
492
|
+
(JobKind.ACTIVATE, Side.NON_PRODUCTION): ("fetch", "notify"),
|
|
493
|
+
}
|
|
494
|
+
"""The spec sections each job reads: its secrets and host paths come only from these,
|
|
495
|
+
so a job never receives another's credentials. Every job reads ``notify``, whose
|
|
496
|
+
webhooks it posts to."""
|
|
497
|
+
_PRUNE_TARGETS = {Side.PRODUCTION: ("store", "export"), Side.NON_PRODUCTION: ("staging",)}
|
|
498
|
+
_STAGES = "plan,extract,load,transform,package,verify,store"
|
|
499
|
+
_HOST_PATH = re.compile(r"/[^\s*?\[\]{}:]+")
|
|
500
|
+
_SPACE = re.compile(r"\s")
|
|
501
|
+
_BUILD_MINUTES = 12 * 60
|
|
502
|
+
LOCK_ARTIFACTS = "datadouble-lock"
|
|
503
|
+
"""Where the ``lock`` job writes the new lock and its changes, in the workspace."""
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def side_of(kinds: Iterable[JobKind], side: Side | None) -> Side:
|
|
507
|
+
"""The side the jobs run on; ``side`` is needed only for ``prune`` alone."""
|
|
508
|
+
chosen = set(kinds)
|
|
509
|
+
production = chosen & PRODUCTION_JOBS
|
|
510
|
+
others = chosen & NON_PRODUCTION_JOBS
|
|
511
|
+
if production and others:
|
|
512
|
+
message = (
|
|
513
|
+
f"{', '.join(sorted(production))} run in production and"
|
|
514
|
+
f" {', '.join(sorted(others))} outside it; generate each side separately"
|
|
515
|
+
)
|
|
516
|
+
raise CiError(message)
|
|
517
|
+
found = Side.PRODUCTION if production else Side.NON_PRODUCTION if others else side
|
|
518
|
+
if found is None:
|
|
519
|
+
message = "prune runs on either side; name the side"
|
|
520
|
+
raise CiError(message)
|
|
521
|
+
if side is not None and side is not found:
|
|
522
|
+
message = f"those jobs run on the {found} side, not {side}"
|
|
523
|
+
raise CiError(message)
|
|
524
|
+
return found
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def sections(kind: JobKind, side: Side) -> tuple[str, ...]:
|
|
528
|
+
"""The spec sections a job reads, such as ``runtime`` for jobs that start engines."""
|
|
529
|
+
return _SECTIONS[kind, side]
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
@dataclass(frozen=True, slots=True)
|
|
533
|
+
class RemoteSettings:
|
|
534
|
+
"""The settings each installed adapter declares remote, by adapter name (decision 140).
|
|
535
|
+
|
|
536
|
+
A remote setting names a path that is not on the machine running the job,
|
|
537
|
+
such as ``k8s-pv``'s ``nfs.path`` on the NFS server. Adapters declare them
|
|
538
|
+
with :func:`datadouble.settings.remote`, and :func:`host_paths` leaves them
|
|
539
|
+
out, so they never become mounts. Engines' keys are inside the source.
|
|
540
|
+
"""
|
|
541
|
+
|
|
542
|
+
engines: Mapping[str, tuple[SettingKey, ...]] = field(
|
|
543
|
+
default_factory=dict[str, tuple[SettingKey, ...]]
|
|
544
|
+
)
|
|
545
|
+
stores: Mapping[str, tuple[SettingKey, ...]] = field(
|
|
546
|
+
default_factory=dict[str, tuple[SettingKey, ...]]
|
|
547
|
+
)
|
|
548
|
+
replicators: Mapping[str, tuple[SettingKey, ...]] = field(
|
|
549
|
+
default_factory=dict[str, tuple[SettingKey, ...]]
|
|
550
|
+
)
|
|
551
|
+
announcers: Mapping[str, tuple[SettingKey, ...]] = field(
|
|
552
|
+
default_factory=dict[str, tuple[SettingKey, ...]]
|
|
553
|
+
)
|
|
554
|
+
runtimes: Mapping[str, tuple[SettingKey, ...]] = field(
|
|
555
|
+
default_factory=dict[str, tuple[SettingKey, ...]]
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
type _Location = tuple[str | int, ...]
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _remote_engines(spec: Spec, remote: RemoteSettings) -> Iterator[_Location]:
|
|
563
|
+
"""Where each engine setting declared remote is: in each source, and in ``files``."""
|
|
564
|
+
engines: list[tuple[_Location, str]] = [
|
|
565
|
+
(("sources", name), source.engine) for name, source in spec.sources.items()
|
|
566
|
+
]
|
|
567
|
+
if spec.files is not None:
|
|
568
|
+
engines.append((("files",), FILES))
|
|
569
|
+
for at, engine in engines:
|
|
570
|
+
for key in remote.engines.get(engine, ()):
|
|
571
|
+
yield (*at, *key)
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _remote(spec: Spec, remote: RemoteSettings) -> Iterator[_Location]:
|
|
575
|
+
"""Where, in the dumped spec, each setting an installed adapter declared remote is."""
|
|
576
|
+
yield from _remote_engines(spec, remote)
|
|
577
|
+
adapters: list[tuple[_Location, AdapterSettings, Mapping[str, tuple[SettingKey, ...]]]] = [
|
|
578
|
+
*((("store", i), store, remote.stores) for i, store in enumerate(spec.store)),
|
|
579
|
+
*((("announce", i), each, remote.announcers) for i, each in enumerate(spec.announce)),
|
|
580
|
+
]
|
|
581
|
+
if spec.promote is not None:
|
|
582
|
+
adapters += [
|
|
583
|
+
(("promote", "to", i), to, remote.stores) for i, to in enumerate(spec.promote.to)
|
|
584
|
+
]
|
|
585
|
+
if spec.fetch is not None:
|
|
586
|
+
adapters.append((("fetch", "from"), spec.fetch.source, remote.stores))
|
|
587
|
+
if spec.replicate is not None:
|
|
588
|
+
adapters.append((("replicate", "using"), spec.replicate.using, remote.replicators))
|
|
589
|
+
if spec.runtime is not None:
|
|
590
|
+
adapters.append((("runtime",), spec.runtime, remote.runtimes))
|
|
591
|
+
for at, adapter, declared in adapters:
|
|
592
|
+
for name in adapter:
|
|
593
|
+
for key in declared.get(name, ()):
|
|
594
|
+
yield (*at, name, *key)
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def _leave_out(value: JsonValue, location: _Location) -> None:
|
|
598
|
+
"""Remove what is at ``location`` inside ``value``, if it is there."""
|
|
599
|
+
step, *rest = location
|
|
600
|
+
if isinstance(value, dict) and isinstance(step, str):
|
|
601
|
+
if rest:
|
|
602
|
+
_leave_out(value.get(step), tuple(rest))
|
|
603
|
+
else:
|
|
604
|
+
value.pop(step, None)
|
|
605
|
+
elif isinstance(value, list) and isinstance(step, int):
|
|
606
|
+
_leave_out(value[step], tuple(rest))
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _sections(
|
|
610
|
+
spec: Spec, kind: JobKind, side: Side, remote: RemoteSettings | None = None
|
|
611
|
+
) -> list[JsonValue]:
|
|
612
|
+
"""The job's spec sections; with ``remote``, without settings naming paths elsewhere."""
|
|
613
|
+
dumped = spec.model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
614
|
+
# Of package, only accounts' password references name secrets or files: a
|
|
615
|
+
# plain-text password or a user name that looks like a path must never become
|
|
616
|
+
# a mount, and so reach a command line.
|
|
617
|
+
dumped["package"] = [
|
|
618
|
+
account.password.model_dump(mode="json")
|
|
619
|
+
for account in spec.package.accounts
|
|
620
|
+
if not isinstance(account.password, str)
|
|
621
|
+
]
|
|
622
|
+
if remote is not None:
|
|
623
|
+
# Of files, only the connection names paths here: the find tests, the
|
|
624
|
+
# excluded directories and the referenced paths are relative to the
|
|
625
|
+
# tree, and the cleanup commands run in the cleanup image.
|
|
626
|
+
if spec.files is not None:
|
|
627
|
+
dumped["files"] = {"connection": spec.files.connection}
|
|
628
|
+
for location in _remote(spec, remote):
|
|
629
|
+
_leave_out(dumped, location)
|
|
630
|
+
# The kubernetes runtime's other claims say where the job's pod mounts
|
|
631
|
+
# them (other_claims), not paths a job opens.
|
|
632
|
+
_leave_out(dumped, ("runtime", "kubernetes", "claims"))
|
|
633
|
+
return [dumped[name] for name in _SECTIONS[kind, side] if name in dumped]
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def _walk(value: JsonValue) -> Iterator[JsonValue]:
|
|
637
|
+
yield value
|
|
638
|
+
if isinstance(value, dict):
|
|
639
|
+
for item in value.values():
|
|
640
|
+
yield from _walk(item)
|
|
641
|
+
elif isinstance(value, list):
|
|
642
|
+
for item in value:
|
|
643
|
+
yield from _walk(item)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def secret_names(spec: Spec, kind: JobKind, side: Side) -> tuple[str, ...]:
|
|
647
|
+
"""The environment variables a job's spec sections read secrets from."""
|
|
648
|
+
names: set[str] = set()
|
|
649
|
+
for section in _sections(spec, kind, side):
|
|
650
|
+
for value in _walk(section):
|
|
651
|
+
if isinstance(value, dict) and len(value) == 1:
|
|
652
|
+
name = value.get("env")
|
|
653
|
+
if isinstance(name, str):
|
|
654
|
+
names.add(name)
|
|
655
|
+
return tuple(sorted(names))
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def host_paths(
|
|
659
|
+
spec: Spec,
|
|
660
|
+
kind: JobKind,
|
|
661
|
+
side: Side,
|
|
662
|
+
extra: Iterable[Path] = (),
|
|
663
|
+
remote: RemoteSettings | None = None,
|
|
664
|
+
) -> tuple[str, ...]:
|
|
665
|
+
"""Absolute paths a job's spec sections name, with none inside another.
|
|
666
|
+
|
|
667
|
+
Settings the installed adapters declare remote (``remote``) and the
|
|
668
|
+
``files`` settings other than its connection name paths that are not on
|
|
669
|
+
the job's machine, so they are left out.
|
|
670
|
+
"""
|
|
671
|
+
found = {str(path) for path in extra}
|
|
672
|
+
found |= {
|
|
673
|
+
value.rstrip("/")
|
|
674
|
+
for section in _sections(spec, kind, side, remote or RemoteSettings())
|
|
675
|
+
for value in _walk(section)
|
|
676
|
+
if isinstance(value, str) and _HOST_PATH.fullmatch(value) and value != "/"
|
|
677
|
+
}
|
|
678
|
+
ordered = sorted(found)
|
|
679
|
+
return tuple(
|
|
680
|
+
path
|
|
681
|
+
for path in ordered
|
|
682
|
+
if not any(path.startswith(other + "/") for other in ordered if other != path)
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def _replicate_mode(spec: Spec) -> ReplicateMode:
|
|
687
|
+
if spec.replicate is None:
|
|
688
|
+
message = "provision and release need the spec's `replicate` section"
|
|
689
|
+
raise CiError(message)
|
|
690
|
+
return spec.replicate.mode
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
@dataclass(frozen=True, slots=True)
|
|
694
|
+
class _Context:
|
|
695
|
+
spec: str
|
|
696
|
+
model: Spec
|
|
697
|
+
side: Side
|
|
698
|
+
chosen: frozenset[JobKind]
|
|
699
|
+
work: str
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _build(context: _Context) -> Job:
|
|
703
|
+
arguments = ("run", _STAGES, "--spec", context.spec, "--work", context.work)
|
|
704
|
+
return Job(
|
|
705
|
+
JobKind.BUILD,
|
|
706
|
+
(Trigger.SCHEDULE, Trigger.MANUAL),
|
|
707
|
+
(Invocation((*arguments, "--retry-key", Placeholder.RUN)),),
|
|
708
|
+
schedule="0 2 * * 1",
|
|
709
|
+
timeout_minutes=_BUILD_MINUTES,
|
|
710
|
+
)
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def _promote(context: _Context) -> Job:
|
|
714
|
+
after = JobKind.BUILD if JobKind.BUILD in context.chosen else None
|
|
715
|
+
return Job(
|
|
716
|
+
JobKind.PROMOTE,
|
|
717
|
+
(Trigger.AFTER, Trigger.MANUAL) if after else (Trigger.MANUAL,),
|
|
718
|
+
(Invocation(("promote", "--spec", context.spec)),),
|
|
719
|
+
after=after,
|
|
720
|
+
)
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def _fetch(context: _Context) -> Job:
|
|
724
|
+
return Job(
|
|
725
|
+
JobKind.FETCH,
|
|
726
|
+
(Trigger.SCHEDULE, Trigger.MANUAL),
|
|
727
|
+
(Invocation(("fetch", "--spec", context.spec)),),
|
|
728
|
+
schedule="*/15 * * * *",
|
|
729
|
+
)
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _provision(context: _Context) -> Job:
|
|
733
|
+
if _replicate_mode(context.model) is ReplicateMode.ON_DEMAND:
|
|
734
|
+
return Job(
|
|
735
|
+
JobKind.PROVISION,
|
|
736
|
+
(Trigger.REQUEST_OPENED,),
|
|
737
|
+
(Invocation(("replicate", "--spec", context.spec, "--owner", Placeholder.OWNER)),),
|
|
738
|
+
)
|
|
739
|
+
after = JobKind.FETCH if JobKind.FETCH in context.chosen else None
|
|
740
|
+
triggers = (Trigger.SCHEDULE, Trigger.MANUAL)
|
|
741
|
+
return Job(
|
|
742
|
+
JobKind.PROVISION,
|
|
743
|
+
(*triggers, Trigger.AFTER) if after else triggers,
|
|
744
|
+
(Invocation(("replicate", "--spec", context.spec)),),
|
|
745
|
+
schedule="0 * * * *",
|
|
746
|
+
after=after,
|
|
747
|
+
)
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _release(context: _Context) -> Job:
|
|
751
|
+
sweep = ("release", "--spec", context.spec, "--expired")
|
|
752
|
+
if _replicate_mode(context.model) is ReplicateMode.ON_DEMAND:
|
|
753
|
+
closed = Invocation(
|
|
754
|
+
("release", "--spec", context.spec, "--owner", Placeholder.OWNER),
|
|
755
|
+
when=(Trigger.REQUEST_CLOSED,),
|
|
756
|
+
)
|
|
757
|
+
return Job(
|
|
758
|
+
JobKind.RELEASE,
|
|
759
|
+
(Trigger.REQUEST_CLOSED, Trigger.SCHEDULE, Trigger.MANUAL),
|
|
760
|
+
(closed, Invocation(sweep, when=(Trigger.SCHEDULE, Trigger.MANUAL))),
|
|
761
|
+
schedule="30 3 * * *",
|
|
762
|
+
)
|
|
763
|
+
return Job(
|
|
764
|
+
JobKind.RELEASE,
|
|
765
|
+
(Trigger.SCHEDULE, Trigger.MANUAL),
|
|
766
|
+
(Invocation(sweep),),
|
|
767
|
+
schedule="30 3 * * *",
|
|
768
|
+
)
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def _prune(context: _Context) -> Job:
|
|
772
|
+
return Job(
|
|
773
|
+
JobKind.PRUNE,
|
|
774
|
+
(Trigger.SCHEDULE, Trigger.MANUAL),
|
|
775
|
+
tuple(
|
|
776
|
+
Invocation(("prune", "--spec", context.spec, "--target", target, Placeholder.DRY_RUN))
|
|
777
|
+
for target in _PRUNE_TARGETS[context.side]
|
|
778
|
+
),
|
|
779
|
+
schedule="0 4 * * *",
|
|
780
|
+
parameters=(Placeholder.DRY_RUN,),
|
|
781
|
+
)
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def _lock(context: _Context) -> Job:
|
|
785
|
+
"""Re-lock by hand: the new lock and its changes are published for review, never committed."""
|
|
786
|
+
return Job(
|
|
787
|
+
JobKind.LOCK,
|
|
788
|
+
(Trigger.MANUAL,),
|
|
789
|
+
(Invocation(("lock", "--spec", context.spec, "--output", LOCK_ARTIFACTS)),),
|
|
790
|
+
artifacts=LOCK_ARTIFACTS,
|
|
791
|
+
)
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def _activate(context: _Context) -> Job:
|
|
795
|
+
return Job(
|
|
796
|
+
JobKind.ACTIVATE,
|
|
797
|
+
(Trigger.MANUAL,),
|
|
798
|
+
(Invocation(("activate", Placeholder.GENERATION, "--spec", context.spec)),),
|
|
799
|
+
parameters=(Placeholder.GENERATION,),
|
|
800
|
+
)
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
_JOBS: dict[JobKind, Callable[[_Context], Job]] = {
|
|
804
|
+
JobKind.BUILD: _build,
|
|
805
|
+
JobKind.PROMOTE: _promote,
|
|
806
|
+
JobKind.FETCH: _fetch,
|
|
807
|
+
JobKind.PROVISION: _provision,
|
|
808
|
+
JobKind.RELEASE: _release,
|
|
809
|
+
JobKind.PRUNE: _prune,
|
|
810
|
+
JobKind.ACTIVATE: _activate,
|
|
811
|
+
JobKind.LOCK: _lock,
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def _implicit(spec: Spec, kind: JobKind) -> tuple[str, ...]:
|
|
816
|
+
"""Secrets the job's programs read without the spec naming them."""
|
|
817
|
+
keyed = spec.signing is not None and spec.signing.cosign.key is not None
|
|
818
|
+
return ("COSIGN_PASSWORD",) if kind is JobKind.BUILD and keyed else ()
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
@dataclass(frozen=True, slots=True)
|
|
822
|
+
class PipelineOptions:
|
|
823
|
+
"""What ``ci init`` was asked for, beyond the spec."""
|
|
824
|
+
|
|
825
|
+
kinds: tuple[JobKind, ...]
|
|
826
|
+
spec_path: str
|
|
827
|
+
"""The path jobs pass as ``--spec`` (:func:`spec_path`)."""
|
|
828
|
+
image: str
|
|
829
|
+
version: str
|
|
830
|
+
owner: str
|
|
831
|
+
runner: str | None = None
|
|
832
|
+
work: Path | None = None
|
|
833
|
+
side: Side | None = None
|
|
834
|
+
spec_files: tuple[tuple[str, str], ...] = ()
|
|
835
|
+
"""Every file the spec is read from: its path from the spec's directory, and its text."""
|
|
836
|
+
lock_text: str = ""
|
|
837
|
+
environment: tuple[str, ...] = ()
|
|
838
|
+
"""More environment variables every job passes on, for credentials adapters read
|
|
839
|
+
from the environment rather than the spec, such as ``AWS_ACCESS_KEY_ID``."""
|
|
840
|
+
docker: str | None = None
|
|
841
|
+
"""The Docker command native steps use, written into the configuration."""
|
|
842
|
+
docker_socket: Path | None = None
|
|
843
|
+
"""The Docker daemon's socket native steps use, written into the configuration."""
|
|
844
|
+
agent: Agent = Agent.DOCKER
|
|
845
|
+
cloud: str | None = None
|
|
846
|
+
remote: RemoteSettings = field(default_factory=RemoteSettings)
|
|
847
|
+
"""The settings the installed adapters declare remote, which never become mounts."""
|
|
848
|
+
spec_source: SpecSource = SpecSourceKind.CHECKOUT
|
|
849
|
+
manual: bool = False
|
|
850
|
+
"""Leave out every schedule and follow-on trigger, so only a person starts the jobs."""
|
|
851
|
+
library_remote: str | None = None
|
|
852
|
+
"""A Git URL of a mirror of this repository (:attr:`Pipeline.library_remote`)."""
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
_STARTERS = frozenset({Trigger.SCHEDULE, Trigger.AFTER})
|
|
856
|
+
"""What starts a job without anyone asking: its schedule, and another job finishing."""
|
|
857
|
+
MANUAL_NOTE = (
|
|
858
|
+
"Generated with --manual, to try jobs out: no schedules and no follow-on triggers, so"
|
|
859
|
+
" only a person, or a request for on-demand copies, starts them."
|
|
860
|
+
)
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
def _manual(job: Job, *, manual: bool) -> Job:
|
|
864
|
+
"""With ``manual``, the job without its schedule and follow-on trigger.
|
|
865
|
+
|
|
866
|
+
Only a person starts it then. Request triggers stay: on-demand copies are
|
|
867
|
+
made for the request that asks. Every command line that runs on a schedule
|
|
868
|
+
also runs by hand, so each keeps a trigger.
|
|
869
|
+
"""
|
|
870
|
+
if not manual:
|
|
871
|
+
return job
|
|
872
|
+
return replace(
|
|
873
|
+
job,
|
|
874
|
+
triggers=tuple(t for t in job.triggers if t not in _STARTERS),
|
|
875
|
+
invocations=tuple(
|
|
876
|
+
replace(invocation, when=tuple(t for t in invocation.when if t not in _STARTERS))
|
|
877
|
+
for invocation in job.invocations
|
|
878
|
+
),
|
|
879
|
+
schedule=None,
|
|
880
|
+
after=None,
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def manual_note(pipeline: "Pipeline", comment: str) -> str:
|
|
885
|
+
"""Comment lines saying why ``--manual`` jobs have no triggers; nothing otherwise.
|
|
886
|
+
|
|
887
|
+
Adapters add them to their generated files' headers, after a line of
|
|
888
|
+
``comment`` alone.
|
|
889
|
+
"""
|
|
890
|
+
if not pipeline.manual:
|
|
891
|
+
return ""
|
|
892
|
+
lines = [comment, *(f"{comment} {line}" for line in textwrap.wrap(MANUAL_NOTE, 76))]
|
|
893
|
+
return "".join(f"{line}\n" for line in lines)
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def _spec_mounts(options: PipelineOptions) -> tuple[Path, ...]:
|
|
897
|
+
"""The host paths every job mounts for a ``mounted`` spec source, checked for the agent.
|
|
898
|
+
|
|
899
|
+
On a Docker agent the spec's directory is a path on the runner, mounted
|
|
900
|
+
like any other. On Kubernetes it is a ConfigMap the pod mounts, which
|
|
901
|
+
``claim_mount`` must not see, since it is not on the work claim; a
|
|
902
|
+
ConfigMap holds files in one directory, so the spec's files must all be
|
|
903
|
+
directly in it.
|
|
904
|
+
"""
|
|
905
|
+
source = options.spec_source
|
|
906
|
+
if not isinstance(source, MountedSource):
|
|
907
|
+
return ()
|
|
908
|
+
mounted = source.mounted
|
|
909
|
+
match options.agent:
|
|
910
|
+
case Agent.DOCKER:
|
|
911
|
+
if mounted.config_map is not None:
|
|
912
|
+
message = (
|
|
913
|
+
"a ConfigMap applies only to kubernetes agents; on a docker agent the spec's"
|
|
914
|
+
f" directory {mounted.path} is a path on the runner, mounted into the job"
|
|
915
|
+
)
|
|
916
|
+
raise CiError(message)
|
|
917
|
+
return (Path(mounted.path),)
|
|
918
|
+
case Agent.KUBERNETES:
|
|
919
|
+
if mounted.config_map is None:
|
|
920
|
+
message = (
|
|
921
|
+
f"on kubernetes agents a mounted spec directory comes from a ConfigMap; name"
|
|
922
|
+
f" the ConfigMap that holds {mounted.path}'s files"
|
|
923
|
+
)
|
|
924
|
+
raise CiError(message)
|
|
925
|
+
nested = [path for path, _ in options.spec_files if "/" in path]
|
|
926
|
+
if nested:
|
|
927
|
+
message = (
|
|
928
|
+
f"a ConfigMap holds files in one directory, but the spec reads"
|
|
929
|
+
f" {', '.join(nested)} from a subdirectory; keep its files beside it"
|
|
930
|
+
)
|
|
931
|
+
raise CiError(message)
|
|
932
|
+
return ()
|
|
933
|
+
case _:
|
|
934
|
+
assert_never(options.agent)
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _distinct_credential(source: SpecSource, jobs: tuple[Job, ...]) -> None:
|
|
938
|
+
"""Refuse a ``git`` credential named like a secret the jobs read from the environment.
|
|
939
|
+
|
|
940
|
+
The two are different kinds of secret on some systems (a Jenkins
|
|
941
|
+
credential that clones, and a Secret text one), so one name can't be both.
|
|
942
|
+
"""
|
|
943
|
+
if not isinstance(source, GitSource):
|
|
944
|
+
return
|
|
945
|
+
if any(source.git.credential in job.environment for job in jobs):
|
|
946
|
+
message = (
|
|
947
|
+
f"the spec source's credential {source.git.credential} has the name of a secret the"
|
|
948
|
+
" jobs read from the environment; give the clone's credential its own name"
|
|
949
|
+
)
|
|
950
|
+
raise CiError(message)
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
_UNQUOTABLE = re.compile(r"""[\s'"`\\]""")
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def _library_remote(options: PipelineOptions) -> str | None:
|
|
957
|
+
"""The mirror's Git URL, checked: one word, without quotes or backslashes."""
|
|
958
|
+
remote = options.library_remote
|
|
959
|
+
if remote is not None and (not remote or _UNQUOTABLE.search(remote)):
|
|
960
|
+
message = (
|
|
961
|
+
"the library's remote is a Git URL, without spaces, quotes or backslashes;"
|
|
962
|
+
f" {remote!r} is not one"
|
|
963
|
+
)
|
|
964
|
+
raise CiError(message)
|
|
965
|
+
return remote
|
|
966
|
+
|
|
967
|
+
|
|
968
|
+
def _docker(options: PipelineOptions) -> tuple[str | None, str | None]:
|
|
969
|
+
"""The Docker command and socket to write into the configuration, checked."""
|
|
970
|
+
docker = options.docker
|
|
971
|
+
if docker is not None and (not docker or _SPACE.search(docker) or docker.startswith("~")):
|
|
972
|
+
message = (
|
|
973
|
+
"the Docker command is one program, a name or an absolute path, without arguments or ~"
|
|
974
|
+
)
|
|
975
|
+
raise CiError(message)
|
|
976
|
+
socket = options.docker_socket
|
|
977
|
+
if socket is not None and (not socket.is_absolute() or ":" in str(socket)):
|
|
978
|
+
message = "the Docker socket must be an absolute path without `:`"
|
|
979
|
+
raise CiError(message)
|
|
980
|
+
return options.docker, None if socket is None else str(socket)
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def pipeline(spec: Spec, options: PipelineOptions) -> Pipeline:
|
|
984
|
+
"""The jobs to generate for one side of the boundary, decided here for every system."""
|
|
985
|
+
side = side_of(options.kinds, options.side)
|
|
986
|
+
chosen = frozenset(options.kinds)
|
|
987
|
+
docker, docker_socket = _docker(options)
|
|
988
|
+
if options.agent is Agent.KUBERNETES and (docker is not None or docker_socket is not None):
|
|
989
|
+
message = (
|
|
990
|
+
"on Kubernetes every job is a pod that runs the Datadouble image itself, without"
|
|
991
|
+
" Docker; leave out the Docker command and socket"
|
|
992
|
+
)
|
|
993
|
+
raise CiError(message)
|
|
994
|
+
if side is Side.PRODUCTION and not options.runner:
|
|
995
|
+
message = (
|
|
996
|
+
"build, promote and lock run only inside the production boundary; name the"
|
|
997
|
+
" runner they run on (decision 19)"
|
|
998
|
+
)
|
|
999
|
+
raise CiError(message)
|
|
1000
|
+
extra: list[Path] = []
|
|
1001
|
+
if JobKind.BUILD in chosen:
|
|
1002
|
+
if options.work is None or not options.work.is_absolute():
|
|
1003
|
+
message = (
|
|
1004
|
+
"build needs a work directory: an absolute path in production scratch space,"
|
|
1005
|
+
" kept between runs so a retried build resumes"
|
|
1006
|
+
)
|
|
1007
|
+
raise CiError(message)
|
|
1008
|
+
extra.append(options.work)
|
|
1009
|
+
if JobKind.PROMOTE in chosen and spec.promote is None:
|
|
1010
|
+
message = "promote needs the spec's `promote` section"
|
|
1011
|
+
raise CiError(message)
|
|
1012
|
+
if JobKind.FETCH in chosen and spec.fetch is None:
|
|
1013
|
+
message = "fetch needs the spec's `fetch` section"
|
|
1014
|
+
raise CiError(message)
|
|
1015
|
+
shared = _spec_mounts(options)
|
|
1016
|
+
records = _records(spec, side, options.work)
|
|
1017
|
+
context = _Context(options.spec_path, spec, side, chosen, str(options.work))
|
|
1018
|
+
jobs = tuple(
|
|
1019
|
+
replace(
|
|
1020
|
+
_manual(_recording(_JOBS[kind](context), spec, records), manual=options.manual),
|
|
1021
|
+
mounts=host_paths(
|
|
1022
|
+
spec,
|
|
1023
|
+
kind,
|
|
1024
|
+
side,
|
|
1025
|
+
(
|
|
1026
|
+
*(extra if kind is JobKind.BUILD else ()),
|
|
1027
|
+
*(() if records is None else (records,)),
|
|
1028
|
+
*shared,
|
|
1029
|
+
),
|
|
1030
|
+
options.remote,
|
|
1031
|
+
),
|
|
1032
|
+
environment=tuple(
|
|
1033
|
+
sorted(
|
|
1034
|
+
{*secret_names(spec, kind, side), *_implicit(spec, kind), *options.environment}
|
|
1035
|
+
)
|
|
1036
|
+
),
|
|
1037
|
+
)
|
|
1038
|
+
for kind in JobKind
|
|
1039
|
+
if kind in chosen
|
|
1040
|
+
)
|
|
1041
|
+
_distinct_credential(options.spec_source, jobs)
|
|
1042
|
+
return Pipeline(
|
|
1043
|
+
spec=options.spec_path,
|
|
1044
|
+
name=spec.name,
|
|
1045
|
+
side=side,
|
|
1046
|
+
jobs=jobs,
|
|
1047
|
+
runner=options.runner,
|
|
1048
|
+
image=options.image,
|
|
1049
|
+
version=options.version,
|
|
1050
|
+
user=options.owner,
|
|
1051
|
+
identity_token=(
|
|
1052
|
+
JobKind.BUILD in chosen and spec.signing is not None and spec.signing.cosign.keyless
|
|
1053
|
+
),
|
|
1054
|
+
spec_files=options.spec_files,
|
|
1055
|
+
lock_text=options.lock_text,
|
|
1056
|
+
notify=spec.notify,
|
|
1057
|
+
docker=docker,
|
|
1058
|
+
docker_socket=docker_socket,
|
|
1059
|
+
agent=options.agent,
|
|
1060
|
+
cloud=options.cloud,
|
|
1061
|
+
runtime=spec.runtime,
|
|
1062
|
+
spec_source=options.spec_source,
|
|
1063
|
+
manual=options.manual,
|
|
1064
|
+
library_remote=_library_remote(options),
|
|
1065
|
+
)
|
|
1066
|
+
|
|
1067
|
+
|
|
1068
|
+
RECORDS = ".datadouble-notify"
|
|
1069
|
+
"""The directory, in the work directory or staging, where jobs record their last outcomes."""
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def _records(spec: Spec, side: Side, work: Path | None) -> Path | None:
|
|
1073
|
+
"""Where the side's jobs record their outcomes, when a webhook hears of recoveries.
|
|
1074
|
+
|
|
1075
|
+
The production side records in the work directory, and the other side in
|
|
1076
|
+
staging (decision 142): each job's own side, kept between runs.
|
|
1077
|
+
"""
|
|
1078
|
+
if spec.notify is None or not spec.notify.recovers:
|
|
1079
|
+
return None
|
|
1080
|
+
if side is Side.PRODUCTION:
|
|
1081
|
+
if work is None or not work.is_absolute():
|
|
1082
|
+
message = (
|
|
1083
|
+
"notify's recovery webhooks need each job's last outcome, which production jobs"
|
|
1084
|
+
" record in the work directory: give the work directory as an absolute path"
|
|
1085
|
+
)
|
|
1086
|
+
raise CiError(message)
|
|
1087
|
+
return work
|
|
1088
|
+
if spec.fetch is None:
|
|
1089
|
+
message = (
|
|
1090
|
+
"notify's recovery webhooks need each job's last outcome, which non-production"
|
|
1091
|
+
" jobs record in staging: add the spec's `fetch` section"
|
|
1092
|
+
)
|
|
1093
|
+
raise CiError(message)
|
|
1094
|
+
return spec.fetch.staging
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def _recording(job: Job, spec: Spec, records: Path | None) -> Job:
|
|
1098
|
+
"""The job with each command line naming its record file after the command, if it keeps one.
|
|
1099
|
+
|
|
1100
|
+
A job with several command lines keeps a record for each, since each
|
|
1101
|
+
notifies on its own.
|
|
1102
|
+
"""
|
|
1103
|
+
if records is None:
|
|
1104
|
+
return job
|
|
1105
|
+
several = len(job.invocations) > 1
|
|
1106
|
+
return replace(
|
|
1107
|
+
job,
|
|
1108
|
+
invocations=tuple(
|
|
1109
|
+
replace(
|
|
1110
|
+
invocation,
|
|
1111
|
+
arguments=(
|
|
1112
|
+
invocation.arguments[0],
|
|
1113
|
+
"--ci-record",
|
|
1114
|
+
str(
|
|
1115
|
+
records
|
|
1116
|
+
/ RECORDS
|
|
1117
|
+
/ f"{spec.name}.{job.kind}{f'.{index}' if several else ''}.json"
|
|
1118
|
+
),
|
|
1119
|
+
*invocation.arguments[1:],
|
|
1120
|
+
),
|
|
1121
|
+
)
|
|
1122
|
+
for index, invocation in enumerate(job.invocations, start=1)
|
|
1123
|
+
),
|
|
1124
|
+
)
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
CLAIM = "datadouble"
|
|
1128
|
+
"""The PersistentVolumeClaim, in each side's namespace, that its pods share."""
|
|
1129
|
+
DEFAULT_MOUNT = "/srv/datadouble"
|
|
1130
|
+
"""Where the work claim is mounted when the spec names no path."""
|
|
1131
|
+
_OBJECT_NAME = re.compile(r"[a-z0-9]([-a-z0-9.]*[a-z0-9])?")
|
|
1132
|
+
_OBJECT_NAME_LENGTH = 253
|
|
1133
|
+
_POD_PATHS = ("/workspace", "/home/jenkins", "/etc/datadouble-boundary")
|
|
1134
|
+
"""What a job's pod already has at fixed paths on some system: the Argo CD chart's
|
|
1135
|
+
workspace and spec, the Jenkins agent's workspace, and the boundary mark."""
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
@dataclass(frozen=True, slots=True)
|
|
1139
|
+
class Claim:
|
|
1140
|
+
"""Another PersistentVolumeClaim the jobs' pods mount, and where."""
|
|
1141
|
+
|
|
1142
|
+
name: str
|
|
1143
|
+
mount: str
|
|
1144
|
+
|
|
1145
|
+
|
|
1146
|
+
def _claim(item: JsonValue, work: JsonValue) -> Claim:
|
|
1147
|
+
"""One entry of ``runtime.kubernetes.claims``, checked."""
|
|
1148
|
+
where = "each of the spec's runtime.kubernetes.claims"
|
|
1149
|
+
if not isinstance(item, dict) or set(item) != {"claim", "mount"}:
|
|
1150
|
+
message = f"{where} needs a claim and a mount, and nothing else"
|
|
1151
|
+
raise CiError(message)
|
|
1152
|
+
name, mount = item["claim"], item["mount"]
|
|
1153
|
+
if (
|
|
1154
|
+
not isinstance(name, str)
|
|
1155
|
+
or len(name) > _OBJECT_NAME_LENGTH
|
|
1156
|
+
or not _OBJECT_NAME.fullmatch(name)
|
|
1157
|
+
):
|
|
1158
|
+
message = f"{where} names a claim as a Kubernetes object name; {name!r} is not one"
|
|
1159
|
+
raise CiError(message)
|
|
1160
|
+
if name in (CLAIM, work):
|
|
1161
|
+
message = f"{name} is the work claim; runtime.kubernetes.claims lists the others"
|
|
1162
|
+
raise CiError(message)
|
|
1163
|
+
normal = (
|
|
1164
|
+
"/" + posixpath.normpath(mount).lstrip("/")
|
|
1165
|
+
if isinstance(mount, str)
|
|
1166
|
+
and mount.startswith("/")
|
|
1167
|
+
and ".." not in PurePosixPath(mount).parts
|
|
1168
|
+
else ""
|
|
1169
|
+
)
|
|
1170
|
+
if not _HOST_PATH.fullmatch(normal) or normal == "/":
|
|
1171
|
+
message = (
|
|
1172
|
+
f"the claim {name} must be mounted at an absolute directory other than /, without"
|
|
1173
|
+
" `..`, spaces, `:` or globs"
|
|
1174
|
+
)
|
|
1175
|
+
raise CiError(message)
|
|
1176
|
+
taken = [
|
|
1177
|
+
path
|
|
1178
|
+
for path in _POD_PATHS
|
|
1179
|
+
if PurePosixPath(normal).is_relative_to(path) or PurePosixPath(path).is_relative_to(normal)
|
|
1180
|
+
]
|
|
1181
|
+
if taken:
|
|
1182
|
+
message = (
|
|
1183
|
+
f"the claim {name} is mounted at {normal}, which a job's pod already uses for"
|
|
1184
|
+
f" {taken[0]}; mount it elsewhere"
|
|
1185
|
+
)
|
|
1186
|
+
raise CiError(message)
|
|
1187
|
+
return Claim(name, normal)
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
def other_claims(pipeline: Pipeline) -> tuple[Claim, ...]:
|
|
1191
|
+
"""The claims the jobs' pods mount besides the work claim: ``runtime.kubernetes.claims``.
|
|
1192
|
+
|
|
1193
|
+
They hold paths no engine reads or writes, such as ``promote``'s export
|
|
1194
|
+
directory, which can then be shared with a web server that never sees the
|
|
1195
|
+
work directory. Engine pods mount only the work claim.
|
|
1196
|
+
"""
|
|
1197
|
+
settings = (pipeline.runtime or {}).get("kubernetes")
|
|
1198
|
+
if not isinstance(settings, dict) or settings.get("claims") is None:
|
|
1199
|
+
return ()
|
|
1200
|
+
listed = settings["claims"]
|
|
1201
|
+
if not isinstance(listed, list):
|
|
1202
|
+
message = "the spec's runtime.kubernetes.claims is a list of claims and their mounts"
|
|
1203
|
+
raise CiError(message)
|
|
1204
|
+
claims = tuple(_claim(item, settings.get("claim")) for item in listed)
|
|
1205
|
+
mounted = pipeline.mounted()
|
|
1206
|
+
for claim in claims:
|
|
1207
|
+
if mounted is not None and (
|
|
1208
|
+
PurePosixPath(claim.mount).is_relative_to(mounted.path)
|
|
1209
|
+
or mounted.path.is_relative_to(claim.mount)
|
|
1210
|
+
):
|
|
1211
|
+
message = (
|
|
1212
|
+
f"the claim {claim.name} is mounted at {claim.mount}, which overlaps the spec's"
|
|
1213
|
+
f" directory {mounted.path}; mount it elsewhere"
|
|
1214
|
+
)
|
|
1215
|
+
raise CiError(message)
|
|
1216
|
+
names = [claim.name for claim in claims]
|
|
1217
|
+
if len(set(names)) != len(names):
|
|
1218
|
+
message = "the spec's runtime.kubernetes.claims names a claim more than once"
|
|
1219
|
+
raise CiError(message)
|
|
1220
|
+
for claim in claims:
|
|
1221
|
+
for other in claims:
|
|
1222
|
+
if other is not claim and PurePosixPath(claim.mount).is_relative_to(other.mount):
|
|
1223
|
+
message = (
|
|
1224
|
+
f"the claims {other.name} and {claim.name} are mounted one inside the other"
|
|
1225
|
+
)
|
|
1226
|
+
raise CiError(message)
|
|
1227
|
+
return claims
|
|
1228
|
+
|
|
1229
|
+
|
|
1230
|
+
def _holder(claims: tuple[Claim, ...], path: str) -> Claim | None:
|
|
1231
|
+
"""The other claim ``path`` is on, if it is on one."""
|
|
1232
|
+
return next((c for c in claims if PurePosixPath(path).is_relative_to(c.mount)), None)
|
|
1233
|
+
|
|
1234
|
+
|
|
1235
|
+
def runtime_namespace(pipeline: Pipeline, namespace: str) -> None:
|
|
1236
|
+
"""Refuse a ``kubernetes`` runtime that starts a side's engine pods in another namespace.
|
|
1237
|
+
|
|
1238
|
+
Engine pods mount the side's claim, which lives in the side's namespace
|
|
1239
|
+
(``--runner``). Left out, the runtime's namespace is the one Datadouble's
|
|
1240
|
+
own pod runs in, which is that side's, so one spec serves both sides; set,
|
|
1241
|
+
it must be this side's for jobs that start engines.
|
|
1242
|
+
"""
|
|
1243
|
+
settings = (pipeline.runtime or {}).get("kubernetes")
|
|
1244
|
+
if not isinstance(settings, dict):
|
|
1245
|
+
return
|
|
1246
|
+
named = settings.get("namespace")
|
|
1247
|
+
starting = any("runtime" in sections(job.kind, pipeline.side) for job in pipeline.jobs)
|
|
1248
|
+
if starting and named is not None and named != namespace:
|
|
1249
|
+
message = (
|
|
1250
|
+
f"the spec's runtime.kubernetes.namespace is {named}, but the {pipeline.side}"
|
|
1251
|
+
f" side's pods run in {namespace} (--runner), whose claim the engine pods mount;"
|
|
1252
|
+
" leave the namespace out, so engine pods start in each side's own namespace"
|
|
1253
|
+
)
|
|
1254
|
+
raise CiError(message)
|
|
1255
|
+
|
|
1256
|
+
|
|
1257
|
+
def claim_mount(pipeline: Pipeline, mount: str | None = None) -> str:
|
|
1258
|
+
"""The directory of the work claim, which every path the jobs mount is on but the others'.
|
|
1259
|
+
|
|
1260
|
+
On Kubernetes, Datadouble's pod and the engine pods share files through one
|
|
1261
|
+
claim, mounted at the same path in each, so every path the spec names must
|
|
1262
|
+
be under its mount: ``mount`` when the spec's runtime names it, otherwise
|
|
1263
|
+
the paths' common directory. The exceptions are paths on the other claims
|
|
1264
|
+
the spec's runtime lists (:func:`other_claims`), which only the jobs' own
|
|
1265
|
+
pods mount, so no job that starts engines may name one.
|
|
1266
|
+
"""
|
|
1267
|
+
others = other_claims(pipeline)
|
|
1268
|
+
for job in pipeline.jobs:
|
|
1269
|
+
if "runtime" not in sections(job.kind, pipeline.side):
|
|
1270
|
+
continue
|
|
1271
|
+
elsewhere = [
|
|
1272
|
+
f"{path} ({claim.name})" for path in job.mounts if (claim := _holder(others, path))
|
|
1273
|
+
]
|
|
1274
|
+
if elsewhere:
|
|
1275
|
+
message = (
|
|
1276
|
+
f"{job.kind} starts engine pods, which mount only the work claim, but these of"
|
|
1277
|
+
f" its paths are on other claims: {', '.join(elsewhere)}"
|
|
1278
|
+
)
|
|
1279
|
+
raise CiError(message)
|
|
1280
|
+
paths = sorted(
|
|
1281
|
+
{path for job in pipeline.jobs for path in job.mounts if _holder(others, path) is None}
|
|
1282
|
+
)
|
|
1283
|
+
if mount is not None:
|
|
1284
|
+
outside = [path for path in paths if not PurePosixPath(path).is_relative_to(mount)]
|
|
1285
|
+
if outside:
|
|
1286
|
+
message = (
|
|
1287
|
+
"on Kubernetes every path the spec names lives on the work claim, mounted at"
|
|
1288
|
+
f" {mount}, or on a claim runtime.kubernetes.claims lists; these are on"
|
|
1289
|
+
f" neither: {', '.join(outside)}"
|
|
1290
|
+
)
|
|
1291
|
+
raise CiError(message)
|
|
1292
|
+
work = mount
|
|
1293
|
+
elif not paths:
|
|
1294
|
+
work = DEFAULT_MOUNT
|
|
1295
|
+
else:
|
|
1296
|
+
work = posixpath.commonpath(paths)
|
|
1297
|
+
if work == "/":
|
|
1298
|
+
message = (
|
|
1299
|
+
"on Kubernetes every path the spec names lives on one PersistentVolumeClaim,"
|
|
1300
|
+
" or on a claim runtime.kubernetes.claims lists, so the others must share a"
|
|
1301
|
+
f" directory; these do not: {', '.join(paths)}"
|
|
1302
|
+
)
|
|
1303
|
+
raise CiError(message)
|
|
1304
|
+
for claim in others:
|
|
1305
|
+
if PurePosixPath(claim.mount).is_relative_to(work) or PurePosixPath(work).is_relative_to(
|
|
1306
|
+
claim.mount
|
|
1307
|
+
):
|
|
1308
|
+
message = (
|
|
1309
|
+
f"the claim {claim.name} is mounted at {claim.mount}, which overlaps the work"
|
|
1310
|
+
f" claim's {work}; mount it apart"
|
|
1311
|
+
)
|
|
1312
|
+
raise CiError(message)
|
|
1313
|
+
return work
|
|
1314
|
+
|
|
1315
|
+
|
|
1316
|
+
def job_claims(pipeline: Pipeline, job: Job) -> tuple[Claim, ...]:
|
|
1317
|
+
"""The other claims a job's pod mounts: those its own paths are on.
|
|
1318
|
+
|
|
1319
|
+
One spec serves both sides, and a claim such as production's export
|
|
1320
|
+
exists only on the side that uses it, so a job mounts no claim it has no
|
|
1321
|
+
path on.
|
|
1322
|
+
"""
|
|
1323
|
+
return tuple(
|
|
1324
|
+
claim
|
|
1325
|
+
for claim in other_claims(pipeline)
|
|
1326
|
+
if any(_holder((claim,), path) for path in job.mounts)
|
|
1327
|
+
)
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
def side_claims(pipeline: Pipeline) -> tuple[Claim, ...]:
|
|
1331
|
+
"""The other claims any of the side's jobs mount, in the spec's order."""
|
|
1332
|
+
used = {claim for job in pipeline.jobs for claim in job_claims(pipeline, job)}
|
|
1333
|
+
return tuple(claim for claim in other_claims(pipeline) if claim in used)
|
|
1334
|
+
|
|
1335
|
+
|
|
1336
|
+
def other_claim_steps(pipeline: Pipeline, namespace: str) -> tuple[str, ...]:
|
|
1337
|
+
"""The setup steps for the other claims the side's jobs mount, for Kubernetes systems."""
|
|
1338
|
+
return tuple(
|
|
1339
|
+
f"in {namespace}, create the PersistentVolumeClaim {claim.name}, holding {claim.mount},"
|
|
1340
|
+
f" owned by {pipeline.user}; the pods of the jobs with paths on it mount it, and engine"
|
|
1341
|
+
" pods never do"
|
|
1342
|
+
for claim in side_claims(pipeline)
|
|
1343
|
+
)
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
def config_map_step(pipeline: Pipeline, namespace: str) -> tuple[str, ...]:
|
|
1347
|
+
"""The setup step for a ``mounted`` spec source's ConfigMap, for Kubernetes systems."""
|
|
1348
|
+
mounted = pipeline.mounted()
|
|
1349
|
+
if mounted is None or mounted.config_map is None:
|
|
1350
|
+
return ()
|
|
1351
|
+
name = PurePosixPath(pipeline.spec).name
|
|
1352
|
+
step = (
|
|
1353
|
+
f"in {namespace}, keep the ConfigMap {mounted.config_map} holding the spec's directory,"
|
|
1354
|
+
f" one key per file name: {name}, the specs it extends and its lock; the pods mount it"
|
|
1355
|
+
f" read-only at {mounted.path}"
|
|
1356
|
+
)
|
|
1357
|
+
return (step,)
|