datadouble-docker 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.
@@ -0,0 +1,262 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Docker replicate adapter for Datadouble.
5
+
6
+ Spec settings::
7
+
8
+ replicate:
9
+ using:
10
+ docker-volume:
11
+ kind: instance # or volume (the default)
12
+ server_image: postgres:18-trixie@sha256:... # optional
13
+ host: db-clones.internal # how consumers reach published ports
14
+ network: ci # optional
15
+
16
+ A copy is a volume named ``datadouble-<copy id>``, filled by streaming the
17
+ staged image into a short-lived container as a tar archive, so it works the
18
+ same against a local or a remote daemon. An instance copy also runs the
19
+ engine's server on the volume, with a generated password. A group's files,
20
+ when the spec has them, go into a second volume, ``datadouble-<copy id>-files``,
21
+ even for an instance copy: they have no server. Everything is done with the
22
+ ``docker`` command, so ``DOCKER_HOST`` and contexts apply.
23
+ """
24
+
25
+ import io
26
+ import secrets
27
+ import tarfile
28
+ import time
29
+ from collections.abc import Callable, Mapping
30
+ from pathlib import Path
31
+ from typing import Protocol
32
+
33
+ from pydantic import BaseModel, ConfigDict, JsonValue
34
+
35
+ from datadouble.engine import ServerPlan
36
+ from datadouble.images import ImageSummary
37
+ from datadouble.programs import locate, run_program
38
+ from datadouble.registry import installed
39
+ from datadouble.replicate import (
40
+ ClaimState,
41
+ Copy,
42
+ CopyKind,
43
+ Made,
44
+ ReplicateError,
45
+ Replicator,
46
+ StagedImage,
47
+ copy_names,
48
+ files_id,
49
+ )
50
+ from datadouble.runtime import identity
51
+ from datadouble.settings import parse_settings
52
+
53
+ _READY_SECONDS = 120
54
+
55
+
56
+ class DockerSettings(BaseModel):
57
+ """Settings for the ``docker-volume`` replicate adapter."""
58
+
59
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
60
+
61
+ kind: CopyKind = CopyKind.VOLUME
62
+ server_image: str | None = None
63
+ host: str = "localhost"
64
+ """The address consumers use for published ports: the Docker host."""
65
+ network: str | None = None
66
+ """A Docker network instances join; they are reached by name there, too."""
67
+
68
+
69
+ def docker_binary() -> str:
70
+ """The ``docker`` command."""
71
+ found = locate("docker")
72
+ if found is None:
73
+ message = "the docker command was not found"
74
+ raise ReplicateError(message)
75
+ return found
76
+
77
+
78
+ def _docker(
79
+ arguments: list[str],
80
+ action: str,
81
+ *,
82
+ stdin: bytes | None = None,
83
+ env: Mapping[str, str] | None = None,
84
+ ) -> str:
85
+ done = run_program(docker_binary(), arguments, stdin=stdin, env=env)
86
+ if done.status != 0:
87
+ message = f"{action} failed: {done.last_error()}"
88
+ raise ReplicateError(message)
89
+ return done.stdout
90
+
91
+
92
+ def _archive(image: Path) -> bytes:
93
+ """The image directory's contents as an uncompressed tar archive."""
94
+ buffer = io.BytesIO()
95
+ with tarfile.open(fileobj=buffer, mode="w") as archive:
96
+ for item in sorted(image.iterdir()):
97
+ archive.add(item, arcname=item.name)
98
+ return buffer.getvalue()
99
+
100
+
101
+ def _labels(copy_id: str, summary: ImageSummary) -> list[str]:
102
+ identity = summary.identity
103
+ labels = {
104
+ "datadouble.copy": copy_id,
105
+ "datadouble.spec": identity.spec,
106
+ "datadouble.group": identity.group,
107
+ "datadouble.engine": f"{identity.engine}-{identity.engine_version}",
108
+ "datadouble.generation": identity.generation,
109
+ }
110
+ return [argument for key, value in labels.items() for argument in ("--label", f"{key}={value}")]
111
+
112
+
113
+ class Serves(Protocol):
114
+ """The part of an engine adapter this adapter needs."""
115
+
116
+ def server(self, image: Path, server_image: str | None, /) -> ServerPlan:
117
+ """How to serve a copy of ``image``."""
118
+ ...
119
+
120
+
121
+ class DockerReplicator:
122
+ """Volume and instance copies on a Docker daemon."""
123
+
124
+ def __init__(self, settings: DockerSettings, engines: Callable[[str], Serves]) -> None:
125
+ """Use ``engines`` to find the engine adapter for an image."""
126
+ self.settings = settings
127
+ self.engines = engines
128
+
129
+ @property
130
+ def kind(self) -> CopyKind:
131
+ """Volumes or instances, as configured."""
132
+ return self.settings.kind
133
+
134
+ def create(
135
+ self, copy_id: str, image: Path, summary: ImageSummary, files: StagedImage | None = None
136
+ ) -> Made:
137
+ """Fill a volume from the image; for an instance, start the server on it.
138
+
139
+ The group's files, if given, fill a second volume, which only Datadouble's user
140
+ owns, in the engine's server image.
141
+ """
142
+ plan = self.engines(summary.identity.engine).server(image, self.settings.server_image)
143
+ name = f"datadouble-{copy_id}"
144
+ labels = _labels(copy_id, summary)
145
+ self._fill(name, labels, image, plan, files=False)
146
+ made = (
147
+ Made(location={"volume": name})
148
+ if self.settings.kind is CopyKind.VOLUME
149
+ else self._start(name, labels, plan)
150
+ )
151
+ if files is None:
152
+ return made
153
+ volume = f"datadouble-{files_id(copy_id)}"
154
+ self._fill(volume, _labels(copy_id, files.summary), files.path, plan, files=True)
155
+ return made.model_copy(update={"files": {"volume": volume}})
156
+
157
+ @staticmethod
158
+ def _fill(name: str, labels: list[str], image: Path, plan: ServerPlan, *, files: bool) -> None:
159
+ mount, owner = ("/files", identity()) if files else (plan.mount, plan.owner)
160
+ _docker(["volume", "create", *labels, name], "creating the volume")
161
+ # The archive's files already belong to the serving user (decision 86),
162
+ # and extracting as root keeps that; only the new volume's root is root's.
163
+ fill = f"tar -x -C {mount} && chown {owner} {mount}"
164
+ _docker(
165
+ [
166
+ "run",
167
+ "--rm",
168
+ "--interactive",
169
+ "--user",
170
+ "0:0",
171
+ "--entrypoint",
172
+ "sh",
173
+ "--volume",
174
+ f"{name}:{mount}",
175
+ plan.image,
176
+ "-c",
177
+ fill,
178
+ ],
179
+ "filling the volume",
180
+ stdin=_archive(image),
181
+ )
182
+
183
+ def _start(self, name: str, labels: list[str], plan: ServerPlan) -> Made:
184
+ password = secrets.token_hex(16)
185
+ network = ["--network", self.settings.network] if self.settings.network else []
186
+ # The password reaches the container through the docker command's own
187
+ # environment, so it never appears on a command line.
188
+ _docker(
189
+ [
190
+ "run",
191
+ "--detach",
192
+ "--name",
193
+ name,
194
+ *labels,
195
+ *network,
196
+ "--user",
197
+ plan.owner,
198
+ "--volume",
199
+ f"{name}:{plan.mount}",
200
+ "--env",
201
+ "DATADOUBLE_PASSWORD",
202
+ "--publish",
203
+ str(plan.port),
204
+ "--entrypoint",
205
+ plan.command[0],
206
+ plan.image,
207
+ *plan.command[1:],
208
+ ],
209
+ "starting the server",
210
+ env={"DATADOUBLE_PASSWORD": password},
211
+ )
212
+ deadline = time.monotonic() + _READY_SECONDS
213
+ while not self._ready(name, plan):
214
+ if time.monotonic() > deadline:
215
+ message = f"the server in {name} was not ready after {_READY_SECONDS} seconds"
216
+ raise ReplicateError(message)
217
+ time.sleep(1)
218
+ published = _docker(["port", name, f"{plan.port}/tcp"], "reading the port")
219
+ port = int(published.splitlines()[0].rsplit(":", 1)[1])
220
+ return Made(
221
+ location={
222
+ "host": self.settings.host,
223
+ "port": port,
224
+ "database": plan.database,
225
+ "user": plan.user,
226
+ "container": name,
227
+ "volume": name,
228
+ },
229
+ secrets={"password": password},
230
+ )
231
+
232
+ @staticmethod
233
+ def _ready(name: str, plan: ServerPlan) -> bool:
234
+ """Whether the server answers; raises if its container has stopped."""
235
+ running = _docker(["inspect", "--format", "{{.State.Running}}", name], "inspecting")
236
+ if running.strip() != "true":
237
+ logs = run_program(docker_binary(), ["logs", "--tail", "5", name])
238
+ lines = (logs.stdout + logs.stderr).strip().splitlines()
239
+ last = lines[-1] if lines else "no output"
240
+ message = f"the server in {name} stopped: {last}"
241
+ raise ReplicateError(message)
242
+ return run_program(docker_binary(), ["exec", name, *plan.ready]).status == 0
243
+
244
+ def destroy(self, copy: Copy) -> None:
245
+ """Remove the container, if any, and the volumes."""
246
+ name = f"datadouble-{copy.id}"
247
+ if self.settings.kind is CopyKind.INSTANCE:
248
+ run_program(docker_binary(), ["rm", "--force", "--volumes", name])
249
+ for volume in copy_names(copy):
250
+ run_program(docker_binary(), ["volume", "rm", "--force", f"datadouble-{volume}"])
251
+
252
+ def claim_state(self, _copy: Copy, /) -> ClaimState:
253
+ """Claims are recorded by ``claim``."""
254
+ return ClaimState.UNKNOWN
255
+
256
+
257
+ def docker_replicator(settings: Mapping[str, JsonValue]) -> Replicator:
258
+ """The entry point named in ``datadouble.replicators``."""
259
+ registry = installed()
260
+ return DockerReplicator(
261
+ parse_settings(DockerSettings, settings, "docker-volume replicate"), registry.engine
262
+ )
File without changes
@@ -0,0 +1,223 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Docker container runtime: engine software on any Docker-compatible daemon.
5
+
6
+ Spec settings::
7
+
8
+ runtime:
9
+ docker:
10
+ publish: 127.0.0.1 # the daemon host's address server ports are published on
11
+ address: 127.0.0.1 # where Datadouble reaches published ports
12
+ network: builds # optional: a network every container joins
13
+
14
+ Paths are bind-mounted at the same absolute path, so the work directory must
15
+ exist at that path on the daemon's host: true for a local daemon, and arranged
16
+ with a shared volume for a remote one. Containers run as Datadouble's own user
17
+ and group. Everything is done with the ``docker`` command, so ``DOCKER_HOST``
18
+ and contexts apply; secrets reach containers through the command's own
19
+ environment, never its arguments.
20
+ """
21
+
22
+ import secrets
23
+ import time
24
+ from collections.abc import Generator, Mapping, Sequence
25
+ from contextlib import contextmanager
26
+ from pathlib import Path
27
+
28
+ from pydantic import BaseModel, ConfigDict, Field, JsonValue
29
+
30
+ from datadouble.programs import locate, run_program
31
+ from datadouble.runtime import (
32
+ Completed,
33
+ Container,
34
+ ContainerError,
35
+ ContainerRuntime,
36
+ Endpoint,
37
+ absolute,
38
+ check,
39
+ identity,
40
+ )
41
+ from datadouble.settings import parse_settings
42
+
43
+ _OWNER = "datadouble.owner"
44
+
45
+
46
+ class DockerRuntimeSettings(BaseModel):
47
+ """Settings for the ``docker`` container runtime."""
48
+
49
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
50
+
51
+ publish: str = "127.0.0.1"
52
+ """The daemon host's address server ports are published on."""
53
+ address: str = "127.0.0.1"
54
+ """Where Datadouble reaches published ports."""
55
+ network: str | None = None
56
+ """A Docker network every container joins, for reaching the source."""
57
+ ready_seconds: int = Field(default=300, ge=1)
58
+ stop_seconds: int = Field(default=300, ge=1)
59
+
60
+
61
+ def _docker(arguments: Sequence[str], env: Mapping[str, str] | None = None) -> Completed:
62
+ binary = locate("docker")
63
+ if binary is None:
64
+ message = "the docker command was not found"
65
+ raise ContainerError(message)
66
+ return run_program(binary, arguments, env=env)
67
+
68
+
69
+ def _field(key: str, value: Path) -> str:
70
+ """One field of a ``--mount`` value, quoted as CSV so a comma in a path stays in it."""
71
+ return '"{}"'.format(f"{key}={value}".replace('"', '""'))
72
+
73
+
74
+ def _options(container: Container, network: str | None) -> list[str]:
75
+ """``docker run`` options shared by jobs and servers."""
76
+ options = ["--label", f"{_OWNER}={absolute([container.owner])[0]}", "--user", identity()]
77
+ if network:
78
+ options += ["--network", network]
79
+ # --mount refuses a directory that does not exist, where --volume would
80
+ # create it as root: a container that an interrupted run had already
81
+ # asked for cannot recreate a stage directory its resume just cleared.
82
+ for path in absolute(container.mounts):
83
+ options += ["--mount", f"type=bind,{_field('source', path)},{_field('target', path)}"]
84
+ for key, value in container.env.items():
85
+ options += ["--env", f"{key}={value}"]
86
+ for key in container.secrets:
87
+ options += ["--env", key]
88
+ return options
89
+
90
+
91
+ class DockerServer:
92
+ """A server container started by :class:`DockerRuntime`."""
93
+
94
+ def __init__(self, name: str, endpoint: Endpoint) -> None:
95
+ """Wrap the running container ``name``."""
96
+ self.name = name
97
+ self._endpoint = endpoint
98
+
99
+ @property
100
+ def endpoint(self) -> Endpoint:
101
+ """The published port, at the configured address."""
102
+ return self._endpoint
103
+
104
+ def execute(self, command: Sequence[str], env: Mapping[str, str] | None = None) -> Completed:
105
+ """``docker exec``; ``env`` reaches the command through docker's environment."""
106
+ options = [argument for key in env or {} for argument in ("--env", key)]
107
+ return _docker(["exec", *options, self.name, *command], env)
108
+
109
+
110
+ class DockerRuntime:
111
+ """Runs containers with the ``docker`` command."""
112
+
113
+ def __init__(self, settings: DockerRuntimeSettings) -> None:
114
+ """Use ``settings`` for every container."""
115
+ self.settings = settings
116
+
117
+ def run(self, container: Container) -> Completed:
118
+ """``docker run --rm``, waiting for the command to finish."""
119
+ return _docker(
120
+ [
121
+ "run",
122
+ "--rm",
123
+ *_options(container, self.settings.network),
124
+ "--entrypoint",
125
+ container.command[0],
126
+ container.image,
127
+ *container.command[1:],
128
+ ],
129
+ container.secrets,
130
+ )
131
+
132
+ @contextmanager
133
+ def serve(self, container: Container) -> Generator[DockerServer]:
134
+ """Start a detached server, publish its port, and stop it cleanly afterwards."""
135
+ if container.port is None:
136
+ message = "a server container needs a port"
137
+ raise ContainerError(message)
138
+ name = f"datadouble-{secrets.token_hex(6)}"
139
+ check(
140
+ _docker(
141
+ [
142
+ "run",
143
+ "--detach",
144
+ "--name",
145
+ name,
146
+ *_options(container, self.settings.network),
147
+ "--publish",
148
+ f"{self.settings.publish}::{container.port}",
149
+ "--stop-timeout",
150
+ str(self.settings.stop_seconds),
151
+ "--entrypoint",
152
+ container.command[0],
153
+ container.image,
154
+ *container.command[1:],
155
+ ],
156
+ container.secrets,
157
+ ),
158
+ f"starting {container.image}",
159
+ )
160
+ try:
161
+ self._wait(name, container)
162
+ yield DockerServer(name, self._endpoint(name, container.port))
163
+ self._stop(name)
164
+ finally:
165
+ _docker(["rm", "--force", name])
166
+
167
+ def _endpoint(self, name: str, port: int) -> Endpoint:
168
+ published = check(_docker(["port", name, f"{port}/tcp"]), "reading the published port")
169
+ return Endpoint(
170
+ host=self.settings.address,
171
+ port=int(published.stdout.splitlines()[0].rsplit(":", 1)[1]),
172
+ )
173
+
174
+ def _wait(self, name: str, container: Container) -> None:
175
+ deadline = time.monotonic() + self.settings.ready_seconds
176
+ while True:
177
+ state = _docker(["inspect", "--format", "{{.State.Running}}", name])
178
+ if state.stdout.strip() != "true":
179
+ raise ContainerError(self._stopped(name, "stopped while starting"))
180
+ if _docker(["exec", name, *container.ready]).status == 0:
181
+ return
182
+ if time.monotonic() > deadline:
183
+ message = (
184
+ f"{container.image} was not ready after {self.settings.ready_seconds} seconds"
185
+ )
186
+ raise ContainerError(message)
187
+ time.sleep(1)
188
+
189
+ def _stop(self, name: str) -> None:
190
+ """Stop the server with its normal signal; it must exit cleanly."""
191
+ check(_docker(["stop", name]), "stopping the server")
192
+ status = _docker(["inspect", "--format", "{{.State.ExitCode}}", name]).stdout.strip()
193
+ if status != "0":
194
+ raise ContainerError(self._stopped(name, f"exited with status {status}"))
195
+
196
+ @staticmethod
197
+ def _stopped(name: str, what: str) -> str:
198
+ logs = _docker(["logs", "--tail", "5", name])
199
+ lines = (logs.stdout + logs.stderr).strip().splitlines()
200
+ return f"the server {what}: {lines[-1] if lines else 'no output'}"
201
+
202
+ def release(self, owner: Path) -> None:
203
+ """Remove containers labelled with ``owner`` or a directory under it."""
204
+ root = absolute([owner])[0]
205
+ listed = _docker(
206
+ [
207
+ "ps",
208
+ "--all",
209
+ "--filter",
210
+ f"label={_OWNER}",
211
+ "--format",
212
+ f'{{{{.ID}}}} {{{{.Label "{_OWNER}"}}}}',
213
+ ]
214
+ )
215
+ for line in listed.stdout.splitlines():
216
+ container, _, labelled = line.partition(" ")
217
+ if Path(labelled).is_relative_to(root):
218
+ _docker(["rm", "--force", container])
219
+
220
+
221
+ def docker_runtime(settings: Mapping[str, JsonValue]) -> ContainerRuntime:
222
+ """The entry point named in ``datadouble.runtimes``."""
223
+ return DockerRuntime(parse_settings(DockerRuntimeSettings, settings, "docker runtime"))
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.5
2
+ Name: datadouble-docker
3
+ Version: 0.0.3
4
+ Summary: Docker replicate adapter 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 :: Software Development :: Testing
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.13
18
+ Requires-Dist: datadouble
19
+ Description-Content-Type: text/markdown
20
+
21
+ # datadouble-docker
22
+
23
+ The Docker replicate adapter for [Datadouble](https://datadouble.tightlinesoftware.com/):
24
+ copies of staged images as Docker volumes, or as containers running a server on
25
+ such a volume.
26
+
27
+ ```yaml
28
+ replicate:
29
+ using:
30
+ docker-volume:
31
+ kind: instance # or volume (the default)
32
+ server_image: postgres:18-trixie@sha256:... # optional; the engine's choice otherwise
33
+ host: db-clones.internal # how consumers reach published ports
34
+ network: ci # optional: attach instances to a Docker network
35
+ ```
36
+
37
+ It uses the `docker` command, so `DOCKER_HOST` and Docker contexts work as usual.
@@ -0,0 +1,8 @@
1
+ datadouble_docker/__init__.py,sha256=__VUfXI9dy-hoEz2UiuwS8u3sulZa4lIAP48cDeMkN4,9417
2
+ datadouble_docker/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ datadouble_docker/runtime.py,sha256=A0LBxE2fKqZO_kIdC2QYYy3KywUtStLXHCKNzaW2Uj4,8476
4
+ datadouble_docker-0.0.3.dist-info/METADATA,sha256=6C5dReiKAhm8nJ962UbB4kblRI9XPvWy9K4eMzL6IbU,1379
5
+ datadouble_docker-0.0.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ datadouble_docker-0.0.3.dist-info/entry_points.txt,sha256=PgH2maVC31sNU47JONH0KMblnj2a0VOb0vSytenCn_M,150
7
+ datadouble_docker-0.0.3.dist-info/licenses/LICENSE,sha256=2LcT-SSMiSa7vrHsdC41sUWNmkcwZqIYdYBaSVmqqT8,1072
8
+ datadouble_docker-0.0.3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [datadouble.replicators]
2
+ docker-volume = datadouble_docker:docker_replicator
3
+
4
+ [datadouble.runtimes]
5
+ docker = datadouble_docker.runtime:docker_runtime
@@ -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.