#!/usr/bin/env python3 """Incremental, scheduled filesystem backup manager.""" from __future__ import annotations import argparse import fnmatch import hashlib import json import logging import os import re import shutil import sqlite3 import sys import time from datetime import datetime, timedelta from pathlib import Path from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple SNAPSHOT_FMT = "%Y-%m-%d_%H%M%S" COPY = "copied" LINK = "linked" UNCHANGED = "unchanged" DEFAULT_CONFIG = "backup_config.json" log = logging.getLogger("backup_manager") def expand_path(value: str, base: Optional[Path] = None) -> Path: expanded = os.path.expandvars(os.path.expanduser(value)) path = Path(expanded) if not path.is_absolute() and base is not None: path = (base / path).resolve() return path class CronExpression: """Minimal standard cron matcher (minute hour day month weekday).""" FIELDS = (("minute", 0, 59), ("hour", 0, 23), ("dom", 1, 31), ("month", 1, 12), ("dow", 0, 6)) def __init__(self, expr: str): parts = expr.split() if len(parts) != 5: raise ValueError(f"cron expression needs 5 fields: {expr!r}") parsed = {} for (name, low, high), field in zip(self.FIELDS, parts): parsed[name] = (field, self._parse_field(field, low, high)) self.minute = parsed["minute"][1] self.hour = parsed["hour"][1] self.dom = parsed["dom"][1] self.month = parsed["month"][1] self.dow = parsed["dow"][1] self.dom_star = parts[2].strip() == "*" self.dow_star = parts[4].strip() == "*" self.expression = expr @staticmethod def _parse_field(field: str, low: int, high: int) -> Set[int]: values: Set[int] = set() for chunk in field.split(","): chunk = chunk.strip() if not chunk: raise ValueError("empty cron field") step = 1 if "/" in chunk: chunk, step_str = chunk.split("/", 1) step = int(step_str) if step < 1: raise ValueError("cron step must be >= 1") if chunk in ("*", ""): start, end = low, high elif "-" in chunk: start_str, end_str = chunk.split("-", 1) start, end = int(start_str), int(end_str) else: start = end = int(chunk) if start < low or end > high or start > end: raise ValueError(f"cron value out of range {low}-{high}: {chunk}") values.update(range(start, end + 1, step)) if not values: raise ValueError("empty cron field") return values def matches(self, when: datetime) -> bool: if when.minute not in self.minute or when.hour not in self.hour: return False if when.month not in self.month: return False dom_match = when.day in self.dom dow_match = ((when.weekday() + 1) % 7) in self.dow if self.dom_star and self.dow_star: day_match = True elif self.dom_star: day_match = dow_match elif self.dow_star: day_match = dom_match else: day_match = dom_match or dow_match return day_match def parse_schedule_md(path: Path) -> CronExpression: """Read a cron expression from a markdown file (line containing 'cron').""" if not path.is_file(): raise FileNotFoundError(f"schedule file not found: {path}") for line in path.read_text(encoding="utf-8").splitlines(): if not re.search(r"\bcron\b", line, re.IGNORECASE): continue ticked = re.findall(r"`([^`]+)`", line) if ticked: candidate = ticked[0].strip() else: parts = re.split(r"[:=]", line, maxsplit=1) if len(parts) < 2: continue candidate = parts[1].strip().strip("*`").strip() candidate = " ".join(candidate.split()) if len(candidate.split()) == 5: return CronExpression(candidate) raise ValueError(f"no 'cron:' schedule found in {path}") class StateDB: """SQLite store of last seen (size, mtime, checksum) per source file.""" def __init__(self, path: Path): path.parent.mkdir(parents=True, exist_ok=True) self.conn = sqlite3.connect(str(path)) self.conn.execute( """CREATE TABLE IF NOT EXISTS files ( source TEXT NOT NULL, relpath TEXT NOT NULL, size INTEGER NOT NULL, mtime REAL NOT NULL, sha256 TEXT NOT NULL, PRIMARY KEY (source, relpath) )""" ) self.conn.commit() def get(self, source: str, relpath: str) -> Optional[Tuple[int, float, str]]: row = self.conn.execute( "SELECT size, mtime, sha256 FROM files WHERE source=? AND relpath=?", (source, relpath), ).fetchone() return row def upsert(self, source: str, relpath: str, size: int, mtime: float, sha256: str) -> None: self.conn.execute( """INSERT INTO files (source, relpath, size, mtime, sha256) VALUES (?, ?, ?, ?, ?) ON CONFLICT(source, relpath) DO UPDATE SET size=excluded.size, mtime=excluded.mtime, sha256=excluded.sha256""", (source, relpath, size, mtime, sha256), ) def delete_missing(self, source: str, present: Set[str]) -> int: removed = 0 rows = self.conn.execute("SELECT relpath FROM files WHERE source=?", (source,)).fetchall() for (relpath,) in rows: if relpath not in present: self.conn.execute("DELETE FROM files WHERE source=? AND relpath=?", (source, relpath)) removed += 1 return removed def commit(self) -> None: self.conn.commit() def close(self) -> None: self.conn.close() def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str: digest = hashlib.sha256() with open(path, "rb") as handle: for block in iter(lambda: handle.read(chunk_size), b""): digest.update(block) return digest.hexdigest() def is_excluded(relpath: Path, patterns: Sequence[str]) -> bool: parts = relpath.parts text = relpath.as_posix() for pattern in patterns: if any(fnmatch.fnmatch(part, pattern) for part in parts): return True if fnmatch.fnmatch(text, pattern): return True return False def iter_files(root: Path, excludes: Sequence[str], follow_symlinks: bool = False ) -> Iterable[Tuple[Path, Path]]: for dirpath, dirnames, filenames in os.walk(root, followlinks=follow_symlinks): current = Path(dirpath) rel_dir = current.relative_to(root) dirnames[:] = [d for d in dirnames if not is_excluded(rel_dir / d, excludes)] for name in filenames: relpath = rel_dir / name if is_excluded(relpath, excludes): continue full = current / name if full.is_symlink() and not follow_symlinks: continue if full.is_file(): yield relpath, full def load_config(path: Path) -> dict: if not path.is_file(): raise FileNotFoundError(f"config file not found: {path}") with open(path, "r", encoding="utf-8") as handle: return json.load(handle) def _resolve(config: dict, config_dir: Path) -> dict: resolved = dict(config) resolved["destination"] = expand_path(config.get("destination", "backups"), config_dir) resolved["state_db"] = expand_path(config.get("state_db", "backup_state.db"), config_dir) resolved["schedule_file"] = expand_path(config.get("schedule_file", "schedule.md"), config_dir) if config.get("log_file"): resolved["log_file"] = expand_path(config["log_file"], config_dir) return resolved def find_latest_snapshot(destination: Path) -> Optional[Path]: if not destination.is_dir(): return None latest, latest_dt = None, None for entry in destination.iterdir(): if not entry.is_dir(): continue try: dt = datetime.strptime(entry.name, SNAPSHOT_FMT) except ValueError: continue if latest_dt is None or dt > latest_dt: latest, latest_dt = entry, dt return latest def _link_or_copy(previous: Optional[Path], source: Path, target: Path) -> str: if previous is not None and previous.is_file(): try: os.link(str(previous), str(target)) return LINK except OSError: pass shutil.copy2(source, target) return COPY def perform_backup(config: dict, dry_run: bool = False, now: Optional[datetime] = None) -> Optional[Path]: destination = Path(config["destination"]) state = StateDB(Path(config["state_db"])) follow = bool(config.get("follow_symlinks", False)) retention = int(config.get("retention_days", 14)) now = now or datetime.now() previous = find_latest_snapshot(destination) timestamp = now.strftime(SNAPSHOT_FMT) snapshot = destination / timestamp manifest: Dict[str, object] = { "timestamp": timestamp, "created": now.isoformat(timespec="seconds"), "previous": previous.name if previous else None, "sources": [], } stats = {COPY: 0, LINK: 0} total_bytes = 0 if not dry_run: snapshot.mkdir(parents=True, exist_ok=True) try: for index, source_cfg in enumerate(config.get("sources", [])): source_path = expand_path(source_cfg["path"]) label = source_cfg.get("name") or f"{source_path.name or 'source'}" if any(s["label"] == label for s in manifest["sources"]): label = f"{label}_{index}" excludes = source_cfg.get("exclude", []) if not source_path.is_dir(): log.warning("source missing, skipping: %s", source_path) manifest["sources"].append( {"label": label, "path": str(source_path), "missing": True, "files": []} ) continue source_key = str(source_path) present: Set[str] = set() entries: List[dict] = [] for relpath, full in iter_files(source_path, excludes, follow): rel = relpath.as_posix() present.add(rel) stat = full.stat() size = stat.st_size mtime = stat.st_mtime cached = state.get(source_key, rel) if cached and cached[0] == size and abs(cached[1] - mtime) < 1e-6: changed, digest = False, cached[2] else: digest = sha256_file(full) changed = not (cached and cached[2] == digest and cached[0] == size) target = snapshot / label / relpath if changed: if not dry_run: target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(full, target) action = COPY else: if not dry_run: target.parent.mkdir(parents=True, exist_ok=True) action = _link_or_copy(previous / label / relpath if previous else None, full, target) else: action = UNCHANGED if not dry_run: state.upsert(source_key, rel, size, mtime, digest) if action in stats: stats[action] += 1 total_bytes += size entries.append({ "relpath": rel, "size": size, "mtime": mtime, "sha256": digest, "action": action, }) removed = 0 if dry_run else state.delete_missing(source_key, present) manifest["sources"].append({ "label": label, "path": source_key, "files": entries, "removed": removed, }) log.info("source %s: %d files (%s)", label, len(entries), source_path) manifest["stats"] = dict(stats) manifest["total_bytes"] = total_bytes if not dry_run: (snapshot / "manifest.json").write_text( json.dumps(manifest, indent=2), encoding="utf-8" ) state.commit() rotate(destination, retention, now) log.info("snapshot %s: %d copied, %d linked, %.2f MiB", timestamp, stats[COPY], stats[LINK], total_bytes / 1024 / 1024) finally: state.close() return snapshot def rotate(destination: Path, retention_days: int, now: Optional[datetime] = None) -> List[str]: if not destination.is_dir(): return [] cutoff = (now or datetime.now()) - timedelta(days=retention_days) removed: List[str] = [] for entry in destination.iterdir(): if not entry.is_dir(): continue try: dt = datetime.strptime(entry.name, SNAPSHOT_FMT) except ValueError: continue if dt < cutoff: shutil.rmtree(entry, ignore_errors=True) removed.append(entry.name) log.info("rotated out old snapshot: %s", entry.name) return removed def list_snapshots(config: dict) -> None: destination = Path(config["destination"]) snapshots = sorted( (e for e in destination.iterdir() if e.is_dir() and _is_snapshot(e)) if destination.is_dir() else [], key=lambda p: p.name ) if not snapshots: print(f"no snapshots in {destination}") return for snap in snapshots: size = sum(f.stat().st_size for f in snap.rglob("*") if f.is_file()) files = sum(1 for f in snap.rglob("*") if f.is_file()) print(f"{snap.name} {files:>6} files {size / 1024 / 1024:>10.2f} MiB") def _is_snapshot(path: Path) -> bool: try: datetime.strptime(path.name, SNAPSHOT_FMT) return True except ValueError: return False def verify_snapshot(config: dict, name: Optional[str]) -> int: destination = Path(config["destination"]) snapshot = destination / name if name else find_latest_snapshot(destination) if snapshot is None or not snapshot.is_dir(): print("no snapshot to verify", file=sys.stderr) return 2 manifest_path = snapshot / "manifest.json" if not manifest_path.is_file(): print(f"manifest missing: {manifest_path}", file=sys.stderr) return 2 manifest = json.loads(manifest_path.read_text(encoding="utf-8")) errors = 0 for source in manifest.get("sources", []): label = source["label"] for entry in source.get("files", []): target = snapshot / label / entry["relpath"] if not target.is_file(): print(f"MISSING {target}", file=sys.stderr) errors += 1 continue if sha256_file(target) != entry["sha256"]: print(f"CORRUPT {target}", file=sys.stderr) errors += 1 if errors: print(f"verify FAILED: {errors} problem(s) in {snapshot.name}", file=sys.stderr) return 1 print(f"verify OK: {snapshot.name}") return 0 def setup_logging(config: dict, verbose: bool = False) -> None: level = logging.DEBUG if verbose else logging.INFO handlers: List[logging.Handler] = [logging.StreamHandler(sys.stdout)] log_file = config.get("log_file") if log_file: handlers.append(logging.FileHandler(str(log_file), encoding="utf-8")) logging.basicConfig( level=level, format="%(asctime)s %(levelname)s %(message)s", handlers=handlers, force=True, ) def watch(config: dict) -> int: schedule = parse_schedule_md(Path(config["schedule_file"])) log.info("watching schedule %r (%s)", schedule.expression, config["schedule_file"]) last_minute: Optional[datetime] = None while True: now = datetime.now() minute = now.replace(second=0, microsecond=0) if schedule.matches(now) and minute != last_minute: try: perform_backup(config) except Exception: log.exception("scheduled backup failed") last_minute = minute time.sleep(20) def write_defaults(config_path: Path, force: bool = False) -> None: if config_path.exists() and not force: log.info("config already exists: %s", config_path) else: template = { "sources": [ {"name": "documents", "path": "~/Documents", "exclude": [".git", "node_modules", "*.tmp", "__pycache__"]} ], "destination": "backups", "retention_days": 14, "schedule_file": "schedule.md", "state_db": "backup_state.db", "log_file": "backup_manager.log", "follow_symlinks": False, } config_path.write_text(json.dumps(template, indent=2), encoding="utf-8") log.info("wrote default config: %s", config_path) schedule_path = config_path.parent / "schedule.md" if not schedule_path.exists() or force: schedule_path.write_text( "# Backup Schedule\n\n" "## Schedule\n\n" "- **cron:** `0 3 * * *`\n", encoding="utf-8", ) log.info("wrote schedule file: %s", schedule_path) def build_parser() -> argparse.ArgumentParser: common = argparse.ArgumentParser(add_help=False) common.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})") common.add_argument("-v", "--verbose", action="store_true", help="debug logging") parser = argparse.ArgumentParser(description="Incremental scheduled backups") sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("init", parents=[common], help="write a default config and schedule" ).add_argument("--force", action="store_true", help="overwrite existing files") run = sub.add_parser("run", parents=[common], help="perform a single backup") run.add_argument("--dry-run", action="store_true", help="scan without writing") sub.add_parser("watch", parents=[common], help="run continuously following the md schedule") sub.add_parser("list", parents=[common], help="list snapshots") verify = sub.add_parser("verify", parents=[common], help="verify snapshot integrity") verify.add_argument("snapshot", nargs="?", help="snapshot name (default: latest)") return parser def main(argv: Optional[Sequence[str]] = None) -> int: args = build_parser().parse_args(argv) config_path = expand_path(args.config, Path.cwd()) if args.command == "init": setup_logging({"log_file": None}, args.verbose) write_defaults(config_path, args.force) return 0 config = _resolve(load_config(config_path), config_path.parent) setup_logging(config, args.verbose) if args.command == "run": perform_backup(config, dry_run=args.dry_run) return 0 if args.command == "watch": return watch(config) if args.command == "list": list_snapshots(config) return 0 if args.command == "verify": return verify_snapshot(config, args.snapshot) return 1 if __name__ == "__main__": sys.exit(main())