irsync 0.1.0__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.
- irsync/__init__.py +3 -0
- irsync/__main__.py +12 -0
- irsync/backup.py +951 -0
- irsync/cli.py +275 -0
- irsync/diff.py +434 -0
- irsync/options.py +400 -0
- irsync/paths.py +61 -0
- irsync/preflight.py +254 -0
- irsync/py.typed +0 -0
- irsync/replay.py +168 -0
- irsync/rsync_runner.py +224 -0
- irsync/snapshot.py +346 -0
- irsync/statx.py +139 -0
- irsync-0.1.0.dist-info/METADATA +267 -0
- irsync-0.1.0.dist-info/RECORD +18 -0
- irsync-0.1.0.dist-info/WHEEL +4 -0
- irsync-0.1.0.dist-info/entry_points.txt +2 -0
- irsync-0.1.0.dist-info/licenses/LICENSE +201 -0
irsync/preflight.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Pre-flight checks that an endpoint is the thing the user meant.
|
|
2
|
+
|
|
3
|
+
irsync's guards all assume a path's existence proves its identity. That
|
|
4
|
+
assumption fails for removable drives: an unmounted drive under
|
|
5
|
+
``/media/<user>`` leaves an empty directory behind, which every downstream
|
|
6
|
+
check reads as a legitimate empty tree. These functions establish identity
|
|
7
|
+
before any file is created.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, Literal
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from irsync.snapshot import Row
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class EndpointNotMounted(Exception):
|
|
22
|
+
"""An endpoint that should live on its own filesystem is not mounted.
|
|
23
|
+
|
|
24
|
+
Base class for :class:`SourceNotMounted` and
|
|
25
|
+
:class:`DestinationNotMounted`. Existing code that catches this base
|
|
26
|
+
class (``cli.main``'s refusal boundary, the ``--allow-unmounted``
|
|
27
|
+
handler in ``run_backup``) keeps working unchanged, since both
|
|
28
|
+
subclasses are also instances of this type.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SourceNotMounted(EndpointNotMounted):
|
|
33
|
+
"""The source endpoint's drive is not mounted.
|
|
34
|
+
|
|
35
|
+
``run_all_backups`` treats this the same as a missing drive: a skip,
|
|
36
|
+
not an error. ``Options.all_backups`` lists every drive the user might
|
|
37
|
+
ever attach, and on any given day most of them are absent, so a source
|
|
38
|
+
that isn't there is the normal case, not a failure.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class DestinationNotMounted(EndpointNotMounted):
|
|
43
|
+
"""The destination endpoint's drive is not mounted.
|
|
44
|
+
|
|
45
|
+
Unlike :class:`SourceNotMounted`, ``run_all_backups`` counts this as a
|
|
46
|
+
real error, not a skip: if the source drive IS mounted but its backup
|
|
47
|
+
drive is not, the run would back up nothing while looking like success.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class UnsafeDestination(Exception):
|
|
52
|
+
"""A run with no baseline would write into a destination holding data."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class RsyncUnavailable(Exception):
|
|
56
|
+
"""The rsync binary is not on PATH."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def mount_gate_root(path: Path, base_dir: Path) -> Path | None:
|
|
60
|
+
"""Return the component below ``base_dir`` that must be a mountpoint.
|
|
61
|
+
|
|
62
|
+
Configured endpoints often resolve to subdirectories of a mounted drive
|
|
63
|
+
rather than to mountpoints themselves (an endpoint's backup typically
|
|
64
|
+
lands in a folder inside a drive), so the gate is applied to the first
|
|
65
|
+
component below ``base_dir``, not to the endpoint.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
path: The resolved endpoint.
|
|
69
|
+
base_dir: The drive-letter base directory, e.g. ``/media/<user>``.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
The path that must be a mountpoint, or ``None`` when ``path`` is
|
|
73
|
+
outside ``base_dir`` or is ``base_dir`` itself.
|
|
74
|
+
"""
|
|
75
|
+
try:
|
|
76
|
+
rel = path.relative_to(base_dir)
|
|
77
|
+
except ValueError:
|
|
78
|
+
return None
|
|
79
|
+
if not rel.parts:
|
|
80
|
+
return None
|
|
81
|
+
return base_dir / rel.parts[0]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def check_mounted(
|
|
85
|
+
endpoint: Path | str,
|
|
86
|
+
base_dir: Path,
|
|
87
|
+
*,
|
|
88
|
+
gate_outside_base: bool = False,
|
|
89
|
+
role: Literal["source", "destination"] = "source",
|
|
90
|
+
) -> None:
|
|
91
|
+
"""Raise a not-mounted error unless ``endpoint``'s drive is mounted.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
endpoint: A resolved local path, or a string for an rsync remote.
|
|
95
|
+
Remotes are always exempt — there is no local mount to check.
|
|
96
|
+
base_dir: The drive-letter base directory.
|
|
97
|
+
gate_outside_base: When True, endpoints outside ``base_dir`` must
|
|
98
|
+
themselves be mountpoints (the ``--require-mount`` opt-in). However,
|
|
99
|
+
``base_dir`` itself is always exempt — it is by definition the
|
|
100
|
+
ordinary directory that contains mountpoints, never a mountpoint.
|
|
101
|
+
role: Either ``"source"`` or ``"destination"``, selecting which
|
|
102
|
+
exception subclass is raised so callers (``run_all_backups``)
|
|
103
|
+
can tell the two apart: an unmounted source is a skip, an
|
|
104
|
+
unmounted destination is a real error.
|
|
105
|
+
|
|
106
|
+
Raises:
|
|
107
|
+
SourceNotMounted: If ``role="source"`` and the gate path is not a
|
|
108
|
+
mountpoint.
|
|
109
|
+
DestinationNotMounted: If ``role="destination"`` and the gate path
|
|
110
|
+
is not a mountpoint.
|
|
111
|
+
"""
|
|
112
|
+
if not isinstance(endpoint, Path):
|
|
113
|
+
return
|
|
114
|
+
gate = mount_gate_root(endpoint, base_dir)
|
|
115
|
+
if gate is None:
|
|
116
|
+
if not gate_outside_base:
|
|
117
|
+
return
|
|
118
|
+
if endpoint == base_dir:
|
|
119
|
+
return
|
|
120
|
+
gate = endpoint
|
|
121
|
+
if not os.path.ismount(gate):
|
|
122
|
+
message = (
|
|
123
|
+
f"{gate} is not a mountpoint, so {endpoint} is not the drive it "
|
|
124
|
+
"appears to be. The drive is probably not mounted."
|
|
125
|
+
)
|
|
126
|
+
if role == "destination":
|
|
127
|
+
raise DestinationNotMounted(message)
|
|
128
|
+
raise SourceNotMounted(message)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _non_reserved_names(root: Path) -> list[str]:
|
|
132
|
+
"""List ``root``'s top-level entries, excluding irsync's own reserved files.
|
|
133
|
+
|
|
134
|
+
Shared by :func:`foreign_dest_entries` (destination side) and
|
|
135
|
+
:func:`source_root_is_empty` (source side) so the reserved-namespace
|
|
136
|
+
list — :data:`~irsync.snapshot.SNAPSHOT_FILENAME`,
|
|
137
|
+
:data:`~irsync.snapshot.LOCKFILE_NAME`,
|
|
138
|
+
:data:`~irsync.snapshot.SNAPSHOT_TEMPFILE_PREFIX` — is spelled out in
|
|
139
|
+
exactly one place rather than duplicated per caller.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
root: Directory to list.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
Sorted names of entries that are not part of irsync's namespace.
|
|
146
|
+
|
|
147
|
+
Raises:
|
|
148
|
+
FileNotFoundError: If ``root`` does not exist. Left to the caller to
|
|
149
|
+
interpret — an absent destination counts as empty, but an
|
|
150
|
+
absent source root is a different situation entirely.
|
|
151
|
+
NotADirectoryError: If ``root`` exists but is not a directory.
|
|
152
|
+
PermissionError: If ``root`` exists but cannot be listed.
|
|
153
|
+
"""
|
|
154
|
+
from irsync.snapshot import (
|
|
155
|
+
LOCKFILE_NAME,
|
|
156
|
+
SNAPSHOT_FILENAME,
|
|
157
|
+
SNAPSHOT_TEMPFILE_PREFIX,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
names = sorted(p.name for p in root.iterdir())
|
|
161
|
+
return [
|
|
162
|
+
name
|
|
163
|
+
for name in names
|
|
164
|
+
if name not in (SNAPSHOT_FILENAME, LOCKFILE_NAME)
|
|
165
|
+
and not name.startswith(SNAPSHOT_TEMPFILE_PREFIX)
|
|
166
|
+
]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def foreign_dest_entries(dest_root: Path) -> list[str]:
|
|
170
|
+
"""Return destination-root entries that are not irsync's own files.
|
|
171
|
+
|
|
172
|
+
irsync's reserved namespace is excluded so that a destination holding
|
|
173
|
+
only a snapshot from an interrupted first backup still counts as empty
|
|
174
|
+
and can be retried without an override.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
dest_root: The destination root to inspect. A destination that does
|
|
178
|
+
not exist yet counts as empty.
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
Sorted names of entries that are not part of irsync's namespace.
|
|
182
|
+
|
|
183
|
+
Raises:
|
|
184
|
+
UnsafeDestination: If the destination exists but cannot be read. An
|
|
185
|
+
unreadable destination is not a proven-empty one, so this fails
|
|
186
|
+
closed rather than reporting no entries.
|
|
187
|
+
"""
|
|
188
|
+
try:
|
|
189
|
+
return _non_reserved_names(dest_root)
|
|
190
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
191
|
+
return []
|
|
192
|
+
except PermissionError as e:
|
|
193
|
+
raise UnsafeDestination(
|
|
194
|
+
f"Cannot read destination {dest_root} to check whether it is empty: {e}"
|
|
195
|
+
) from e
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def source_root_is_empty(src_root: Path) -> bool:
|
|
199
|
+
"""Return True if ``src_root`` has no entries besides irsync's own files.
|
|
200
|
+
|
|
201
|
+
Used on the ``--no-snapshot`` path, which never calls
|
|
202
|
+
:func:`~irsync.snapshot.snapshot_tree` and so never produces rows for
|
|
203
|
+
:func:`fresh_snapshot_is_empty` to inspect. This performs the same
|
|
204
|
+
reserved-namespace filtering directly against the filesystem, so a
|
|
205
|
+
source holding only a leftover ``.irsync.lock`` still counts as empty.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
src_root: The source root to inspect.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
True if ``src_root`` does not exist, or exists with no entries
|
|
212
|
+
outside irsync's reserved namespace.
|
|
213
|
+
|
|
214
|
+
Raises:
|
|
215
|
+
PermissionError: If ``src_root`` exists but cannot be listed. An
|
|
216
|
+
unreadable source is not a proven-non-empty one, so — like
|
|
217
|
+
:func:`foreign_dest_entries`'s identical stance on the
|
|
218
|
+
destination side — this fails closed by propagating rather than
|
|
219
|
+
guessing empty or non-empty.
|
|
220
|
+
"""
|
|
221
|
+
try:
|
|
222
|
+
return not _non_reserved_names(src_root)
|
|
223
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
224
|
+
return True
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def fresh_snapshot_is_empty(rows: list[Row]) -> bool:
|
|
228
|
+
"""Return True if a fresh snapshot walk found nothing but the root.
|
|
229
|
+
|
|
230
|
+
:func:`~irsync.snapshot.snapshot_tree` always includes the root
|
|
231
|
+
directory itself as a row with ``path == "."``, so an empty source
|
|
232
|
+
yields exactly one row, never zero — a caller that checked
|
|
233
|
+
``len(rows) == 0`` would never see this fire.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
rows: Rows from a fresh :func:`~irsync.snapshot.snapshot_tree` walk.
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
True if ``rows`` contains only the root entry.
|
|
240
|
+
"""
|
|
241
|
+
return len(rows) == 1 and rows[0]["path"] == "."
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def check_rsync_available() -> None:
|
|
245
|
+
"""Raise :class:`RsyncUnavailable` if the rsync binary is not on PATH.
|
|
246
|
+
|
|
247
|
+
Raises:
|
|
248
|
+
RsyncUnavailable: If ``shutil.which`` cannot find rsync.
|
|
249
|
+
"""
|
|
250
|
+
if shutil.which("rsync") is None:
|
|
251
|
+
raise RsyncUnavailable(
|
|
252
|
+
"rsync was not found on PATH. Install it (on Debian/Ubuntu: "
|
|
253
|
+
"sudo apt install rsync) and try again."
|
|
254
|
+
)
|
irsync/py.typed
ADDED
|
File without changes
|
irsync/replay.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Apply detected moves directly on the destination tree using ``os.rename``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import errno
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path, PurePosixPath
|
|
10
|
+
|
|
11
|
+
from irsync.diff import make_parent_substituter, plan_directory_moves
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CrossDeviceMoveError(OSError):
|
|
15
|
+
"""Raised by the apply_moves pre-flight when a planned move would cross devices.
|
|
16
|
+
|
|
17
|
+
Subclass of :class:`OSError` (with ``errno = EXDEV``) so callers that already
|
|
18
|
+
handle generic OS errors keep working. The orchestrator catches this
|
|
19
|
+
explicitly to surface a clear message and avoid the perpetual-retry trap
|
|
20
|
+
where a mid-flight EXDEV would leave dest in partial state.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class ReplayResult:
|
|
26
|
+
"""Counts of operations performed during a replay pass."""
|
|
27
|
+
|
|
28
|
+
dirs_moved: int
|
|
29
|
+
files_moved: int
|
|
30
|
+
skipped: int
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _dev_of(path: Path) -> int:
|
|
34
|
+
"""Return ``st_dev`` of ``path`` or its deepest existing ancestor.
|
|
35
|
+
|
|
36
|
+
A planned move's new location may not exist yet; in that case the
|
|
37
|
+
filesystem boundary is still determined by the ancestor that does.
|
|
38
|
+
"""
|
|
39
|
+
p = path
|
|
40
|
+
while True:
|
|
41
|
+
try:
|
|
42
|
+
return int(p.stat().st_dev)
|
|
43
|
+
except FileNotFoundError:
|
|
44
|
+
parent = p.parent
|
|
45
|
+
if parent == p:
|
|
46
|
+
raise
|
|
47
|
+
p = parent
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _preflight_check_xdev(
|
|
51
|
+
dir_moves: list[tuple[str, str]],
|
|
52
|
+
file_moves: list[tuple[str, str]],
|
|
53
|
+
dest_root: Path,
|
|
54
|
+
) -> None:
|
|
55
|
+
"""Refuse upfront if any planned move would cross filesystems on dest.
|
|
56
|
+
|
|
57
|
+
``apply_moves`` runs `os.rename` which fails with EXDEV across mounts.
|
|
58
|
+
Without this pre-flight, a mid-flight EXDEV would leave moves 1..k
|
|
59
|
+
applied and k+1..N pending, the orchestrator wouldn't persist the new
|
|
60
|
+
snapshot, and the next run would re-issue the same plan, hit the same
|
|
61
|
+
EXDEV at the same point, and never make forward progress (NEW-H2).
|
|
62
|
+
"""
|
|
63
|
+
root_dev = _dev_of(dest_root)
|
|
64
|
+
checked: set[Path] = set()
|
|
65
|
+
|
|
66
|
+
def check(rel: str) -> None:
|
|
67
|
+
p = (dest_root / PurePosixPath(rel)).resolve(strict=False)
|
|
68
|
+
if p in checked:
|
|
69
|
+
return
|
|
70
|
+
checked.add(p)
|
|
71
|
+
try:
|
|
72
|
+
dev = _dev_of(p)
|
|
73
|
+
except FileNotFoundError:
|
|
74
|
+
return
|
|
75
|
+
if dev != root_dev:
|
|
76
|
+
raise CrossDeviceMoveError(
|
|
77
|
+
errno.EXDEV,
|
|
78
|
+
f"path {p} is on a different filesystem than dest_root {dest_root} "
|
|
79
|
+
f"(st_dev {dev} vs {root_dev})",
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
for old_rel, new_rel in (*dir_moves, *file_moves):
|
|
83
|
+
check(old_rel)
|
|
84
|
+
check(new_rel)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _move_no_clobber(src: Path, dst: Path) -> str:
|
|
88
|
+
"""Atomically rename ``src`` to ``dst`` if ``dst`` does not already exist.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
``"moved"`` if the rename happened, ``"skipped_missing_src"`` if the source
|
|
92
|
+
was absent (e.g. dest tree hasn't been seeded yet), ``"skipped_dst_exists"``
|
|
93
|
+
if the destination already exists.
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
OSError: With ``errno == EXDEV`` for cross-filesystem moves; other OS errors propagate.
|
|
97
|
+
"""
|
|
98
|
+
if not src.exists() and not src.is_symlink():
|
|
99
|
+
logging.debug("replay: source missing, skipping: %s", src)
|
|
100
|
+
return "skipped_missing_src"
|
|
101
|
+
try:
|
|
102
|
+
# lexists check via lstat — handles regular files, dirs, and dangling symlinks
|
|
103
|
+
dst.lstat()
|
|
104
|
+
logging.warning("replay: destination exists, skipping: %s", dst)
|
|
105
|
+
return "skipped_dst_exists"
|
|
106
|
+
except FileNotFoundError:
|
|
107
|
+
pass
|
|
108
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
os.rename(src, dst) # raises OSError(EXDEV) if cross-filesystem
|
|
110
|
+
return "moved"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def apply_moves(
|
|
114
|
+
*,
|
|
115
|
+
dir_moves: list[tuple[str, str]],
|
|
116
|
+
file_moves: list[tuple[str, str]],
|
|
117
|
+
dest_root: Path,
|
|
118
|
+
) -> ReplayResult:
|
|
119
|
+
"""Apply directory and file moves to ``dest_root`` using atomic renames.
|
|
120
|
+
|
|
121
|
+
Directory moves are scheduled via :func:`plan_directory_moves` so cycles are
|
|
122
|
+
broken with temp paths. File moves are then applied with their source path
|
|
123
|
+
rewritten through :func:`make_parent_substituter` so any prior directory
|
|
124
|
+
rename is reflected. Operation is non-clobbering: existing destinations are
|
|
125
|
+
left alone (and counted as ``skipped``).
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
dir_moves: ``(old, new)`` directory pairs from :class:`irsync.diff.Changes`.
|
|
129
|
+
file_moves: ``(old, new)`` file pairs from :class:`irsync.diff.Changes`.
|
|
130
|
+
dest_root: Root of the destination (backup) tree.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
A :class:`ReplayResult` summarizing the outcome.
|
|
134
|
+
|
|
135
|
+
Raises:
|
|
136
|
+
CrossDeviceMoveError: When the pre-flight detects that any planned
|
|
137
|
+
move would cross filesystems on the destination. Raised before
|
|
138
|
+
any rename runs so dest is left untouched.
|
|
139
|
+
OSError: With ``errno == EXDEV`` if a rename unexpectedly crosses
|
|
140
|
+
filesystems (the destination tree must be a single filesystem).
|
|
141
|
+
"""
|
|
142
|
+
_preflight_check_xdev(dir_moves, file_moves, dest_root)
|
|
143
|
+
|
|
144
|
+
dirs_moved = 0
|
|
145
|
+
files_moved = 0
|
|
146
|
+
skipped = 0
|
|
147
|
+
|
|
148
|
+
for old_rel, new_rel in plan_directory_moves(dir_moves):
|
|
149
|
+
src = dest_root / PurePosixPath(old_rel)
|
|
150
|
+
dst = dest_root / PurePosixPath(new_rel)
|
|
151
|
+
outcome = _move_no_clobber(src, dst)
|
|
152
|
+
if outcome == "moved":
|
|
153
|
+
dirs_moved += 1
|
|
154
|
+
else:
|
|
155
|
+
skipped += 1
|
|
156
|
+
|
|
157
|
+
subst = make_parent_substituter(dir_moves)
|
|
158
|
+
for old_rel, new_rel in file_moves:
|
|
159
|
+
rewritten = subst(old_rel)
|
|
160
|
+
src = dest_root / PurePosixPath(rewritten)
|
|
161
|
+
dst = dest_root / PurePosixPath(new_rel)
|
|
162
|
+
outcome = _move_no_clobber(src, dst)
|
|
163
|
+
if outcome == "moved":
|
|
164
|
+
files_moved += 1
|
|
165
|
+
else:
|
|
166
|
+
skipped += 1
|
|
167
|
+
|
|
168
|
+
return ReplayResult(dirs_moved=dirs_moved, files_moved=files_moved, skipped=skipped)
|
irsync/rsync_runner.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Run rsync on behalf of the orchestrator: build commands, execute, stream output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import datetime as dt
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import shlex
|
|
10
|
+
import signal
|
|
11
|
+
import subprocess # noqa: S404 — invoking rsync is the whole point of this module
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from irsync.snapshot import (
|
|
17
|
+
LOCKFILE_NAME,
|
|
18
|
+
SNAPSHOT_FILENAME,
|
|
19
|
+
SNAPSHOT_TEMPFILE_PREFIX,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build_rsync_command(
|
|
24
|
+
*,
|
|
25
|
+
source: str,
|
|
26
|
+
dest: str,
|
|
27
|
+
dry_run: bool,
|
|
28
|
+
exclude_dirs: list[str] | None = None,
|
|
29
|
+
no_exclude: bool = False,
|
|
30
|
+
ssh_port: int | None = None,
|
|
31
|
+
ssh_key: str | Path | None = None,
|
|
32
|
+
) -> list[str]:
|
|
33
|
+
"""Construct the rsync command line for a backup run.
|
|
34
|
+
|
|
35
|
+
Uses ``--sparse -avhP -i --stats --one-file-system --delete-before`` and
|
|
36
|
+
anchored excludes for the three reserved-namespace files (snapshot,
|
|
37
|
+
lockfile, snapshot tempfiles) so the inode snapshot is managed by
|
|
38
|
+
irsync, not by rsync.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
source: Source endpoint (local path with trailing slash, or ``host:/path/``).
|
|
42
|
+
dest: Destination endpoint.
|
|
43
|
+
dry_run: If True, append ``--dry-run``.
|
|
44
|
+
exclude_dirs: Directory names to pass with ``--exclude``.
|
|
45
|
+
no_exclude: If True, ignore ``exclude_dirs`` and transfer everything under the source root (other than the reserved-namespace files).
|
|
46
|
+
ssh_port: Optional SSH port for remote endpoints.
|
|
47
|
+
ssh_key: Optional SSH key path for remote endpoints.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
The full argv list for ``subprocess.Popen``.
|
|
51
|
+
"""
|
|
52
|
+
cmd: list[str] = [
|
|
53
|
+
"rsync",
|
|
54
|
+
"--sparse",
|
|
55
|
+
"-a",
|
|
56
|
+
"-v",
|
|
57
|
+
"-h",
|
|
58
|
+
"-P",
|
|
59
|
+
"-i",
|
|
60
|
+
"--stats",
|
|
61
|
+
"--one-file-system",
|
|
62
|
+
"--delete-before",
|
|
63
|
+
]
|
|
64
|
+
if dry_run:
|
|
65
|
+
cmd.append("--dry-run")
|
|
66
|
+
|
|
67
|
+
is_remote_source = ":" in source and not source.startswith("/")
|
|
68
|
+
is_remote_dest = ":" in dest and not dest.startswith("/")
|
|
69
|
+
if is_remote_source or is_remote_dest:
|
|
70
|
+
ssh_cmd = "ssh"
|
|
71
|
+
if ssh_port is not None:
|
|
72
|
+
ssh_cmd += f" -p {ssh_port}"
|
|
73
|
+
if ssh_key is not None:
|
|
74
|
+
ssh_cmd += f" -i {shlex.quote(os.fspath(ssh_key))}"
|
|
75
|
+
cmd.extend(["-e", ssh_cmd])
|
|
76
|
+
|
|
77
|
+
# Anchor each pattern with a leading "/" so only the file at the source
|
|
78
|
+
# root is excluded; without the anchor, rsync's pattern matches the
|
|
79
|
+
# basename at every depth and would silently skip user files that happen
|
|
80
|
+
# to share the name. These three are irsync's reserved namespace at the
|
|
81
|
+
# source root: the snapshot itself, the lockfile, and any orphan
|
|
82
|
+
# tempfiles from a killed _atomic_write_snapshot.
|
|
83
|
+
cmd.extend(["--exclude", f"/{SNAPSHOT_FILENAME}"])
|
|
84
|
+
cmd.extend(["--exclude", f"/{LOCKFILE_NAME}"])
|
|
85
|
+
cmd.extend(["--exclude", f"/{SNAPSHOT_TEMPFILE_PREFIX}*"])
|
|
86
|
+
|
|
87
|
+
if not no_exclude and exclude_dirs:
|
|
88
|
+
for d in exclude_dirs:
|
|
89
|
+
cmd.extend(["--exclude", d])
|
|
90
|
+
|
|
91
|
+
cmd.extend([source, dest])
|
|
92
|
+
return cmd
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def run_dry_run(cmd: list[str]) -> str:
|
|
96
|
+
"""Run an rsync ``--dry-run`` command and capture stdout for preview.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
cmd: The full rsync command (must already include ``--dry-run``).
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
The captured stdout text.
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
subprocess.CalledProcessError: If rsync exits non-zero.
|
|
106
|
+
"""
|
|
107
|
+
logging.info("Dry run: %r", cmd)
|
|
108
|
+
result = subprocess.run( # noqa: S603 — cmd is built internally, not from user shell
|
|
109
|
+
cmd,
|
|
110
|
+
check=True,
|
|
111
|
+
text=True,
|
|
112
|
+
stdout=subprocess.PIPE,
|
|
113
|
+
)
|
|
114
|
+
return result.stdout
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def run_real_sync(cmd: list[str]) -> int:
|
|
118
|
+
"""Run a real (non-dry-run) rsync command, streaming stderr live.
|
|
119
|
+
|
|
120
|
+
The child runs in its own session (``start_new_session=True``) so a
|
|
121
|
+
parent SIGKILL doesn't leave it as an orphan that races subsequent
|
|
122
|
+
irsync runs against the same destination (7th-NEW-H2). On any
|
|
123
|
+
exception leaving this function — KeyboardInterrupt, the parent's
|
|
124
|
+
own SIGTERM after Python's default handler, etc. — the child is
|
|
125
|
+
terminated before the exception propagates, so it can't continue
|
|
126
|
+
writing to dest after we've aborted.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
cmd: The full rsync command without ``--dry-run``.
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
The rsync exit code (0 on success).
|
|
133
|
+
"""
|
|
134
|
+
logging.info("Executing: %r", cmd)
|
|
135
|
+
started = dt.datetime.now()
|
|
136
|
+
proc = subprocess.Popen( # noqa: S603
|
|
137
|
+
cmd,
|
|
138
|
+
stdout=None,
|
|
139
|
+
stderr=subprocess.PIPE,
|
|
140
|
+
text=True,
|
|
141
|
+
start_new_session=True,
|
|
142
|
+
)
|
|
143
|
+
stderr_buf: list[str] = []
|
|
144
|
+
if proc.stderr is None:
|
|
145
|
+
raise RuntimeError("rsync subprocess did not expose stderr")
|
|
146
|
+
|
|
147
|
+
# 8th-NEW-H3: Python's default SIGTERM handler kills the process
|
|
148
|
+
# without raising, so the BaseException cleanup below would never
|
|
149
|
+
# fire on cron-timeout / systemctl stop and rsync would orphan
|
|
150
|
+
# exactly as it did before 7th-NEW-H2. Install a handler that
|
|
151
|
+
# raises KeyboardInterrupt — this piggybacks on the existing
|
|
152
|
+
# cleanup path. signal.signal must be called from the main thread,
|
|
153
|
+
# so skip on non-main threads (no test runs there) rather than
|
|
154
|
+
# crash. Always restore the previous handler on exit.
|
|
155
|
+
def _sigterm_to_keyboardinterrupt(_signum: int, _frame: object) -> None:
|
|
156
|
+
raise KeyboardInterrupt("rsync run interrupted by SIGTERM")
|
|
157
|
+
|
|
158
|
+
on_main_thread = threading.current_thread() is threading.main_thread()
|
|
159
|
+
previous_sigterm: object = None
|
|
160
|
+
sigterm_installed = False
|
|
161
|
+
if on_main_thread:
|
|
162
|
+
try:
|
|
163
|
+
previous_sigterm = signal.signal(
|
|
164
|
+
signal.SIGTERM, _sigterm_to_keyboardinterrupt
|
|
165
|
+
)
|
|
166
|
+
sigterm_installed = True
|
|
167
|
+
except (ValueError, OSError):
|
|
168
|
+
# Off-main-thread / restricted env: leave the default in place.
|
|
169
|
+
sigterm_installed = False
|
|
170
|
+
|
|
171
|
+
try:
|
|
172
|
+
try:
|
|
173
|
+
for line in proc.stderr:
|
|
174
|
+
sys.stderr.write(line)
|
|
175
|
+
sys.stderr.flush()
|
|
176
|
+
stderr_buf.append(line)
|
|
177
|
+
ret = proc.wait()
|
|
178
|
+
except BaseException:
|
|
179
|
+
# KeyboardInterrupt (incl. our SIGTERM-as-KI), SystemExit, or
|
|
180
|
+
# any unexpected exception. We MUST stop rsync before
|
|
181
|
+
# propagating, or it will keep updating dest in the
|
|
182
|
+
# background and a subsequent run will race it. Signal the
|
|
183
|
+
# whole process group (8th-NEW-H2): with start_new_session
|
|
184
|
+
# the rsync child leads its own pgrp, and rsync may have
|
|
185
|
+
# forked ssh for remote endpoints. plain proc.terminate()
|
|
186
|
+
# targets only the leader; we need killpg so the ssh child
|
|
187
|
+
# dies with rsync. Best-effort: ProcessLookupError on
|
|
188
|
+
# already-exited child is fine.
|
|
189
|
+
with contextlib.suppress(Exception):
|
|
190
|
+
try:
|
|
191
|
+
pgid = os.getpgid(proc.pid)
|
|
192
|
+
except (ProcessLookupError, OSError):
|
|
193
|
+
pgid = None
|
|
194
|
+
if pgid is not None:
|
|
195
|
+
with contextlib.suppress(ProcessLookupError, OSError):
|
|
196
|
+
os.killpg(pgid, signal.SIGTERM)
|
|
197
|
+
try:
|
|
198
|
+
proc.wait(timeout=5)
|
|
199
|
+
except subprocess.TimeoutExpired:
|
|
200
|
+
if pgid is not None:
|
|
201
|
+
with contextlib.suppress(ProcessLookupError, OSError):
|
|
202
|
+
os.killpg(pgid, signal.SIGKILL)
|
|
203
|
+
with contextlib.suppress(Exception):
|
|
204
|
+
proc.wait(timeout=2)
|
|
205
|
+
raise
|
|
206
|
+
finally:
|
|
207
|
+
if proc.stderr is not None:
|
|
208
|
+
with contextlib.suppress(Exception):
|
|
209
|
+
proc.stderr.close()
|
|
210
|
+
finally:
|
|
211
|
+
if sigterm_installed:
|
|
212
|
+
with contextlib.suppress(Exception):
|
|
213
|
+
signal.signal(signal.SIGTERM, previous_sigterm) # type: ignore[arg-type]
|
|
214
|
+
elapsed = dt.datetime.now() - started
|
|
215
|
+
if ret != 0:
|
|
216
|
+
logging.error(
|
|
217
|
+
"rsync failed (code %s) after %s. stderr:\n%s",
|
|
218
|
+
ret,
|
|
219
|
+
elapsed,
|
|
220
|
+
"".join(stderr_buf),
|
|
221
|
+
)
|
|
222
|
+
else:
|
|
223
|
+
logging.info("rsync completed successfully in %s.", elapsed)
|
|
224
|
+
return ret
|