datadouble-kubernetes 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_kubernetes/__init__.py +580 -0
- datadouble_kubernetes/py.typed +0 -0
- datadouble_kubernetes/runtime.py +432 -0
- datadouble_kubernetes-0.0.3.dist-info/METADATA +267 -0
- datadouble_kubernetes-0.0.3.dist-info/RECORD +8 -0
- datadouble_kubernetes-0.0.3.dist-info/WHEEL +4 -0
- datadouble_kubernetes-0.0.3.dist-info/entry_points.txt +8 -0
- datadouble_kubernetes-0.0.3.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Kubernetes adapters for Datadouble: ``k8s-pv`` (replicate) and ``k8s-secret`` (announce).
|
|
5
|
+
|
|
6
|
+
A ``k8s-pv`` copy is a directory and a PersistentVolume pointing at it, either
|
|
7
|
+
a local volume on one node or an NFS export. The volume is both the copy's
|
|
8
|
+
handle and its announcement: it carries the copy's labels, which consumers
|
|
9
|
+
match with a PersistentVolumeClaim selector. A bound volume counts as claimed;
|
|
10
|
+
when its claim is deleted the volume is released, and the copy is removed and
|
|
11
|
+
the pool refilled. A group's files, when the spec has them, get a second
|
|
12
|
+
directory and volume, ``datadouble-<copy id>-files``, labelled with the same
|
|
13
|
+
copy and ``engine: files``; the database's volume decides whether the copy is
|
|
14
|
+
claimed.
|
|
15
|
+
|
|
16
|
+
``k8s-secret`` writes a Secret per copy with where it is and, for instance
|
|
17
|
+
copies, its credentials, into ``namespace``; left out, the namespace
|
|
18
|
+
``kubectl`` would use (:func:`current_namespace`), as for the ``kubernetes``
|
|
19
|
+
runtime. Both drive ``kubectl``.
|
|
20
|
+
|
|
21
|
+
Every Kubernetes adapter takes an optional ``kubeconfig``, a secret reference
|
|
22
|
+
to a kubeconfig's content, and an optional ``context``. The kubeconfig is
|
|
23
|
+
written to a private temporary file for each ``kubectl`` call, passed with
|
|
24
|
+
``--kubeconfig``, and removed when the call ends, whether or not it
|
|
25
|
+
succeeded. Without one, ``kubectl`` uses the in-cluster service account or
|
|
26
|
+
the ambient configuration.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import re
|
|
32
|
+
import shutil
|
|
33
|
+
import tempfile
|
|
34
|
+
from collections.abc import Generator, Iterator, Mapping, Sequence
|
|
35
|
+
from contextlib import contextmanager, suppress
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import TYPE_CHECKING, Self
|
|
38
|
+
|
|
39
|
+
import yaml
|
|
40
|
+
from pydantic import (
|
|
41
|
+
BaseModel,
|
|
42
|
+
ConfigDict,
|
|
43
|
+
Field,
|
|
44
|
+
JsonValue,
|
|
45
|
+
TypeAdapter,
|
|
46
|
+
ValidationError,
|
|
47
|
+
model_validator,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
from datadouble.announce import Announced, AnnounceError, Announcer
|
|
51
|
+
from datadouble.files import copy_tree
|
|
52
|
+
from datadouble.images import ImageSummary
|
|
53
|
+
from datadouble.programs import Completed, locate, run_program, start_program
|
|
54
|
+
from datadouble.replicate import (
|
|
55
|
+
ClaimState,
|
|
56
|
+
Copy,
|
|
57
|
+
CopyKind,
|
|
58
|
+
Made,
|
|
59
|
+
ReplicateError,
|
|
60
|
+
Replicator,
|
|
61
|
+
StagedImage,
|
|
62
|
+
copy_names,
|
|
63
|
+
files_id,
|
|
64
|
+
)
|
|
65
|
+
from datadouble.secrets import SecretError, resolve_secret
|
|
66
|
+
from datadouble.settings import parse_settings, remote
|
|
67
|
+
from datadouble.spec import EnvSecret, FileSecret, SecretRef
|
|
68
|
+
|
|
69
|
+
if TYPE_CHECKING:
|
|
70
|
+
import subprocess
|
|
71
|
+
|
|
72
|
+
_LABEL = "datadouble.dev"
|
|
73
|
+
_PHASES = {
|
|
74
|
+
"Available": ClaimState.FREE,
|
|
75
|
+
"Pending": ClaimState.FREE,
|
|
76
|
+
"Bound": ClaimState.CLAIMED,
|
|
77
|
+
"Released": ClaimState.RETURNED,
|
|
78
|
+
"Failed": ClaimState.RETURNED,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class KubectlError(Exception):
|
|
83
|
+
"""A ``kubectl`` command that failed."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def kubectl_binary() -> str:
|
|
87
|
+
"""``DATADOUBLE_KUBECTL``, or ``kubectl`` on ``PATH``."""
|
|
88
|
+
binary = locate("kubectl", "DATADOUBLE_KUBECTL")
|
|
89
|
+
if not binary:
|
|
90
|
+
message = "kubectl was not found; install it or set DATADOUBLE_KUBECTL"
|
|
91
|
+
raise KubectlError(message)
|
|
92
|
+
return binary
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
REDACTED_LENGTH = 16
|
|
96
|
+
"""String values of a kubeconfig at least this long are secret (tokens, keys,
|
|
97
|
+
certificates, server URLs): masked in CI logs and removed from ``kubectl``'s output."""
|
|
98
|
+
_LINE_VALUE = re.compile(r"""^[\s-]*(?:["']?[\w.-]+["']?\s*:\s*)?(.*?)[\s,]*$""")
|
|
99
|
+
"""A line's value, after any list marker and key, in YAML or JSON."""
|
|
100
|
+
_JSON: TypeAdapter[JsonValue] = TypeAdapter(JsonValue)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _strings(value: JsonValue) -> Iterator[str]:
|
|
104
|
+
if isinstance(value, str):
|
|
105
|
+
yield value
|
|
106
|
+
elif isinstance(value, dict):
|
|
107
|
+
for item in value.values():
|
|
108
|
+
yield from _strings(item)
|
|
109
|
+
elif isinstance(value, list):
|
|
110
|
+
for item in value:
|
|
111
|
+
yield from _strings(item)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def secret_values(content: str) -> tuple[str, ...]:
|
|
115
|
+
"""A kubeconfig's secret values, longest first.
|
|
116
|
+
|
|
117
|
+
Those are its string values at least :data:`REDACTED_LENGTH` characters long,
|
|
118
|
+
from YAML or JSON, and from each line in case it does not parse.
|
|
119
|
+
"""
|
|
120
|
+
found: set[str] = set()
|
|
121
|
+
with suppress(yaml.YAMLError, ValidationError):
|
|
122
|
+
found.update(_strings(_JSON.validate_python(yaml.safe_load(content))))
|
|
123
|
+
for line in content.splitlines():
|
|
124
|
+
found.add(_LINE_VALUE.sub(r"\1", line).strip("'\""))
|
|
125
|
+
return tuple(sorted((v for v in found if len(v) >= REDACTED_LENGTH), key=len, reverse=True))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class Kubectl:
|
|
129
|
+
"""``kubectl``, with a cluster's kubeconfig and context when they are given."""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
kubeconfig: SecretRef | None = None,
|
|
134
|
+
context: str | None = None,
|
|
135
|
+
*,
|
|
136
|
+
avoid: Path | None = None,
|
|
137
|
+
) -> None:
|
|
138
|
+
"""Use ``kubeconfig``, a reference to a kubeconfig's content, and ``context``.
|
|
139
|
+
|
|
140
|
+
The kubeconfig's temporary file is never written under ``avoid``, such as
|
|
141
|
+
a work directory that pods mount.
|
|
142
|
+
"""
|
|
143
|
+
self.kubeconfig = kubeconfig
|
|
144
|
+
self.context = context
|
|
145
|
+
self.avoid = avoid
|
|
146
|
+
self._content: str | None = None
|
|
147
|
+
self._secrets: tuple[str, ...] = ()
|
|
148
|
+
|
|
149
|
+
def resolve(self) -> None:
|
|
150
|
+
"""Resolve the kubeconfig now, so a missing one fails before any work.
|
|
151
|
+
|
|
152
|
+
Raises :class:`~datadouble.secrets.SecretError` when it cannot be resolved.
|
|
153
|
+
"""
|
|
154
|
+
if self.kubeconfig is not None and self._content is None:
|
|
155
|
+
content = resolve_secret(self.kubeconfig, masked=secret_values)
|
|
156
|
+
self._secrets = secret_values(content)
|
|
157
|
+
self._content = content
|
|
158
|
+
|
|
159
|
+
def _directory(self) -> Path:
|
|
160
|
+
"""A new private directory (0700), outside ``avoid``."""
|
|
161
|
+
for base in (Path(tempfile.gettempdir()), Path.home()):
|
|
162
|
+
inside = self.avoid is not None and base.resolve().is_relative_to(self.avoid.resolve())
|
|
163
|
+
if not inside:
|
|
164
|
+
return Path(tempfile.mkdtemp(prefix="datadouble-kubeconfig-", dir=base))
|
|
165
|
+
message = (
|
|
166
|
+
f"the temporary directory and home are under {self.avoid}, which pods mount;"
|
|
167
|
+
" set TMPDIR elsewhere for the kubeconfig"
|
|
168
|
+
)
|
|
169
|
+
raise KubectlError(message)
|
|
170
|
+
|
|
171
|
+
@contextmanager
|
|
172
|
+
def options(self) -> Generator[list[str]]:
|
|
173
|
+
"""Global options for ``kubectl`` calls inside the block.
|
|
174
|
+
|
|
175
|
+
A kubeconfig is written to a file only its owner can read, in a private
|
|
176
|
+
temporary directory, both removed when the block ends, even after a failure.
|
|
177
|
+
"""
|
|
178
|
+
options = [f"--context={self.context}"] if self.context else []
|
|
179
|
+
self.resolve()
|
|
180
|
+
if self._content is None:
|
|
181
|
+
yield options
|
|
182
|
+
return
|
|
183
|
+
directory = self._directory()
|
|
184
|
+
path = directory / "kubeconfig"
|
|
185
|
+
try:
|
|
186
|
+
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
187
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
188
|
+
handle.write(self._content + "\n")
|
|
189
|
+
yield [f"--kubeconfig={path}", *options]
|
|
190
|
+
finally:
|
|
191
|
+
path.unlink(missing_ok=True)
|
|
192
|
+
directory.rmdir()
|
|
193
|
+
|
|
194
|
+
def run(self, arguments: Sequence[str], *, stdin: str | None = None) -> Completed:
|
|
195
|
+
"""Run ``kubectl`` and return what it did, without the kubeconfig's secret values."""
|
|
196
|
+
binary = kubectl_binary()
|
|
197
|
+
with self.options() as options:
|
|
198
|
+
done = run_program(binary, [*options, *arguments], stdin=stdin)
|
|
199
|
+
return Completed(done.status, self.redact(done.stdout), self.redact(done.stderr))
|
|
200
|
+
|
|
201
|
+
@contextmanager
|
|
202
|
+
def started(self, arguments: Sequence[str]) -> "Generator[subprocess.Popen[str]]":
|
|
203
|
+
"""``kubectl`` running for the block, such as a port-forward; stopped afterwards."""
|
|
204
|
+
binary = kubectl_binary()
|
|
205
|
+
with self.options() as options:
|
|
206
|
+
process = start_program(binary, [*options, *arguments])
|
|
207
|
+
try:
|
|
208
|
+
yield process
|
|
209
|
+
finally:
|
|
210
|
+
process.terminate()
|
|
211
|
+
process.wait()
|
|
212
|
+
|
|
213
|
+
def __call__(self, arguments: Sequence[str], *, stdin: str | None = None) -> str:
|
|
214
|
+
"""Run ``kubectl``; raise :class:`KubectlError` with its last error line."""
|
|
215
|
+
done = self.run(arguments, stdin=stdin)
|
|
216
|
+
if done.status != 0:
|
|
217
|
+
message = f"kubectl {arguments[0]} failed: {done.last_error()}"
|
|
218
|
+
raise KubectlError(message)
|
|
219
|
+
return done.stdout
|
|
220
|
+
|
|
221
|
+
def redact(self, text: str) -> str:
|
|
222
|
+
"""``text`` with each of the kubeconfig's secret values replaced by ``[redacted]``."""
|
|
223
|
+
for value in self._secrets:
|
|
224
|
+
text = text.replace(value, "[redacted]")
|
|
225
|
+
return text
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
SERVICE_ACCOUNT_NAMESPACE = Path("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
|
|
229
|
+
"""The namespace of the pod a process runs in, as Kubernetes mounts it for its service account."""
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _kubeconfig_source(kubectl: Kubectl) -> str:
|
|
233
|
+
"""Which kubeconfig and context ``kubectl`` reads, for errors; never their content."""
|
|
234
|
+
kubeconfig = kubectl.kubeconfig
|
|
235
|
+
if isinstance(kubeconfig, EnvSecret):
|
|
236
|
+
source = f"the kubeconfig in {kubeconfig.env}"
|
|
237
|
+
elif isinstance(kubeconfig, FileSecret):
|
|
238
|
+
source = f"the kubeconfig at {kubeconfig.file}"
|
|
239
|
+
elif os.environ.get("KUBECONFIG"):
|
|
240
|
+
source = "the kubeconfig KUBECONFIG names"
|
|
241
|
+
else:
|
|
242
|
+
source = "the default kubeconfig"
|
|
243
|
+
context = f"context {kubectl.context}" if kubectl.context else "the current context"
|
|
244
|
+
return f"{context} of {source}"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def current_namespace(kubectl: Kubectl) -> str:
|
|
248
|
+
"""The namespace ``kubectl`` uses when told none.
|
|
249
|
+
|
|
250
|
+
Inside a cluster, with no kubeconfig (neither the settings' nor a non-empty
|
|
251
|
+
``KUBECONFIG``), that is the namespace of the pod Datadouble runs in;
|
|
252
|
+
otherwise the namespace of the kubeconfig's context (the settings'
|
|
253
|
+
``context``, or its current one), or ``default`` when it names none.
|
|
254
|
+
Raises :class:`KubectlError` when ``kubectl`` cannot be found or cannot
|
|
255
|
+
read that context, naming the kubeconfig and context.
|
|
256
|
+
"""
|
|
257
|
+
in_cluster = kubectl.kubeconfig is None and not os.environ.get("KUBECONFIG")
|
|
258
|
+
if in_cluster and SERVICE_ACCOUNT_NAMESPACE.is_file():
|
|
259
|
+
return SERVICE_ACCOUNT_NAMESPACE.read_text(encoding="utf-8").strip()
|
|
260
|
+
done = kubectl.run(["config", "view", "--minify", "--output=jsonpath={..namespace}"])
|
|
261
|
+
if done.status != 0:
|
|
262
|
+
message = (
|
|
263
|
+
f"cannot read the namespace of {_kubeconfig_source(kubectl)}:"
|
|
264
|
+
f" kubectl config failed: {done.last_error()}"
|
|
265
|
+
)
|
|
266
|
+
raise KubectlError(message)
|
|
267
|
+
return done.stdout.strip() or "default"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _labels(values: Mapping[str, str]) -> dict[str, str]:
|
|
271
|
+
"""Kubernetes-safe labels under the datadouble.dev prefix."""
|
|
272
|
+
safe: dict[str, str] = {}
|
|
273
|
+
for key, value in values.items():
|
|
274
|
+
cleaned = "".join(c if c.isalnum() or c in "-_." else "-" for c in value)[:63]
|
|
275
|
+
safe[f"{_LABEL}/{key}"] = cleaned.strip("-_.") or "none"
|
|
276
|
+
return safe
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class LocalVolume(BaseModel):
|
|
280
|
+
"""A local volume on one node, where ``path`` is that node's filesystem."""
|
|
281
|
+
|
|
282
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
283
|
+
|
|
284
|
+
node: str
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
class NfsVolume(BaseModel):
|
|
288
|
+
"""An NFS export; ``path`` here is the export path matching the adapter's ``path``."""
|
|
289
|
+
|
|
290
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
291
|
+
|
|
292
|
+
server: str
|
|
293
|
+
path: str
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
class ClusterSettings(BaseModel):
|
|
297
|
+
"""How a Kubernetes adapter reaches its cluster."""
|
|
298
|
+
|
|
299
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
300
|
+
|
|
301
|
+
kubeconfig: SecretRef | None = None
|
|
302
|
+
"""A reference to a kubeconfig's content (``{env: NAME}`` or ``{file: path}``);
|
|
303
|
+
without one, the in-cluster service account or the ambient configuration."""
|
|
304
|
+
context: str | None = Field(default=None, min_length=1)
|
|
305
|
+
"""The kubeconfig's context to use; its current context otherwise."""
|
|
306
|
+
|
|
307
|
+
def kubectl(self, avoid: Path | None = None) -> Kubectl:
|
|
308
|
+
"""``kubectl`` for this cluster, keeping its kubeconfig out of ``avoid``."""
|
|
309
|
+
return Kubectl(self.kubeconfig, self.context, avoid=avoid)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class PvSettings(ClusterSettings):
|
|
313
|
+
"""Settings for the ``k8s-pv`` replicate adapter."""
|
|
314
|
+
|
|
315
|
+
path: Path
|
|
316
|
+
"""Where copies are written, as this process sees it."""
|
|
317
|
+
local: LocalVolume | None = None
|
|
318
|
+
nfs: NfsVolume | None = None
|
|
319
|
+
storage_class: str = "datadouble"
|
|
320
|
+
access_mode: str = "ReadWriteOnce"
|
|
321
|
+
capacity: str = Field(default="1Gi", pattern=r"^\d+[KMGT]i$")
|
|
322
|
+
|
|
323
|
+
@model_validator(mode="after")
|
|
324
|
+
def _one_kind(self) -> Self:
|
|
325
|
+
if (self.local is None) == (self.nfs is None):
|
|
326
|
+
message = "give exactly one of `local` or `nfs`"
|
|
327
|
+
raise ValueError(message)
|
|
328
|
+
return self
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class PvReplicator:
|
|
332
|
+
"""Directory copies exposed as PersistentVolumes."""
|
|
333
|
+
|
|
334
|
+
def __init__(self, settings: PvSettings) -> None:
|
|
335
|
+
"""Copy under ``settings.path``."""
|
|
336
|
+
self.settings = settings
|
|
337
|
+
self.kubectl = settings.kubectl()
|
|
338
|
+
|
|
339
|
+
@property
|
|
340
|
+
def kind(self) -> CopyKind:
|
|
341
|
+
"""Volumes."""
|
|
342
|
+
return CopyKind.VOLUME
|
|
343
|
+
|
|
344
|
+
def _source(self, directory: str) -> dict[str, JsonValue]:
|
|
345
|
+
settings = self.settings
|
|
346
|
+
if settings.nfs is not None:
|
|
347
|
+
path = f"{settings.nfs.path.rstrip('/')}/{directory}"
|
|
348
|
+
return {"nfs": {"server": settings.nfs.server, "path": path}}
|
|
349
|
+
node = settings.local.node if settings.local else ""
|
|
350
|
+
return {
|
|
351
|
+
"local": {"path": str(settings.path / directory)},
|
|
352
|
+
"nodeAffinity": {
|
|
353
|
+
"required": {
|
|
354
|
+
"nodeSelectorTerms": [
|
|
355
|
+
{
|
|
356
|
+
"matchExpressions": [
|
|
357
|
+
{
|
|
358
|
+
"key": "kubernetes.io/hostname",
|
|
359
|
+
"operator": "In",
|
|
360
|
+
"values": [node],
|
|
361
|
+
}
|
|
362
|
+
]
|
|
363
|
+
}
|
|
364
|
+
]
|
|
365
|
+
}
|
|
366
|
+
},
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
def create(
|
|
370
|
+
self, copy_id: str, image: Path, summary: ImageSummary, files: StagedImage | None = None
|
|
371
|
+
) -> Made:
|
|
372
|
+
"""Copy the image, then create the volume; the same for the group's files, if given."""
|
|
373
|
+
self.kubectl.resolve()
|
|
374
|
+
made = Made(location=self._volume(copy_id, copy_id, image, summary))
|
|
375
|
+
if files is None:
|
|
376
|
+
return made
|
|
377
|
+
location = self._volume(copy_id, files_id(copy_id), files.path, files.summary)
|
|
378
|
+
return made.model_copy(update={"files": location})
|
|
379
|
+
|
|
380
|
+
def _volume(
|
|
381
|
+
self, copy_id: str, directory: str, image: Path, summary: ImageSummary
|
|
382
|
+
) -> dict[str, JsonValue]:
|
|
383
|
+
root = self.settings.path
|
|
384
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
385
|
+
partial = root / f".{directory}.partial"
|
|
386
|
+
problem = copy_tree(image, partial)
|
|
387
|
+
if problem:
|
|
388
|
+
shutil.rmtree(partial, ignore_errors=True)
|
|
389
|
+
message = f"copying {summary.identity.generation} failed: {problem}"
|
|
390
|
+
raise ReplicateError(message)
|
|
391
|
+
partial.rename(root / directory)
|
|
392
|
+
identity = summary.identity
|
|
393
|
+
name = f"datadouble-{directory}"
|
|
394
|
+
labels = _labels(
|
|
395
|
+
{
|
|
396
|
+
"copy": copy_id,
|
|
397
|
+
"spec": identity.spec,
|
|
398
|
+
"group": identity.group,
|
|
399
|
+
"engine": identity.engine,
|
|
400
|
+
"engine-version": identity.engine_version,
|
|
401
|
+
"generation": identity.generation,
|
|
402
|
+
**({"server-version": summary.server_version} if summary.server_version else {}),
|
|
403
|
+
}
|
|
404
|
+
)
|
|
405
|
+
volume: dict[str, JsonValue] = {
|
|
406
|
+
"apiVersion": "v1",
|
|
407
|
+
"kind": "PersistentVolume",
|
|
408
|
+
"metadata": {"name": name, "labels": dict(labels)},
|
|
409
|
+
"spec": {
|
|
410
|
+
"capacity": {"storage": self.settings.capacity},
|
|
411
|
+
"accessModes": [self.settings.access_mode],
|
|
412
|
+
"persistentVolumeReclaimPolicy": "Retain",
|
|
413
|
+
"storageClassName": self.settings.storage_class,
|
|
414
|
+
"volumeMode": "Filesystem",
|
|
415
|
+
**self._source(directory),
|
|
416
|
+
},
|
|
417
|
+
}
|
|
418
|
+
try:
|
|
419
|
+
self.kubectl(["apply", "--filename=-", "--output=name"], stdin=json.dumps(volume))
|
|
420
|
+
except KubectlError as error:
|
|
421
|
+
shutil.rmtree(root / directory, ignore_errors=True)
|
|
422
|
+
raise ReplicateError(str(error)) from None
|
|
423
|
+
return {
|
|
424
|
+
"persistent_volume": name,
|
|
425
|
+
"storage_class": self.settings.storage_class,
|
|
426
|
+
"path": str(root / directory),
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
def destroy(self, copy: Copy) -> None:
|
|
430
|
+
"""Delete the volumes and the directories."""
|
|
431
|
+
for directory in copy_names(copy):
|
|
432
|
+
try:
|
|
433
|
+
self.kubectl(
|
|
434
|
+
[
|
|
435
|
+
"delete",
|
|
436
|
+
"persistentvolume",
|
|
437
|
+
f"datadouble-{directory}",
|
|
438
|
+
"--ignore-not-found",
|
|
439
|
+
"--wait=false",
|
|
440
|
+
]
|
|
441
|
+
)
|
|
442
|
+
except KubectlError as error:
|
|
443
|
+
raise ReplicateError(str(error)) from None
|
|
444
|
+
for path in (
|
|
445
|
+
self.settings.path / directory,
|
|
446
|
+
self.settings.path / f".{directory}.partial",
|
|
447
|
+
):
|
|
448
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
449
|
+
|
|
450
|
+
def claim_state(self, copy: Copy, /) -> ClaimState:
|
|
451
|
+
"""The volume's phase: available, bound (claimed), or released (returned)."""
|
|
452
|
+
try:
|
|
453
|
+
phase = self.kubectl(
|
|
454
|
+
[
|
|
455
|
+
"get",
|
|
456
|
+
"persistentvolume",
|
|
457
|
+
f"datadouble-{copy.id}",
|
|
458
|
+
"--ignore-not-found",
|
|
459
|
+
"--output=jsonpath={.status.phase}",
|
|
460
|
+
]
|
|
461
|
+
).strip()
|
|
462
|
+
except KubectlError as error:
|
|
463
|
+
raise ReplicateError(str(error)) from None
|
|
464
|
+
return _PHASES.get(phase, ClaimState.RETURNED)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
class SecretSettings(ClusterSettings):
|
|
468
|
+
"""Settings for the ``k8s-secret`` announce adapter."""
|
|
469
|
+
|
|
470
|
+
namespace: str | None = Field(default=None, min_length=1)
|
|
471
|
+
"""Where Secrets are written; Datadouble's own namespace (or kubectl's) when left out."""
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
class SecretAnnouncer:
|
|
475
|
+
"""A Secret per copy, named ``datadouble-<copy id>``."""
|
|
476
|
+
|
|
477
|
+
def __init__(self, settings: SecretSettings) -> None:
|
|
478
|
+
"""Write Secrets into ``settings.namespace``, or :func:`current_namespace`."""
|
|
479
|
+
self.settings = settings
|
|
480
|
+
self.kubectl = settings.kubectl()
|
|
481
|
+
self._namespace = settings.namespace
|
|
482
|
+
|
|
483
|
+
@property
|
|
484
|
+
def namespace(self) -> str:
|
|
485
|
+
"""Where Secrets are written: the settings', or :func:`current_namespace`."""
|
|
486
|
+
if self._namespace is None:
|
|
487
|
+
try:
|
|
488
|
+
self._namespace = current_namespace(self.kubectl)
|
|
489
|
+
except KubectlError as error:
|
|
490
|
+
raise AnnounceError(str(error)) from None
|
|
491
|
+
return self._namespace
|
|
492
|
+
|
|
493
|
+
def announce(self, copies: tuple[Announced, ...]) -> tuple[str, ...]:
|
|
494
|
+
"""Create or update one Secret per copy."""
|
|
495
|
+
written: list[str] = []
|
|
496
|
+
for copy in copies:
|
|
497
|
+
data = {key: str(value) for key, value in copy.location.items()}
|
|
498
|
+
data.update(copy.secrets)
|
|
499
|
+
data["copy_id"] = copy.copy_id
|
|
500
|
+
secret = {
|
|
501
|
+
"apiVersion": "v1",
|
|
502
|
+
"kind": "Secret",
|
|
503
|
+
"type": "Opaque",
|
|
504
|
+
"metadata": {
|
|
505
|
+
"name": f"datadouble-{copy.copy_id}",
|
|
506
|
+
"namespace": self.namespace,
|
|
507
|
+
"labels": _labels({"copy": copy.copy_id, **copy.labels}),
|
|
508
|
+
},
|
|
509
|
+
"stringData": data,
|
|
510
|
+
}
|
|
511
|
+
try:
|
|
512
|
+
self.kubectl(["apply", "--filename=-", "--output=name"], stdin=json.dumps(secret))
|
|
513
|
+
except KubectlError as error:
|
|
514
|
+
raise AnnounceError(str(error), written=tuple(written)) from None
|
|
515
|
+
written.append(f"k8s-secret:{self.namespace}/datadouble-{copy.copy_id}")
|
|
516
|
+
return tuple(written)
|
|
517
|
+
|
|
518
|
+
def _places(
|
|
519
|
+
self, copy_ids: tuple[str, ...], announced: tuple[str, ...]
|
|
520
|
+
) -> tuple[dict[str, list[str]], list[str]]:
|
|
521
|
+
"""Each namespace's Secrets to delete, and copies whose namespace is unknown."""
|
|
522
|
+
recorded: dict[str, list[str]] = {}
|
|
523
|
+
for target in announced:
|
|
524
|
+
adapter, _, place = target.partition(":")
|
|
525
|
+
namespace, _, name = place.partition("/")
|
|
526
|
+
if adapter == "k8s-secret" and namespace and name:
|
|
527
|
+
recorded.setdefault(name, []).append(namespace)
|
|
528
|
+
places: dict[str, list[str]] = {}
|
|
529
|
+
unknown: list[str] = []
|
|
530
|
+
for copy_id in copy_ids:
|
|
531
|
+
name = f"datadouble-{copy_id}"
|
|
532
|
+
namespaces = recorded.get(name)
|
|
533
|
+
if not namespaces:
|
|
534
|
+
try:
|
|
535
|
+
namespaces = [self.namespace]
|
|
536
|
+
except AnnounceError as error:
|
|
537
|
+
unknown.append(f"{name} in an unknown namespace ({error})")
|
|
538
|
+
continue
|
|
539
|
+
for namespace in namespaces:
|
|
540
|
+
places.setdefault(namespace, []).append(name)
|
|
541
|
+
return places, unknown
|
|
542
|
+
|
|
543
|
+
def withdraw(self, copy_ids: tuple[str, ...], announced: tuple[str, ...], /) -> tuple[str, ...]:
|
|
544
|
+
"""Delete the copies' Secrets from the namespaces they were announced into.
|
|
545
|
+
|
|
546
|
+
A copy with no announcement recorded, such as one announced before the
|
|
547
|
+
registry kept them, is looked for in :attr:`namespace`. Every namespace is
|
|
548
|
+
tried; then one :class:`AnnounceError` names each Secret left behind.
|
|
549
|
+
"""
|
|
550
|
+
places, failures = self._places(copy_ids, announced)
|
|
551
|
+
removed: list[str] = []
|
|
552
|
+
for namespace, names in places.items():
|
|
553
|
+
targets = [f"k8s-secret:{namespace}/{name}" for name in names]
|
|
554
|
+
try:
|
|
555
|
+
self.kubectl(
|
|
556
|
+
["delete", "secret", *names, f"--namespace={namespace}", "--ignore-not-found"]
|
|
557
|
+
)
|
|
558
|
+
except (KubectlError, SecretError) as error:
|
|
559
|
+
failures.append(f"{', '.join(targets)} ({error})")
|
|
560
|
+
else:
|
|
561
|
+
removed.extend(targets)
|
|
562
|
+
if failures:
|
|
563
|
+
message = "left behind: " + "; ".join(failures)
|
|
564
|
+
raise AnnounceError(message)
|
|
565
|
+
return tuple(removed)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
@remote("nfs.path")
|
|
569
|
+
def pv_replicator(settings: Mapping[str, JsonValue]) -> Replicator:
|
|
570
|
+
"""The ``k8s-pv`` entry point.
|
|
571
|
+
|
|
572
|
+
``nfs.path`` is the export's path on the NFS server, which the volumes point
|
|
573
|
+
at; Datadouble writes copies through ``path``, so only ``path`` is mounted.
|
|
574
|
+
"""
|
|
575
|
+
return PvReplicator(parse_settings(PvSettings, settings, "k8s-pv replicate"))
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def secret_announcer(settings: Mapping[str, JsonValue]) -> Announcer:
|
|
579
|
+
"""The ``k8s-secret`` entry point."""
|
|
580
|
+
return SecretAnnouncer(parse_settings(SecretSettings, settings, "k8s-secret announce"))
|
|
File without changes
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The Kubernetes container runtime: engine software in pods.
|
|
5
|
+
|
|
6
|
+
Spec settings::
|
|
7
|
+
|
|
8
|
+
runtime:
|
|
9
|
+
kubernetes:
|
|
10
|
+
namespace: datadouble # optional: see below
|
|
11
|
+
claim: datadouble-work # the PersistentVolumeClaim holding the work directory
|
|
12
|
+
mount: /work # where that claim is mounted in Datadouble's own pod
|
|
13
|
+
node: worker-3 # optional: run pods on this node (ReadWriteOnce claims)
|
|
14
|
+
access: pod-ip # or port-forward, when Datadouble runs outside the cluster
|
|
15
|
+
image_pull_secrets: [registry]
|
|
16
|
+
kubeconfig: # optional: another cluster's kubeconfig
|
|
17
|
+
env: SHOP_KUBECONFIG
|
|
18
|
+
context: build # optional: the kubeconfig's context to use
|
|
19
|
+
claims: # optional: more claims the CI job's pod mounts
|
|
20
|
+
- claim: datadouble-export
|
|
21
|
+
mount: /export
|
|
22
|
+
|
|
23
|
+
Datadouble runs with the work directory on ``claim``, mounted at ``mount``;
|
|
24
|
+
every pod mounts the same claim at the same path, so paths mean the same on
|
|
25
|
+
both sides, and every mounted path must be under ``mount``. Pods run as
|
|
26
|
+
Datadouble's own user and group. Secrets reach a pod through a Secret object
|
|
27
|
+
made for it and removed with it. A command's output is written to files on the
|
|
28
|
+
claim and read back, which keeps standard output and standard error apart.
|
|
29
|
+
Everything is done with ``kubectl``: with the kubeconfig and context the
|
|
30
|
+
settings give, written to a private temporary directory outside ``mount`` for
|
|
31
|
+
each call, or else in-cluster or ambient configuration. A kubeconfig that
|
|
32
|
+
cannot be resolved fails ``run``, ``serve`` and ``release`` with
|
|
33
|
+
:class:`~datadouble.secrets.SecretError` before any pod starts.
|
|
34
|
+
|
|
35
|
+
``claims`` are for ``ci init``, not for this runtime: the job's own pod on a
|
|
36
|
+
Kubernetes agent mounts each one as well as ``claim``, so a directory the
|
|
37
|
+
engines never touch, such as ``promote``'s export, can live on a claim of its
|
|
38
|
+
own. Engine pods mount only ``claim``.
|
|
39
|
+
|
|
40
|
+
Without ``namespace``, pods start where ``kubectl`` itself would put them:
|
|
41
|
+
inside a cluster (no kubeconfig in the settings or ``KUBECONFIG``, and a
|
|
42
|
+
service account's namespace file), the namespace of Datadouble's own pod, so
|
|
43
|
+
one spec serves pods in each side's namespace; otherwise the kubeconfig
|
|
44
|
+
context's namespace, or ``default``.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
import json
|
|
48
|
+
import os
|
|
49
|
+
import re
|
|
50
|
+
import secrets
|
|
51
|
+
import time
|
|
52
|
+
from collections.abc import Generator, Mapping, Sequence
|
|
53
|
+
from contextlib import contextmanager
|
|
54
|
+
from enum import StrEnum
|
|
55
|
+
from pathlib import Path
|
|
56
|
+
|
|
57
|
+
from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter
|
|
58
|
+
|
|
59
|
+
from datadouble.runtime import (
|
|
60
|
+
Completed,
|
|
61
|
+
Container,
|
|
62
|
+
ContainerError,
|
|
63
|
+
ContainerRuntime,
|
|
64
|
+
Endpoint,
|
|
65
|
+
absolute,
|
|
66
|
+
)
|
|
67
|
+
from datadouble.settings import parse_settings
|
|
68
|
+
from datadouble_kubernetes import ClusterSettings, KubectlError, current_namespace
|
|
69
|
+
|
|
70
|
+
_OWNER = "datadouble.dev/owner"
|
|
71
|
+
_RUNTIME_LABEL = "datadouble.dev/runtime"
|
|
72
|
+
_STUCK = ("ErrImagePull", "ImagePullBackOff", "InvalidImageName", "CreateContainerConfigError")
|
|
73
|
+
_FORWARDING = re.compile(r"Forwarding from 127\.0\.0\.1:(\d+)")
|
|
74
|
+
_MAIN = "main"
|
|
75
|
+
_OBJECT: TypeAdapter[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue])
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _mapping(value: JsonValue) -> dict[str, JsonValue]:
|
|
79
|
+
"""``value`` if it is a JSON object, else an empty one."""
|
|
80
|
+
return _OBJECT.validate_python(value) if isinstance(value, dict) else {}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Access(StrEnum):
|
|
84
|
+
"""How Datadouble reaches a server pod's port."""
|
|
85
|
+
|
|
86
|
+
POD_IP = "pod-ip"
|
|
87
|
+
"""Directly, at the pod's address: Datadouble runs in the cluster."""
|
|
88
|
+
PORT_FORWARD = "port-forward"
|
|
89
|
+
"""Through ``kubectl port-forward``: Datadouble runs outside it."""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class OtherClaim(BaseModel):
|
|
93
|
+
"""A PersistentVolumeClaim the CI job's own pod mounts besides the work claim."""
|
|
94
|
+
|
|
95
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
96
|
+
|
|
97
|
+
claim: str = Field(min_length=1)
|
|
98
|
+
mount: Path
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class KubernetesRuntimeSettings(ClusterSettings):
|
|
102
|
+
"""Settings for the ``kubernetes`` container runtime."""
|
|
103
|
+
|
|
104
|
+
namespace: str | None = None
|
|
105
|
+
"""Where pods start; Datadouble's own namespace (or kubectl's) when left out."""
|
|
106
|
+
claim: str
|
|
107
|
+
mount: Path
|
|
108
|
+
node: str | None = None
|
|
109
|
+
access: Access = Access.POD_IP
|
|
110
|
+
image_pull_secrets: tuple[str, ...] = ()
|
|
111
|
+
ready_seconds: int = Field(default=300, ge=1)
|
|
112
|
+
stop_seconds: int = Field(default=300, ge=1)
|
|
113
|
+
claims: tuple[OtherClaim, ...] = ()
|
|
114
|
+
"""More claims the CI job's own pod mounts, for ``ci init``; engine pods mount only
|
|
115
|
+
``claim``, so nothing an engine reads or writes may be on them."""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class KubernetesServer:
|
|
119
|
+
"""A server pod started by :class:`KubernetesRuntime`."""
|
|
120
|
+
|
|
121
|
+
def __init__(self, runtime: "KubernetesRuntime", name: str, endpoint: Endpoint) -> None:
|
|
122
|
+
"""Wrap the running pod ``name``."""
|
|
123
|
+
self.runtime = runtime
|
|
124
|
+
self.name = name
|
|
125
|
+
self._endpoint = endpoint
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def endpoint(self) -> Endpoint:
|
|
129
|
+
"""The pod's address, or the local end of a port-forward."""
|
|
130
|
+
return self._endpoint
|
|
131
|
+
|
|
132
|
+
def execute(self, command: Sequence[str], env: Mapping[str, str] | None = None) -> Completed:
|
|
133
|
+
"""``kubectl exec``; ``env`` is passed in the exec request, so it must not be secret."""
|
|
134
|
+
assignments = [f"{key}={value}" for key, value in (env or {}).items()]
|
|
135
|
+
prefix = ["env", *assignments] if assignments else []
|
|
136
|
+
return self.runtime.invoke(
|
|
137
|
+
[
|
|
138
|
+
"exec",
|
|
139
|
+
f"--namespace={self.runtime.namespace}",
|
|
140
|
+
self.name,
|
|
141
|
+
f"--container={_MAIN}",
|
|
142
|
+
"--",
|
|
143
|
+
*prefix,
|
|
144
|
+
*command,
|
|
145
|
+
]
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class KubernetesRuntime:
|
|
150
|
+
"""Runs containers as pods with ``kubectl``."""
|
|
151
|
+
|
|
152
|
+
def __init__(self, settings: KubernetesRuntimeSettings) -> None:
|
|
153
|
+
"""Use ``settings`` for every pod."""
|
|
154
|
+
self.settings = settings
|
|
155
|
+
self.kubectl = settings.kubectl(avoid=settings.mount)
|
|
156
|
+
self._namespace = settings.namespace
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def namespace(self) -> str:
|
|
160
|
+
"""The namespace pods start in: the settings', or :func:`current_namespace`."""
|
|
161
|
+
if self._namespace is None:
|
|
162
|
+
try:
|
|
163
|
+
self._namespace = current_namespace(self.kubectl)
|
|
164
|
+
except KubectlError as error:
|
|
165
|
+
raise ContainerError(str(error)) from None
|
|
166
|
+
return self._namespace
|
|
167
|
+
|
|
168
|
+
def invoke(self, arguments: Sequence[str]) -> Completed:
|
|
169
|
+
"""Run ``kubectl`` and return what it did, whether or not it succeeded."""
|
|
170
|
+
try:
|
|
171
|
+
return self.kubectl.run(arguments)
|
|
172
|
+
except KubectlError as error:
|
|
173
|
+
raise ContainerError(str(error)) from None
|
|
174
|
+
|
|
175
|
+
def _kubectl(self, arguments: list[str], action: str, *, stdin: str | None = None) -> str:
|
|
176
|
+
try:
|
|
177
|
+
return self.kubectl(arguments, stdin=stdin)
|
|
178
|
+
except KubectlError as error:
|
|
179
|
+
message = f"{action}: {error}"
|
|
180
|
+
raise ContainerError(message) from None
|
|
181
|
+
|
|
182
|
+
# Pods
|
|
183
|
+
|
|
184
|
+
def manifest(
|
|
185
|
+
self, name: str, container: Container, command: Sequence[str]
|
|
186
|
+
) -> dict[str, JsonValue]:
|
|
187
|
+
"""The pod running ``command`` for ``container``."""
|
|
188
|
+
mount = self.settings.mount
|
|
189
|
+
for path in absolute(container.mounts):
|
|
190
|
+
if not path.is_relative_to(mount):
|
|
191
|
+
message = f"{path} is not on the work claim, which is mounted at {mount}"
|
|
192
|
+
raise ContainerError(message)
|
|
193
|
+
env: list[JsonValue] = [{"name": k, "value": v} for k, v in container.env.items()]
|
|
194
|
+
for key in container.secrets:
|
|
195
|
+
reference: dict[str, JsonValue] = {"name": name, "key": key}
|
|
196
|
+
env.append({"name": key, "valueFrom": {"secretKeyRef": reference}})
|
|
197
|
+
main: dict[str, JsonValue] = {
|
|
198
|
+
"name": _MAIN,
|
|
199
|
+
"image": container.image,
|
|
200
|
+
"command": list(command),
|
|
201
|
+
"env": env,
|
|
202
|
+
"volumeMounts": [{"name": "work", "mountPath": str(mount)}],
|
|
203
|
+
}
|
|
204
|
+
if container.port is not None:
|
|
205
|
+
main["ports"] = [{"containerPort": container.port}]
|
|
206
|
+
main["readinessProbe"] = {
|
|
207
|
+
"exec": {"command": list(container.ready)},
|
|
208
|
+
"periodSeconds": 1,
|
|
209
|
+
"failureThreshold": 1,
|
|
210
|
+
}
|
|
211
|
+
spec: dict[str, JsonValue] = {
|
|
212
|
+
"restartPolicy": "Never",
|
|
213
|
+
"terminationGracePeriodSeconds": self.settings.stop_seconds,
|
|
214
|
+
"securityContext": {"runAsUser": os.getuid(), "runAsGroup": os.getgid()},
|
|
215
|
+
"volumes": [
|
|
216
|
+
{"name": "work", "persistentVolumeClaim": {"claimName": self.settings.claim}}
|
|
217
|
+
],
|
|
218
|
+
"containers": [main],
|
|
219
|
+
"imagePullSecrets": [{"name": s} for s in self.settings.image_pull_secrets],
|
|
220
|
+
}
|
|
221
|
+
if self.settings.node:
|
|
222
|
+
spec["nodeSelector"] = {"kubernetes.io/hostname": self.settings.node}
|
|
223
|
+
return {
|
|
224
|
+
"apiVersion": "v1",
|
|
225
|
+
"kind": "Pod",
|
|
226
|
+
"metadata": {
|
|
227
|
+
"name": name,
|
|
228
|
+
"namespace": self.namespace,
|
|
229
|
+
"labels": {_RUNTIME_LABEL: "true"},
|
|
230
|
+
"annotations": {_OWNER: str(absolute([container.owner])[0])},
|
|
231
|
+
},
|
|
232
|
+
"spec": spec,
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
def create(self, name: str, container: Container, command: Sequence[str]) -> None:
|
|
236
|
+
"""Create the pod, and its Secret when it has secrets."""
|
|
237
|
+
namespace = f"--namespace={self.namespace}"
|
|
238
|
+
if container.secrets:
|
|
239
|
+
secret = {
|
|
240
|
+
"apiVersion": "v1",
|
|
241
|
+
"kind": "Secret",
|
|
242
|
+
"metadata": {
|
|
243
|
+
"name": name,
|
|
244
|
+
"namespace": self.namespace,
|
|
245
|
+
"labels": {_RUNTIME_LABEL: "true"},
|
|
246
|
+
},
|
|
247
|
+
"stringData": dict(container.secrets),
|
|
248
|
+
}
|
|
249
|
+
self._kubectl(
|
|
250
|
+
["create", namespace, "-f", "-"], "creating the secret", stdin=json.dumps(secret)
|
|
251
|
+
)
|
|
252
|
+
pod = json.dumps(self.manifest(name, container, command))
|
|
253
|
+
self._kubectl(["create", namespace, "-f", "-"], f"starting {container.image}", stdin=pod)
|
|
254
|
+
|
|
255
|
+
def _status(self, name: str) -> dict[str, JsonValue]:
|
|
256
|
+
output = self._kubectl(
|
|
257
|
+
["get", f"--namespace={self.namespace}", "pod", name, "--output=json"],
|
|
258
|
+
"reading the pod",
|
|
259
|
+
)
|
|
260
|
+
return _mapping(_OBJECT.validate_json(output).get("status"))
|
|
261
|
+
|
|
262
|
+
@staticmethod
|
|
263
|
+
def container_state(status: Mapping[str, JsonValue]) -> tuple[str | None, int | None, bool]:
|
|
264
|
+
"""The main container's waiting reason, exit code once terminated, and readiness."""
|
|
265
|
+
statuses = status.get("containerStatuses")
|
|
266
|
+
if not isinstance(statuses, list) or not statuses:
|
|
267
|
+
return None, None, False
|
|
268
|
+
main = _mapping(statuses[0])
|
|
269
|
+
state = _mapping(main.get("state"))
|
|
270
|
+
reason = _mapping(state.get("waiting")).get("reason")
|
|
271
|
+
code = _mapping(state.get("terminated")).get("exitCode")
|
|
272
|
+
return (
|
|
273
|
+
reason if isinstance(reason, str) else None,
|
|
274
|
+
code if isinstance(code, int) else None,
|
|
275
|
+
main.get("ready") is True,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
def delete(self, name: str) -> None:
|
|
279
|
+
"""Delete a pod and its Secret, if they exist."""
|
|
280
|
+
namespace = f"--namespace={self.namespace}"
|
|
281
|
+
for kind in ("pod", "secret"):
|
|
282
|
+
self.invoke(["delete", namespace, kind, name, "--ignore-not-found", "--wait=false"])
|
|
283
|
+
|
|
284
|
+
def _logs(self, name: str) -> str:
|
|
285
|
+
result = self.invoke(["logs", f"--namespace={self.namespace}", name, "--tail=5"])
|
|
286
|
+
lines = (result.stdout + result.stderr).strip().splitlines()
|
|
287
|
+
return lines[-1] if lines else "no output"
|
|
288
|
+
|
|
289
|
+
# The runtime
|
|
290
|
+
|
|
291
|
+
def run(self, container: Container) -> Completed:
|
|
292
|
+
"""Run a pod to completion; its output comes back through files on the claim."""
|
|
293
|
+
self.kubectl.resolve()
|
|
294
|
+
name = f"datadouble-{secrets.token_hex(6)}"
|
|
295
|
+
outputs = absolute([container.owner])[0] / f".{name}"
|
|
296
|
+
outputs.mkdir(parents=True, exist_ok=True)
|
|
297
|
+
command = [
|
|
298
|
+
"sh",
|
|
299
|
+
"-c",
|
|
300
|
+
f'"$@" > {outputs}/stdout 2> {outputs}/stderr',
|
|
301
|
+
"sh",
|
|
302
|
+
*container.command,
|
|
303
|
+
]
|
|
304
|
+
try:
|
|
305
|
+
self.create(name, container, command)
|
|
306
|
+
while True:
|
|
307
|
+
reason, code, _ = self.container_state(self._status(name))
|
|
308
|
+
if code is not None:
|
|
309
|
+
return Completed(
|
|
310
|
+
status=code,
|
|
311
|
+
stdout=(outputs / "stdout").read_text("utf-8", errors="replace"),
|
|
312
|
+
stderr=(outputs / "stderr").read_text("utf-8", errors="replace"),
|
|
313
|
+
)
|
|
314
|
+
if reason in _STUCK:
|
|
315
|
+
message = f"{container.image} could not start: {reason}"
|
|
316
|
+
raise ContainerError(message)
|
|
317
|
+
time.sleep(1)
|
|
318
|
+
finally:
|
|
319
|
+
self.delete(name)
|
|
320
|
+
for item in outputs.glob("*"):
|
|
321
|
+
item.unlink()
|
|
322
|
+
outputs.rmdir()
|
|
323
|
+
|
|
324
|
+
@contextmanager
|
|
325
|
+
def serve(self, container: Container) -> Generator[KubernetesServer]:
|
|
326
|
+
"""Start a server pod, wait until it is ready, and stop it cleanly afterwards."""
|
|
327
|
+
self.kubectl.resolve()
|
|
328
|
+
if container.port is None:
|
|
329
|
+
message = "a server container needs a port"
|
|
330
|
+
raise ContainerError(message)
|
|
331
|
+
name = f"datadouble-{secrets.token_hex(6)}"
|
|
332
|
+
try:
|
|
333
|
+
self.create(name, container, container.command)
|
|
334
|
+
status = self._wait(name, container)
|
|
335
|
+
with self._endpoint(name, container.port, status) as endpoint:
|
|
336
|
+
yield KubernetesServer(self, name, endpoint)
|
|
337
|
+
self._stop(name)
|
|
338
|
+
finally:
|
|
339
|
+
self.delete(name)
|
|
340
|
+
|
|
341
|
+
def _wait(self, name: str, container: Container) -> dict[str, JsonValue]:
|
|
342
|
+
deadline = time.monotonic() + self.settings.ready_seconds
|
|
343
|
+
while True:
|
|
344
|
+
status = self._status(name)
|
|
345
|
+
reason, code, ready = self.container_state(status)
|
|
346
|
+
if ready:
|
|
347
|
+
return status
|
|
348
|
+
if code is not None:
|
|
349
|
+
message = f"the server stopped while starting: {self._logs(name)}"
|
|
350
|
+
raise ContainerError(message)
|
|
351
|
+
if reason in _STUCK:
|
|
352
|
+
message = f"{container.image} could not start: {reason}"
|
|
353
|
+
raise ContainerError(message)
|
|
354
|
+
if time.monotonic() > deadline:
|
|
355
|
+
message = (
|
|
356
|
+
f"{container.image} was not ready after {self.settings.ready_seconds} seconds"
|
|
357
|
+
)
|
|
358
|
+
raise ContainerError(message)
|
|
359
|
+
time.sleep(1)
|
|
360
|
+
|
|
361
|
+
@contextmanager
|
|
362
|
+
def _endpoint(
|
|
363
|
+
self, name: str, port: int, status: Mapping[str, JsonValue]
|
|
364
|
+
) -> Generator[Endpoint]:
|
|
365
|
+
if self.settings.access is Access.POD_IP:
|
|
366
|
+
yield Endpoint(host=str(status.get("podIP")), port=port)
|
|
367
|
+
return
|
|
368
|
+
arguments = ["port-forward", f"--namespace={self.namespace}", f"pod/{name}"]
|
|
369
|
+
# serve() has run kubectl already, so it is installed and the kubeconfig resolved.
|
|
370
|
+
with self.kubectl.started([*arguments, f":{port}"]) as forward:
|
|
371
|
+
line = forward.stdout.readline() if forward.stdout else ""
|
|
372
|
+
match = _FORWARDING.search(line)
|
|
373
|
+
if match is None:
|
|
374
|
+
message = f"port-forward to {name} failed"
|
|
375
|
+
raise ContainerError(message)
|
|
376
|
+
yield Endpoint(host="127.0.0.1", port=int(match.group(1)))
|
|
377
|
+
|
|
378
|
+
def _stop(self, name: str) -> None:
|
|
379
|
+
"""Signal the server to stop and wait; it must exit cleanly."""
|
|
380
|
+
self._kubectl(
|
|
381
|
+
[
|
|
382
|
+
"exec",
|
|
383
|
+
f"--namespace={self.namespace}",
|
|
384
|
+
name,
|
|
385
|
+
f"--container={_MAIN}",
|
|
386
|
+
"--",
|
|
387
|
+
"sh",
|
|
388
|
+
"-c",
|
|
389
|
+
"kill -TERM 1",
|
|
390
|
+
],
|
|
391
|
+
"stopping the server",
|
|
392
|
+
)
|
|
393
|
+
deadline = time.monotonic() + self.settings.stop_seconds
|
|
394
|
+
while True:
|
|
395
|
+
_, code, _ = self.container_state(self._status(name))
|
|
396
|
+
if code is not None:
|
|
397
|
+
break
|
|
398
|
+
if time.monotonic() > deadline:
|
|
399
|
+
message = f"the server did not stop within {self.settings.stop_seconds} seconds"
|
|
400
|
+
raise ContainerError(message)
|
|
401
|
+
time.sleep(1)
|
|
402
|
+
if code != 0:
|
|
403
|
+
message = f"the server exited with status {code}: {self._logs(name)}"
|
|
404
|
+
raise ContainerError(message)
|
|
405
|
+
|
|
406
|
+
def release(self, owner: Path) -> None:
|
|
407
|
+
"""Remove pods (and their secrets) labelled with ``owner`` or a directory under it."""
|
|
408
|
+
self.kubectl.resolve()
|
|
409
|
+
root = absolute([owner])[0]
|
|
410
|
+
listed = self._kubectl(
|
|
411
|
+
[
|
|
412
|
+
"get",
|
|
413
|
+
f"--namespace={self.namespace}",
|
|
414
|
+
"pods",
|
|
415
|
+
f"--selector={_RUNTIME_LABEL}=true",
|
|
416
|
+
"--output=json",
|
|
417
|
+
],
|
|
418
|
+
"listing pods",
|
|
419
|
+
)
|
|
420
|
+
items = _OBJECT.validate_json(listed).get("items")
|
|
421
|
+
for item in items if isinstance(items, list) else []:
|
|
422
|
+
metadata = _mapping(_mapping(item).get("metadata"))
|
|
423
|
+
labelled = _mapping(metadata.get("annotations")).get(_OWNER)
|
|
424
|
+
if isinstance(labelled, str) and Path(labelled).is_relative_to(root):
|
|
425
|
+
self.delete(str(metadata.get("name")))
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def kubernetes_runtime(settings: Mapping[str, JsonValue]) -> ContainerRuntime:
|
|
429
|
+
"""The entry point named in ``datadouble.runtimes``."""
|
|
430
|
+
return KubernetesRuntime(
|
|
431
|
+
parse_settings(KubernetesRuntimeSettings, settings, "kubernetes runtime")
|
|
432
|
+
)
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: datadouble-kubernetes
|
|
3
|
+
Version: 0.0.3
|
|
4
|
+
Summary: Kubernetes replicate and announce adapters for Datadouble
|
|
5
|
+
Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
|
|
6
|
+
Project-URL: Source, https://github.com/datadouble/datadouble
|
|
7
|
+
Author: Tight Line LLC
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
15
|
+
Classifier: Topic :: System :: Clustering
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.13
|
|
18
|
+
Requires-Dist: datadouble
|
|
19
|
+
Requires-Dist: pyyaml>=6.0.3
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# datadouble-kubernetes
|
|
23
|
+
|
|
24
|
+
Kubernetes adapters for [Datadouble](https://datadouble.tightlinesoftware.com/):
|
|
25
|
+
|
|
26
|
+
- **`k8s-pv`** (replicate): each copy is a directory and a PersistentVolume
|
|
27
|
+
pointing at it, labelled so consumers select it in a PersistentVolumeClaim.
|
|
28
|
+
A spec with `files` adds a second one, `datadouble-<copy id>-files`,
|
|
29
|
+
labelled `datadouble.dev/engine: files`, for the group's files.
|
|
30
|
+
A bound volume counts as claimed; once its claim is deleted the copy is
|
|
31
|
+
removed and the pool refilled.
|
|
32
|
+
- **`k8s-secret`** (announce): a Secret per copy holding where it is and, for
|
|
33
|
+
instance copies, its credentials.
|
|
34
|
+
- **`kubernetes`** (container runtime): engine software in pods, sharing the
|
|
35
|
+
work directory through a PersistentVolumeClaim (decision 73).
|
|
36
|
+
|
|
37
|
+
```yaml
|
|
38
|
+
replicate:
|
|
39
|
+
using:
|
|
40
|
+
k8s-pv:
|
|
41
|
+
path: /srv/clones # where copies are written
|
|
42
|
+
local: # a local volume on that node, or
|
|
43
|
+
node: worker-1
|
|
44
|
+
# nfs:
|
|
45
|
+
# server: nfs.internal
|
|
46
|
+
# path: /exports/clones
|
|
47
|
+
storage_class: datadouble
|
|
48
|
+
announce:
|
|
49
|
+
- k8s-secret: {} # Secrets in Datadouble's own namespace
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Datadouble writes each copy into a directory under `path`, as the job's own
|
|
53
|
+
machine sees it. With `local`, the volume points at that same directory on
|
|
54
|
+
the node. With `nfs`, `path` must be where the export is mounted on the job's
|
|
55
|
+
machine, and `nfs.path` is the export's own path on the NFS server, which the
|
|
56
|
+
volumes point at. Datadouble never opens `nfs.path`, so `ci init` mounts only
|
|
57
|
+
`path` into the jobs it writes, never `nfs.path`
|
|
58
|
+
([which settings become mounts](../../docs/ci-cd.md#which-settings-become-mounts)).
|
|
59
|
+
On a Kubernetes agent, only `path` has to be under the runtime's `mount`:
|
|
60
|
+
|
|
61
|
+
```yaml
|
|
62
|
+
runtime:
|
|
63
|
+
kubernetes:
|
|
64
|
+
claim: datadouble
|
|
65
|
+
mount: /srv/datadouble
|
|
66
|
+
replicate:
|
|
67
|
+
using:
|
|
68
|
+
k8s-pv:
|
|
69
|
+
path: /srv/datadouble/clones # the export, mounted from the claim
|
|
70
|
+
nfs:
|
|
71
|
+
server: nfs.example.com
|
|
72
|
+
path: /exports/datadouble/clones # the same directory on the server
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Each volume carries `datadouble.dev/` labels: `spec`, `group`, `engine`,
|
|
76
|
+
`engine-version`, `server-version`, `generation` and `copy`. `engine-version`
|
|
77
|
+
is the engine's compatibility line (`17` for PostgreSQL, `8.4` for MySQL), not
|
|
78
|
+
the exact version: select on it, and serve copies with the newest release of
|
|
79
|
+
that line (`postgres:17`, `mysql:8.4`), which opens every copy of the line
|
|
80
|
+
(Oracle copies need exactly their `server-version`). `server-version` is the
|
|
81
|
+
exact version that wrote the copy, for consumers that must match it; for
|
|
82
|
+
engines without a server (Salesforce, file trees) it is the image layout's
|
|
83
|
+
version. A Helm chart renders its image before any claim
|
|
84
|
+
binds, so it cannot read the bound volume's labels; choose the image from the
|
|
85
|
+
line, or look up an available volume's `server-version` before rendering.
|
|
86
|
+
|
|
87
|
+
All three drive `kubectl` (`DATADOUBLE_KUBECTL` names another binary).
|
|
88
|
+
|
|
89
|
+
## Namespaces
|
|
90
|
+
|
|
91
|
+
```yaml
|
|
92
|
+
runtime:
|
|
93
|
+
kubernetes:
|
|
94
|
+
claim: datadouble # the PersistentVolumeClaim holding the work directory
|
|
95
|
+
mount: /srv/datadouble # where Datadouble's own pod mounts it
|
|
96
|
+
# namespace: shop-staging # optional
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Leave `namespace` out unless pods must start somewhere else. Then they start
|
|
100
|
+
where `kubectl` would put them unasked: inside a cluster (no `kubeconfig` in
|
|
101
|
+
the settings, no `KUBECONFIG`, and a service account namespace file in
|
|
102
|
+
Datadouble's pod), that pod's own namespace, read from
|
|
103
|
+
`/var/run/secrets/kubernetes.io/serviceaccount/namespace`; otherwise the
|
|
104
|
+
namespace of the kubeconfig's context (the settings' `context`, or its current
|
|
105
|
+
one), or `default` when it names none. So one spec serves CI/CD jobs that run
|
|
106
|
+
as pods in each side's own namespace, which `ci init` requires a set
|
|
107
|
+
namespace to match (decision 133).
|
|
108
|
+
|
|
109
|
+
An empty `KUBECONFIG` counts as unset, as it does for `kubectl`. A context
|
|
110
|
+
`kubectl` cannot read (a bad kubeconfig, an unknown context) fails, naming
|
|
111
|
+
the kubeconfig and context, rather than falling back to `default`.
|
|
112
|
+
|
|
113
|
+
`k8s-secret` follows the same rule, with its own `kubeconfig` and `context`
|
|
114
|
+
(decision 135): left out, its `namespace` is the one `kubectl` would use, so
|
|
115
|
+
copies' Secrets go to the namespace Datadouble's pod runs in, where the Helm
|
|
116
|
+
chart's Role and the Jenkins `instructions` let it write them. `announce`
|
|
117
|
+
reports where each went (`k8s-secret:shop-dev/datadouble-<copy id>`), and
|
|
118
|
+
the copy registry records it, so `release` deletes each Secret from the
|
|
119
|
+
namespace it was written to, even when the releasing process would resolve
|
|
120
|
+
another: a copy claimed from a laptop, whose context names `alice`, gets its
|
|
121
|
+
Secret in `alice`, and the scheduled sweep running in `shop-dev` deletes it
|
|
122
|
+
there. Two things must hold for that:
|
|
123
|
+
|
|
124
|
+
- **One cluster.** Every process that announces or releases with the spec
|
|
125
|
+
reaches the same cluster through the `k8s-secret` entry. The registry
|
|
126
|
+
records namespaces, not clusters.
|
|
127
|
+
- **Delete rights.** The identity that releases (the sweep's service
|
|
128
|
+
account) may `delete` Secrets in every namespace a copy was announced
|
|
129
|
+
into, `alice` here.
|
|
130
|
+
|
|
131
|
+
Release tries every Secret, then fails once, naming each one it could not
|
|
132
|
+
delete (`k8s-secret:alice/datadouble-<copy id>`). The copy is already gone
|
|
133
|
+
from the registry, so delete those by hand. Consumers look for a Secret
|
|
134
|
+
where it went, so run `claim` from where consumers expect it, or set
|
|
135
|
+
`namespace`. Set `namespace` to write Secrets anywhere else, such as the
|
|
136
|
+
namespace consumers run in, and grant Datadouble's service account `get`,
|
|
137
|
+
`create`, `patch` and `delete` on Secrets there.
|
|
138
|
+
|
|
139
|
+
Before decision 135 `k8s-secret` always wrote to `default`, and the
|
|
140
|
+
registry did not record it. Releases now look for those Secrets in the newly
|
|
141
|
+
resolved namespace, so keep `namespace: default` in the spec until copies
|
|
142
|
+
announced before the change are released, or delete their
|
|
143
|
+
`datadouble-<copy id>` Secrets in `default` by hand.
|
|
144
|
+
|
|
145
|
+
## Claims for the CI job's own pod
|
|
146
|
+
|
|
147
|
+
Every pod the runtime starts mounts one claim, the work claim, so every path
|
|
148
|
+
an engine reads or writes is on it. The work claim also holds the work
|
|
149
|
+
directory, where a build keeps the data it extracts from the source.
|
|
150
|
+
|
|
151
|
+
Some directories are never touched by an engine. `promote`'s export directory
|
|
152
|
+
is one: Datadouble's own process copies images into it. Often a web server
|
|
153
|
+
serves the export to the non-production side, through the read-only `http`
|
|
154
|
+
fetch store, so the export has to be on that server's share. If the export
|
|
155
|
+
were on the work claim, the web server could reach the work directory too.
|
|
156
|
+
|
|
157
|
+
`claims` lists more claims for the CI job's own pod, the pod that runs
|
|
158
|
+
Datadouble on Jenkins' Kubernetes agents and in the Argo CD chart:
|
|
159
|
+
|
|
160
|
+
```yaml
|
|
161
|
+
runtime:
|
|
162
|
+
kubernetes:
|
|
163
|
+
claim: datadouble
|
|
164
|
+
mount: /srv/datadouble
|
|
165
|
+
claims:
|
|
166
|
+
- claim: shop-export # a PersistentVolumeClaim in the side's namespace
|
|
167
|
+
mount: /export # where the job's pod mounts it
|
|
168
|
+
promote:
|
|
169
|
+
to:
|
|
170
|
+
- filesystem:
|
|
171
|
+
path: /export/shop
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
- The runtime itself ignores `claims`. Engine pods mount only `claim`.
|
|
175
|
+
- A job's pod mounts only the claims its own paths are on, beside the work
|
|
176
|
+
claim, and `ci init` lists in its `instructions` only the claims the
|
|
177
|
+
side's jobs mount. So one spec can name a claim only one side has: here,
|
|
178
|
+
only `promote` and production's `prune` mount `shop-export`, and the
|
|
179
|
+
non-production side never needs it.
|
|
180
|
+
- A path on one of these claims need not be under the work claim's `mount`.
|
|
181
|
+
Jobs that start engines (`build`, `provision`, `release`) can't name one, so
|
|
182
|
+
the store, staging and the work directory stay on the work claim.
|
|
183
|
+
- The mounts can't overlap each other, the work claim's mount, or a path the
|
|
184
|
+
job's pod already uses: `/etc/datadouble-boundary`, the Jenkins agent's
|
|
185
|
+
`/home/jenkins`, the Argo CD chart's `/workspace`, and a mounted spec
|
|
186
|
+
directory. `claims` can't list the work claim.
|
|
187
|
+
|
|
188
|
+
## Reaching the cluster
|
|
189
|
+
|
|
190
|
+
Without settings, `kubectl` uses the pod's service account when Datadouble
|
|
191
|
+
runs in the cluster, or the ambient configuration (`KUBECONFIG`,
|
|
192
|
+
`~/.kube/config`) otherwise. A job in the cluster it drives, such as the Argo
|
|
193
|
+
CD jobs, needs nothing more.
|
|
194
|
+
|
|
195
|
+
To drive a cluster from outside it, give each adapter that talks to it a
|
|
196
|
+
`kubeconfig`, a secret reference to a kubeconfig's content, and optionally
|
|
197
|
+
the `context` to use:
|
|
198
|
+
|
|
199
|
+
```yaml
|
|
200
|
+
runtime:
|
|
201
|
+
kubernetes:
|
|
202
|
+
claim: datadouble-work
|
|
203
|
+
mount: /work
|
|
204
|
+
kubeconfig:
|
|
205
|
+
env: BUILD_KUBECONFIG
|
|
206
|
+
context: build
|
|
207
|
+
replicate:
|
|
208
|
+
using:
|
|
209
|
+
k8s-pv:
|
|
210
|
+
path: /srv/clones
|
|
211
|
+
local:
|
|
212
|
+
node: worker-1
|
|
213
|
+
kubeconfig:
|
|
214
|
+
env: DEV_KUBECONFIG
|
|
215
|
+
announce:
|
|
216
|
+
- k8s-secret:
|
|
217
|
+
namespace: dev
|
|
218
|
+
kubeconfig:
|
|
219
|
+
env: DEV_KUBECONFIG
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
- **A secret reference to the content, not the runner's kubeconfig file.**
|
|
223
|
+
`{env: NAME}` holds the kubeconfig itself, not a path to one: in CI jobs
|
|
224
|
+
Datadouble runs in its image, which sees only the paths in the spec,
|
|
225
|
+
and as the engine's user (decision 86), who cannot read the runner user's
|
|
226
|
+
`~/.kube/config`. `{file: /path}` is for a secret file mounted for this
|
|
227
|
+
purpose, such as a Kubernetes Secret volume: `ci init` mounts that path
|
|
228
|
+
into the job, so it must exist on the runner and be readable by the
|
|
229
|
+
engine's user (`999:999` for PostgreSQL). On Argo CD it must also be under
|
|
230
|
+
the claim's directory, so prefer `{env: NAME}` there.
|
|
231
|
+
- **Credentials the image can use.** The Datadouble image holds `kubectl`
|
|
232
|
+
and nothing else, so a kubeconfig whose user runs an exec credential
|
|
233
|
+
plugin (`aws eks get-token`, `gke-gcloud-auth-plugin`, `kubelogin`) fails.
|
|
234
|
+
For EKS, GKE or AKS, use a kubeconfig with a service account token or a
|
|
235
|
+
client certificate, embedded in it (`token`, `client-certificate-data`),
|
|
236
|
+
not in files it names (`tokenFile`, `client-certificate`), since those
|
|
237
|
+
paths are not mounted.
|
|
238
|
+
- **`ci init` lists the variable** among the secrets of each job whose part
|
|
239
|
+
of the spec references it, and only those: the runtime's for `build`,
|
|
240
|
+
`provision` and `release`; `k8s-pv`'s for `provision`, `release` and the
|
|
241
|
+
non-production `prune`; `k8s-secret`'s for `provision` and `release`.
|
|
242
|
+
Define it in each system's own secret store, as for any other secret
|
|
243
|
+
(repository secrets, CI/CD variables, Jenkins credentials, a Kubernetes
|
|
244
|
+
Secret, or a Vault-backed secret the CI system injects).
|
|
245
|
+
- **Defining a multi-line secret.** GitHub Actions and Kubernetes Secrets
|
|
246
|
+
take a kubeconfig as it is. In GitLab, make it a CI/CD variable of type
|
|
247
|
+
"Variable", not "File" (a File variable holds a path, which the job's
|
|
248
|
+
container cannot see), protected, with masking off: GitLab masks only
|
|
249
|
+
single-line values. In Jenkins, a Secret text credential holds one line in
|
|
250
|
+
the web form, so create a multi-line one through the API or Configuration
|
|
251
|
+
as Code.
|
|
252
|
+
- **Datadouble writes the kubeconfig to a private temporary file** for each
|
|
253
|
+
`kubectl` call: a file only its user can read (mode 0600), in a directory
|
|
254
|
+
of its own (mode 0700), passed with `--kubeconfig` (and `--context`), both
|
|
255
|
+
removed when the call ends, even after a failure or when the job is
|
|
256
|
+
cancelled (SIGTERM); a `kubernetes` port-forward keeps its file until the
|
|
257
|
+
forward stops. The directory is made in the system's temporary directory
|
|
258
|
+
(`TMPDIR`), or in the home directory when that is under the `kubernetes`
|
|
259
|
+
runtime's `mount`, which pods see; if both are, the call fails, asking for
|
|
260
|
+
`TMPDIR` elsewhere.
|
|
261
|
+
- **What is hidden.** Every string value in the kubeconfig at least 16
|
|
262
|
+
characters long (tokens, keys, certificates, server URLs) is replaced with
|
|
263
|
+
`[redacted]` in everything `kubectl` prints that Datadouble passes on, and
|
|
264
|
+
only those values are handed to the CI system's log masking, so lines such
|
|
265
|
+
as `kind: Config` stay readable. A kubeconfig that cannot be resolved
|
|
266
|
+
fails with `unresolved_reference` before any work, including before a
|
|
267
|
+
`kubernetes` runtime starts a pod.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
datadouble_kubernetes/__init__.py,sha256=HDbc7PitwlWt5qg2p3XQiZNrbtdfPprBilFAU_d_QGs,22854
|
|
2
|
+
datadouble_kubernetes/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
datadouble_kubernetes/runtime.py,sha256=1oKTGqeslGKzOGbDKEvEERaTj-yUNXfsTxadvXVuUsI,17809
|
|
4
|
+
datadouble_kubernetes-0.0.3.dist-info/METADATA,sha256=fSn7KQ73EisEFgyUXEDvEeJG5VnXc7v1ch25avMRBCE,12656
|
|
5
|
+
datadouble_kubernetes-0.0.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
datadouble_kubernetes-0.0.3.dist-info/entry_points.txt,sha256=XiTMh-iUJJk-Uyp29XTdQd5DAdaz6Z3ZFNv6XcKCB3Q,232
|
|
7
|
+
datadouble_kubernetes-0.0.3.dist-info/licenses/LICENSE,sha256=2LcT-SSMiSa7vrHsdC41sUWNmkcwZqIYdYBaSVmqqT8,1072
|
|
8
|
+
datadouble_kubernetes-0.0.3.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026- Tight Line LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|