datadouble-docker 0.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ __pycache__/
5
+ *.py[cod]
6
+ .venv/
7
+ .env
8
+ .coverage
9
+ .coverage.*
10
+ coverage.xml
11
+ .reports/
12
+ .pytest_cache/
13
+ .mypy_cache/
14
+ .ruff_cache/
15
+ dist/
16
+ site/
17
+ .cache/
18
+
19
+ # The default work directory of `datadouble run`.
20
+ .datadouble/
21
+ node_modules/
@@ -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.
@@ -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,17 @@
1
+ # datadouble-docker
2
+
3
+ The Docker replicate adapter for [Datadouble](https://datadouble.tightlinesoftware.com/):
4
+ copies of staged images as Docker volumes, or as containers running a server on
5
+ such a volume.
6
+
7
+ ```yaml
8
+ replicate:
9
+ using:
10
+ docker-volume:
11
+ kind: instance # or volume (the default)
12
+ server_image: postgres:18-trixie@sha256:... # optional; the engine's choice otherwise
13
+ host: db-clones.internal # how consumers reach published ports
14
+ network: ci # optional: attach instances to a Docker network
15
+ ```
16
+
17
+ It uses the `docker` command, so `DOCKER_HOST` and Docker contexts work as usual.
@@ -0,0 +1,41 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ [project]
5
+ name = "datadouble-docker"
6
+ # All packages share one version until 1.0 (decision 38); scripts/make_tag.py
7
+ # sets it at release time.
8
+ version = "0.0.3"
9
+ description = "Docker replicate adapter for Datadouble"
10
+ readme = "README.md"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Tight Line LLC" }]
14
+ requires-python = ">=3.13"
15
+ dependencies = ["datadouble"]
16
+ classifiers = [
17
+ "Development Status :: 2 - Pre-Alpha",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Programming Language :: Python :: 3.15",
22
+ "Topic :: Software Development :: Testing",
23
+ "Typing :: Typed",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://datadouble.tightlinesoftware.com/"
28
+ Source = "https://github.com/datadouble/datadouble"
29
+
30
+ [project.entry-points."datadouble.replicators"]
31
+ docker-volume = "datadouble_docker:docker_replicator"
32
+
33
+ [project.entry-points."datadouble.runtimes"]
34
+ docker = "datadouble_docker.runtime:docker_runtime"
35
+
36
+ [build-system]
37
+ requires = ["hatchling>=1.33.0"]
38
+ build-backend = "hatchling.build"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/datadouble_docker"]
@@ -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,364 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Docker replicate adapter, and the whole non-production side with real tools.
5
+
6
+ These tests build an image from a scratch PostgreSQL database, sign it with a
7
+ real cosign key pair, promote and fetch it, and serve copies from the
8
+ Docker-in-Docker daemon in the Compose default group.
9
+ """
10
+
11
+ import datetime as dt
12
+ import json
13
+ import os
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ from collections.abc import Generator
19
+ from pathlib import Path
20
+
21
+ import psycopg
22
+ import pytest
23
+
24
+ import datadouble_docker
25
+ from datadouble.api import CopiesResponse, ErrorResponse, handle_json
26
+ from datadouble.catalog import CatalogLock, write_lock
27
+ from datadouble.engine import ServerPlan
28
+ from datadouble.images import ImageIdentity, ImageSummary, Verification
29
+ from datadouble.names import EngineName, Generation, GroupName, SpecName
30
+ from datadouble.replicate import ClaimState, Copy, CopyKind, CopyState, ReplicateError, StagedImage
31
+ from datadouble.runtime import identity
32
+ from datadouble.spec import ReplicateMode, Strict
33
+ from datadouble_conformance.engine import runtime_for_tests
34
+ from datadouble_docker import DockerReplicator, DockerSettings, docker_binary
35
+ from datadouble_postgres import PostgresEngine
36
+ from test_conformance import PostgresScratch, scratch
37
+
38
+ SERVER = (
39
+ "postgres:18-trixie@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42"
40
+ )
41
+
42
+
43
+ @pytest.fixture
44
+ def source() -> Generator[PostgresScratch]:
45
+ with scratch() as made:
46
+ assert isinstance(made, PostgresScratch)
47
+ made.add_table("people")
48
+ made.add_column("name")
49
+ for number in range(1, 4):
50
+ made.insert(number)
51
+ yield made
52
+
53
+
54
+ @pytest.fixture
55
+ def keys(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
56
+ monkeypatch.setenv("COSIGN_PASSWORD", "test-only")
57
+ cosign = shutil.which("cosign")
58
+ assert cosign is not None
59
+ subprocess.run([cosign, "generate-key-pair"], cwd=tmp_path, check=True, capture_output=True)
60
+ return tmp_path
61
+
62
+
63
+ def write_spec(source: PostgresScratch, tmp_path: Path, keys: Path, kind: str) -> Path:
64
+ address = os.environ.get("DATADOUBLE_TEST_DOCKER_ADDRESS", "localhost")
65
+ spec = {
66
+ "name": "scratch",
67
+ "sources": {"app": {"engine": "postgres", "connection": dict(source.connection)}},
68
+ "subset": {"seeds": {"items": "id > 0"}, "unselected": "none"},
69
+ "runtime": runtime_for_tests(),
70
+ "store": [{"filesystem": {"path": str(tmp_path / "build")}}],
71
+ "signing": {
72
+ "cosign": {"key": {"file": str(keys / "cosign.key")}, "transparency_log": False}
73
+ },
74
+ "trust": {
75
+ "cosign": {"public_key": {"file": str(keys / "cosign.pub")}, "transparency_log": False}
76
+ },
77
+ "promote": {"to": [{"filesystem": {"path": str(tmp_path / "export")}}]},
78
+ "fetch": {
79
+ "from": {"filesystem": {"path": str(tmp_path / "export")}},
80
+ "staging": str(tmp_path / "staging"),
81
+ },
82
+ "replicate": {
83
+ "using": {"docker-volume": {"kind": kind, "server_image": SERVER, "host": address}},
84
+ "mode": "on-demand",
85
+ "size": 1,
86
+ },
87
+ "announce": [{"dotenv": {"path": str(tmp_path / "clone.env")}}],
88
+ }
89
+ path = tmp_path / "spec.json"
90
+ path.write_text(json.dumps(spec), encoding="utf-8")
91
+ with PostgresEngine().connect(source.connection) as session:
92
+ write_lock(CatalogLock.of(session.catalog()), tmp_path / "spec.lock")
93
+ return path
94
+
95
+
96
+ def call(**request: object) -> object:
97
+ response = handle_json(json.dumps(request))
98
+ assert not isinstance(response, ErrorResponse), response
99
+ return response
100
+
101
+
102
+ def build_and_stage(spec: Path, tmp_path: Path) -> None:
103
+ call(
104
+ command="run",
105
+ spec=str(spec),
106
+ stages=["plan", "extract", "load", "transform", "package", "verify", "store"],
107
+ work=str(tmp_path / "work"),
108
+ )
109
+ call(command="promote", spec=str(spec))
110
+ call(command="fetch", spec=str(spec))
111
+
112
+
113
+ def docker(*arguments: str) -> str:
114
+ return subprocess.run(
115
+ [docker_binary(), *arguments], check=True, capture_output=True, text=True
116
+ ).stdout
117
+
118
+
119
+ @pytest.mark.integration
120
+ def test_instance_copies_serve_the_image(
121
+ source: PostgresScratch, tmp_path: Path, keys: Path
122
+ ) -> None:
123
+ spec = write_spec(source, tmp_path, keys, "instance")
124
+ build_and_stage(spec, tmp_path)
125
+ made = call(command="replicate", spec=str(spec), owner="mr-1")
126
+ assert isinstance(made, CopiesResponse)
127
+ (copy,) = made.result.created
128
+ assert copy.secrets == {}
129
+ env = dict(line.split("=", 1) for line in (tmp_path / "clone.env").read_text().splitlines())
130
+ with psycopg.connect(
131
+ host=env["DATADOUBLE_HOST"],
132
+ port=int(env["DATADOUBLE_PORT"]),
133
+ dbname=env["DATADOUBLE_DATABASE"],
134
+ user=env["DATADOUBLE_USER"],
135
+ password=env["DATADOUBLE_PASSWORD"],
136
+ ) as connection:
137
+ rows = connection.execute("SELECT id FROM public.items ORDER BY id").fetchall()
138
+ assert rows == [(1,), (2,), (3,)]
139
+ assert docker("ps", "--quiet", "--filter", f"name=datadouble-{copy.id}").strip()
140
+ call(command="release", spec=str(spec), owner="mr-1")
141
+ assert not docker("ps", "--all", "--quiet", "--filter", f"name=datadouble-{copy.id}").strip()
142
+ assert not (tmp_path / "clone.env").exists()
143
+
144
+
145
+ @pytest.mark.integration
146
+ def test_volume_copies(source: PostgresScratch, tmp_path: Path, keys: Path) -> None:
147
+ spec = write_spec(source, tmp_path, keys, "volume")
148
+ build_and_stage(spec, tmp_path)
149
+ made = call(command="replicate", spec=str(spec), owner="mr-2")
150
+ assert isinstance(made, CopiesResponse)
151
+ (copy,) = made.result.created
152
+ volume = str(copy.location["volume"])
153
+ listing = docker(
154
+ "run",
155
+ "--rm",
156
+ "--volume",
157
+ f"{volume}:/data",
158
+ "--entrypoint",
159
+ "ls",
160
+ SERVER,
161
+ "-n",
162
+ "/data/pgdata",
163
+ )
164
+ assert "PG_VERSION" in listing
165
+ assert " 999 " in listing
166
+ call(command="release", spec=str(spec), copy_ids=[copy.id])
167
+ with pytest.raises(subprocess.CalledProcessError):
168
+ docker("volume", "inspect", volume)
169
+
170
+
171
+ def test_missing_docker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
172
+ assert DockerSettings().kind == "volume"
173
+ monkeypatch.setenv("PATH", str(tmp_path))
174
+ with pytest.raises(ReplicateError, match="docker command was not found"):
175
+ docker_binary()
176
+
177
+
178
+ FAKE_DOCKER = """
179
+ import json, sys
180
+ from pathlib import Path
181
+ state_file = Path(sys.argv[0]).with_name("state.json")
182
+ state = json.loads(state_file.read_text())
183
+ args = sys.argv[1:]
184
+ command = args[0] if args[0] != "volume" else "volume " + args[1]
185
+ state.setdefault("calls", []).append(args)
186
+ state_file.write_text(json.dumps(state))
187
+ if command in state.get("fail", {}):
188
+ sys.stderr.write(state["fail"][command])
189
+ sys.exit(1)
190
+ if command == "run" and "--interactive" in args:
191
+ sys.stdin.buffer.read()
192
+ elif command == "inspect":
193
+ print("true" if state.get("running", True) else "false")
194
+ elif command == "logs":
195
+ print(state.get("logs", ""), end="")
196
+ elif command == "exec":
197
+ state["polls"] = state.get("polls", 0) + 1
198
+ state_file.write_text(json.dumps(state))
199
+ sys.exit(0 if state["polls"] >= state.get("ready_after", 1) else 1)
200
+ elif command == "port":
201
+ print("0.0.0.0:49153")
202
+ """
203
+
204
+
205
+ class _Engine:
206
+ """Just enough of an engine adapter to plan a server."""
207
+
208
+ def server(self, image: Path, server_image: str | None) -> ServerPlan:
209
+ return ServerPlan(
210
+ image=server_image or "engine:1",
211
+ mount="/data",
212
+ owner="9:9",
213
+ command=("serve", "--now"),
214
+ ready=("check",),
215
+ port=5432,
216
+ database=image.name,
217
+ user="owner",
218
+ )
219
+
220
+
221
+ def _no_sleep(_seconds: float) -> None:
222
+ return
223
+
224
+
225
+ @pytest.fixture
226
+ def fake_docker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
227
+ script = tmp_path / "bin" / "docker"
228
+ script.parent.mkdir()
229
+ script.write_text(f"#!{sys.executable}\n{FAKE_DOCKER}", encoding="utf-8")
230
+ script.chmod(0o755)
231
+ state = script.with_name("state.json")
232
+ state.write_text("{}", encoding="utf-8")
233
+ monkeypatch.setenv("PATH", f"{script.parent}{os.pathsep}{os.environ['PATH']}")
234
+ monkeypatch.setattr(time, "sleep", _no_sleep)
235
+ return state
236
+
237
+
238
+ def configure(state: Path, **values: object) -> None:
239
+ current = json.loads(state.read_text())
240
+ current.update(values)
241
+ state.write_text(json.dumps(current))
242
+
243
+
244
+ def replicator(
245
+ kind: CopyKind, *, network: str | None = None, server_image: str | None = None
246
+ ) -> DockerReplicator:
247
+ return DockerReplicator(
248
+ DockerSettings(kind=kind, server_image=server_image, network=network),
249
+ lambda _name: _Engine(),
250
+ )
251
+
252
+
253
+ def summary() -> ImageSummary:
254
+ return ImageSummary(
255
+ identity=ImageIdentity(
256
+ spec=SpecName("shop"),
257
+ group=GroupName("all"),
258
+ engine=EngineName("fake"),
259
+ engine_version="1",
260
+ generation=Generation("0193a7c21b4e9f30"),
261
+ ),
262
+ built_at=dt.datetime(2026, 11, 1, tzinfo=dt.UTC),
263
+ archives=(),
264
+ manifest_sha256="0" * 64,
265
+ verification=Verification(passed=True, checks=1, failed=0),
266
+ strict=Strict(),
267
+ )
268
+
269
+
270
+ def unit_copy(copy_id: str, kind: CopyKind) -> Copy:
271
+ return Copy(
272
+ id=copy_id,
273
+ prefix="shop/all/fake-1",
274
+ generation=Generation("0193a7c21b4e9f30"),
275
+ kind=kind,
276
+ mode=ReplicateMode.POOL,
277
+ adapter="docker-volume",
278
+ state=CopyState.READY,
279
+ created_at=dt.datetime(2026, 11, 1, tzinfo=dt.UTC),
280
+ built_at=dt.datetime(2026, 11, 1, tzinfo=dt.UTC),
281
+ )
282
+
283
+
284
+ def image_dir(tmp_path: Path) -> Path:
285
+ image = tmp_path / "image"
286
+ image.mkdir(parents=True)
287
+ (image / "file").write_text("x", encoding="utf-8")
288
+ return image
289
+
290
+
291
+ def test_instances_with_a_stand_in_docker(tmp_path: Path, fake_docker: Path) -> None:
292
+ configure(fake_docker, ready_after=3)
293
+ instance = replicator(CopyKind.INSTANCE, network="ci", server_image="custom:2")
294
+ made = instance.create("abc", image_dir(tmp_path), summary())
295
+ assert made.location == {
296
+ "host": "localhost",
297
+ "port": 49153,
298
+ "database": "image",
299
+ "user": "owner",
300
+ "container": "datadouble-abc",
301
+ "volume": "datadouble-abc",
302
+ }
303
+ assert len(made.secrets["password"]) == 32
304
+ calls = json.loads(fake_docker.read_text())["calls"]
305
+ start = next(c for c in calls if "--detach" in c)
306
+ assert start[start.index("--network") : start.index("--network") + 2] == ["--network", "ci"]
307
+ assert "DATADOUBLE_PASSWORD" in start
308
+ assert made.secrets["password"] not in " ".join(start)
309
+ assert start[start.index("--entrypoint") + 1 :] == ["serve", "custom:2", "--now"]
310
+ instance.destroy(unit_copy("abc", CopyKind.INSTANCE))
311
+ assert ["rm", "--force", "--volumes", "datadouble-abc"] in json.loads(fake_docker.read_text())[
312
+ "calls"
313
+ ]
314
+ assert instance.claim_state(unit_copy("abc", CopyKind.INSTANCE)) is ClaimState.UNKNOWN
315
+
316
+
317
+ def test_servers_that_stop_or_never_answer(
318
+ tmp_path: Path, fake_docker: Path, monkeypatch: pytest.MonkeyPatch
319
+ ) -> None:
320
+ configure(fake_docker, running=False, logs="FATAL: data directory has wrong ownership\n")
321
+ with pytest.raises(ReplicateError, match="stopped: FATAL: data directory has wrong ownership"):
322
+ replicator(CopyKind.INSTANCE).create("a", image_dir(tmp_path), summary())
323
+ configure(fake_docker, logs="")
324
+ with pytest.raises(ReplicateError, match="stopped: no output"):
325
+ replicator(CopyKind.INSTANCE).create("b", image_dir(tmp_path / "b"), summary())
326
+ configure(fake_docker, running=True, ready_after=1000)
327
+ monkeypatch.setattr(datadouble_docker, "_READY_SECONDS", -1)
328
+ with pytest.raises(ReplicateError, match="was not ready after -1 seconds"):
329
+ replicator(CopyKind.INSTANCE).create("c", image_dir(tmp_path / "c"), summary())
330
+
331
+
332
+ def test_docker_failures(tmp_path: Path, fake_docker: Path) -> None:
333
+ configure(fake_docker, fail={"volume create": "Error: no space left on device\n"})
334
+ with pytest.raises(ReplicateError, match="creating the volume failed: Error: no space left"):
335
+ replicator(CopyKind.VOLUME).create("a", image_dir(tmp_path), summary())
336
+ configure(fake_docker, fail={"volume create": ""})
337
+ with pytest.raises(ReplicateError, match="creating the volume failed: status 1"):
338
+ replicator(CopyKind.VOLUME).create("b", image_dir(tmp_path / "b"), summary())
339
+
340
+
341
+ def test_files_go_into_a_volume_of_their_own(tmp_path: Path, fake_docker: Path) -> None:
342
+ instance = replicator(CopyKind.INSTANCE)
343
+ files_summary = summary().model_copy(
344
+ update={
345
+ "identity": summary().identity.model_copy(
346
+ update={"engine": EngineName("files"), "engine_version": "1"}
347
+ )
348
+ }
349
+ )
350
+ made = instance.create(
351
+ "abc", image_dir(tmp_path), summary(), StagedImage(image_dir(tmp_path / "f"), files_summary)
352
+ )
353
+ assert made.files == {"volume": "datadouble-abc-files"}
354
+ assert made.location["volume"] == "datadouble-abc"
355
+ calls = json.loads(fake_docker.read_text())["calls"]
356
+ fill = next(c for c in calls if "datadouble-abc-files:/files" in c)
357
+ assert fill[fill.index("engine:1") :] == [
358
+ "engine:1",
359
+ "-c",
360
+ f"tar -x -C /files && chown {identity()} /files",
361
+ ]
362
+ instance.destroy(unit_copy("abc", CopyKind.INSTANCE).model_copy(update={"files": {}}))
363
+ calls = json.loads(fake_docker.read_text())["calls"]
364
+ assert ["volume", "rm", "--force", "datadouble-abc-files"] in calls
@@ -0,0 +1,126 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Docker container runtime, against the Docker-in-Docker daemon.
5
+
6
+ The test runner and the daemon share the volume temporary files live on, at
7
+ the same path, as a production work directory must be shared with its daemon.
8
+ """
9
+
10
+ import os
11
+ from pathlib import Path
12
+
13
+ import pytest
14
+
15
+ from datadouble.runtime import Container, ContainerError, ContainerRuntime
16
+ from datadouble_docker.runtime import DockerRuntime, DockerRuntimeSettings, docker_runtime
17
+
18
+ pytestmark = pytest.mark.integration
19
+
20
+ IMAGE = "postgres:18-trixie@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42"
21
+ LOOP = "trap 'exit 0' INT TERM; touch /tmp/ready; while :; do sleep 0.2; done"
22
+
23
+
24
+ def runtime(**settings: str | int) -> ContainerRuntime:
25
+ address = os.environ.get("DATADOUBLE_TEST_DOCKER_ADDRESS", "127.0.0.1")
26
+ return docker_runtime({"publish": "0.0.0.0", "address": address, **settings}) # noqa: S104 - published inside the test daemon only
27
+
28
+
29
+ def server(tmp_path: Path, script: str = LOOP) -> Container:
30
+ return Container(
31
+ image=IMAGE,
32
+ command=("sh", "-c", script),
33
+ owner=tmp_path / "stage",
34
+ port=5432,
35
+ ready=("test", "-f", "/tmp/ready"), # noqa: S108 - a path inside the container
36
+ )
37
+
38
+
39
+ def test_jobs_share_files_and_receive_secrets(tmp_path: Path) -> None:
40
+ shared = tmp_path / "shared, with a comma"
41
+ shared.mkdir()
42
+ done = runtime(network="bridge").run(
43
+ Container(
44
+ image=IMAGE,
45
+ command=("sh", "-c", f'id -u; echo "$TOKEN $MODE" > "{shared}/out"'),
46
+ owner=tmp_path / "stage",
47
+ mounts=(shared,),
48
+ env={"MODE": "plain"},
49
+ secrets={"TOKEN": "s3cret"},
50
+ )
51
+ )
52
+ assert done.status == 0, done.stderr
53
+ assert done.stdout.strip() == str(os.getuid())
54
+ written = shared / "out"
55
+ assert written.read_text("utf-8") == "s3cret plain\n"
56
+ assert written.stat().st_uid == os.getuid()
57
+ failed = runtime().run(
58
+ Container(image=IMAGE, command=("sh", "-c", "echo no >&2; exit 3"), owner=tmp_path)
59
+ )
60
+ assert (failed.status, failed.stderr.strip()) == (3, "no")
61
+
62
+
63
+ def test_missing_mounts_are_refused_not_created(tmp_path: Path) -> None:
64
+ missing = tmp_path / "cleared"
65
+ refused = runtime().run(
66
+ Container(image=IMAGE, command=("true",), owner=tmp_path, mounts=(missing,))
67
+ )
68
+ assert refused.status != 0
69
+ assert "does not exist" in refused.stderr
70
+ assert not missing.exists()
71
+
72
+
73
+ def test_servers_publish_execute_and_stop(tmp_path: Path) -> None:
74
+ with runtime().serve(server(tmp_path)) as running:
75
+ assert running.endpoint.port > 0
76
+ assert running.endpoint.host == os.environ.get(
77
+ "DATADOUBLE_TEST_DOCKER_ADDRESS", "127.0.0.1"
78
+ )
79
+ done = running.execute(["sh", "-c", 'echo "$WORD"'], {"WORD": "inside"})
80
+ assert done.stdout.strip() == "inside"
81
+
82
+
83
+ def test_server_failures(tmp_path: Path) -> None:
84
+ with (
85
+ pytest.raises(ContainerError, match="stopped while starting: going away"),
86
+ runtime().serve(server(tmp_path, "echo going away; exit 3")),
87
+ ):
88
+ pass
89
+ never = server(tmp_path, "trap 'exit 0' INT TERM; while :; do sleep 0.2; done")
90
+ with (
91
+ pytest.raises(ContainerError, match="was not ready after 1 seconds"),
92
+ runtime(ready_seconds=1).serve(never),
93
+ ):
94
+ pass
95
+ unclean = server(
96
+ tmp_path, "trap 'echo bye; exit 4' INT TERM; touch /tmp/ready; while :; do sleep 0.2; done"
97
+ )
98
+ with pytest.raises(ContainerError, match="exited with status 4: bye"), runtime().serve(unclean):
99
+ pass
100
+ portless = Container(image=IMAGE, command=("true",), owner=tmp_path)
101
+ with pytest.raises(ContainerError, match="needs a port"), runtime().serve(portless):
102
+ pass
103
+ with (
104
+ pytest.raises(ContainerError, match=r"starting postgres:18.*failed"),
105
+ runtime().serve(Container(image=IMAGE, command=("/nonexistent",), owner=tmp_path, port=1)),
106
+ ):
107
+ pass
108
+
109
+
110
+ def test_release_removes_leftovers(tmp_path: Path) -> None:
111
+ docker = runtime()
112
+ assert isinstance(docker, DockerRuntime)
113
+ other = docker.serve(server(tmp_path / "elsewhere"))
114
+ other.__enter__()
115
+ left = docker.serve(server(tmp_path / "load"))
116
+ left.__enter__()
117
+ docker.release(tmp_path / "load")
118
+ with pytest.raises(ContainerError, match="stopping the server failed"):
119
+ left.__exit__(None, None, None)
120
+ other.__exit__(None, None, None)
121
+
122
+
123
+ def test_missing_docker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
124
+ monkeypatch.setenv("PATH", str(tmp_path))
125
+ with pytest.raises(ContainerError, match="docker command was not found"):
126
+ DockerRuntime(DockerRuntimeSettings()).run(server(tmp_path))