datadouble 0.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- datadouble/__init__.py +10 -0
- datadouble/announce.py +380 -0
- datadouble/anonymize.py +165 -0
- datadouble/api.py +1159 -0
- datadouble/boundary.py +47 -0
- datadouble/catalog.py +677 -0
- datadouble/channels.py +62 -0
- datadouble/ci.py +1357 -0
- datadouble/cli.py +940 -0
- datadouble/closure.py +712 -0
- datadouble/engine.py +435 -0
- datadouble/files.py +78 -0
- datadouble/images.py +265 -0
- datadouble/jailer.py +403 -0
- datadouble/names.py +114 -0
- datadouble/notify.py +262 -0
- datadouble/objects.py +195 -0
- datadouble/outcome.py +27 -0
- datadouble/pii.py +109 -0
- datadouble/planner.py +1492 -0
- datadouble/programs.py +68 -0
- datadouble/promote.py +190 -0
- datadouble/prune.py +258 -0
- datadouble/py.typed +0 -0
- datadouble/redaction.py +131 -0
- datadouble/registry.py +128 -0
- datadouble/replicate.py +562 -0
- datadouble/resolve.py +201 -0
- datadouble/run.py +1075 -0
- datadouble/runtime.py +154 -0
- datadouble/secrets.py +57 -0
- datadouble/settings.py +81 -0
- datadouble/signing.py +98 -0
- datadouble/spec.py +1590 -0
- datadouble/staging.py +346 -0
- datadouble/storage.py +222 -0
- datadouble/strict.py +498 -0
- datadouble/subset.py +406 -0
- datadouble/verify.py +171 -0
- datadouble/versions.py +25 -0
- datadouble-0.0.3.dist-info/METADATA +36 -0
- datadouble-0.0.3.dist-info/RECORD +45 -0
- datadouble-0.0.3.dist-info/WHEEL +4 -0
- datadouble-0.0.3.dist-info/entry_points.txt +12 -0
- datadouble-0.0.3.dist-info/licenses/LICENSE +21 -0
datadouble/engine.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The engine adapter interface.
|
|
5
|
+
|
|
6
|
+
An engine adapter does everything that depends on the engine: introspecting
|
|
7
|
+
the catalog, reading one consistent snapshot, building working databases in
|
|
8
|
+
scratch space, applying anonymization in native updates, packaging golden
|
|
9
|
+
images and restoring them for verification. The core drives these through the
|
|
10
|
+
protocols below and never contains engine-specific logic.
|
|
11
|
+
|
|
12
|
+
Engine software (servers and tools) runs in the vendor's container images
|
|
13
|
+
through a :class:`~datadouble.runtime.ContainerRuntime`; see
|
|
14
|
+
:mod:`datadouble.runtime`.
|
|
15
|
+
|
|
16
|
+
Adapters register under the ``datadouble.engines`` entry point group; the
|
|
17
|
+
entry point names a zero-argument callable that returns an
|
|
18
|
+
:class:`EngineAdapter`.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import datetime as dt
|
|
22
|
+
import fnmatch
|
|
23
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
24
|
+
from contextlib import AbstractContextManager
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Protocol, runtime_checkable
|
|
28
|
+
|
|
29
|
+
from pydantic import BaseModel, ConfigDict, Field, JsonValue
|
|
30
|
+
|
|
31
|
+
from datadouble.catalog import Catalog, Requirement
|
|
32
|
+
from datadouble.names import ColumnRef, EngineName, GroupName, TableName
|
|
33
|
+
from datadouble.planner import Capabilities, Plan, PlannedGroup, PlannedRule
|
|
34
|
+
from datadouble.runtime import ContainerRuntime, identity
|
|
35
|
+
from datadouble.spec import AccountPrivileges, Hook, ImageFormat, TransformHook
|
|
36
|
+
from datadouble.subset import Condition, Edge, KeyReader
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class EngineError(Exception):
|
|
40
|
+
"""An engine operation that failed; the message is safe to show and log."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RequirementError(Exception):
|
|
44
|
+
"""The working image lacks requirements the sources use.
|
|
45
|
+
|
|
46
|
+
``problems`` lists each, with the source that uses it.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, problems: tuple[tuple[str, str], ...]) -> None:
|
|
50
|
+
"""Name every unmet requirement and its source."""
|
|
51
|
+
super().__init__(
|
|
52
|
+
f"the working image lacks {len(problems)} requirement(s) of the sources;"
|
|
53
|
+
" name an image that has them in sources.<name>.image, or leave them out with"
|
|
54
|
+
" sources.<name>.omit"
|
|
55
|
+
)
|
|
56
|
+
self.problems = problems
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def unmet(needed: Iterable[Requirement], available: Iterable[Requirement]) -> tuple[str, ...]:
|
|
60
|
+
"""What ``needed`` asks for that ``available`` does not provide.
|
|
61
|
+
|
|
62
|
+
An available requirement without a version provides every version.
|
|
63
|
+
"""
|
|
64
|
+
offered: dict[tuple[str, str], set[str | None]] = {}
|
|
65
|
+
for requirement in available:
|
|
66
|
+
offered.setdefault((requirement.kind, requirement.name), set()).add(requirement.version)
|
|
67
|
+
problems: list[str] = []
|
|
68
|
+
for requirement in needed:
|
|
69
|
+
versions = offered.get((requirement.kind, requirement.name))
|
|
70
|
+
if versions is None:
|
|
71
|
+
problems.append(f"{requirement.kind} {requirement.name} is not in the working image")
|
|
72
|
+
elif None not in versions and requirement.version not in versions:
|
|
73
|
+
listed = ", ".join(sorted(v for v in versions if v is not None))
|
|
74
|
+
problems.append(
|
|
75
|
+
f"{requirement.kind} {requirement.name} {requirement.version} is not in the"
|
|
76
|
+
f" working image, which has {listed}"
|
|
77
|
+
)
|
|
78
|
+
return tuple(problems)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _Model(BaseModel):
|
|
82
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class TableCount(_Model):
|
|
86
|
+
"""Rows in one table."""
|
|
87
|
+
|
|
88
|
+
table: TableName
|
|
89
|
+
rows: int
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class ExtractResult(_Model):
|
|
93
|
+
"""What ``extract`` read."""
|
|
94
|
+
|
|
95
|
+
server_version: str
|
|
96
|
+
snapshot: str
|
|
97
|
+
"""The engine's identifier for the snapshot, for the manifest."""
|
|
98
|
+
snapshots: dict[str, str] = Field(default_factory=dict[str, str])
|
|
99
|
+
"""Each database's snapshot, by database, for engines that read each
|
|
100
|
+
database under its own (``snapshot`` is then empty)."""
|
|
101
|
+
snapshot_seconds: float
|
|
102
|
+
"""How long the snapshot was held open."""
|
|
103
|
+
counts: tuple[TableCount, ...]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True, slots=True)
|
|
107
|
+
class Tooling:
|
|
108
|
+
"""Where engine software runs: the runtime, the spec's image override and server settings."""
|
|
109
|
+
|
|
110
|
+
runtime: ContainerRuntime
|
|
111
|
+
image: str | None = None
|
|
112
|
+
"""The sources' ``image``; when None the adapter picks the vendor image itself."""
|
|
113
|
+
server: Mapping[str, JsonValue] = field(default_factory=dict[str, JsonValue])
|
|
114
|
+
"""The sources' ``server`` settings, which the adapter parses."""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
type Mapper = Callable[[PlannedRule, Iterable[str]], Mapping[str, str]]
|
|
118
|
+
"""Turns a rule and the distinct values of its column into replacements."""
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass(frozen=True, slots=True)
|
|
122
|
+
class Transformation:
|
|
123
|
+
"""The anonymization ``transform`` applies to one working database."""
|
|
124
|
+
|
|
125
|
+
rules: tuple[PlannedRule, ...]
|
|
126
|
+
mapper: Mapper
|
|
127
|
+
"""Replacements for value rules (faker, hash, format-preserving)."""
|
|
128
|
+
hooks: tuple[TransformHook, ...]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class Snapshot(KeyReader, Protocol):
|
|
132
|
+
"""One consistent point-in-time view of the source."""
|
|
133
|
+
|
|
134
|
+
def extract(
|
|
135
|
+
self,
|
|
136
|
+
plan: Plan,
|
|
137
|
+
selections: Mapping[TableName, Condition],
|
|
138
|
+
directory: Path,
|
|
139
|
+
tooling: Tooling,
|
|
140
|
+
) -> ExtractResult:
|
|
141
|
+
"""Write every extracted table's definition and chosen rows under ``directory``."""
|
|
142
|
+
...
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class SourceSession(Protocol):
|
|
146
|
+
"""An open connection to the source."""
|
|
147
|
+
|
|
148
|
+
def server_version(self) -> str:
|
|
149
|
+
"""The source server's version, which picks the default working image."""
|
|
150
|
+
...
|
|
151
|
+
|
|
152
|
+
def namespaces(self) -> tuple[str, ...]:
|
|
153
|
+
"""The outermost namespaces (databases) the source reads, empty ones included.
|
|
154
|
+
|
|
155
|
+
Several sources of a spec must not share one, since one working server
|
|
156
|
+
holds them all. Engines whose namespaces exist only through their
|
|
157
|
+
tables answer :func:`outermost` of the catalog.
|
|
158
|
+
"""
|
|
159
|
+
...
|
|
160
|
+
|
|
161
|
+
def catalog(self) -> Catalog:
|
|
162
|
+
"""Introspect the tables, columns, keys and requirements."""
|
|
163
|
+
...
|
|
164
|
+
|
|
165
|
+
def snapshot(self, as_of: dt.datetime) -> AbstractContextManager[Snapshot]:
|
|
166
|
+
"""Open a consistent snapshot; every read inside it sees the same data.
|
|
167
|
+
|
|
168
|
+
``as_of`` is the plan's anchor time, bound wherever spec SQL says ``:as_of``.
|
|
169
|
+
"""
|
|
170
|
+
...
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class RestoredImage(Protocol):
|
|
174
|
+
"""A golden image restored into scratch space for verification."""
|
|
175
|
+
|
|
176
|
+
def counts(self, tables: Iterable[TableName]) -> dict[TableName, int]:
|
|
177
|
+
"""Rows in each table."""
|
|
178
|
+
...
|
|
179
|
+
|
|
180
|
+
def orphans(self, edge: Edge) -> int:
|
|
181
|
+
"""Child rows whose non-null reference has no parent row."""
|
|
182
|
+
...
|
|
183
|
+
|
|
184
|
+
def text_values(self, column: ColumnRef) -> Iterable[str]:
|
|
185
|
+
"""The distinct non-null values of a column, as text."""
|
|
186
|
+
...
|
|
187
|
+
|
|
188
|
+
def failing_rows(self, query: str) -> int:
|
|
189
|
+
"""Rows a native assertion query returns; zero means it passed."""
|
|
190
|
+
...
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class WorkingDatabases(Protocol):
|
|
194
|
+
"""Working databases and images in scratch space."""
|
|
195
|
+
|
|
196
|
+
def server_version(self) -> str:
|
|
197
|
+
"""The version of the server that builds and restores images."""
|
|
198
|
+
...
|
|
199
|
+
|
|
200
|
+
def available(self) -> tuple[Requirement, ...] | None:
|
|
201
|
+
"""The requirements the working image can provide, one entry per version.
|
|
202
|
+
|
|
203
|
+
An entry without a version provides every version of it. None means the
|
|
204
|
+
working databases need none of the source's add-ons to hold its data,
|
|
205
|
+
such as Salesforce's local copies of an org's managed packages' objects.
|
|
206
|
+
"""
|
|
207
|
+
...
|
|
208
|
+
|
|
209
|
+
def close(self) -> None:
|
|
210
|
+
"""Stop whatever the working databases kept running between calls.
|
|
211
|
+
|
|
212
|
+
A run calls it once it has finished with them, even after a failure;
|
|
213
|
+
nothing is called afterwards.
|
|
214
|
+
"""
|
|
215
|
+
...
|
|
216
|
+
|
|
217
|
+
def load(
|
|
218
|
+
self,
|
|
219
|
+
plan: Plan,
|
|
220
|
+
group: PlannedGroup,
|
|
221
|
+
extracts: tuple[Path, ...],
|
|
222
|
+
directory: Path,
|
|
223
|
+
hooks: tuple[Hook, ...],
|
|
224
|
+
) -> tuple[TableCount, ...]:
|
|
225
|
+
"""Build the group's working database in ``directory`` from the extracts.
|
|
226
|
+
|
|
227
|
+
``extracts`` holds one directory per source, in the spec's order, each
|
|
228
|
+
written by that source's snapshot; every source's databases go into
|
|
229
|
+
the one working database. There is more than one only when the
|
|
230
|
+
engine's capabilities allow several sources. Runs ``before_load``
|
|
231
|
+
hooks first, in the first source's default database, applies the
|
|
232
|
+
group's fixups, and leaves the database stopped. A standalone group's
|
|
233
|
+
database holds exactly its closure: the tables of ``group.packaged()``,
|
|
234
|
+
with the rows of :func:`group_extract` where it has them, and of the
|
|
235
|
+
group's objects, created in dependency order, no others.
|
|
236
|
+
"""
|
|
237
|
+
...
|
|
238
|
+
|
|
239
|
+
def transform(
|
|
240
|
+
self,
|
|
241
|
+
group: PlannedGroup,
|
|
242
|
+
source: Path,
|
|
243
|
+
directory: Path,
|
|
244
|
+
transformation: Transformation,
|
|
245
|
+
) -> tuple[TableCount, ...]:
|
|
246
|
+
"""Copy the loaded database to ``directory`` and anonymize it there.
|
|
247
|
+
|
|
248
|
+
Every rule for a table is applied in one native update; the column rules
|
|
249
|
+
and then the ``after_transform`` hooks run in one transaction, so an
|
|
250
|
+
interrupted transform leaves nothing half done. Returns the row counts
|
|
251
|
+
afterwards, since hooks may add or remove rows.
|
|
252
|
+
"""
|
|
253
|
+
...
|
|
254
|
+
|
|
255
|
+
def package(self, source: Path, image_format: ImageFormat, directory: Path) -> None:
|
|
256
|
+
"""Write the working database in ``source`` as an image in ``directory``."""
|
|
257
|
+
...
|
|
258
|
+
|
|
259
|
+
def restore(
|
|
260
|
+
self, image: Path, image_format: ImageFormat, directory: Path
|
|
261
|
+
) -> AbstractContextManager[RestoredImage]:
|
|
262
|
+
"""Restore an image into ``directory`` and open it for checks."""
|
|
263
|
+
...
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@dataclass(frozen=True)
|
|
267
|
+
class Account:
|
|
268
|
+
"""One of ``package.accounts``, with its password resolved; the password never prints."""
|
|
269
|
+
|
|
270
|
+
user: str
|
|
271
|
+
password: str = field(repr=False)
|
|
272
|
+
privileges: AccountPrivileges = AccountPrivileges.ALL
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@runtime_checkable
|
|
276
|
+
class Accounts(Protocol):
|
|
277
|
+
"""Working databases that can give a physical image accounts (``Capabilities.accounts``)."""
|
|
278
|
+
|
|
279
|
+
def add_accounts(self, image: Path, accounts: Sequence[Account]) -> None:
|
|
280
|
+
"""Give the physical image in ``image`` the accounts, each with its privileges.
|
|
281
|
+
|
|
282
|
+
An existing user of an account's name gets the account's password and
|
|
283
|
+
privileges. Each account must then log in over the network with its
|
|
284
|
+
password, and only with it, or this raises :class:`EngineError`. The
|
|
285
|
+
password must not appear in messages, or in plain text in any statement
|
|
286
|
+
a server could log.
|
|
287
|
+
"""
|
|
288
|
+
...
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class ServerPlan(_Model):
|
|
292
|
+
"""How to run a server on a copy of a physical image, in a container.
|
|
293
|
+
|
|
294
|
+
The copy is mounted at ``mount``, owned by ``owner``; ``command`` runs as
|
|
295
|
+
that owner, with the copy's password in the environment variable
|
|
296
|
+
``DATADOUBLE_PASSWORD``, and must leave a server listening on ``port``
|
|
297
|
+
that accepts ``user`` with that password over the network. ``ready``
|
|
298
|
+
exits successfully once it does.
|
|
299
|
+
"""
|
|
300
|
+
|
|
301
|
+
image: str
|
|
302
|
+
mount: str
|
|
303
|
+
owner: str
|
|
304
|
+
command: tuple[str, ...]
|
|
305
|
+
ready: tuple[str, ...]
|
|
306
|
+
port: int
|
|
307
|
+
database: str
|
|
308
|
+
"""The database clients connect to by default; a copy holds every database
|
|
309
|
+
its image does, and this is the source's default one."""
|
|
310
|
+
user: str
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
GROUP_EXTRACTS = "groups"
|
|
314
|
+
"""Where, in the extract stage's directory beside ``data``, standalone groups' own rows go."""
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def group_extract_path(extract: Path, group: GroupName) -> Path:
|
|
318
|
+
"""Where a standalone group's own rows from one source are extracted.
|
|
319
|
+
|
|
320
|
+
``extract`` is that source's shared extract, ``data/<source>``; the
|
|
321
|
+
group's own extract of it is ``groups/<group>/<source>``, beside ``data``,
|
|
322
|
+
so it can never be taken for a source's.
|
|
323
|
+
"""
|
|
324
|
+
return extract.parent.parent / GROUP_EXTRACTS / group / extract.name
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def group_extract(extract: Path, group: GroupName) -> Path | None:
|
|
328
|
+
"""A standalone group's own extract, if it has one.
|
|
329
|
+
|
|
330
|
+
It holds, in the shared extract's format, the rows of the tables the
|
|
331
|
+
group's closure pulls in, and of its own tables when they gained rows a
|
|
332
|
+
pulled-in table references. ``load`` takes the tables it lists from
|
|
333
|
+
here, the group's other own tables from the shared extract, and leaves
|
|
334
|
+
pulled-in tables it does not list without rows.
|
|
335
|
+
"""
|
|
336
|
+
path = group_extract_path(extract, group)
|
|
337
|
+
return path if path.is_dir() else None
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def choose_databases(
|
|
341
|
+
present: Iterable[str], wanted: Iterable[str], reserved: frozenset[str] = frozenset()
|
|
342
|
+
) -> tuple[str, ...]:
|
|
343
|
+
"""The databases a source's ``connection.databases`` names or matches, sorted.
|
|
344
|
+
|
|
345
|
+
Each entry is a name or a shell-style glob. A name must be ``present`` and a
|
|
346
|
+
glob must match at least one present database, so a typing mistake fails
|
|
347
|
+
rather than quietly reading less. ``reserved`` databases (the engine's own)
|
|
348
|
+
are never matched, and naming one fails.
|
|
349
|
+
"""
|
|
350
|
+
available = frozenset(present)
|
|
351
|
+
chosen: set[str] = set()
|
|
352
|
+
for entry in wanted:
|
|
353
|
+
if not any(character in entry for character in "*?["):
|
|
354
|
+
if entry in reserved:
|
|
355
|
+
message = f"database {entry} belongs to the server itself and cannot be read"
|
|
356
|
+
raise EngineError(message)
|
|
357
|
+
if entry not in available:
|
|
358
|
+
message = f"database {entry} is not on the source, or the user cannot see it"
|
|
359
|
+
raise EngineError(message)
|
|
360
|
+
chosen.add(entry)
|
|
361
|
+
continue
|
|
362
|
+
matched = {name for name in available - reserved if fnmatch.fnmatchcase(name, entry)}
|
|
363
|
+
if not matched:
|
|
364
|
+
message = f"the database pattern {entry} matches no database on the source"
|
|
365
|
+
raise EngineError(message)
|
|
366
|
+
chosen |= matched
|
|
367
|
+
return tuple(sorted(chosen))
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def outermost(catalog: Catalog) -> tuple[str, ...]:
|
|
371
|
+
"""The outermost namespaces of a catalog's tables, in catalog order."""
|
|
372
|
+
return tuple(dict.fromkeys(table.name.outermost for table in catalog.tables))
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def one_extract(extracts: tuple[Path, ...]) -> Path:
|
|
376
|
+
"""The one extract of an engine that reads one source per spec."""
|
|
377
|
+
if len(extracts) != 1:
|
|
378
|
+
message = f"this engine loads one source's extract, not {len(extracts)}"
|
|
379
|
+
raise EngineError(message)
|
|
380
|
+
return extracts[0]
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def check_owner(engine: "EngineAdapter") -> None:
|
|
384
|
+
"""Fail unless Datadouble runs as the user the engine's copies are served as."""
|
|
385
|
+
if identity() != engine.owner:
|
|
386
|
+
message = (
|
|
387
|
+
f"{engine.name} images are served as {engine.owner}, so their files must belong to"
|
|
388
|
+
f" that user and group; Datadouble runs as {identity()}. Run it as {engine.owner}"
|
|
389
|
+
f" (for example `docker run --user {engine.owner}` or a pod's runAsUser and"
|
|
390
|
+
" runAsGroup)"
|
|
391
|
+
)
|
|
392
|
+
raise EngineError(message)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
class EngineAdapter(Protocol):
|
|
396
|
+
"""An engine: its capabilities, the source side and the scratch side."""
|
|
397
|
+
|
|
398
|
+
@property
|
|
399
|
+
def name(self) -> EngineName:
|
|
400
|
+
"""The name specs use for this engine."""
|
|
401
|
+
...
|
|
402
|
+
|
|
403
|
+
@property
|
|
404
|
+
def owner(self) -> str:
|
|
405
|
+
"""The ``uid:gid`` a copy of its images is served as, in its vendor's image.
|
|
406
|
+
|
|
407
|
+
Datadouble runs as this user to build, fetch and replicate the engine's
|
|
408
|
+
images, so their files already belong to the server that will open
|
|
409
|
+
them (decision 86).
|
|
410
|
+
"""
|
|
411
|
+
...
|
|
412
|
+
|
|
413
|
+
def capabilities(self) -> Capabilities:
|
|
414
|
+
"""What the engine supports, for planning."""
|
|
415
|
+
...
|
|
416
|
+
|
|
417
|
+
def connect(self, connection: Mapping[str, JsonValue]) -> AbstractContextManager[SourceSession]:
|
|
418
|
+
"""Open one source, described by its ``connection`` in the spec's ``sources``."""
|
|
419
|
+
...
|
|
420
|
+
|
|
421
|
+
def working(self, scratch: Path, tooling: Tooling, source_version: str) -> WorkingDatabases:
|
|
422
|
+
"""Working databases under ``scratch``, which only holds files this run owns.
|
|
423
|
+
|
|
424
|
+
They run in ``tooling.image``, or by default the vendor's image for
|
|
425
|
+
``source_version``: the newest version of the sources the extracts
|
|
426
|
+
were read from, which all share one version line.
|
|
427
|
+
"""
|
|
428
|
+
...
|
|
429
|
+
|
|
430
|
+
def server(self, image: Path, server_image: str | None) -> ServerPlan:
|
|
431
|
+
"""How to serve a copy of the unpacked physical image ``image``.
|
|
432
|
+
|
|
433
|
+
``server_image`` overrides the container image the engine would choose.
|
|
434
|
+
"""
|
|
435
|
+
...
|
datadouble/files.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Copying directory trees, sharing blocks where the filesystem allows.
|
|
5
|
+
|
|
6
|
+
Copies run in this process rather than through ``cp``, so a copy never
|
|
7
|
+
outlives Datadouble: a run that is killed and resumed cannot have an earlier
|
|
8
|
+
attempt's copy still writing into the directory the new attempt uses. Blocks
|
|
9
|
+
are shared with the ``FICLONE`` ioctl (reflinks, on btrfs, XFS and others);
|
|
10
|
+
otherwise the kernel's copy is used.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import fcntl
|
|
14
|
+
import shutil
|
|
15
|
+
from enum import StrEnum
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
_FICLONE = 0x40049409
|
|
19
|
+
"""The Linux ioctl that makes a file share its source's blocks."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Reflink(StrEnum):
|
|
23
|
+
"""Whether a copy shares data blocks with its source."""
|
|
24
|
+
|
|
25
|
+
AUTO = "auto"
|
|
26
|
+
"""Share blocks if the filesystem can, copy them otherwise."""
|
|
27
|
+
ALWAYS = "always"
|
|
28
|
+
"""Share blocks, or fail."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _file(source: Path, destination: Path, reflink: Reflink) -> None:
|
|
32
|
+
with source.open("rb") as reading, destination.open("xb") as writing:
|
|
33
|
+
try:
|
|
34
|
+
fcntl.ioctl(writing.fileno(), _FICLONE, reading.fileno())
|
|
35
|
+
cloned = True
|
|
36
|
+
except OSError:
|
|
37
|
+
if reflink is Reflink.ALWAYS:
|
|
38
|
+
raise
|
|
39
|
+
cloned = False
|
|
40
|
+
if not cloned:
|
|
41
|
+
shutil.copyfile(source, destination)
|
|
42
|
+
shutil.copystat(source, destination)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _tree(source: Path, destination: Path, reflink: Reflink) -> None:
|
|
46
|
+
if source.is_symlink():
|
|
47
|
+
destination.symlink_to(source.readlink())
|
|
48
|
+
elif source.is_dir():
|
|
49
|
+
destination.mkdir()
|
|
50
|
+
for child in sorted(source.iterdir()):
|
|
51
|
+
_tree(child, destination / child.name, reflink)
|
|
52
|
+
shutil.copystat(source, destination)
|
|
53
|
+
else:
|
|
54
|
+
_file(source, destination, reflink)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def copy_tree(
|
|
58
|
+
source: Path,
|
|
59
|
+
destination: Path,
|
|
60
|
+
reflink: Reflink = Reflink.AUTO,
|
|
61
|
+
*,
|
|
62
|
+
contents: bool = False,
|
|
63
|
+
) -> str | None:
|
|
64
|
+
"""Copy ``source`` to the new path ``destination``; return the error, or None.
|
|
65
|
+
|
|
66
|
+
Modes, timestamps and symbolic links are kept. With ``contents``,
|
|
67
|
+
``source``'s contents go into the existing directory ``destination``
|
|
68
|
+
rather than ``source`` itself becoming it.
|
|
69
|
+
"""
|
|
70
|
+
try:
|
|
71
|
+
if contents:
|
|
72
|
+
for child in sorted(source.iterdir()):
|
|
73
|
+
_tree(child, destination / child.name, reflink)
|
|
74
|
+
else:
|
|
75
|
+
_tree(source, destination, reflink)
|
|
76
|
+
except OSError as error:
|
|
77
|
+
return f"{error.strerror or type(error).__name__}: {error.filename or source}"
|
|
78
|
+
return None
|