-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafekeep.py
More file actions
1540 lines (1335 loc) · 58.9 KB
/
Copy pathsafekeep.py
File metadata and controls
1540 lines (1335 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""SafeKeep - lightweight, bulletproof snapshot backup.
Backs up multiple source folders to one or more destinations as dated,
point-in-time snapshots. Local/NAS destinations are implemented today using
NTFS hardlinks for space-efficient dedup and `robocopy` for reliable copying.
Google Drive and other clouds drop into the same `Destination` interface later
(see RcloneDestination stub and README).
Standard library only - no pip installs required.
Usage:
safekeep.py run # do one backup pass (one snapshot per dest)
safekeep.py list [--dest NAME] # show snapshots
safekeep.py verify [--dest NAME] [--hash]
safekeep.py restore --source LABEL --to PATH [--dest NAME] [--snapshot S]
safekeep.py prune [--dest NAME] [--keep N]
safekeep.py install # register daily Task Scheduler job
safekeep.py uninstall # remove the scheduled job
Global flags: --config PATH, --verbose
"""
from __future__ import annotations
import argparse
import ctypes
import hashlib
import json
import logging
import logging.handlers
import os
import shutil
import stat
import subprocess
import sys
import time
import tomllib
from dataclasses import dataclass, field
from datetime import datetime
from fnmatch import fnmatch
from pathlib import Path
VERSION = "1.0"
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_CONFIG = SCRIPT_DIR / "config.toml"
LOCKFILE = SCRIPT_DIR / ".safekeep.lock"
LOG_DIR = SCRIPT_DIR / "logs"
MAX_LOCK_AGE_SEC = 6 * 3600 # a lock older than this is treated as stale/abandoned
# On Windows, stop child processes (robocopy, powershell) from popping up their
# own console windows - important when the GUI runs under pythonw.
_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
def resolve_unc(path) -> Path:
"""If `path` is on a mapped network drive, return its UNC form, else unchanged.
Mapped letters (U:\\) belong to a user's logon session and are NOT visible to
an elevated (UAC) process - so a backup run elevated can't find U:\\. UNC
paths (\\\\server\\share) work everywhere.
"""
class _UNI(ctypes.Structure):
_fields_ = [("lpUniversalName", ctypes.c_wchar_p)]
s = str(path)
if os.name != "nt" or len(s) < 2 or s[1] != ":":
return Path(s)
try:
mpr = ctypes.WinDLL("mpr.dll")
size = ctypes.c_uint(32768)
buf = (ctypes.c_char * 32768)()
if mpr.WNetGetUniversalNameW(s.replace("/", "\\"), 1, buf, ctypes.byref(size)) == 0:
unc = ctypes.cast(buf, ctypes.POINTER(_UNI)).contents.lpUniversalName
if unc:
return Path(unc)
except Exception:
pass
return Path(s)
DEFAULT_EXCLUDES = [
"**/node_modules",
"**/__pycache__",
"**/.venv",
"**/venv",
"**/.DS_Store",
"**/Thumbs.db",
]
log = logging.getLogger("safekeep")
def _progress(progress, stage: str, frac, msg: str) -> None:
"""Push a progress update to an optional callback (used by the GUI).
stage: "scan" | "hardlink" | "copy" | "prune" | "info" | "done"
frac: float in 0..1, or None for indeterminate ("working…")
"""
if progress is not None:
try:
progress(stage, frac, msg)
except Exception:
pass
# --------------------------------------------------------------------------- #
# Logging
# --------------------------------------------------------------------------- #
def setup_logging(verbose: bool = False, enable_console: bool = True) -> None:
level = logging.DEBUG if verbose else logging.INFO
log.setLevel(logging.DEBUG)
for h in list(log.handlers): # idempotent: avoid duplicate handlers on repeat calls
log.removeHandler(h)
fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s", "%Y-%m-%d %H:%M:%S")
if enable_console and sys.stderr is not None: # sys.stderr is None under pythonw
sh = logging.StreamHandler()
sh.setLevel(level)
sh.setFormatter(fmt)
log.addHandler(sh)
try:
LOG_DIR.mkdir(parents=True, exist_ok=True)
fh = logging.handlers.RotatingFileHandler(
LOG_DIR / "safekeep.log", maxBytes=2_000_000, backupCount=3, encoding="utf-8"
)
fh.setLevel(logging.DEBUG)
fh.setFormatter(fmt)
log.addHandler(fh)
except Exception as exc: # pragma: no cover - best effort
print(f"warning: could not open log file: {exc}", file=sys.stderr)
# --------------------------------------------------------------------------- #
# Config
# --------------------------------------------------------------------------- #
@dataclass
class SourceSpec:
path: Path
label: str
exclude: list[str]
@dataclass
class DestinationSpec:
name: str
type: str
path: Path | None = None
remote: str | None = None
retention: int | None = None
sources: list[str] | None = None # if set, only these source labels go here
exclude_sources: list[str] = field(default_factory=list)
@dataclass
class Config:
retention: int
use_hardlinks: bool
copy_security: bool
daily_time: str
default_exclude: list[str]
sources: list[SourceSpec]
destinations: list[DestinationSpec]
backup_mode: bool = False # robocopy /B - read all files (needs admin/Backup rights)
restartable: bool = False # robocopy /Z (or /ZB with backup_mode) - resilient on flaky links
ignore_access_errors: bool = True # rc=8 from permission errors is a warning, not a failure
def load_config(path: Path) -> Config:
with open(path, "rb") as fh:
data = tomllib.load(fh)
b = data.get("backup", {})
cfg = Config(
retention=int(b.get("retention", 14)),
use_hardlinks=bool(b.get("use_hardlinks", True)),
copy_security=bool(b.get("copy_security", False)),
daily_time=str(b.get("daily_time", "03:00")),
default_exclude=list(b.get("default_exclude", DEFAULT_EXCLUDES)),
sources=[],
destinations=[],
backup_mode=bool(b.get("backup_mode", False)),
restartable=bool(b.get("restartable", False)),
ignore_access_errors=bool(b.get("ignore_access_errors", True)),
)
for s in data.get("sources", []):
if "path" not in s:
raise ValueError("each [[sources]] entry needs a 'path'")
sp = Path(s["path"]).expanduser()
label = s.get("label") or sp.name or "source"
excl = list(s.get("exclude", cfg.default_exclude))
cfg.sources.append(SourceSpec(path=sp, label=label, exclude=excl))
for d in data.get("destinations", []):
if "name" not in d:
raise ValueError("each [[destinations]] entry needs a 'name'")
dtype = d.get("type", "local")
cfg.destinations.append(
DestinationSpec(
name=d["name"],
type=dtype,
path=Path(d["path"]).expanduser() if d.get("path") else None,
remote=d.get("remote"),
retention=int(d["retention"]) if "retention" in d else None,
sources=list(d["sources"]) if "sources" in d else None,
exclude_sources=list(d.get("exclude_sources", [])),
)
)
# Normalise local destination paths to UNC so they work even when elevated
# (mapped letters like U:\ aren't visible to an elevated process).
for d in cfg.destinations:
if d.type == "local" and d.path is not None:
d.path = resolve_unc(d.path)
_validate_config(cfg)
return cfg
def _validate_config(cfg: Config) -> None:
if not cfg.sources:
raise ValueError("config defines no [[sources]] - nothing to back up")
if not cfg.destinations:
raise ValueError("config defines no [[destinations]] - nowhere to back up to")
labels = [s.label for s in cfg.sources]
if len(set(labels)) != len(labels):
raise ValueError(f"source labels must be unique: {labels}")
names = [d.name for d in cfg.destinations]
if len(set(names)) != len(names):
raise ValueError(f"destination names must be unique: {names}")
for d in cfg.destinations:
if d.type == "local" and d.path is None:
raise ValueError(f"local destination '{d.name}' needs a 'path'")
if d.type == "rclone" and d.remote is None:
raise ValueError(f"rclone destination '{d.name}' needs a 'remote'")
def _q(value) -> str:
"""Quote a value for TOML (forward-slash paths, escape embedded quotes)."""
return '"' + str(value).replace("\\", "/").replace('"', '\\"') + '"'
def save_config(cfg: Config, path: Path) -> None:
"""Serialise Config back to TOML.
The standard library has no TOML *writer*, so this handles our fixed schema.
NOTE: round-tripping discards comments - the file is GUI/CLI managed data.
"""
lines = [
"# SafeKeep configuration (managed by the GUI / CLI). See README.md.",
"",
"[backup]",
f"retention = {int(cfg.retention)}",
f"use_hardlinks = {'true' if cfg.use_hardlinks else 'false'}",
f"copy_security = {'true' if cfg.copy_security else 'false'}",
f"backup_mode = {'true' if cfg.backup_mode else 'false'}",
f"restartable = {'true' if cfg.restartable else 'false'}",
f"ignore_access_errors = {'true' if cfg.ignore_access_errors else 'false'}",
f'daily_time = {_q(cfg.daily_time)}',
]
if cfg.default_exclude:
lines.append("default_exclude = [" + ", ".join(_q(e) for e in cfg.default_exclude) + "]")
lines.append("")
for d in cfg.destinations:
lines.append("[[destinations]]")
lines.append(f"name = {_q(d.name)}")
lines.append(f"type = {_q(d.type)}")
if d.path is not None:
lines.append(f"path = {_q(resolve_unc(d.path))}")
if d.remote is not None:
lines.append(f"remote = {_q(d.remote)}")
if d.retention is not None:
lines.append(f"retention = {int(d.retention)}")
if d.sources is not None:
lines.append("sources = [" + ", ".join(_q(s) for s in d.sources) + "]")
if d.exclude_sources:
lines.append("exclude_sources = [" + ", ".join(_q(s) for s in d.exclude_sources) + "]")
lines.append("")
for s in cfg.sources:
lines.append("[[sources]]")
lines.append(f"path = {_q(s.path)}")
lines.append(f"label = {_q(s.label)}")
if s.exclude != cfg.default_exclude:
lines.append("exclude = [" + ", ".join(_q(e) for e in s.exclude) + "]")
lines.append("")
path.write_text("\n".join(lines), encoding="utf-8")
# --------------------------------------------------------------------------- #
# Exclude matching (used by the source scan)
# --------------------------------------------------------------------------- #
def _excl_leaf(pattern: str) -> str:
leaf = pattern.replace("\\", "/")
if leaf.startswith("**/"):
leaf = leaf[3:]
return leaf.rsplit("/", 1)[-1]
def _excl_leaves(patterns: list[str]) -> list[str]:
out: set[str] = set()
for p in patterns:
leaf = _excl_leaf(p)
if leaf:
out.add(leaf)
return sorted(out)
def is_excluded(rel_posix: str, patterns: list[str]) -> bool:
"""rel_posix is a '/'-separated path relative to the source root ('.' = root)."""
base = rel_posix.rsplit("/", 1)[-1]
for pat in patterns:
leaf = _excl_leaf(pat)
if leaf and (base == leaf or fnmatch(base, leaf)):
return True
if fnmatch(rel_posix, pat) or (leaf and fnmatch(rel_posix, leaf)):
return True
return False
# --------------------------------------------------------------------------- #
# Source scan -> shared manifest for a run
# --------------------------------------------------------------------------- #
@dataclass
class FileEntry:
rel: str # posix relpath
path: Path # absolute source path
size: int
mtime: int # whole seconds
@dataclass
class SourceScan:
spec: SourceSpec
files: list[FileEntry]
def scan_source(spec: SourceSpec, progress=None) -> list[FileEntry]:
root = spec.path
files: list[FileEntry] = []
if not root.is_dir():
log.warning("source '%s' not found (skipping its scan): %s", spec.label, root)
return files
for dirpath, dirnames, filenames in os.walk(root):
rel_dir = Path(dirpath).relative_to(root).as_posix()
# prune excluded directories in-place so os.walk doesn't descend
kept: list[str] = []
for d in dirnames:
rd = f"{rel_dir}/{d}" if rel_dir != "." else d
if is_excluded(rd, spec.exclude):
continue
kept.append(d)
dirnames[:] = kept
for fn in filenames:
rf = f"{rel_dir}/{fn}" if rel_dir != "." else fn
if is_excluded(rf, spec.exclude):
continue
full = Path(dirpath) / fn
try:
st = full.stat() # follows symlinks; fine for project trees
except OSError as exc:
log.debug("stat failed %s: %s", full, exc)
continue
if not stat.S_ISREG(st.st_mode):
continue
files.append(FileEntry(rel=rf, path=full, size=st.st_size, mtime=int(st.st_mtime)))
if progress is not None and len(files) % 2000 == 0:
_progress(progress, "scan", None,
f"Scanning '{spec.label}'… {len(files):,} files")
return files
# --------------------------------------------------------------------------- #
# Destination interface
# --------------------------------------------------------------------------- #
class Destination:
"""Base interface. Subclasses implement storage-specific behaviour."""
type = "base"
def __init__(self, spec: DestinationSpec, cfg: Config) -> None:
self.spec = spec
self.cfg = cfg
@property
def retention(self) -> int:
return self.spec.retention if self.spec.retention is not None else self.cfg.retention
# --- to implement ---
def preflight(self) -> tuple[bool, str | None]:
raise NotImplementedError
def list_snapshots(self) -> list[str]:
raise NotImplementedError
def create_snapshot(self, stamp, sources, prev_stamp, dry_run):
raise NotImplementedError
def delete_snapshot(self, stamp):
raise NotImplementedError
def write_manifest(self, stamp, manifest):
raise NotImplementedError
def verify_against_sources(self, sources, snapshot, use_hash=False) -> int:
"""Compare a snapshot to live sources; return number of problems."""
raise NotImplementedError
def restore(self, snapshot, label, to_path, assume_yes=False) -> int:
"""Restore one source label from a snapshot into to_path. Return rc."""
raise NotImplementedError
def _rmtree_error_handler(func, path, exc_info): # noqa: ANN001
# On SMB shares a file/dir may briefly be "in use" (AV scan, oplock); retry.
for _ in range(6):
try:
time.sleep(1.0)
func(path)
return
except OSError:
continue
try:
os.chmod(path, 0o777)
func(path)
except Exception:
pass
def rmtree(path: Path) -> None:
if path.exists():
shutil.rmtree(path, onexc=_rmtree_error_handler)
def safe_rename(src: Path, dst: Path, attempts: int = 15, delay: float = 2.0) -> None:
"""Rename with retries - renaming a dir on SMB often fails transiently
(WinError 5) while a handle is open, then succeeds once it closes."""
last = None
for _ in range(attempts):
try:
os.rename(src, dst)
return
except OSError as exc:
last = exc
time.sleep(delay)
raise last
# robocopy action words that indicate a file/dir being acted on (for live progress)
_ROBOCOPY_ACTIONS = ("New File", "Newer", "Older", "Changed", "Tweaked",
"New Dir", "Lonely", "Same", "Extra")
_ROBOCOPY_FILE_ACTIONS = ("New File", "Newer", "Older", "Changed", "Tweaked")
def _parse_robocopy_line(line: str):
"""Return (action, name) if `line` is a robocopy file/dir action, else None.
robocopy prints e.g. ' Newer 1.0 m sub\\file.bin' (and a leading
percentage when /NP is absent). We locate the action word and treat the text
after it as the item name.
"""
s = line.strip()
if s and s[0].isdigit(): # strip a leading 'NN%' percentage
parts = s.split("%", 1)
if len(parts) == 2:
s = parts[1].lstrip()
for w in _ROBOCOPY_ACTIONS:
idx = s.find(w)
if idx != -1:
return w, s[idx + len(w):].strip()
return None
class LocalDestination(Destination):
type = "local"
def __init__(self, spec: DestinationSpec, cfg: Config) -> None:
super().__init__(spec, cfg)
self.supports_security: bool | None = None # probed at preflight
def snapshots_root(self) -> Path:
assert self.spec.path is not None
return self.spec.path / "snapshots"
def snapshot_dir(self, stamp: str) -> Path:
return self.snapshots_root() / stamp
def manifest_path(self, stamp: str) -> Path:
assert self.spec.path is not None
return self.spec.path / "manifest" / f"{stamp}.json"
def preflight(self) -> tuple[bool, str | None]:
try:
assert self.spec.path is not None
self.spec.path.mkdir(parents=True, exist_ok=True)
(self.spec.path / "manifest").mkdir(exist_ok=True)
test = self.spec.path / ".safekeep_write_test"
test.write_text("ok", encoding="utf-8")
test.unlink()
except Exception as exc:
return False, str(exc)
# Only attempt to copy NTFS security if the destination can actually
# accept owners/ACLs (a NAS or FAT/exFAT volume cannot -> Error 1307,
# which aborts the copy). Probe once with a throwaway file.
if self.cfg.copy_security:
self.supports_security = self._probe_security()
if not self.supports_security:
log.warning(
"destination '%s' does not support NTFS security/owner; "
"copying data only (turn off 'Copy security/ACLs' to silence).",
self.spec.name,
)
else:
self.supports_security = False
return True, None
def _probe_security(self) -> bool:
"""Return True if a tiny /COPY:DATS copy into this destination succeeds."""
import tempfile
src_dir = Path(tempfile.mkdtemp(prefix="skprobe_"))
dest_probe = self.root() / ".safekeep_probe"
try:
(src_dir / "probe.bin").write_bytes(b"safekeep")
dest_probe.mkdir(exist_ok=True)
args = ["robocopy", str(src_dir), str(dest_probe), "probe.bin",
"/COPY:DATS", "/R:0", "/W:0", "/NJH", "/NJS", "/NP", "/NFL", "/NDL"]
cp = subprocess.run(args, capture_output=True, text=True,
encoding="utf-8", errors="replace",
creationflags=_NO_WINDOW)
out = (cp.stdout or "") + (cp.stderr or "")
return cp.returncode < 8 and "ERROR 1307" not in out and "Access is denied" not in out
except Exception:
return False
finally:
rmtree(dest_probe)
rmtree(src_dir)
def root(self) -> Path:
assert self.spec.path is not None
return self.spec.path
def list_snapshots(self) -> list[str]:
root = self.snapshots_root()
if not root.exists():
return []
out = [
p.name
for p in root.iterdir()
if p.is_dir() and not p.name.endswith(".partial")
]
return sorted(out)
def recover_partials(self) -> None:
"""Finalise complete-but-unrenamed partials; drop incomplete ones.
A partial with a .safekeep_complete marker had all its data copied and
only failed the final rename (e.g. a transient SMB error) - recover it
into a real snapshot. A partial without the marker was interrupted
mid-copy and is incomplete - remove it.
"""
root = self.snapshots_root()
if not root.exists():
return
for p in root.iterdir():
if not (p.is_dir() and p.name.endswith(".partial")):
continue
stamp = p.name[: -len(".partial")]
if (p / ".safekeep_complete").exists():
target = self.snapshot_dir(stamp)
if target.exists():
target = self.snapshot_dir(stamp + "_recovered")
log.info("recovering complete partial snapshot: %s", p.name)
try:
safe_rename(p, target)
except OSError as exc:
log.warning("could not finalise partial %s: %s (will retry next run)",
p.name, exc)
else:
log.info("removing incomplete partial snapshot: %s", p.name)
rmtree(p)
def create_snapshot(self, stamp, sources, prev_stamp, dry_run=False, progress=None):
new_dir = self.snapshot_dir(stamp + ".partial")
prev_dir = self.snapshot_dir(prev_stamp) if prev_stamp else None
stats = []
if not dry_run:
new_dir.mkdir(parents=True, exist_ok=True)
for sc in sources:
s = self._copy_source(sc, new_dir, prev_dir, dry_run, progress)
s["label"] = sc.spec.label
s["source"] = str(sc.spec.path)
stats.append(s)
if not dry_run:
# Mark complete BEFORE the rename. If the rename fails, this lets the
# next run recover the fully-copied partial instead of deleting it.
(new_dir / ".safekeep_complete").write_text("ok", encoding="utf-8")
final = self.snapshot_dir(stamp)
if final.exists(): # same-second collision; rename away
final = self.snapshot_dir(stamp + "_2")
safe_rename(new_dir, final) # retried - SMB renames can fail transiently
try:
(final / ".safekeep_complete").unlink() # tidy: marker not needed once final
except OSError:
pass
return stats
def _copy_source(self, sc, new_dir, prev_dir, dry_run, progress=None):
label = sc.spec.label
total = len(sc.files)
label_dir = new_dir / sc.spec.label
st = {
"files": total,
"bytes": sum(f.size for f in sc.files),
"hardlinked": 0,
"copied": 0,
"robocopy_rc": None,
"errors": [],
}
if dry_run or not sc.files:
st["robocopy_rc"] = 0 if dry_run else None
return st
label_dir.mkdir(parents=True, exist_ok=True)
# 1) hardlink pass: unchanged files (same size+mtime vs previous snapshot)
if self.cfg.use_hardlinks and prev_dir is not None:
prev_label = prev_dir / sc.spec.label
_progress(progress, "hardlink", 0.0, f"Linking unchanged files in '{label}'…")
for fe in sc.files:
prev_file = prev_label / fe.rel
if not prev_file.exists():
continue
try:
ps = prev_file.stat()
except OSError:
continue
if ps.st_size != fe.size or int(ps.st_mtime) != fe.mtime:
continue # changed since previous snapshot -> let robocopy copy
dst = label_dir / fe.rel
try:
dst.parent.mkdir(parents=True, exist_ok=True)
if dst.exists() or dst.is_symlink():
dst.unlink()
os.link(prev_file, dst)
st["hardlinked"] += 1
if progress is not None and st["hardlinked"] % 2000 == 0:
_progress(progress, "hardlink", st["hardlinked"] / total,
f"Linking '{label}'… {st['hardlinked']:,}/{total:,}")
except OSError as exc:
# hardlink not supported here, or transient error -> robocopy will copy
log.debug("hardlink failed %s: %s", dst, exc)
if progress is not None:
_progress(progress, "hardlink", 1.0,
f"Linked {st['hardlinked']:,} unchanged file(s) in '{label}'")
# 2) robocopy pass: copies new/changed files; skips identical (incl. hardlinks)
expected = max(total - st["hardlinked"], 1)
_progress(progress, "copy", 0.0,
f"Copying changed/new files in '{label}'…"
if expected > 1 else f"Syncing '{label}'…")
rc, copied, perm_errors, admin_err = self._robocopy(
sc.spec.path, label_dir, sc.spec.exclude,
progress=progress, label=label, expected=expected,
use_backup=self.cfg.backup_mode, use_restartable=self.cfg.restartable)
# /B (backup mode) without admin rights makes robocopy fail entirely (rc=16).
# Retry once without it so the run still succeeds instead of copying nothing.
if rc >= 16 and admin_err and self.cfg.backup_mode:
log.warning("backup mode (/B) needs administrator rights - retrying '%s' "
"without backup mode.", label)
_progress(progress, "copy", 0.0, f"Retrying '{label}' without backup mode…")
rc, copied, perm_errors, admin_err = self._robocopy(
sc.spec.path, label_dir, sc.spec.exclude,
progress=progress, label=label, expected=expected,
use_backup=False, use_restartable=self.cfg.restartable)
st["robocopy_rc"] = rc
st["copied"] = copied
st["skipped"] = perm_errors
if rc is None or rc >= 16:
st["errors"].append(f"robocopy exit code {rc}")
elif rc >= 8:
# some files/dirs failed to copy - almost always permission/security errors
if self.cfg.ignore_access_errors:
if perm_errors:
log.warning("'%s': %d file/dir(s) skipped due to permission/security "
"errors (treated as warning).", label, perm_errors)
else:
st["errors"].append(f"robocopy exit code {rc} ({perm_errors} permission errors)")
if progress is not None:
_progress(progress, "copy", 1.0, f"Finished '{label}'")
return st
def _robocopy(self, source: Path, dest: Path, excludes: list[str],
progress=None, label: str = "", expected: int = 0,
use_backup: bool | None = None, use_restartable: bool | None = None):
"""Run robocopy, streaming its output for live progress.
Returns (exit_code, copied_file_count, permission_error_count, admin_error).
admin_error is True when /B was requested but the process lacks Backup rights.
"""
if use_backup is None:
use_backup = self.cfg.backup_mode
if use_restartable is None:
use_restartable = self.cfg.restartable
if shutil.which("robocopy") is None:
log.error("robocopy not found on PATH - cannot copy")
return 16, 0, 0, False
want_sec = bool(self.cfg.copy_security and self.supports_security)
copyflags = "DATS" if want_sec else "DAT"
leaves = _excl_leaves(excludes)
args = [
"robocopy",
str(source),
str(dest),
"/E",
f"/COPY:{copyflags}",
"/DCOPY:DAT",
"/R:2",
"/W:5",
"/MT:8",
"/NP",
"/NJH",
]
# permission / access modes (backup mode needs admin / Backup rights)
if use_backup and use_restartable:
args.append("/ZB")
elif use_backup:
args.append("/B")
elif use_restartable:
args.append("/Z")
if leaves:
args += ["/XD", *leaves, "/XF", *leaves]
# No /NFL or /NDL: we read file/dir lines as they arrive for live progress.
copied = 0
perm_errors = 0
admin_error = False
last_report = 0.0
tail: list[str] = []
try:
proc = subprocess.Popen(
args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding="utf-8", errors="replace", bufsize=1,
creationflags=_NO_WINDOW,
)
except Exception as exc:
log.error("robocopy launch failed: %s", exc)
return 16, 0, 0, False
assert proc.stdout is not None
for line in proc.stdout:
line = line.rstrip("\r\n")
if not line:
continue
tail.append(line)
if len(tail) > 40:
tail.pop(0)
low = line.lower()
if "backup and restore files user rights" in low:
admin_error = True
continue
if ("error 1307" in low) or ("error 5 " in low) or ("access is denied" in low):
perm_errors += 1
continue
parsed = _parse_robocopy_line(line)
if parsed is None:
continue
kind, name = parsed
if kind in _ROBOCOPY_FILE_ACTIONS:
copied += 1
now = time.time()
if progress is not None and (copied % 25 == 0 or now - last_report > 0.5):
last_report = now
frac = min(copied / expected, 0.999) if expected else 0.0
short = name if len(name) <= 70 else "…" + name[-69:]
_progress(progress, "copy", frac,
f"Copying '{label}': {copied:,} {short}")
proc.wait()
rc = proc.returncode
if rc >= 16:
log.error("robocopy serious failure (rc=%d) for %s", rc, source)
log.debug("robocopy tail:\n%s", "\n".join(tail))
elif rc >= 8:
log.debug("robocopy %s rc=%d (copied %d, permission errors %d)",
source, rc, copied, perm_errors)
else:
log.debug("robocopy %s -> %s rc=%d (copied %d)", source, dest, rc, copied)
return rc, copied, perm_errors, admin_error
def delete_snapshot(self, stamp):
d = self.snapshot_dir(stamp)
rmtree(d)
try:
self.manifest_path(stamp).unlink()
except FileNotFoundError:
pass
def write_manifest(self, stamp, manifest):
try:
self.manifest_path(stamp).parent.mkdir(parents=True, exist_ok=True)
self.manifest_path(stamp).write_text(
json.dumps(manifest, indent=2, default=str), encoding="utf-8"
)
except Exception as exc:
log.warning("could not write manifest for %s: %s", stamp, exc)
# ----- verify / restore (local) -----
def verify_against_sources(self, sources, snapshot, use_hash=False) -> int:
problems = 0
for s in sources:
snap_label = self.snapshot_dir(snapshot) / s.label
if not snap_label.exists():
log.error("source '%s' missing from snapshot", s.label)
problems += 1
continue
live = {f.rel: f for f in scan_source(s)}
snap_files = {}
for dp, _dirs, fns in os.walk(snap_label):
rel_dir = Path(dp).relative_to(snap_label).as_posix()
for fn in fns:
rf = f"{rel_dir}/{fn}" if rel_dir != "." else fn
full = Path(dp) / fn
try:
stt = full.stat()
except OSError:
continue
snap_files[rf] = (full, stt.st_size, int(stt.st_mtime))
missing = [r for r in live if r not in snap_files]
mismatch = []
for r, fe in live.items():
if r in snap_files:
_full, size, mtime = snap_files[r]
if size != fe.size or mtime != fe.mtime:
if use_hash:
if _hash(fe.path) != _hash(_full):
mismatch.append(r)
else:
mismatch.append(r)
log.info("'%s': %d in source, %d in snapshot | missing=%d mismatch=%d",
s.label, len(live), len(snap_files), len(missing), len(mismatch))
for r in missing[:10]:
log.warning(" missing from snapshot: %s", r)
for r in mismatch[:10]:
log.warning(" differs: %s", r)
problems += len(missing) + len(mismatch)
return problems
def restore(self, snapshot, label, to_path, assume_yes=False) -> int:
src_dir = self.snapshot_dir(snapshot) / label
if not src_dir.exists():
log.error("source '%s' not found in snapshot %s", label, snapshot)
return 1
to = Path(to_path).expanduser()
to.mkdir(parents=True, exist_ok=True)
if not assume_yes:
if input(f"Restore '{label}' from {snapshot} into {to}? [y/N] ").strip().lower() != "y":
print("aborted")
return 1
if shutil.which("robocopy") is None:
log.error("robocopy not found")
return 1
log.info("restoring %s -> %s", src_dir, to)
cp = subprocess.run(
["robocopy", str(src_dir), str(to), "/E", "/COPY:DAT", "/DCOPY:DAT",
"/R:2", "/W:5", "/NFL", "/NDL", "/NP", "/NJH"],
capture_output=True, text=True, encoding="utf-8", errors="replace",
creationflags=_NO_WINDOW,
)
log.info("robocopy rc=%d", cp.returncode)
return 0 if cp.returncode < 8 else 1
# --------------------------------------------------------------------------- #
# rclone (cloud) destination - Google Drive, S3, B2, OneDrive, Dropbox, ...
# --------------------------------------------------------------------------- #
def _try_json(line: str):
try:
return json.loads(line)
except Exception:
return None
def _rclone_exclude(pattern: str) -> str:
"""Convert a SafeKeep glob exclude into an rclone --exclude pattern."""
p = pattern.replace("\\", "/")
if p.startswith("**/"):
p = p[3:]
if "/" in p:
return f"{p}/**" # path-style (e.g. .git/objects) -> exclude its contents
return p # bare name -> matches at any depth in rclone
def _run_cmd(args, timeout=None):
"""Run a command quietly (no window); return CompletedProcess (never raises)."""
try:
return subprocess.run(args, capture_output=True, text=True,
encoding="utf-8", errors="replace",
creationflags=_NO_WINDOW, timeout=timeout)
except FileNotFoundError:
return subprocess.CompletedProcess(args, 127, "", "command not found")
except Exception as exc:
return subprocess.CompletedProcess(args, 1, "", str(exc))
def _run_rclone(args, progress=None, label=""):
"""Run rclone, streaming JSON log lines for progress. Returns (rc, copied)."""
copied = 0
last = 0.0
try:
proc = subprocess.Popen(
args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding="utf-8", errors="replace", bufsize=1,
creationflags=_NO_WINDOW,
)
except Exception as exc:
log.error("rclone launch failed: %s", exc)
return 16, 0
assert proc.stdout is not None
for line in proc.stdout:
line = line.strip()
if not line:
continue
obj = _try_json(line)
if isinstance(obj, dict) and isinstance(obj.get("stats"), dict):
st = obj["stats"]
tr = st.get("transfers", 0) or 0
tot = st.get("totalTransfers", 0) or 0
b = st.get("bytes", 0) or 0
tb = st.get("totalBytes", 0) or 0
copied = max(copied, tr)
now = time.time()
if progress is not None and now - last > 1.0:
last = now
frac = (tr / tot) if tot else ((b / tb) if tb else None)
_progress(progress, "copy", frac,
f"Cloud '{label}': {tr}/{tot} files, "
f"{_human_bytes(b)}/{_human_bytes(tb)}")
elif isinstance(obj, dict) and obj.get("level") in ("error", "warning"):
log.log(log.ERROR if obj.get("level") == "error" else log.WARNING,
"rclone: %s", obj.get("message", line))
proc.wait()
return proc.returncode, copied
class RcloneDestination(Destination):
"""Cloud destination via rclone.
Snapshots live at <remote>/snapshots/<stamp>/<label>/... . Unchanged files
are deduplicated against the previous snapshot using rclone's --copy-dest
(a server-side copy where the provider supports it), so each run uploads
only new/changed files. Requires rclone installed and a configured remote
(run `rclone config`), e.g. remote = "gdrive:backups/safekeep".
"""
type = "rclone"
def _remote(self, *parts) -> str:
base = self.spec.remote or ""
return "/".join([base, *parts])
def preflight(self) -> tuple[bool, str | None]:
if shutil.which("rclone") is None:
return (False, "rclone is not installed or not on PATH. Install it "
"from https://rclone.org and configure a remote with "
"'rclone config'.")
if not self.spec.remote:
return False, "no rclone 'remote' configured for this destination."
# mkdir is idempotent and confirms the remote is reachable + writable
cp = _run_cmd(["rclone", "mkdir", self.spec.remote], timeout=120)
if cp.returncode != 0:
tail = " ".join((cp.stderr or cp.stdout or "").strip().splitlines()[-1:])
return False, f"rclone remote '{self.spec.remote}' not reachable: {tail}"
return True, None
def list_snapshots(self) -> list[str]:
cp = _run_cmd(["rclone", "lsf", self._remote("snapshots") + "/", "--dirs-only"])
if cp.returncode != 0:
return []
return sorted(
ln.strip("/").strip() for ln in cp.stdout.splitlines()
if ln.strip() and not ln.strip().startswith(".")
)
def create_snapshot(self, stamp, sources, prev_stamp, dry_run=False, progress=None):
stats = []
for sc in sources:
s = self._copy_source(sc, stamp, prev_stamp, dry_run, progress)
s["label"] = sc.spec.label
s["source"] = str(sc.spec.path)