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/backup.py ADDED
@@ -0,0 +1,951 @@
1
+ """End-to-end orchestrator: snapshot, diff, optionally replay-and-rsync, persist."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import fcntl
8
+ import logging
9
+ import os
10
+ import shutil
11
+ import subprocess # noqa: S404 — needed for paging via less
12
+ import tempfile
13
+ from collections.abc import Iterator
14
+ from pathlib import Path
15
+
16
+ from irsync.diff import Changes, compute_changes
17
+ from irsync.options import Endpoints, Options, resolve_endpoints, resolve_source
18
+ from irsync.paths import with_trailing_slash
19
+ from irsync.preflight import (
20
+ DestinationNotMounted,
21
+ EndpointNotMounted,
22
+ UnsafeDestination,
23
+ check_mounted,
24
+ check_rsync_available,
25
+ foreign_dest_entries,
26
+ fresh_snapshot_is_empty,
27
+ source_root_is_empty,
28
+ )
29
+ from irsync.replay import CrossDeviceMoveError, apply_moves
30
+ from irsync.rsync_runner import build_rsync_command, run_dry_run, run_real_sync
31
+ from irsync.snapshot import (
32
+ LOCKFILE_NAME,
33
+ SNAPSHOT_FILENAME,
34
+ SNAPSHOT_TEMPFILE_PREFIX,
35
+ Row,
36
+ SnapshotMismatch,
37
+ read_snapshot,
38
+ snapshot_tree,
39
+ write_snapshot,
40
+ )
41
+
42
+ # Refuse to proceed when the diff says this fraction of the previously-recorded
43
+ # tree is gone — almost always a swapped-args / wrong-snapshot accident.
44
+ CATASTROPHIC_DELETE_RATIO: float = 0.5
45
+
46
+ # Process exit codes. Named so the non-obvious values aren't bare literals
47
+ # scattered across the orchestrator's early returns.
48
+ EXIT_REFUSED: int = 2 # bad invocation / refused for safety; nothing was written
49
+ EXIT_LOCK_HELD: int = 75 # EX_TEMPFAIL — another run holds the lock, try again later
50
+ EXIT_ABORTED: int = 130 # 128 + SIGINT, the shell convention for "user aborted"
51
+
52
+
53
+ @contextlib.contextmanager
54
+ def _source_lock(src_root: Path) -> Iterator[None]:
55
+ """Hold an exclusive flock on ``<src_root>/.irsync.lock`` for the duration.
56
+
57
+ Two concurrent irsync runs against the same source would otherwise race
58
+ on snapshot read/write and apply_moves. This is non-blocking: if the lock
59
+ is held, raise BlockingIOError immediately so the caller can exit cleanly
60
+ rather than wait indefinitely.
61
+ """
62
+ src_root.mkdir(parents=True, exist_ok=True)
63
+ lock_path = src_root / LOCKFILE_NAME
64
+ f = lock_path.open("w")
65
+ try:
66
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
67
+ except BlockingIOError:
68
+ f.close()
69
+ raise
70
+ try:
71
+ yield
72
+ finally:
73
+ try:
74
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
75
+ except OSError:
76
+ pass
77
+ f.close()
78
+
79
+
80
+ def _log_lock_conflict(root: Path) -> int:
81
+ """Log the "lock already held" refusal for ``root`` and return the exit code."""
82
+ logging.error(
83
+ "Another irsync run is already in progress against %s "
84
+ "(lock %s is held). Refusing to race.",
85
+ root,
86
+ root / LOCKFILE_NAME,
87
+ )
88
+ return EXIT_LOCK_HELD
89
+
90
+
91
+ def _log_source_permission_error(root: Path, e: PermissionError) -> int:
92
+ """Log the "can't write to the source root" refusal and return the exit code.
93
+
94
+ Scoped to callers that know the failure genuinely happened while writing
95
+ to ``root`` itself (lock acquisition, or a snapshot write with no
96
+ destination in play) — never wrap a broader operation in
97
+ ``except PermissionError`` and blame the source root for whatever failed
98
+ inside it. A blanket handler around the orchestrator would misattribute
99
+ downstream (e.g. destination) permission errors to the wrong disk.
100
+ """
101
+ logging.error(
102
+ "Cannot write to the source root %s (%s). irsync needs to create "
103
+ "its lockfile and snapshot there.",
104
+ root,
105
+ e,
106
+ )
107
+ return EXIT_REFUSED
108
+
109
+
110
+ def _atomic_write_snapshot(rows: list[Row], source_root: Path, target: Path) -> None:
111
+ """Write rows + provenance header to ``target`` atomically (tempfile + replace).
112
+
113
+ The provenance header records ``source_root`` so a later run that finds a
114
+ snapshot from a different tree at the source root can refuse to use it.
115
+ """
116
+ target.parent.mkdir(parents=True, exist_ok=True)
117
+ fd, tmpname = tempfile.mkstemp(prefix=SNAPSHOT_TEMPFILE_PREFIX, dir=target.parent)
118
+ os.close(fd)
119
+ tmp_path = Path(tmpname)
120
+ try:
121
+ write_snapshot(rows, source_root=source_root, out_file=tmp_path)
122
+ # 10th-F3: fsync the tempfile before replacing the live snapshot.
123
+ # os.replace is atomic at the directory-entry level, but the
124
+ # tempfile's data blocks may still be sitting in the kernel's
125
+ # page cache. A power loss between rename and flush leaves the
126
+ # new dirent pointing at empty/partial content; the next run's
127
+ # read_snapshot then chokes on malformed JSONL with no recovery.
128
+ with open(tmp_path, "rb") as f:
129
+ os.fsync(f.fileno())
130
+ os.replace(tmp_path, target)
131
+ except Exception:
132
+ tmp_path.unlink(missing_ok=True)
133
+ raise
134
+
135
+
136
+ def _persist_snapshots(rows: list[Row], src_root: Path, dest_root: Path | None) -> None:
137
+ """Write the fresh snapshot to (if local) the dest root, then the source root.
138
+
139
+ Order matters (7th-M1): a failure / SIGKILL between the two writes used
140
+ to leave src updated and dest stale. On a DR restore (source disk dies,
141
+ user copies dest content + dest snapshot back), that asymmetry produced
142
+ a baseline that didn't match the restored content. By writing dest first,
143
+ a dest failure aborts the function before src is touched, leaving the
144
+ src baseline at its OLD value so the next run still reconciles cleanly.
145
+ """
146
+ if dest_root is not None:
147
+ _atomic_write_snapshot(rows, src_root, dest_root / SNAPSHOT_FILENAME)
148
+ _atomic_write_snapshot(rows, src_root, src_root / SNAPSHOT_FILENAME)
149
+
150
+
151
+ def _format_preview(changes: Changes) -> str:
152
+ """Build the full pre-confirmation preview text — every move, deletion, creation.
153
+
154
+ The deletion list is the safety-critical part: rsync's ``--delete-before`` will
155
+ remove these from the backup tree, so the user must see the actual paths (not
156
+ just a count) before saying yes.
157
+ """
158
+ lines: list[str] = []
159
+ lines.append(f"=== Directory moves ({len(changes.dir_moves)}) ===")
160
+ for o, n in changes.dir_moves:
161
+ lines.append(f" {o} -> {n}")
162
+ lines.append(f"=== File moves ({len(changes.file_moves)}) ===")
163
+ for o, n in changes.file_moves:
164
+ lines.append(f" {o} -> {n}")
165
+ lines.append(
166
+ f"=== Modified in place, will be re-transferred ({len(changes.modified)}) ==="
167
+ )
168
+ for p in changes.modified:
169
+ lines.append(f" ~ {p}")
170
+ lines.append(
171
+ f"=== Created on source, will be transferred ({len(changes.created)}) ==="
172
+ )
173
+ for p in changes.created:
174
+ lines.append(f" + {p}")
175
+ lines.append(
176
+ f"=== Deleted on source, will be REMOVED FROM BACKUP ({len(changes.deleted)}) ==="
177
+ )
178
+ for p in changes.deleted:
179
+ lines.append(f" - {p}")
180
+ return "\n".join(lines) + "\n"
181
+
182
+
183
+ def _format_size(total_bytes: int) -> str:
184
+ """Render a byte count as a human-scaled ``value unit`` string.
185
+
186
+ A fixed GiB unit reads as "0.0 GiB" for any source under half a
187
+ gibibyte, which is accurate but useless for judging scale on a small
188
+ tree. Scaling to the largest unit under which the value is at least 1
189
+ (falling back to bytes) keeps the summary meaningful across both a
190
+ handful of config files and a multi-terabyte archive, with no added
191
+ dependency.
192
+
193
+ The threshold check compares ``round(value, 1)`` rather than the raw
194
+ value: a raw value of e.g. 1023.999... KiB is < 1024 and would render
195
+ as "1024.0 KiB" once formatted to one decimal place, which reads like
196
+ it should have rolled over to the next unit. Rounding before comparing
197
+ makes the displayed number and the unit choice agree at every boundary.
198
+ """
199
+ value = float(total_bytes)
200
+ for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
201
+ if round(value, 1) < 1024 or unit == "TiB":
202
+ if unit == "B":
203
+ return f"{int(value)} {unit}"
204
+ return f"{value:.1f} {unit}"
205
+ value /= 1024
206
+ return f"{value:.1f} TiB" # unreachable, satisfies mypy's no-implicit-return
207
+
208
+
209
+ def _format_first_run_preview(
210
+ rows: list[Row],
211
+ src_root: Path,
212
+ dest_root: Path | None,
213
+ foreign_count: int,
214
+ ) -> str:
215
+ """Summarize a backup that has no baseline to diff against.
216
+
217
+ With no prior snapshot there is no move/delete plan to show, but the run
218
+ is the most consequential one: it transfers the whole source and removes
219
+ anything at the destination that is not on it. Report the scale of both
220
+ so the confirmation prompt is not answered blind.
221
+ """
222
+ total_bytes = sum(r["size"] for r in rows if r["type"] == "f")
223
+ size_str = _format_size(total_bytes)
224
+ # A remote destination is never scanned for foreign_dest_entries (Task 3
225
+ # only counts a local dest's existing entries), so foreign_count is
226
+ # always 0 here — not because the destination is empty, but because it
227
+ # was never checked. Say so instead of presenting an unchecked 0 as fact.
228
+ if dest_root is None:
229
+ dest_desc = "n/a (remote)"
230
+ existing_desc = "not checked (remote)"
231
+ else:
232
+ dest_desc = str(dest_root)
233
+ existing_desc = f"{foreign_count} existing entries"
234
+ lines = [
235
+ "=== FIRST BACKUP — no prior snapshot ===",
236
+ f"Source: {src_root} {len(rows):,} entries, {size_str}",
237
+ f"Destination: {dest_desc} {existing_desc}",
238
+ "rsync will transfer the source in full and DELETE anything at the",
239
+ "destination that is not on the source.",
240
+ ]
241
+ return "\n".join(lines) + "\n"
242
+
243
+
244
+ def _dry_run_preview(cmd: list[str]) -> tuple[str | None, int]:
245
+ """Run the preview dry-run, converting an rsync failure into an exit code.
246
+
247
+ ``run_dry_run`` uses ``check=True``, so a non-zero rsync exit raises
248
+ ``CalledProcessError``. Both preview call sites used to let that escape
249
+ all the way out of :func:`irsync.cli.main`, so a routine rsync failure
250
+ (23 partial transfer, 24 vanished source files, 255 ssh error) surfaced
251
+ as a Python traceback with the exit code flattened to 1.
252
+
253
+ Returns:
254
+ ``(output, 0)`` when rsync succeeded, or ``(None, exit_code)`` when it
255
+ failed. A process killed by a signal reports a negative returncode,
256
+ which is not a usable exit status, so those map to
257
+ :data:`EXIT_REFUSED`.
258
+ """
259
+ try:
260
+ return run_dry_run(cmd), 0
261
+ except subprocess.CalledProcessError as e:
262
+ logging.error(
263
+ "rsync dry-run failed (exit %s); refusing to continue. Command: %r",
264
+ e.returncode,
265
+ cmd,
266
+ )
267
+ rc = e.returncode if e.returncode and e.returncode > 0 else EXIT_REFUSED
268
+ return None, rc
269
+
270
+
271
+ def _show_preview(changes: Changes, *, interactive: bool) -> None:
272
+ """Render the preview, paging through ``less`` if interactive."""
273
+ text = _format_preview(changes)
274
+ if interactive:
275
+ _page_output(text)
276
+ else:
277
+ # Non-interactive (--yes): still log it so the run is auditable, but
278
+ # don't bother with the pager.
279
+ print(text)
280
+
281
+
282
+ def _confirm_or_abort(args: argparse.Namespace) -> bool:
283
+ """Return True if the user confirmed (or --yes was passed)."""
284
+ if args.yes:
285
+ return True
286
+ answer = input("Proceed with replay + rsync? [yes/N]: ")
287
+ return answer.casefold() == "yes"
288
+
289
+
290
+ def run_backup(
291
+ *,
292
+ source_arg: str,
293
+ destination_arg: str | None,
294
+ options: Options,
295
+ args: argparse.Namespace,
296
+ ) -> int:
297
+ """Run a single backup and return a process-style exit code.
298
+
299
+ Args:
300
+ source_arg: Raw source argument from the CLI.
301
+ destination_arg: Raw destination argument, or None.
302
+ options: Path defaults.
303
+ args: Parsed argparse namespace from :func:`irsync.cli.main`.
304
+
305
+ Returns:
306
+ 0 on success (or when there was no work to do), non-zero on error.
307
+
308
+ Raises:
309
+ SourceNotMounted: If the source's drive is not mounted and
310
+ ``args.allow_unmounted`` is not set. Callers that iterate
311
+ several drives (:func:`run_all_backups`) catch this and treat
312
+ it as a skip.
313
+ DestinationNotMounted: If the destination's drive is not mounted
314
+ and ``args.allow_unmounted`` is not set. Unlike a missing
315
+ source drive, :func:`run_all_backups` counts this as a real
316
+ error, not a skip: the source drive being mounted while its
317
+ backup drive is not means the run would back up nothing while
318
+ looking like success.
319
+ UnsafeDestination: If there is no usable snapshot baseline and the
320
+ destination cannot be read to check whether it is empty.
321
+ Callers that iterate several drives (:func:`run_all_backups`)
322
+ catch this and count it as a real error, not a skip.
323
+ RsyncUnavailable: If the rsync binary is not on PATH and this run
324
+ will actually invoke rsync (``--snapshot-only`` never does, so
325
+ it is exempt). Checked up front so a missing rsync install
326
+ surfaces as a clean refusal rather than a ``FileNotFoundError``
327
+ traceback from deep inside ``run_dry_run``/``run_real_sync``.
328
+ """
329
+ # --snapshot-only doesn't need a destination at all — it just records the
330
+ # current state of the source for use as a future baseline. Route around
331
+ # resolve_endpoints so the user can snapshot any local directory without
332
+ # having to invent a dest argument.
333
+ if args.snapshot_only and not destination_arg:
334
+ return _run_snapshot_only(source_arg=source_arg, options=options, args=args)
335
+
336
+ # --snapshot-only never runs rsync, whether or not a destination was also
337
+ # given (see the early return above and the args.snapshot_only branch in
338
+ # _run_backup_for_endpoints), so it must not be gated on rsync's
339
+ # presence. Every other path below eventually calls run_dry_run or
340
+ # run_real_sync.
341
+ if not args.snapshot_only:
342
+ check_rsync_available()
343
+
344
+ endpoints = resolve_endpoints(source_arg, destination_arg, options)
345
+
346
+ # The gate runs BEFORE _source_lock: that function mkdirs the source root
347
+ # and opens .irsync.lock for writing, so locking an unmounted source
348
+ # creates files on the disk the gate exists to protect.
349
+ try:
350
+ check_mounted(
351
+ endpoints.source,
352
+ options.base_dir,
353
+ gate_outside_base=args.require_mount,
354
+ role="source",
355
+ )
356
+ check_mounted(
357
+ endpoints.dest,
358
+ options.base_dir,
359
+ gate_outside_base=args.require_mount,
360
+ role="destination",
361
+ )
362
+ except EndpointNotMounted:
363
+ if not args.allow_unmounted:
364
+ raise
365
+ logging.warning("Proceeding past the mount check (--allow-unmounted).")
366
+
367
+ src_root = endpoints.source if isinstance(endpoints.source, Path) else None
368
+ if src_root is None:
369
+ # Remote source: nowhere to put the lock. Skip the lock and let
370
+ # rsync's own protocol coordinate with the remote.
371
+ return _run_backup_for_endpoints(
372
+ endpoints=endpoints, options=options, args=args
373
+ )
374
+
375
+ # The lock's __enter__/__exit__ are called explicitly (rather than via
376
+ # `with`) so lock ACQUISITION has its own try/except, scoped only to
377
+ # `_source_lock`'s mkdir + lockfile open. Everything downstream
378
+ # (_persist_snapshots writes to dest before src; apply_moves renames
379
+ # inside the dest tree) can also raise PermissionError, but that failure
380
+ # is not about the source root, so it must not be reported as one.
381
+ lock_cm = _source_lock(src_root)
382
+ try:
383
+ lock_cm.__enter__()
384
+ except BlockingIOError:
385
+ return _log_lock_conflict(src_root)
386
+ except PermissionError as e:
387
+ return _log_source_permission_error(src_root, e)
388
+
389
+ try:
390
+ return _run_backup_for_endpoints(
391
+ endpoints=endpoints, options=options, args=args
392
+ )
393
+ except PermissionError as e:
394
+ # Deliberately generic: unlike the lock-acquisition case above, this
395
+ # PermissionError could have come from anywhere downstream (most
396
+ # often a read-only destination), so it must not name the source
397
+ # root as the culprit.
398
+ logging.error(
399
+ "Refusing: permission denied during the backup (%s). This may "
400
+ "be the source or the destination — check that irsync can "
401
+ "write to both.",
402
+ e,
403
+ )
404
+ return EXIT_REFUSED
405
+ finally:
406
+ lock_cm.__exit__(None, None, None)
407
+
408
+
409
+ def _run_snapshot_only(
410
+ *, source_arg: str, options: Options, args: argparse.Namespace
411
+ ) -> int:
412
+ """Take a snapshot of ``source_arg`` and write it next to the source. No dest.
413
+
414
+ Raises:
415
+ SourceNotMounted: If the source's drive is not mounted and
416
+ ``args.allow_unmounted`` is not set.
417
+ ValueError: If ``source_arg`` is empty, or is a drive id that no
418
+ loaded config defines (from :func:`~irsync.options.resolve_source`).
419
+ FileNotFoundError: If the resolved source does not exist.
420
+ NotADirectoryError: If the resolved source is not a directory.
421
+ """
422
+ # PermissionError from _source_lock is caught below and turned into
423
+ # EXIT_REFUSED rather than documented here as a raise: it never escapes
424
+ # this function.
425
+ #
426
+ # Drive ids and endpoint names are resolved by the shared resolver in
427
+ # irsync.options rather than re-implemented here: this path used to carry
428
+ # its own copy of the shorthand rules, which is exactly how the two could
429
+ # drift into disagreeing about what a drive id points at.
430
+ src = resolve_source(source_arg, options)
431
+
432
+ try:
433
+ check_mounted(
434
+ src, options.base_dir, gate_outside_base=args.require_mount, role="source"
435
+ )
436
+ except EndpointNotMounted:
437
+ if not args.allow_unmounted:
438
+ raise
439
+ logging.warning("Proceeding past the mount check (--allow-unmounted).")
440
+
441
+ # Acquire the same lock as a regular backup. Without it, a concurrent
442
+ # `_run_backup_for_endpoints` could call `_cleanup_orphan_tempfiles` and
443
+ # delete this run's `.irsync-snap-*` tempfile mid-write, which would make
444
+ # `os.replace(tmp_path, target)` fail with FileNotFoundError.
445
+ # Same explicit-__enter__/__exit__ split as run_backup, for the same
446
+ # reason: lock acquisition is the only step here proven to be about the
447
+ # source root. There is no destination in this path, so snapshot_tree and
448
+ # _atomic_write_snapshot below also only ever touch src — but keeping the
449
+ # same structure (and the same _log_source_permission_error helper) means
450
+ # a future edit that adds a destination here doesn't have to rediscover
451
+ # this scoping.
452
+ lock_cm = _source_lock(src)
453
+ try:
454
+ lock_cm.__enter__()
455
+ except BlockingIOError:
456
+ return _log_lock_conflict(src)
457
+ except PermissionError as e:
458
+ return _log_source_permission_error(src, e)
459
+
460
+ try:
461
+ rows = snapshot_tree(src)
462
+ _atomic_write_snapshot(rows, src, src / SNAPSHOT_FILENAME)
463
+ except PermissionError as e:
464
+ return _log_source_permission_error(src, e)
465
+ finally:
466
+ lock_cm.__exit__(None, None, None)
467
+
468
+ logging.info(
469
+ "Snapshot-only: wrote %d rows to %s", len(rows), src / SNAPSHOT_FILENAME
470
+ )
471
+ return 0
472
+
473
+
474
+ def _cleanup_orphan_tempfiles(root: Path) -> int:
475
+ """Delete leftover ``.irsync-snap-*`` tempfiles from prior killed runs.
476
+
477
+ ``_atomic_write_snapshot`` uses ``tempfile.mkstemp`` and could leave an
478
+ orphan if the process dies between mkstemp and os.replace. Orphans
479
+ accumulate at the root because rsync's anchored ``/.irsync-snap-*``
480
+ exclude prevents both transfer and ``--delete-before`` cleanup.
481
+
482
+ Must be called for both the source root AND the dest root (when
483
+ local): 7th-M1 flipped persist order to dest-first, so a kill
484
+ between mkstemp and os.replace during the dest write strands the
485
+ tempfile there too (8th-NEW-H1).
486
+ """
487
+ removed = 0
488
+ try:
489
+ entries = list(root.iterdir())
490
+ except (FileNotFoundError, PermissionError):
491
+ return 0
492
+ for p in entries:
493
+ if p.name.startswith(SNAPSHOT_TEMPFILE_PREFIX) and p.is_file():
494
+ try:
495
+ p.unlink()
496
+ removed += 1
497
+ except OSError as e:
498
+ logging.warning("Could not remove orphan tempfile %s: %s", p, e)
499
+ if removed:
500
+ logging.info(
501
+ "Cleaned up %d orphan .irsync-snap-* tempfile(s) in %s.", removed, root
502
+ )
503
+ return removed
504
+
505
+
506
+ def _run_backup_for_endpoints(
507
+ *,
508
+ endpoints: Endpoints,
509
+ options: Options,
510
+ args: argparse.Namespace,
511
+ ) -> int:
512
+ src_str = with_trailing_slash(endpoints.source, remote=endpoints.source_is_remote)
513
+ dest_str = with_trailing_slash(endpoints.dest, remote=endpoints.dest_is_remote)
514
+ logging.info(
515
+ "Backup initiated.\nSource: %s\nDestination: %s", src_str, dest_str
516
+ )
517
+
518
+ src_root: Path | None = (
519
+ endpoints.source if isinstance(endpoints.source, Path) else None
520
+ )
521
+ dest_root: Path | None = (
522
+ endpoints.dest if isinstance(endpoints.dest, Path) else None
523
+ )
524
+
525
+ # Sweep up any orphan tempfiles at SRC before snapshotting, so the
526
+ # snapshot doesn't include them and the next diff isn't polluted.
527
+ # The DEST cleanup is deliberately deferred to just before apply_moves
528
+ # below: AD-2 requires that a no-change run never wakes the backup
529
+ # drive (10th-F2). The 8th-NEW-H1 dest-orphan recovery is preserved —
530
+ # any run that actually writes to dest hits the cleanup before the
531
+ # write.
532
+ if src_root is not None:
533
+ _cleanup_orphan_tempfiles(src_root)
534
+
535
+ # --snapshot-only: just write the snapshot to the source root and exit.
536
+ if args.snapshot_only:
537
+ if src_root is None:
538
+ logging.error("--snapshot-only requires a local source.")
539
+ return EXIT_REFUSED
540
+ rows = snapshot_tree(src_root)
541
+ _atomic_write_snapshot(rows, src_root, src_root / SNAPSHOT_FILENAME)
542
+ logging.info(
543
+ "Snapshot-only: wrote %d rows to %s",
544
+ len(rows),
545
+ src_root / SNAPSHOT_FILENAME,
546
+ )
547
+ return 0
548
+
549
+ # --no-snapshot OR remote source: skip the inode logic and just run rsync.
550
+ if args.no_snapshot or src_root is None:
551
+ if src_root is None:
552
+ logging.warning("Source is remote; inode rename detection disabled.")
553
+ elif args.no_snapshot and not args.allow_empty_source:
554
+ # --no-snapshot never walks the tree, so there is no fresh_rows
555
+ # for fresh_snapshot_is_empty to inspect (that check covers the
556
+ # snapshot path below). A baseline file CAN still exist on disk
557
+ # from an earlier snapshot-taking run — what's true is that this
558
+ # code path never reads or consults one, so it can't tell a
559
+ # genuine "I emptied my source on purpose" run (which a real
560
+ # baseline would prove) from the unmounted/mistyped-source
561
+ # signature. Consequence: a user with a real baseline who
562
+ # genuinely emptied their source and runs --no-snapshot is
563
+ # steered to --allow-empty-source rather than
564
+ # --allow-massive-delete, because the >50% deletion guard is
565
+ # unreachable on this path (it only runs where a baseline is
566
+ # actually read, in the snapshot branch below).
567
+ if source_root_is_empty(src_root):
568
+ logging.error(
569
+ "Refusing: source %s is empty and --no-snapshot has no "
570
+ "baseline to compare against. This usually means the "
571
+ "source drive is not mounted or the path is wrong. Pass "
572
+ "--allow-empty-source to proceed anyway.",
573
+ src_root,
574
+ )
575
+ return EXIT_REFUSED
576
+ return _run_rsync_only(
577
+ src_str=src_str, dest_str=dest_str, options=options, args=args
578
+ )
579
+
580
+ # Take fresh snapshot of source.
581
+ fresh_rows = snapshot_tree(src_root)
582
+
583
+ before_path = src_root / SNAPSHOT_FILENAME
584
+ changes: Changes | None = None
585
+ before_rows: list[Row] = []
586
+ have_before = False
587
+ if before_path.exists():
588
+ try:
589
+ _header, before_rows = read_snapshot(
590
+ before_path, expected_source_root=src_root
591
+ )
592
+ have_before = True
593
+ except SnapshotMismatch as e:
594
+ logging.warning(
595
+ "Existing snapshot at %s does not match source root %s: %s. "
596
+ "Treating as first backup; rsync will reconcile.",
597
+ before_path,
598
+ src_root,
599
+ e,
600
+ )
601
+ else:
602
+ logging.info("No prior snapshot; treating as first backup.")
603
+
604
+ if have_before:
605
+ changes = compute_changes(before_rows, fresh_rows)
606
+ logging.info(
607
+ "Diff: %d dir moves, %d file moves, %d created, %d deleted.",
608
+ len(changes.dir_moves),
609
+ len(changes.file_moves),
610
+ len(changes.created),
611
+ len(changes.deleted),
612
+ )
613
+ if not changes.any_changes() and not args.force:
614
+ logging.info("No source changes since last backup; backup drive untouched.")
615
+ return 0
616
+ # Sanity check: a diff that says >50% of the previous tree is gone
617
+ # is almost certainly a wrong-source / stale-snapshot / swapped-args
618
+ # accident. Refuse unless the user explicitly opts in with
619
+ # --allow-massive-delete.
620
+ if before_rows and not args.allow_massive_delete:
621
+ ratio = len(changes.deleted) / len(before_rows)
622
+ if ratio > CATASTROPHIC_DELETE_RATIO:
623
+ logging.error(
624
+ "Refusing: diff would delete %d of %d previously-recorded "
625
+ "entries (%.0f%%). This usually means the source tree has "
626
+ "been swapped, the snapshot is from a different tree, or "
627
+ "args were reversed. Pass --allow-massive-delete to override.",
628
+ len(changes.deleted),
629
+ len(before_rows),
630
+ ratio * 100,
631
+ )
632
+ return EXIT_REFUSED
633
+
634
+ # No usable baseline AND an empty source: never a legitimate backup. A
635
+ # user who genuinely has an empty tree to back up has nothing worth
636
+ # protecting yet; what this actually catches is the unmounted/mistyped
637
+ # source that presents as an empty directory. Deliberately independent
638
+ # of what the destination holds — even an equally-empty destination is
639
+ # refused, because "empty source, no baseline" is itself the signature,
640
+ # not a symptom that requires a non-empty destination to notice. Must
641
+ # not also fire when a baseline EXISTS: that case (a real deletion) is
642
+ # already covered by the catastrophic-delete guard above.
643
+ if (
644
+ not have_before
645
+ and not args.allow_empty_source
646
+ and fresh_snapshot_is_empty(fresh_rows)
647
+ ):
648
+ logging.error(
649
+ "Refusing: source %s is empty and there is no prior snapshot to "
650
+ "use as a baseline. This usually means the source drive is not "
651
+ "mounted or the path is wrong. Pass --allow-empty-source to "
652
+ "proceed anyway.",
653
+ src_root,
654
+ )
655
+ return EXIT_REFUSED
656
+
657
+ # No usable baseline: this run will transfer the whole source and delete
658
+ # everything at the destination that is not on it. If the destination
659
+ # already holds data, that is the unmounted-source scenario — refuse.
660
+ foreign: list[str] = []
661
+ if not have_before and dest_root is not None:
662
+ foreign = foreign_dest_entries(dest_root)
663
+ # A dry run writes nothing — it is the natural way to inspect what's
664
+ # at the destination before deciding whether to adopt it — so it must
665
+ # not be blocked by the same refusal that guards the real transfer.
666
+ # `foreign` is still computed unconditionally above: the first-run
667
+ # preview (Rule 3) reports it regardless of --dry-run.
668
+ if foreign and not args.allow_nonempty_dest and not args.dry_run:
669
+ shown = ", ".join(foreign[:10])
670
+ more = f" (and {len(foreign) - 10} more)" if len(foreign) > 10 else ""
671
+ logging.error(
672
+ "Refusing: no prior snapshot, but the destination %s already "
673
+ "contains %d entries: %s%s. rsync would DELETE them. This "
674
+ "usually means the source drive is not mounted. Pass "
675
+ "--allow-nonempty-dest to adopt this destination anyway.",
676
+ dest_root,
677
+ len(foreign),
678
+ shown,
679
+ more,
680
+ )
681
+ return EXIT_REFUSED
682
+
683
+ # Always show the preview before confirming. In interactive mode, page it
684
+ # through less so the user can scroll through the deletion list. In --yes
685
+ # mode, dump it once so the run is at least auditable in scrollback / logs.
686
+ if changes is not None:
687
+ _show_preview(changes, interactive=not args.yes)
688
+ else:
689
+ text = _format_first_run_preview(fresh_rows, src_root, dest_root, len(foreign))
690
+ if args.yes:
691
+ print(text)
692
+ else:
693
+ _page_output(text)
694
+ if not _confirm_or_abort(args):
695
+ logging.info("Aborted by user.")
696
+ return EXIT_ABORTED
697
+
698
+ # --dry-run: show the rsync dry-run; don't touch dest tree or persist snapshot.
699
+ if args.dry_run:
700
+ cmd = build_rsync_command(
701
+ source=src_str,
702
+ dest=dest_str,
703
+ dry_run=True,
704
+ exclude_dirs=options.exclude_dirs,
705
+ no_exclude=args.no_exclude,
706
+ ssh_port=args.ssh_port,
707
+ ssh_key=args.ssh_key,
708
+ )
709
+ out, rc = _dry_run_preview(cmd)
710
+ if out is None:
711
+ return rc
712
+ print(out)
713
+ return 0
714
+
715
+ # 10th-F2: dest cleanup deferred to here so a no-change run (which
716
+ # already returned at the any_changes() short-circuit above) never
717
+ # touches the backup drive. 8th-NEW-H1's "orphan-on-dest" recovery
718
+ # path is still intact: every run that reaches apply_moves / rsync
719
+ # cleans dest first.
720
+ if dest_root is not None:
721
+ _cleanup_orphan_tempfiles(dest_root)
722
+
723
+ # Apply moves on dest tree first (only if we have a local dest and a diff).
724
+ if changes is not None and dest_root is not None:
725
+ try:
726
+ result = apply_moves(
727
+ dir_moves=changes.dir_moves,
728
+ file_moves=changes.file_moves,
729
+ dest_root=dest_root,
730
+ )
731
+ except CrossDeviceMoveError as e:
732
+ # NEW-H2 (5th-pass). Refuse upfront so we don't leave dest in
733
+ # the partial state that would otherwise loop forever (next run
734
+ # would re-issue the same plan and hit the same EXDEV at the
735
+ # same point). Snapshot is intentionally NOT persisted so the
736
+ # corrected re-run still has the right baseline.
737
+ logging.error(
738
+ "Refusing to apply moves: dest tree spans multiple "
739
+ "filesystems (%s). Move every cross-FS path under one "
740
+ "filesystem, or pass --no-snapshot to skip the rename "
741
+ "optimization.",
742
+ e,
743
+ )
744
+ return EXIT_REFUSED
745
+ logging.info(
746
+ "Replay: %d dir moves applied, %d file moves applied, %d skipped.",
747
+ result.dirs_moved,
748
+ result.files_moved,
749
+ result.skipped,
750
+ )
751
+
752
+ # Run real rsync.
753
+ cmd = build_rsync_command(
754
+ source=src_str,
755
+ dest=dest_str,
756
+ dry_run=False,
757
+ exclude_dirs=options.exclude_dirs,
758
+ no_exclude=args.no_exclude,
759
+ ssh_port=args.ssh_port,
760
+ ssh_key=args.ssh_key,
761
+ )
762
+ rc = run_real_sync(cmd)
763
+ if rc != 0:
764
+ logging.error("rsync failed; not updating snapshot.")
765
+ return rc
766
+
767
+ # Persist the fresh snapshot to source and (if local) dest.
768
+ _persist_snapshots(fresh_rows, src_root, dest_root)
769
+ return 0
770
+
771
+
772
+ def _run_rsync_only(
773
+ *,
774
+ src_str: str,
775
+ dest_str: str,
776
+ options: Options,
777
+ args: argparse.Namespace,
778
+ ) -> int:
779
+ dry_cmd = build_rsync_command(
780
+ source=src_str,
781
+ dest=dest_str,
782
+ dry_run=True,
783
+ exclude_dirs=options.exclude_dirs,
784
+ no_exclude=args.no_exclude,
785
+ ssh_port=args.ssh_port,
786
+ ssh_key=args.ssh_key,
787
+ )
788
+ # NEW-M1 (5th-pass). Always run the dry-run so a preview exists. Under
789
+ # --yes (cron), print to stdout for auditability (AD-7); interactively,
790
+ # page through `less` and prompt for confirmation. Mirrors the snapshot
791
+ # path's _show_preview(..., interactive=not args.yes) behavior so the
792
+ # two code paths are consistent.
793
+ out, preview_rc = _dry_run_preview(dry_cmd)
794
+ if out is None:
795
+ # The preview failed, so we have nothing to show the user and no
796
+ # evidence the real transfer would fare better. Abort before touching
797
+ # the destination.
798
+ return preview_rc
799
+ if args.yes:
800
+ print(out)
801
+ else:
802
+ _page_output(out)
803
+ if not _confirm_or_abort(args):
804
+ return EXIT_ABORTED
805
+
806
+ # Hazard H fix: --dry-run was never consulted on this path, so
807
+ # `--no-snapshot --dry-run` fell through to a real, destructive rsync
808
+ # despite the flag. The dry-run preview above already IS rsync's
809
+ # --dry-run output, so honoring the flag here is just: stop before the
810
+ # real transfer and report success, changing nothing — the same
811
+ # contract the snapshot path applies at its own `if args.dry_run:`
812
+ # check in _run_backup_for_endpoints.
813
+ if args.dry_run:
814
+ return 0
815
+
816
+ cmd = build_rsync_command(
817
+ source=src_str,
818
+ dest=dest_str,
819
+ dry_run=False,
820
+ exclude_dirs=options.exclude_dirs,
821
+ no_exclude=args.no_exclude,
822
+ ssh_port=args.ssh_port,
823
+ ssh_key=args.ssh_key,
824
+ )
825
+ return run_real_sync(cmd)
826
+
827
+
828
+ def _page_output(text: str) -> None:
829
+ """Pipe ``text`` through ``less`` if available, else print directly."""
830
+ pager = shutil.which("less")
831
+ if pager:
832
+ # 8th-M1: detach the pager from the parent's tty/session so a
833
+ # SIGKILL of the parent doesn't leave less zombied on the
834
+ # controlling terminal. Parity with run_real_sync's 7th-pass
835
+ # session isolation.
836
+ proc = subprocess.Popen( # noqa: S603
837
+ [pager], stdin=subprocess.PIPE, text=True, start_new_session=True
838
+ )
839
+ # communicate() already writes stdin, closes it, and reaps the child.
840
+ proc.communicate(input=text)
841
+ else:
842
+ print(text)
843
+
844
+
845
+ def run_all_backups(*, options: Options, args: argparse.Namespace) -> int:
846
+ """Iterate :data:`Options.all_backups` and back up each in turn.
847
+
848
+ Exit-code contract: **an unmounted SOURCE is a skip, not an error; an
849
+ unmounted DESTINATION is a real error.**
850
+ :data:`Options.all_backups` is the configured backup order, which lists
851
+ every drive the user might ever attach, and on any given day most of
852
+ them are absent, so a source that isn't there is the normal case and an
853
+ ALL run that skips it still reports success
854
+ (:class:`~irsync.preflight.SourceNotMounted`, alongside a plain missing
855
+ directory). A destination that isn't mounted is different: if a drive is
856
+ mounted but its backup drive is not, the run
857
+ would back up nothing while still exiting 0, which is exactly the
858
+ silent-success hazard this branch exists to close. So
859
+ :class:`~irsync.preflight.DestinationNotMounted` — like an unreadable
860
+ destination (:class:`~irsync.preflight.UnsafeDestination`) — is counted
861
+ as a real error, same as a non-zero ``run_backup`` return, and the
862
+ batch continues to the next drive rather than aborting. A bare
863
+ :class:`PermissionError` is caught alongside them as a backstop: most
864
+ permission failures (e.g. :func:`~irsync.preflight.source_root_is_empty`
865
+ on the ``--no-snapshot`` path) are already turned into a plain non-zero
866
+ return inside ``run_backup`` itself, but one raised earlier — from
867
+ ``resolve_endpoints``/``check_mounted``, before ``run_backup``'s own
868
+ try/except is entered — would otherwise escape uncaught here and abort
869
+ the whole batch instead of just the one drive. Only a real backup
870
+ failure, an unmounted/unreadable destination, or an unreadable source
871
+ makes this return 1; a user abort propagates :data:`EXIT_ABORTED` and
872
+ stops the remaining drives.
873
+
874
+ Both the skipped and the successfully-backed-up entries are named in the
875
+ summary log line so a cron log records what actually happened.
876
+
877
+ Returns:
878
+ 0 when every attempted backup succeeded (whether or not drives were
879
+ skipped), 1 when at least one drive failed, or :data:`EXIT_ABORTED`
880
+ when the user aborted.
881
+ """
882
+ logging.info("Backing up all drives: %s", ", ".join(options.all_backups))
883
+ total_errors = 0
884
+ successful: list[str] = []
885
+ missing: list[str] = []
886
+ for backup in options.all_backups:
887
+ try:
888
+ rc = run_backup(
889
+ source_arg=backup,
890
+ destination_arg=None,
891
+ options=options,
892
+ args=args,
893
+ )
894
+ except (DestinationNotMounted, UnsafeDestination, PermissionError) as e:
895
+ # Caught BEFORE the (broader) EndpointNotMounted clause below:
896
+ # DestinationNotMounted is a subclass of it, and a subclass must
897
+ # be caught before its parent or this handler is dead code.
898
+ # Unlike a missing/unmounted SOURCE, none of these is a benign
899
+ # absence — the run would silently back up nothing (an
900
+ # unmounted destination) or the destination couldn't be checked
901
+ # for safety at all (unreadable). PermissionError is caught here
902
+ # too as a backstop: run_backup already converts a
903
+ # PermissionError raised inside _run_backup_for_endpoints (e.g.
904
+ # from preflight.source_root_is_empty on the --no-snapshot path)
905
+ # into a plain non-zero return, so in practice this clause only
906
+ # fires for a PermissionError raised *before* that point
907
+ # (resolve_endpoints/check_mounted, which run outside
908
+ # run_backup's own try/except). Either way, an unreadable path
909
+ # is a real misconfiguration, not "drive absent today", so it
910
+ # fails closed the same way an unreadable destination does: all
911
+ # three count as a real error (never silently a skip) but do
912
+ # not abort the batch; the next drive still gets a chance.
913
+ logging.error("Error backing up %r: %s", backup, e)
914
+ total_errors += 1
915
+ if total_errors >= options.max_errors:
916
+ logging.error("Max errors (%d) reached; stopping.", options.max_errors)
917
+ return 1
918
+ continue
919
+ except (FileNotFoundError, NotADirectoryError, EndpointNotMounted) as e:
920
+ # A bare EndpointNotMounted (not a DestinationNotMounted
921
+ # instance) and SourceNotMounted both land here, alongside a
922
+ # plain missing/wrong-type path: all are the benign
923
+ # "drive absent today" case commit 044c036 established as a
924
+ # skip, not an error.
925
+ logging.error("Skipping %r (missing/unmounted drive): %s", backup, e)
926
+ missing.append(backup)
927
+ continue
928
+ if rc == 0:
929
+ successful.append(backup)
930
+ elif rc == EXIT_ABORTED:
931
+ logging.info("User aborted; stopping ALL processing.")
932
+ return rc
933
+ else:
934
+ total_errors += 1
935
+ if total_errors >= options.max_errors:
936
+ logging.error("Max errors (%d) reached; stopping.", options.max_errors)
937
+ return 1
938
+ if total_errors == 0 and not missing:
939
+ logging.info(
940
+ "All backups completed successfully: %s.", ", ".join(successful) or "none"
941
+ )
942
+ return 0
943
+ logging.warning(
944
+ "Finished with issues. backed up=%d (%s), errors=%d, missing/skipped=%d (%s).",
945
+ len(successful),
946
+ ", ".join(successful) or "none",
947
+ total_errors,
948
+ len(missing),
949
+ ", ".join(missing) or "none",
950
+ )
951
+ return 1 if total_errors else 0