datadouble-btrfs 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,35 @@
1
+ Metadata-Version: 2.5
2
+ Name: datadouble-btrfs
3
+ Version: 0.0.3
4
+ Summary: btrfs 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 :: System :: Filesystems
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.13
18
+ Requires-Dist: datadouble
19
+ Description-Content-Type: text/markdown
20
+
21
+ # datadouble-btrfs
22
+
23
+ The btrfs replicate adapter for [Datadouble](https://datadouble.tightlinesoftware.com/):
24
+ each copy is a writable snapshot of the staged image, made in moments however
25
+ large the image is.
26
+
27
+ ```yaml
28
+ replicate:
29
+ using:
30
+ btrfs:
31
+ path: /srv/clones # a directory on the same btrfs filesystem as staging
32
+ ```
33
+
34
+ Staging must be on btrfs too. The first copy of a generation turns its staged
35
+ image into a subvolume; later copies snapshot it. Uses the `btrfs` command.
@@ -0,0 +1,15 @@
1
+ # datadouble-btrfs
2
+
3
+ The btrfs replicate adapter for [Datadouble](https://datadouble.tightlinesoftware.com/):
4
+ each copy is a writable snapshot of the staged image, made in moments however
5
+ large the image is.
6
+
7
+ ```yaml
8
+ replicate:
9
+ using:
10
+ btrfs:
11
+ path: /srv/clones # a directory on the same btrfs filesystem as staging
12
+ ```
13
+
14
+ Staging must be on btrfs too. The first copy of a generation turns its staged
15
+ image into a subvolume; later copies snapshot it. Uses the `btrfs` command.
@@ -0,0 +1,38 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ [project]
5
+ name = "datadouble-btrfs"
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 = "btrfs 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 :: System :: Filesystems",
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
+ btrfs = "datadouble_btrfs:btrfs_replicator"
32
+
33
+ [build-system]
34
+ requires = ["hatchling>=1.33.0"]
35
+ build-backend = "hatchling.build"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/datadouble_btrfs"]
@@ -0,0 +1,121 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The btrfs replicate adapter for Datadouble.
5
+
6
+ Spec settings::
7
+
8
+ replicate:
9
+ using:
10
+ btrfs:
11
+ path: /srv/clones # on the same btrfs filesystem as staging
12
+
13
+ Each copy is its own subvolume, filled with reflinked copies of the staged
14
+ image's files: the copy shares every data block with staging until it is
15
+ written to, so it is made in moments and costs no space up front, and
16
+ consumers can snapshot or delete it like any subvolume. Uses the ``btrfs``
17
+ command; staging and ``path`` must be on one btrfs filesystem. A group's
18
+ files, when the spec has them, get their own subvolume, ``<copy id>-files``.
19
+ """
20
+
21
+ from collections.abc import Mapping
22
+ from pathlib import Path
23
+
24
+ from pydantic import BaseModel, ConfigDict, JsonValue
25
+
26
+ from datadouble.files import Reflink, copy_tree
27
+ from datadouble.images import ImageSummary
28
+ from datadouble.programs import locate, run_program
29
+ from datadouble.replicate import (
30
+ ClaimState,
31
+ Copy,
32
+ CopyKind,
33
+ Made,
34
+ ReplicateError,
35
+ Replicator,
36
+ StagedImage,
37
+ copy_names,
38
+ files_id,
39
+ )
40
+ from datadouble.settings import parse_settings
41
+
42
+
43
+ class BtrfsSettings(BaseModel):
44
+ """Settings for the ``btrfs`` replicate adapter."""
45
+
46
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
47
+
48
+ path: Path
49
+
50
+
51
+ def _run(arguments: list[str], action: str) -> None:
52
+ done = run_program(arguments[0], arguments[1:])
53
+ if done.status != 0:
54
+ message = f"{action} failed: {done.last_error()}"
55
+ raise ReplicateError(message)
56
+
57
+
58
+ def btrfs_binary() -> str:
59
+ """``DATADOUBLE_BTRFS``, or ``btrfs`` on ``PATH``."""
60
+ found = locate("btrfs", "DATADOUBLE_BTRFS")
61
+ if not found:
62
+ message = "the btrfs command was not found; install btrfs-progs"
63
+ raise ReplicateError(message)
64
+ return found
65
+
66
+
67
+ class BtrfsReplicator:
68
+ """Volume copies as subvolumes sharing blocks with staging."""
69
+
70
+ def __init__(self, settings: BtrfsSettings) -> None:
71
+ """Make subvolumes under ``settings.path``."""
72
+ self.root = settings.path
73
+
74
+ @property
75
+ def kind(self) -> CopyKind:
76
+ """Volumes."""
77
+ return CopyKind.VOLUME
78
+
79
+ def create(
80
+ self, copy_id: str, image: Path, summary: ImageSummary, files: StagedImage | None = None
81
+ ) -> Made:
82
+ """Create a subvolume, reflink the image into it, then rename it into place.
83
+
84
+ The group's files, if given, get a subvolume of their own, ``<copy id>-files``.
85
+ """
86
+ self.root.mkdir(parents=True, exist_ok=True)
87
+ location: dict[str, JsonValue] = {"path": str(self._copy(copy_id, image, summary))}
88
+ if files is None:
89
+ return Made(location=location)
90
+ copied = self._copy(files_id(copy_id), files.path, files.summary)
91
+ return Made(location=location, files={"path": str(copied)})
92
+
93
+ def _copy(self, copy_id: str, image: Path, summary: ImageSummary) -> Path:
94
+ partial = self.root / f".{copy_id}.partial"
95
+ btrfs = btrfs_binary()
96
+ _run([btrfs, "subvolume", "create", str(partial)], "creating the subvolume")
97
+ problem = copy_tree(image, partial, Reflink.ALWAYS, contents=True)
98
+ if problem:
99
+ run_program(btrfs, ["subvolume", "delete", str(partial)])
100
+ message = f"copying {summary.identity.generation} failed: {problem}"
101
+ raise ReplicateError(message)
102
+ final = self.root / copy_id
103
+ partial.rename(final)
104
+ return final
105
+
106
+ def destroy(self, copy: Copy) -> None:
107
+ """Delete the copy's subvolumes, complete or not."""
108
+ btrfs = btrfs_binary()
109
+ for name in copy_names(copy):
110
+ for path in (self.root / name, self.root / f".{name}.partial"):
111
+ if path.exists():
112
+ _run([btrfs, "subvolume", "delete", str(path)], f"deleting {path.name}")
113
+
114
+ def claim_state(self, _copy: Copy, /) -> ClaimState:
115
+ """Claims are recorded by ``claim``."""
116
+ return ClaimState.UNKNOWN
117
+
118
+
119
+ def btrfs_replicator(settings: Mapping[str, JsonValue]) -> Replicator:
120
+ """The entry point named in ``datadouble.replicators``."""
121
+ return BtrfsReplicator(parse_settings(BtrfsSettings, settings, "btrfs replicate"))
File without changes
@@ -0,0 +1,147 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The btrfs replicate adapter: against a stand-in btrfs, and a real one when available."""
5
+
6
+ import datetime as dt
7
+ import os
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ import datadouble_btrfs
13
+ from datadouble.files import Reflink, copy_tree
14
+ from datadouble.images import ImageIdentity, ImageSummary, Verification
15
+ from datadouble.names import EngineName, Generation, GroupName, SpecName
16
+ from datadouble.registry import installed
17
+ from datadouble.replicate import ClaimState, Copy, CopyKind, CopyState, ReplicateError, StagedImage
18
+ from datadouble.spec import ReplicateMode, Strict
19
+ from datadouble_btrfs import BtrfsReplicator, BtrfsSettings, btrfs_binary, btrfs_replicator
20
+
21
+ FAKE_BTRFS = """#!/bin/sh
22
+ # Stands in for btrfs: subvolumes are plain directories.
23
+ case "$1 $2" in
24
+ "subvolume create") mkdir "$3" ;;
25
+ "subvolume delete") rm -rf "$3" ;;
26
+ *) echo "unexpected: $*" >&2; exit 2 ;;
27
+ esac
28
+ """
29
+
30
+ SUMMARY = ImageSummary(
31
+ identity=ImageIdentity(
32
+ spec=SpecName("shop"),
33
+ group=GroupName("all"),
34
+ engine=EngineName("postgres"),
35
+ engine_version="18",
36
+ generation=Generation("0193a7c21b4e9f30"),
37
+ ),
38
+ built_at=dt.datetime(2026, 11, 1, tzinfo=dt.UTC),
39
+ archives=(),
40
+ manifest_sha256="0" * 64,
41
+ verification=Verification(passed=True, checks=1, failed=0),
42
+ strict=Strict(),
43
+ )
44
+
45
+
46
+ def record(copy_id: str) -> Copy:
47
+ return Copy(
48
+ id=copy_id,
49
+ prefix="shop/all/postgres-18",
50
+ generation=Generation("0193a7c21b4e9f30"),
51
+ kind=CopyKind.VOLUME,
52
+ mode=ReplicateMode.POOL,
53
+ adapter="btrfs",
54
+ state=CopyState.READY,
55
+ created_at=SUMMARY.built_at,
56
+ built_at=SUMMARY.built_at,
57
+ )
58
+
59
+
60
+ def staged_image(root: Path) -> Path:
61
+ image = root / "image"
62
+ (image / "pgdata").mkdir(parents=True)
63
+ (image / "pgdata" / "PG_VERSION").write_text("18\n", encoding="utf-8")
64
+ return image
65
+
66
+
67
+ @pytest.fixture
68
+ def fake(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
69
+ script = tmp_path / "bin" / "btrfs"
70
+ script.parent.mkdir()
71
+ script.write_text(FAKE_BTRFS, encoding="utf-8")
72
+ script.chmod(0o755)
73
+ monkeypatch.setenv("DATADOUBLE_BTRFS", str(script))
74
+
75
+ # Most test filesystems cannot reflink; copy without sharing blocks instead.
76
+ def plain(source: Path, destination: Path, _reflink: Reflink, *, contents: bool) -> str | None:
77
+ return copy_tree(source, destination, contents=contents)
78
+
79
+ monkeypatch.setattr(datadouble_btrfs, "copy_tree", plain)
80
+ return script
81
+
82
+
83
+ @pytest.mark.usefixtures("fake")
84
+ def test_copies_are_subvolumes(tmp_path: Path) -> None:
85
+ replicator = btrfs_replicator({"path": str(tmp_path / "clones")})
86
+ assert replicator.kind is CopyKind.VOLUME
87
+ image = staged_image(tmp_path)
88
+ made = replicator.create("abc", image, SUMMARY)
89
+ assert made.location == {"path": str(tmp_path / "clones" / "abc")}
90
+ assert (tmp_path / "clones" / "abc" / "pgdata" / "PG_VERSION").is_file()
91
+ replicator.destroy(record("abc"))
92
+ assert not (tmp_path / "clones" / "abc").exists()
93
+ replicator.destroy(record("gone"))
94
+ assert replicator.claim_state(record("abc")) is ClaimState.UNKNOWN
95
+
96
+
97
+ def test_failures(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fake: Path) -> None:
98
+ replicator = BtrfsReplicator(BtrfsSettings(path=tmp_path / "clones"))
99
+ (tmp_path / "clones" / ".abc.partial").mkdir(parents=True)
100
+ with pytest.raises(ReplicateError, match="creating the subvolume failed: mkdir"):
101
+ replicator.create("abc", staged_image(tmp_path), SUMMARY)
102
+ (tmp_path / "clones" / ".abc.partial").rmdir()
103
+ with pytest.raises(ReplicateError, match="copying 0193a7c21b4e9f30 failed"):
104
+ replicator.create("abc", tmp_path / "no-image", SUMMARY)
105
+ assert not (tmp_path / "clones" / ".abc.partial").exists()
106
+ (tmp_path / "clones" / ".abc.partial").mkdir()
107
+ fake.write_text("#!/bin/sh\nexit 3\n", encoding="utf-8")
108
+ with pytest.raises(ReplicateError, match=r"deleting \.abc\.partial failed: status 3"):
109
+ replicator.destroy(record("abc"))
110
+ monkeypatch.delenv("DATADOUBLE_BTRFS")
111
+ monkeypatch.setenv("PATH", str(tmp_path / "nowhere"))
112
+ with pytest.raises(ReplicateError, match="btrfs command was not found"):
113
+ btrfs_binary()
114
+ assert "btrfs" in installed().replicators
115
+
116
+
117
+ @pytest.mark.btrfs
118
+ def test_on_btrfs() -> None:
119
+ root = os.environ.get("DATADOUBLE_TEST_BTRFS")
120
+ if not root:
121
+ pytest.skip("no btrfs filesystem; run with the btrfs Compose profile")
122
+ base = Path(root)
123
+ image = staged_image(base / "staging")
124
+ replicator = BtrfsReplicator(BtrfsSettings(path=base / "clones"))
125
+ replicator.create("real", image, SUMMARY)
126
+ # The root directory of a btrfs subvolume always has inode 256.
127
+ assert (base / "clones" / "real").stat().st_ino == 256
128
+ assert (base / "clones" / "real" / "pgdata" / "PG_VERSION").read_text(
129
+ encoding="utf-8"
130
+ ) == "18\n"
131
+ replicator.destroy(record("real"))
132
+ assert not (base / "clones" / "real").exists()
133
+
134
+
135
+ @pytest.mark.usefixtures("fake")
136
+ def test_files_get_a_subvolume_of_their_own(tmp_path: Path) -> None:
137
+ replicator = btrfs_replicator({"path": str(tmp_path / "clones")})
138
+ made = replicator.create(
139
+ "abc",
140
+ staged_image(tmp_path),
141
+ SUMMARY,
142
+ StagedImage(staged_image(tmp_path / "files"), SUMMARY),
143
+ )
144
+ assert made.files == {"path": str(tmp_path / "clones" / "abc-files")}
145
+ assert (tmp_path / "clones" / "abc-files" / "pgdata" / "PG_VERSION").is_file()
146
+ replicator.destroy(record("abc").model_copy(update={"files": made.files}))
147
+ assert not (tmp_path / "clones" / "abc-files").exists()