Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_backup_schedule.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_backup_schedule.py · 60.2 KB · 1415 lines
1"""Scheduled backups that leave the box, and the restore test that proves them.
2
3Losing data is the one failure this server cannot apologise for. Before
4this module there were restore points before package upgrades and a backup
5CLI, and both wrote into the data directory's own disk: a dead disk or a
6deleted VM took the backups with it, and nothing had ever shown that any
7archive restored. This module is the other half, and it is OFF until an
8operator names a destination (DBBASIC_BACKUP_DESTINATION).
9
10What one run does (`run_backup`, driven by object_daemon on an interval,
11or by `POST /admin/backups/scheduled` / `python -m object_backup_schedule
12run`):
13
141. **Refuses a destination that cannot be a backup.** Inside (or
15 containing) the data or objects directory, missing, or not writable:
16 each is refused by name before anything is written. A destination that
17 does not exist is NOT created, because the classic way this fails is an
18 unmounted disk: the mount point is an empty directory on the root disk,
19 and a backup that "succeeds" into it never left the box.
202. **Writes a snapshot directory**, `dbbasic-snapshot-<UTC timestamp>/`,
21 holding `objects/`, `data/...` and `manifest.json`, staged under a
22 `.partial-` name and renamed only when complete, so a crash leaves
23 something that is visibly not a backup (and is swept next run).
243. **Hard-links unchanged files to the previous snapshot** (rsync's
25 --link-dest, with stdlib os.link). See "Why a directory of hard links".
264. **Prunes its own old snapshots** to DBBASIC_BACKUP_KEEP.
275. **Restore-tests the snapshot it just wrote** into a throwaway temp
28 directory (see `restore_test`), and records the outcome.
296. **Optionally runs DBBASIC_BACKUP_AFTER_COMMAND** with the snapshot
30 path, the hook for encryption or shipping (see "Encryption").
31
32Status (last backup, last restore test, problems) is a small JSON file in
33the data directory, `.backup_status.json`, read by /admin/status, the
34system dashboard's attention provider and the daemon's log line.
35
36**Why a directory of hard links and not a tar.gz.** The existing archive
37format (object_backup) re-reads and re-compresses every byte on every run,
38so a box with 40GB of uploaded files writes 40GB to the destination each
39night and keeping a week of them costs 280GB. A snapshot directory lets an
40unchanged file be a hard link to the same file in the previous snapshot:
41each run writes only what changed, every snapshot is still a complete,
42plain tree a person can `cp -a` back, and deleting an old snapshot frees
43only what no newer one shares. It is the rsync --link-dest / Time Machine
44design, it needs nothing outside the standard library, and it works on
45any POSIX filesystem including NFS. Where links are not supported (some
46SMB mounts, a FAT disk) os.link fails and the file is simply copied: the
47run is slower and bigger, never wrong.
48
49"Unchanged" is decided by the LIVE file's (inode, size, mtime_ns) matching
50what the previous manifest recorded, the way rsync's quick check does.
51The server writes collections by atomic rename (a new inode) or by
52append (a new size), so either kind of write defeats the match. Links are
53taken only from a previous snapshot whose own restore test PASSED: a file
54that rotted at the destination would otherwise be linked forward forever,
55so a failed restore test makes the next run a full copy.
56
57**Consistency.** A collection's records.tsv and its change log
58(record_changes/<name>/changes.jsonl) are captured as a pair under that
59collection's own write lock (object_records._records_file_lock, the lock
60every record writer holds while it writes both), so the table and its
61audit trail in a snapshot agree to the row. The lock is held only to open
62the two files and note their sizes; the copy then reads that many bytes
63from the open descriptors after the lock is released. That is exact for
64both storage modes: a classic rewrite renames a new file into place and
65the open descriptor keeps the old one; an append only adds bytes past the
66noted size. Every other file is copied from an open descriptor up to the
67size it had when opened, which is the same "whole old version or whole new
68version" the server's atomic writes already give any reader.
69
70What this does NOT give is one instant across the whole box: collection A
71is captured before collection B, so a write to both in between appears in
72B only. There is no global write barrier in this server to take, and
73inventing one for backups would stall every writer for the length of a
74copy. User file bytes are copied after the `files` records, so a file
75deleted mid-run can leave a record whose bytes are missing; the restore
76test names any such record as a warning (the same check object_backup's
77verify makes), rather than pretending the snapshot is perfect.
78
79**Secrets.** Exactly what object_backup includes, no more: the same
80RUNTIME_DATA_DIRS and RUNTIME_DATA_FILES, the same skip rules. Identity
81contributes users.tsv and accounts.tsv only; password hashes, sessions,
82API keys and third-party service keys stay on the box, as do the exchange
83private keys and environment files. A restored box knows its users, but
84nobody can sign in until credentials are re-issued. That is deliberate: a
85destination is by definition somewhere else -- a NAS, a synced folder --
86and the less it holds the less a stolen backup is worth.
87
88**Encryption.** The standard library has no AES, and this module does not
89invent cryptography. The destination should be an encrypted disk, or the
90tool that syncs it away should encrypt (restic, borg, rclone crypt).
91DBBASIC_BACKUP_AFTER_COMMAND is the clean hook for that: it runs (no
92shell, argv split with shlex) with the finished snapshot's path appended,
93only after the restore test passes, and a failure is recorded as a problem
94like any other.
95
96**Bounded.** Snapshots are bounded by DBBASIC_BACKUP_KEEP; the status
97file keeps the last HISTORY_LIMIT events; a restore test's temp directory
98is removed whether it passes or fails.
99"""
100from __future__ import annotations
101
102import argparse
103import hashlib
104import json
105import os
106import re
107import shlex
108import shutil
109import subprocess
110import sys
111import tempfile
112import threading
113import time
114from contextlib import contextmanager
115from datetime import datetime, timezone
116from pathlib import Path
117from typing import Any, Iterator, Mapping
118
119import object_backup
120
121DESTINATION_ENV = "DBBASIC_BACKUP_DESTINATION"
122INTERVAL_ENV = "DBBASIC_BACKUP_INTERVAL_SECONDS"
123KEEP_ENV = "DBBASIC_BACKUP_KEEP"
124RESTORE_TEST_DIR_ENV = "DBBASIC_BACKUP_RESTORE_TEST_DIR"
125AFTER_COMMAND_ENV = "DBBASIC_BACKUP_AFTER_COMMAND"
126
127DEFAULT_INTERVAL_SECONDS = 86400
128MIN_INTERVAL_SECONDS = 60
129DEFAULT_KEEP = 7
130MIN_KEEP = 2
131# A failed run is retried sooner than a full interval, but not on every
132# daemon tick: a destination that is down should not be hammered.
133RETRY_AFTER_FAILURE_SECONDS = 3600
134AFTER_COMMAND_TIMEOUT_SECONDS = 3600
135FINGERPRINT_TIMEOUT_SECONDS = 3600
136HISTORY_LIMIT = 30
137
138FORMAT_VERSION = 1
139SNAPSHOT_TYPE = "dbbasic-snapshot"
140SNAPSHOT_PREFIX = "dbbasic-snapshot-"
141PARTIAL_PREFIX = ".partial-"
142MANIFEST_NAME = "manifest.json"
143RESTORE_TEST_NAME = "restore-test.json"
144LOCK_NAME = ".dbbasic-backup.lock"
145STATUS_NAME = ".backup_status.json"
146SNAPSHOT_RE = re.compile(r"^dbbasic-snapshot-\d{8}T\d{12}Z$")
147PARTIAL_RE = re.compile(r"^\.partial-dbbasic-snapshot-\d{8}T\d{12}Z$")
148_COPY_CHUNK = 1024 * 1024
149
150_STATUS_LOCK = threading.Lock()
151_RUN_LOCK = threading.Lock()
152
153
154class BackupScheduleError(Exception):
155 """A backup or restore test was refused or could not complete."""
156
157
158# --- settings -----------------------------------------------------------------------
159
160
161def _env_int(env: Mapping[str, str], name: str, default: int, minimum: int) -> int:
162 raw = str(env.get(name, "") or "").strip()
163 if not raw:
164 return default
165 try:
166 return max(minimum, int(raw))
167 except ValueError:
168 return default
169
170
171def config(env: Mapping[str, str] | None = None) -> dict[str, Any]:
172 """The scheduled-backup settings, read from the environment."""
173 env = os.environ if env is None else env
174 destination = str(env.get(DESTINATION_ENV, "") or "").strip()
175 return {
176 "enabled": bool(destination),
177 "destination": destination or None,
178 "interval_seconds": _env_int(env, INTERVAL_ENV, DEFAULT_INTERVAL_SECONDS,
179 MIN_INTERVAL_SECONDS),
180 "keep": _env_int(env, KEEP_ENV, DEFAULT_KEEP, MIN_KEEP),
181 "restore_test_dir": str(env.get(RESTORE_TEST_DIR_ENV, "") or "").strip() or None,
182 "after_command": str(env.get(AFTER_COMMAND_ENV, "") or "").strip() or None,
183 "env": {
184 "destination": DESTINATION_ENV,
185 "interval_seconds": INTERVAL_ENV,
186 "keep": KEEP_ENV,
187 "restore_test_dir": RESTORE_TEST_DIR_ENV,
188 "after_command": AFTER_COMMAND_ENV,
189 },
190 }
191
192
193def _overlaps(a: Path, b: Path) -> bool:
194 a, b = a.resolve(strict=False), b.resolve(strict=False)
195 return a == b or a.is_relative_to(b) or b.is_relative_to(a)
196
197
198def destination_problems(destination: Path | str, *, data_dir: Path | str,
199 objects_dir: Path | str | None = None,
200 probe_write: bool = True) -> list[str]:
201 """Why this destination must be refused; empty when it may be used.
202
203 `probe_write` creates and removes a file to prove the destination is
204 writable (a run does this); status reads pass False and ask os.access,
205 so a dashboard polling every ten seconds does not write to a NAS.
206 """
207 dest = Path(destination)
208 problems: list[str] = []
209 if not dest.is_absolute():
210 problems.append(f"{DESTINATION_ENV} must be an absolute path")
211 for label, root in (("data directory", data_dir), ("objects directory", objects_dir)):
212 if root is not None and _overlaps(dest, Path(root)):
213 problems.append(
214 f"the backup destination overlaps the {label}; a backup must live "
215 "somewhere the box's own data does not")
216 if problems:
217 return problems
218 if not dest.is_dir():
219 return [f"the backup destination does not exist or is not a directory "
220 f"(is the disk mounted?); it is never created automatically"]
221 if not probe_write:
222 if not os.access(dest, os.W_OK | os.X_OK):
223 problems.append("the backup destination is not writable")
224 return problems
225 try:
226 handle, probe = tempfile.mkstemp(prefix=".dbbasic-write-check-", dir=dest)
227 os.close(handle)
228 os.unlink(probe)
229 except OSError as exc:
230 problems.append(f"the backup destination is not writable: {exc.strerror or exc}")
231 return problems
232
233
234def destination_warnings(destination: Path | str, *, data_dir: Path | str) -> list[str]:
235 try:
236 same = os.stat(destination).st_dev == os.stat(data_dir).st_dev
237 except OSError:
238 return []
239 if same:
240 return ["the backup destination is on the same filesystem as the data directory: "
241 "it does not leave the box unless something syncs it away"]
242 return []
243
244
245# --- snapshots on the destination ---------------------------------------------------
246
247
248def _utc_now() -> datetime:
249 return datetime.now(timezone.utc)
250
251
252def _iso(moment: datetime) -> str:
253 return moment.isoformat().replace("+00:00", "Z")
254
255
256def _parse_iso(value: Any) -> datetime | None:
257 text = str(value or "").strip().replace("Z", "+00:00")
258 if not text:
259 return None
260 try:
261 parsed = datetime.fromisoformat(text)
262 except ValueError:
263 return None
264 return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
265
266
267def list_snapshots(destination: Path | str) -> list[Path]:
268 """This module's completed snapshots at the destination, newest first.
269
270 Only directories named like ours AND holding a manifest that says it
271 is ours: retention deletes from this list, so anything else that lives
272 at the destination -- another tool's files, a hand-made copy -- is
273 invisible to it.
274 """
275 dest = Path(destination)
276 if not dest.is_dir():
277 return []
278 found = []
279 for entry in dest.iterdir():
280 if not SNAPSHOT_RE.fullmatch(entry.name) or entry.is_symlink() or not entry.is_dir():
281 continue
282 manifest = _read_json(entry / MANIFEST_NAME)
283 if isinstance(manifest, dict) and manifest.get("type") == SNAPSHOT_TYPE:
284 found.append(entry)
285 return sorted(found, key=lambda path: path.name, reverse=True)
286
287
288def _read_json(path: Path) -> Any:
289 try:
290 return json.loads(path.read_text(encoding="utf-8"))
291 except (OSError, ValueError):
292 return None
293
294
295def _write_json_atomic(path: Path, payload: Any, *, fsync: bool = False) -> None:
296 path.parent.mkdir(parents=True, exist_ok=True)
297 temp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
298 with temp.open("w", encoding="utf-8") as handle:
299 json.dump(payload, handle, indent=2, sort_keys=True)
300 handle.write("\n")
301 if fsync:
302 handle.flush()
303 os.fsync(handle.fileno())
304 os.replace(temp, path)
305
306
307def _restore_test_passed(snapshot: Path) -> bool:
308 result = _read_json(snapshot / RESTORE_TEST_NAME)
309 return isinstance(result, dict) and result.get("ok") is True
310
311
312@contextmanager
313def _destination_lock(destination: Path) -> Iterator[None]:
314 """One run per destination at a time, across processes (the daemon and
315 an HTTP-triggered run in a server worker may both try)."""
316 try:
317 import fcntl
318 except ImportError: # no flock: the in-process lock is all there is
319 fcntl = None
320 if not _RUN_LOCK.acquire(blocking=False):
321 raise BackupScheduleError("another backup or restore test is already running")
322 try:
323 with (destination / LOCK_NAME).open("a") as handle:
324 if fcntl is not None:
325 try:
326 fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
327 except OSError as exc:
328 raise BackupScheduleError(
329 "another backup or restore test is already running "
330 "against this destination") from exc
331 try:
332 yield
333 finally:
334 if fcntl is not None:
335 fcntl.flock(handle, fcntl.LOCK_UN)
336 finally:
337 _RUN_LOCK.release()
338
339
340# --- capture ------------------------------------------------------------------------
341
342
343def _copy_fd(source_fd: int, size: int, target: Path) -> str:
344 """Copy exactly `size` bytes from an open descriptor; return sha256."""
345 digest = hashlib.sha256()
346 remaining = size
347 target.parent.mkdir(parents=True, exist_ok=True)
348 flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
349 out_fd = os.open(target, flags, 0o600)
350 try:
351 offset = 0
352 while remaining > 0:
353 chunk = os.pread(source_fd, min(_COPY_CHUNK, remaining), offset)
354 if not chunk:
355 raise BackupScheduleError(f"file shrank while being copied: {target.name}")
356 os.write(out_fd, chunk)
357 digest.update(chunk)
358 offset += len(chunk)
359 remaining -= len(chunk)
360 finally:
361 os.close(out_fd)
362 return digest.hexdigest()
363
364
365def _sha256_file(path: Path) -> str:
366 digest = hashlib.sha256()
367 with path.open("rb") as handle:
368 for chunk in iter(lambda: handle.read(_COPY_CHUNK), b""):
369 digest.update(chunk)
370 return digest.hexdigest()
371
372
373class _Capture:
374 """Writes one snapshot's files into a staging directory."""
375
376 def __init__(self, staging: Path, previous: Path | None, previous_manifest: dict | None):
377 self.staging = staging
378 self.previous = previous
379 self.previous_files = (previous_manifest or {}).get("files") or {}
380 self.files: dict[str, dict[str, Any]] = {}
381 self.dirs: set[str] = set()
382 self.copied = self.linked = 0
383 self.copied_bytes = 0
384
385 def add_dir(self, rel: str) -> None:
386 self.dirs.add(rel)
387
388 def add_open(self, rel: str, fd: int, size: int, stat_result: os.stat_result) -> None:
389 """Capture `size` bytes of an already-open file as `rel`."""
390 if rel in self.files:
391 return
392 target = self.staging / rel
393 signature = [int(stat_result.st_ino), int(size), int(stat_result.st_mtime_ns)]
394 mode = stat_result.st_mode & 0o777
395 prior = self.previous_files.get(rel)
396 if (self.previous is not None and isinstance(prior, dict)
397 and prior.get("src") == signature and prior.get("size") == size):
398 try:
399 target.parent.mkdir(parents=True, exist_ok=True)
400 os.link(self.previous / rel, target)
401 except OSError:
402 pass # links unsupported or the old file is gone: copy instead
403 else:
404 self.files[rel] = {"sha256": prior["sha256"], "size": size,
405 "mode": mode, "src": signature}
406 self.linked += 1
407 return
408 sha = _copy_fd(fd, size, target)
409 self.files[rel] = {"sha256": sha, "size": size, "mode": mode, "src": signature}
410 self.copied += 1
411 self.copied_bytes += size
412
413 def add_path(self, rel: str, path: Path) -> None:
414 try:
415 fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0))
416 except FileNotFoundError:
417 return # removed between listing and copying: it was not there
418 try:
419 stat_result = os.fstat(fd)
420 self.add_open(rel, fd, stat_result.st_size, stat_result)
421 finally:
422 os.close(fd)
423
424
425def _walk(source_root: Path, rel_root: str) -> Iterator[tuple[str, Path, bool]]:
426 """(relpath, path, is_dir) under source_root, with object_backup's
427 exact skip rules (caches, dotfiles, temp and lock files)."""
428 if not source_root.is_dir():
429 return
430 yield rel_root, source_root, True
431 for path in sorted(source_root.rglob("*"), key=lambda p: p.relative_to(source_root).as_posix()):
432 if object_backup._should_skip(path, source_root):
433 continue
434 rel = f"{rel_root}/{path.relative_to(source_root).as_posix()}"
435 if path.is_symlink():
436 continue
437 yield rel, path, path.is_dir()
438
439
440def _collections_with_records(data_dir: Path) -> list[str]:
441 root = data_dir / "collections"
442 if not root.is_dir():
443 return []
444 return sorted(entry.name for entry in root.iterdir()
445 if entry.is_dir() and not entry.name.startswith(".")
446 and (entry / "records.tsv").is_file())
447
448
449def _capture_collection_pair(capture: _Capture, data_dir: Path, collection: str) -> None:
450 """records.tsv and its change log, opened together under the write lock."""
451 import object_records
452
453 records = data_dir / "collections" / collection / "records.tsv"
454 changes = data_dir / "record_changes" / collection / "changes.jsonl"
455 opened: list[tuple[str, int, os.stat_result]] = []
456 try:
457 with object_records._records_file_lock(records):
458 for rel, path in ((f"data/collections/{collection}/records.tsv", records),
459 (f"data/record_changes/{collection}/changes.jsonl", changes)):
460 try:
461 fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0))
462 except FileNotFoundError:
463 continue
464 opened.append((rel, fd, os.fstat(fd)))
465 for rel, fd, stat_result in opened:
466 capture.add_open(rel, fd, stat_result.st_size, stat_result)
467 finally:
468 for _, fd, _ in opened:
469 os.close(fd)
470
471
472def _excluded_top_level(data_dir: Path) -> list[str]:
473 if not data_dir.is_dir():
474 return []
475 included = set(object_backup.RUNTIME_DATA_DIRS)
476 names = []
477 for entry in sorted(data_dir.iterdir(), key=lambda p: p.name):
478 if entry.name in included:
479 continue
480 if entry.name == "identity":
481 kept = {Path(name).name for name in object_backup.RUNTIME_DATA_FILES}
482 names.extend(f"identity/{child.name}" for child in sorted(entry.iterdir())
483 if child.name not in kept)
484 continue
485 names.append(entry.name)
486 return names
487
488
489def _objects_tree_sha(files: Mapping[str, Mapping[str, Any]]) -> str:
490 digest = hashlib.sha256()
491 for rel in sorted(files):
492 if rel == "objects" or rel.startswith("objects/"):
493 digest.update(f"{rel}\0{files[rel]['sha256']}\n".encode("utf-8"))
494 return digest.hexdigest()
495
496
497def _snapshot_name(moment: datetime) -> str:
498 return SNAPSHOT_PREFIX + moment.strftime("%Y%m%dT%H%M%S%fZ")
499
500
501def create_snapshot(
502 destination: Path | str,
503 *,
504 data_dir: Path | str,
505 objects_dir: Path | str | None = None,
506 now: datetime | None = None,
507) -> dict[str, Any]:
508 """Write one snapshot to the destination; return its summary.
509
510 Raises BackupScheduleError for a refused destination. The caller holds
511 the destination lock (run_backup does).
512 """
513 dest = Path(destination)
514 data_path = Path(data_dir)
515 objects_path = object_backup._objects_dir(objects_dir)
516 problems = destination_problems(dest, data_dir=data_path, objects_dir=objects_path)
517 if problems:
518 raise BackupScheduleError("; ".join(problems))
519
520 started = time.monotonic()
521 moment = now or _utc_now()
522 name = _snapshot_name(moment)
523 final = dest / name
524 if final.exists():
525 raise BackupScheduleError(f"snapshot already exists: {name}")
526 staging = dest / f"{PARTIAL_PREFIX}{name}"
527 _sweep_partials(dest)
528
529 snapshots = list_snapshots(dest)
530 previous = snapshots[0] if snapshots else None
531 previous_manifest = None
532 if previous is not None and _restore_test_passed(previous):
533 previous_manifest = _read_json(previous / MANIFEST_NAME)
534 else:
535 previous = None # untested or failed: never link forward from it
536
537 staging.mkdir(mode=0o700)
538 capture = _Capture(staging, previous, previous_manifest)
539 try:
540 # 1. Each collection's table and change log, as a pair under its lock.
541 collections = _collections_with_records(data_path)
542 for collection in collections:
543 _capture_collection_pair(capture, data_path, collection)
544 # 2. Everything else, in object_backup's order: objects, then data
545 # roots (user_files after the files records, see the docstring).
546 for source, rel_root in object_backup._runtime_sources(objects_path, data_path):
547 rel_text = rel_root.as_posix()
548 if rel_text.removeprefix("data/") in object_backup.RUNTIME_DATA_FILES:
549 if source.is_file():
550 capture.add_path(rel_text, source)
551 continue
552 for rel, path, is_dir in _walk(source, rel_text):
553 if is_dir:
554 capture.add_dir(rel)
555 else:
556 capture.add_path(rel, path)
557 fingerprint = fingerprint_tree(staging)
558 manifest = {
559 "type": SNAPSHOT_TYPE,
560 "format_version": FORMAT_VERSION,
561 "name": name,
562 "created_at": _iso(moment),
563 "files": capture.files,
564 "dirs": sorted(capture.dirs),
565 "file_count": len(capture.files),
566 "bytes": sum(int(entry["size"]) for entry in capture.files.values()),
567 "copied": capture.copied,
568 "linked": capture.linked,
569 "copied_bytes": capture.copied_bytes,
570 "linked_from": previous.name if previous is not None else None,
571 "objects_sha256": _objects_tree_sha(capture.files),
572 "fingerprint": fingerprint,
573 "included": {
574 "objects": "the objects directory (object source)",
575 "data_dirs": list(object_backup.RUNTIME_DATA_DIRS),
576 "data_files": list(object_backup.RUNTIME_DATA_FILES),
577 },
578 "excluded": _excluded_top_level(data_path),
579 "notes": [
580 "identity: users.tsv and accounts.tsv only; password hashes, sessions, "
581 "api keys and service keys are not included",
582 "exchange private keys, environment files, caches, lock and temp "
583 "files are not included",
584 "each collection's records.tsv and change log were captured together "
585 "under its write lock; collections were captured one after another, "
586 "not at a single instant",
587 ],
588 "duration_seconds": round(time.monotonic() - started, 3),
589 }
590 _write_json_atomic(staging / MANIFEST_NAME, manifest, fsync=True)
591 os.rename(staging, final)
592 except BaseException:
593 shutil.rmtree(staging, ignore_errors=True)
594 raise
595 return _summary(final, manifest)
596
597
598def _summary(snapshot: Path, manifest: Mapping[str, Any]) -> dict[str, Any]:
599 return {
600 "name": snapshot.name,
601 "path": str(snapshot),
602 "created_at": manifest.get("created_at"),
603 "files": manifest.get("file_count"),
604 "bytes": manifest.get("bytes"),
605 "copied": manifest.get("copied"),
606 "linked": manifest.get("linked"),
607 "copied_bytes": manifest.get("copied_bytes"),
608 "linked_from": manifest.get("linked_from"),
609 "duration_seconds": manifest.get("duration_seconds"),
610 "collections": len((manifest.get("fingerprint") or {}).get("collections") or {}),
611 }
612
613
614def _sweep_partials(dest: Path) -> list[str]:
615 removed = []
616 for entry in dest.iterdir():
617 if PARTIAL_RE.fullmatch(entry.name) and entry.is_dir() and not entry.is_symlink():
618 shutil.rmtree(entry, ignore_errors=True)
619 removed.append(entry.name)
620 return removed
621
622
623def prune_snapshots(destination: Path | str, keep: int) -> list[str]:
624 """Delete this module's oldest snapshots beyond `keep`.
625
626 Never touches anything list_snapshots does not recognise as its own,
627 never goes below MIN_KEEP, and never removes the newest snapshot whose
628 restore test passed -- if every recent run produced a snapshot that
629 fails its test, the last known-good one is the backup that matters.
630 """
631 keep = max(MIN_KEEP, int(keep))
632 snapshots = list_snapshots(destination)
633 protected = next((snap for snap in snapshots if _restore_test_passed(snap)), None)
634 removed = []
635 for snapshot in snapshots[keep:]:
636 if snapshot == protected:
637 continue
638 shutil.rmtree(snapshot)
639 removed.append(snapshot.name)
640 return removed
641
642
643# --- restore ------------------------------------------------------------------------
644
645
646def _load_manifest(snapshot: Path) -> dict[str, Any]:
647 manifest = _read_json(snapshot / MANIFEST_NAME)
648 if not isinstance(manifest, dict) or manifest.get("type") != SNAPSHOT_TYPE:
649 raise BackupScheduleError(f"{snapshot.name} has no readable {MANIFEST_NAME}")
650 if manifest.get("format_version") != FORMAT_VERSION:
651 raise BackupScheduleError(
652 f"unsupported snapshot format version: {manifest.get('format_version')}")
653 if not isinstance(manifest.get("files"), dict):
654 raise BackupScheduleError("snapshot manifest has no file list")
655 return manifest
656
657
658def _safe_rel(rel: str) -> tuple[str, ...]:
659 parts = tuple(rel.split("/"))
660 if not parts or parts[0] not in ("objects", "data") or any(
661 part in ("", ".", "..") for part in parts) or rel.startswith("/"):
662 raise BackupScheduleError(f"unsafe path in snapshot manifest: {rel!r}")
663 return parts
664
665
666def _target(parts: tuple[str, ...], objects_dir: Path, data_dir: Path) -> Path:
667 root = objects_dir if parts[0] == "objects" else data_dir
668 return root.joinpath(*parts[1:])
669
670
671def restore_snapshot(
672 snapshot: Path | str,
673 *,
674 objects_dir: Path | str,
675 data_dir: Path | str,
676 overwrite: bool = False,
677) -> dict[str, Any]:
678 """Copy a snapshot back into object and data directories.
679
680 The same function the restore test uses, so what the test proves is
681 what an operator runs. Every byte is hashed as it is copied and
682 compared with the manifest; the first mismatch stops the restore.
683 Refuses to replace an existing file unless `overwrite` (stop the
684 server first; see docs/scheduled-backups.md).
685 """
686 snap = Path(snapshot)
687 manifest = _load_manifest(snap)
688 objects_path, data_path = Path(objects_dir), Path(data_dir)
689 planned = []
690 for rel in sorted(manifest["files"]):
691 parts = _safe_rel(rel)
692 target = _target(parts, objects_path, data_path)
693 if target.exists() and not overwrite:
694 raise BackupScheduleError(f"restore target already exists: {target}")
695 planned.append((rel, target))
696 for rel in manifest.get("dirs") or []:
697 _target(_safe_rel(rel), objects_path, data_path).mkdir(parents=True, exist_ok=True)
698 restored_bytes = 0
699 for rel, target in planned:
700 entry = manifest["files"][rel]
701 source = snap / rel
702 target.parent.mkdir(parents=True, exist_ok=True)
703 temp = target.with_name(f".{target.name}.restore.tmp")
704 digest = hashlib.sha256()
705 try:
706 with source.open("rb") as src, temp.open("wb") as out:
707 for chunk in iter(lambda: src.read(_COPY_CHUNK), b""):
708 digest.update(chunk)
709 out.write(chunk)
710 except FileNotFoundError as exc:
711 temp.unlink(missing_ok=True)
712 raise BackupScheduleError(f"missing from snapshot: {rel}") from exc
713 if digest.hexdigest() != entry.get("sha256"):
714 temp.unlink(missing_ok=True)
715 raise BackupScheduleError(f"content does not match the manifest: {rel}")
716 os.chmod(temp, int(entry.get("mode") or 0o600) & 0o777 or 0o600)
717 os.replace(temp, target)
718 restored_bytes += int(entry.get("size") or 0)
719 return {"snapshot": snap.name, "files": len(planned), "bytes": restored_bytes,
720 "objects_dir": str(objects_path), "data_dir": str(data_path)}
721
722
723# --- fingerprint: what the server's own loaders make of a tree ----------------------
724
725
726def _fingerprint_here(data_dir: Path) -> dict[str, Any]:
727 """Load a tree with the server's loaders. Runs in a child process whose
728 DBBASIC_DATA_DIR / DBBASIC_OBJECTS_DIR point at the tree (see
729 fingerprint_tree), so no default path can reach live data."""
730 import object_identity
731 import object_permission_store
732 import object_records
733 import object_schemas
734
735 result: dict[str, Any] = {"collections": {}, "schemas": {}}
736 for collection in _collections_with_records(data_dir):
737 try:
738 rows = object_records.read_collection_records(collection, base_dir=data_dir)
739 except Exception as exc: # noqa: BLE001 -- reported, not raised
740 result["collections"][collection] = {"error": f"{type(exc).__name__}: {exc}"}
741 continue
742 rows = sorted(rows, key=lambda row: str(row.get("id", "")))
743 payload = json.dumps(rows, sort_keys=True, ensure_ascii=False,
744 separators=(",", ":"), default=str)
745 result["collections"][collection] = {
746 "count": len(rows),
747 "sha256": hashlib.sha256(payload.encode("utf-8")).hexdigest(),
748 }
749 schema_root = data_dir / "schemas"
750 if schema_root.is_dir():
751 for path in sorted(schema_root.glob("*.json")):
752 if path.name.startswith("."):
753 continue
754 try:
755 schema = object_schemas.get_schema(path.stem, base_dir=data_dir)
756 fields = schema.get("fields") or []
757 result["schemas"][path.stem] = {"fields": len(fields)}
758 except Exception as exc: # noqa: BLE001
759 result["schemas"][path.stem] = {"error": f"{type(exc).__name__}: {exc}"}
760 policy_file = object_permission_store.policy_path(data_dir)
761 if policy_file.is_file():
762 try:
763 json.loads(policy_file.read_text(encoding="utf-8"))
764 policy = object_permission_store.load_policy(data_dir)
765 result["permissions"] = {"rules": len(policy.rules)}
766 except Exception as exc: # noqa: BLE001
767 result["permissions"] = {"error": f"{type(exc).__name__}: {exc}"}
768 try:
769 result["identity"] = {
770 "users": len(object_identity.list_users(base_dir=data_dir)),
771 "accounts": len(object_identity.list_accounts(base_dir=data_dir)),
772 }
773 except Exception as exc: # noqa: BLE001
774 result["identity"] = {"error": f"{type(exc).__name__}: {exc}"}
775 return result
776
777
778def fingerprint_tree(root: Path | str) -> dict[str, Any]:
779 """Run the server's loaders over `root`/data in a fresh child process.
780
781 A child process because (a) its environment points every default path
782 at the tree being checked, so even code that falls back to
783 DBBASIC_DATA_DIR reads the copy and never the live box; (b) the
784 loaders cache what they read, and those caches belong to a process
785 that is about to exit, not to the daemon; and (c) it is how the box
786 would actually boot after a restore: a new process reading these
787 directories cold.
788 """
789 tree = Path(root)
790 env = dict(os.environ)
791 env["DBBASIC_DATA_DIR"] = str(tree / "data")
792 env["DBBASIC_OBJECTS_DIR"] = str(tree / "objects")
793 env.pop("DBBASIC_OVERRIDES_DIR", None)
794 here = str(Path(__file__).resolve().parent)
795 env["PYTHONPATH"] = here + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
796 try:
797 completed = subprocess.run(
798 [sys.executable, "-m", "object_backup_schedule", "_fingerprint", str(tree / "data")],
799 cwd=str(tree), env=env, capture_output=True, text=True,
800 timeout=FINGERPRINT_TIMEOUT_SECONDS, check=False)
801 except (OSError, subprocess.TimeoutExpired) as exc:
802 raise BackupScheduleError(f"could not load the tree with the server's loaders: {exc}") from exc
803 if completed.returncode != 0:
804 tail = (completed.stderr or completed.stdout or "").strip().splitlines()[-3:]
805 raise BackupScheduleError(
806 "the server's loaders could not read the tree: " + " | ".join(tail))
807 try:
808 return json.loads(completed.stdout)
809 except ValueError as exc:
810 raise BackupScheduleError("the loader process returned unreadable output") from exc
811
812
813# --- the restore test ---------------------------------------------------------------
814
815
816def _compare_fingerprints(expected: Mapping[str, Any], actual: Mapping[str, Any]) -> list[str]:
817 errors = []
818 want = expected.get("collections") or {}
819 got = actual.get("collections") or {}
820 for name in sorted(set(want) | set(got)):
821 if name not in got:
822 errors.append(f"collection {name}: in the snapshot's manifest but did not load")
823 continue
824 if name not in want:
825 errors.append(f"collection {name}: loaded but is not in the manifest")
826 continue
827 if "error" in got[name]:
828 errors.append(f"collection {name}: does not load: {got[name]['error']}")
829 elif got[name] != want[name]:
830 errors.append(
831 f"collection {name}: {got[name].get('count')} record(s) with content hash "
832 f"{str(got[name].get('sha256'))[:12]}, expected {want[name].get('count')} "
833 f"with {str(want[name].get('sha256'))[:12]}")
834 want_schemas = expected.get("schemas") or {}
835 got_schemas = actual.get("schemas") or {}
836 for name in sorted(set(want_schemas) | set(got_schemas)):
837 entry = got_schemas.get(name)
838 if entry is None:
839 errors.append(f"schema {name}: in the manifest but not restored")
840 elif "error" in entry:
841 errors.append(f"schema {name}: does not load: {entry['error']}")
842 elif entry != want_schemas.get(name):
843 errors.append(f"schema {name}: restored {entry}, expected {want_schemas.get(name)}")
844 for key in ("permissions", "identity"):
845 if expected.get(key) != actual.get(key):
846 errors.append(f"{key}: restored {actual.get(key)}, expected {expected.get(key)}")
847 return errors
848
849
850def _missing_file_bytes(data_dir: Path) -> list[str]:
851 records = data_dir / "collections" / "files" / "records.tsv"
852 if not records.is_file():
853 return []
854 import object_backup_index
855
856 try:
857 rows = object_backup_index._parse_tsv_by_id(records.read_bytes())
858 except Exception: # noqa: BLE001 -- its own load check reports an unparseable table
859 return []
860 return [f"files/{record_id} (owner {row.get('owner_id') or ''})"
861 for record_id, row in sorted(rows.items())
862 if not (data_dir / "user_files" / str(row.get("owner_id") or "") / record_id).is_file()]
863
864
865def restore_test(
866 snapshot: Path | str,
867 *,
868 work_dir: Path | str | None = None,
869 live_dirs: tuple[Path | str | None, ...] = (),
870) -> dict[str, Any]:
871 """Restore a snapshot into a throwaway directory and check it.
872
873 Checks, in order, and reports every failure rather than the first:
874 1. the manifest reads and is this format;
875 2. the snapshot holds exactly the manifest's files -- none missing,
876 none of a different size, nothing extra under objects/ or data/;
877 3. restore_snapshot (the operator's restore) copies every file into a
878 fresh temp directory, hashing every byte against the manifest;
879 4. the restored objects tree hashes to the manifest's objects_sha256;
880 5. the server's own loaders, in a fresh process pointed at the temp
881 directory, load every collection to the same record count and
882 content hash recorded when the snapshot was taken, every schema
883 loads, the permission policy loads with the same number of rules,
884 and the users and accounts registries read the same counts.
885 `files` records whose bytes are absent are warnings, not failures.
886
887 Never touches live data: the temp directory is refused if it overlaps
888 any of `live_dirs`, and it is removed afterwards whatever happened.
889 """
890 snap = Path(snapshot)
891 started_at = _utc_now()
892 started = time.monotonic()
893 errors: list[str] = []
894 warnings: list[str] = []
895 checked: dict[str, Any] = {}
896 base = Path(work_dir) if work_dir else Path(tempfile.gettempdir())
897 for live in live_dirs:
898 # One direction only: the scratch directory is a fresh mkdtemp
899 # under `base`, so live data under `base` (the system temp dir
900 # holding a test box, say) is never reached; `base` under live
901 # data would put the restore inside it.
902 if live is not None and base.resolve(strict=False).is_relative_to(
903 Path(live).resolve(strict=False)):
904 raise BackupScheduleError(
905 "the restore test directory overlaps live data; set "
906 f"{RESTORE_TEST_DIR_ENV} somewhere else")
907 try:
908 manifest = _load_manifest(snap)
909 except BackupScheduleError as exc:
910 errors.append(str(exc))
911 manifest = None
912
913 if manifest is not None:
914 files = manifest["files"]
915 for rel, entry in sorted(files.items()):
916 try:
917 _safe_rel(rel)
918 except BackupScheduleError as exc:
919 errors.append(str(exc))
920 continue
921 path = snap / rel
922 if not path.is_file():
923 errors.append(f"missing from snapshot: {rel}")
924 elif path.stat().st_size != int(entry.get("size", -1)):
925 errors.append(f"size differs from the manifest: {rel}")
926 for top in ("objects", "data"):
927 # _walk skips what a capture skips (dotfiles, temp and lock
928 # files): a loader's derived sidecar is not a stowaway.
929 for rel, path, is_dir in _walk(snap / top, top):
930 if not is_dir and rel not in files:
931 errors.append(f"not in the manifest: {rel}")
932
933 scratch = Path(tempfile.mkdtemp(prefix="dbbasic-restore-test-", dir=base))
934 try:
935 if not errors:
936 try:
937 restored = restore_snapshot(snap, objects_dir=scratch / "objects",
938 data_dir=scratch / "data")
939 checked["files"] = restored["files"]
940 checked["bytes"] = restored["bytes"]
941 except BackupScheduleError as exc:
942 errors.append(str(exc))
943 if not errors:
944 restored_files = {}
945 for rel, path, is_dir in _walk_all(scratch / "objects", "objects"):
946 if not is_dir:
947 restored_files[rel] = {"sha256": _sha256_file(path)}
948 objects_sha = _objects_tree_sha(restored_files)
949 checked["objects"] = len(restored_files)
950 if objects_sha != manifest.get("objects_sha256"):
951 errors.append("objects: the restored source tree does not hash to the manifest's")
952 try:
953 actual = fingerprint_tree(scratch)
954 except BackupScheduleError as exc:
955 errors.append(str(exc))
956 else:
957 errors.extend(_compare_fingerprints(manifest.get("fingerprint") or {}, actual))
958 checked["collections"] = len(actual.get("collections") or {})
959 checked["records"] = sum(int(entry.get("count") or 0) for entry in
960 (actual.get("collections") or {}).values())
961 checked["schemas"] = len(actual.get("schemas") or {})
962 warnings.extend(
963 f"file record {name} has no bytes in this snapshot"
964 for name in _missing_file_bytes(scratch / "data"))
965 finally:
966 shutil.rmtree(scratch, ignore_errors=True)
967
968 result = {
969 "ok": not errors,
970 "snapshot": snap.name,
971 "tested_at": _iso(started_at),
972 "duration_seconds": round(time.monotonic() - started, 3),
973 "errors": errors[:50],
974 "error_count": len(errors),
975 "warnings": warnings[:50],
976 "checked": checked,
977 }
978 try:
979 if snap.is_dir():
980 _write_json_atomic(snap / RESTORE_TEST_NAME, result)
981 except OSError:
982 pass # the status file still records it
983 return result
984
985
986def _walk_all(root: Path, rel_root: str) -> Iterator[tuple[str, Path, bool]]:
987 if not root.is_dir():
988 return
989 for path in sorted(root.rglob("*")):
990 rel = f"{rel_root}/{path.relative_to(root).as_posix()}"
991 yield rel, path, path.is_dir() and not path.is_symlink()
992
993
994# --- status -------------------------------------------------------------------------
995
996
997def status_path(data_dir: Path | str) -> Path:
998 return Path(data_dir) / STATUS_NAME
999
1000
1001def read_status(data_dir: Path | str) -> dict[str, Any]:
1002 payload = _read_json(status_path(data_dir))
1003 return payload if isinstance(payload, dict) else {}
1004
1005
1006def _record(data_dir: Path | str, **updates: Any) -> dict[str, Any]:
1007 with _STATUS_LOCK:
1008 current = read_status(data_dir)
1009 event = updates.pop("event", None)
1010 current.update(updates)
1011 if event is not None:
1012 history = list(current.get("history") or [])
1013 history.append(event)
1014 current["history"] = history[-HISTORY_LIMIT:]
1015 _write_json_atomic(status_path(data_dir), current)
1016 return current
1017
1018
1019def _age_seconds(value: Any, now: datetime) -> float | None:
1020 moment = _parse_iso(value)
1021 return None if moment is None else max(0.0, (now - moment).total_seconds())
1022
1023
1024def _live_run(running: Any) -> dict[str, Any] | None:
1025 """The recorded in-progress run, or None if the process that started it
1026 is gone. A daemon killed mid-backup cannot clear its own marker, and a
1027 page saying "running since Tuesday" would be a lie that looks calm."""
1028 if not isinstance(running, dict):
1029 return None
1030 try:
1031 pid = int(running.get("pid"))
1032 except (TypeError, ValueError):
1033 return None
1034 try:
1035 os.kill(pid, 0)
1036 except ProcessLookupError:
1037 return None
1038 except (PermissionError, OSError):
1039 pass # exists but belongs to another user, or cannot be asked: keep it
1040 return running
1041
1042
1043def stale_after_seconds(interval_seconds: int) -> int:
1044 """How old the last good backup (or restore test) may be before it is a
1045 problem: two intervals plus an hour, so one slow or skipped run is not
1046 an alarm and two are."""
1047 return 2 * int(interval_seconds) + 3600
1048
1049
1050def status(data_dir: Path | str, *, env: Mapping[str, str] | None = None,
1051 objects_dir: Path | str | None = None, now: datetime | None = None) -> dict[str, Any]:
1052 """Everything an admin needs to know, with `problems` the loud part.
1053
1054 `healthy` is True only when backups are configured AND nothing is
1055 wrong. A box with backups off is not healthy, it is unprotected; it
1056 says so in `note` and raises no alarm, because turning this on is the
1057 operator's decision and an alarm on every fresh install would teach
1058 everyone to ignore the band it sits in.
1059 """
1060 settings = config(env)
1061 now = now or _utc_now()
1062 state = read_status(data_dir)
1063 problems: list[dict[str, str]] = []
1064 warnings: list[str] = []
1065 payload: dict[str, Any] = {
1066 "enabled": settings["enabled"],
1067 "destination": settings["destination"],
1068 "interval_seconds": settings["interval_seconds"],
1069 "keep": settings["keep"],
1070 "after_command": bool(settings["after_command"]),
1071 "env": settings["env"],
1072 "running": _live_run(state.get("running")),
1073 "last_backup": state.get("last_backup"),
1074 "last_good_backup": state.get("last_good_backup"),
1075 "last_restore_test": state.get("last_restore_test"),
1076 "last_good_restore_test": state.get("last_good_restore_test"),
1077 "last_after_command": state.get("last_after_command"),
1078 }
1079 if not settings["enabled"]:
1080 payload.update(healthy=False, problems=[], warnings=[],
1081 note=f"scheduled backups are off; set {DESTINATION_ENV} to turn them on")
1082 return payload
1083
1084 for message in destination_problems(
1085 settings["destination"], data_dir=data_dir,
1086 objects_dir=object_backup._objects_dir(objects_dir), probe_write=False):
1087 problems.append({"id": "destination_refused", "message": message})
1088 if not problems:
1089 warnings.extend(destination_warnings(settings["destination"], data_dir=data_dir))
1090
1091 stale_after = stale_after_seconds(settings["interval_seconds"])
1092 last = state.get("last_backup") or {}
1093 good = state.get("last_good_backup") or {}
1094 if last and last.get("ok") is False:
1095 problems.append({"id": "backup_failed",
1096 "message": f"the last backup failed: {last.get('error')}"})
1097 good_age = _age_seconds(good.get("finished_at"), now)
1098 payload["last_good_backup_age_seconds"] = good_age
1099 if good_age is None:
1100 problems.append({"id": "backup_missing", "message": "no backup has completed yet"})
1101 elif good_age > stale_after:
1102 problems.append({"id": "backup_stale",
1103 "message": f"the last good backup is {int(good_age // 3600)}h old"})
1104
1105 test = state.get("last_restore_test") or {}
1106 good_test = state.get("last_good_restore_test") or {}
1107 if test and test.get("ok") is False:
1108 first = (test.get("errors") or ["unknown error"])[0]
1109 problems.append({"id": "restore_test_failed",
1110 "message": f"the last restore test of {test.get('snapshot')} failed: {first}"})
1111 test_age = _age_seconds(good_test.get("tested_at"), now)
1112 payload["last_good_restore_test_age_seconds"] = test_age
1113 if test_age is None:
1114 problems.append({"id": "restore_test_missing",
1115 "message": "no backup has passed a restore test yet"})
1116 elif test_age > stale_after:
1117 problems.append({"id": "restore_test_stale",
1118 "message": f"the last passing restore test is {int(test_age // 3600)}h old"})
1119
1120 after = state.get("last_after_command") or {}
1121 if settings["after_command"] and after.get("ok") is False:
1122 problems.append({"id": "after_command_failed",
1123 "message": f"{AFTER_COMMAND_ENV} failed: {after.get('error')}"})
1124
1125 payload.update(healthy=not problems, problems=problems, warnings=warnings)
1126 return payload
1127
1128
1129def summary_line(payload: Mapping[str, Any]) -> str:
1130 """One line for logs and banners."""
1131 if not payload.get("enabled"):
1132 return f"off (set {DESTINATION_ENV})"
1133 good = payload.get("last_good_backup") or {}
1134 test = payload.get("last_restore_test") or {}
1135 parts = [f"every {payload.get('interval_seconds')}s, keep {payload.get('keep')}"]
1136 if good:
1137 parts.append(f"last good {good.get('name')} ({_mb(good.get('bytes'))}, "
1138 f"{good.get('duration_seconds')}s)")
1139 if test:
1140 parts.append(f"restore test {'ok' if test.get('ok') else 'FAILED'} "
1141 f"({test.get('snapshot')})")
1142 if payload.get("problems"):
1143 parts.append("PROBLEMS: " + "; ".join(p["message"] for p in payload["problems"]))
1144 return " | ".join(parts)
1145
1146
1147def _mb(value: Any) -> str:
1148 try:
1149 return f"{int(value) / (1024 * 1024):.1f}MB"
1150 except (TypeError, ValueError):
1151 return "?"
1152
1153
1154# --- runs ---------------------------------------------------------------------------
1155
1156
1157def _run_after_command(command: str, snapshot: Path) -> dict[str, Any]:
1158 started = _utc_now()
1159 try:
1160 completed = subprocess.run(
1161 [*shlex.split(command), str(snapshot)], capture_output=True, text=True,
1162 timeout=AFTER_COMMAND_TIMEOUT_SECONDS, check=False)
1163 except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
1164 return {"ok": False, "at": _iso(started), "snapshot": snapshot.name,
1165 "error": f"{type(exc).__name__}: {exc}"[:500]}
1166 if completed.returncode != 0:
1167 tail = (completed.stderr or completed.stdout or "").strip()[-400:]
1168 return {"ok": False, "at": _iso(started), "snapshot": snapshot.name,
1169 "error": f"exit {completed.returncode}: {tail}"}
1170 return {"ok": True, "at": _iso(started), "snapshot": snapshot.name}
1171
1172
1173def run_restore_test(
1174 data_dir: Path | str,
1175 *,
1176 snapshot: Path | str | None = None,
1177 env: Mapping[str, str] | None = None,
1178 objects_dir: Path | str | None = None,
1179 _locked: bool = False,
1180) -> dict[str, Any]:
1181 """Restore-test a snapshot (the newest by default) and record the result."""
1182 settings = config(env)
1183 if snapshot is None:
1184 if not settings["enabled"]:
1185 raise BackupScheduleError(f"scheduled backups are off; set {DESTINATION_ENV}")
1186 snapshots = list_snapshots(settings["destination"])
1187 if not snapshots:
1188 raise BackupScheduleError("there is no snapshot at the destination to test")
1189 snapshot = snapshots[0]
1190 live = (data_dir, object_backup._objects_dir(objects_dir))
1191
1192 def _test() -> dict[str, Any]:
1193 try:
1194 return restore_test(snapshot, work_dir=settings["restore_test_dir"], live_dirs=live)
1195 except BackupScheduleError as exc:
1196 return {"ok": False, "snapshot": Path(snapshot).name, "tested_at": _iso(_utc_now()),
1197 "errors": [str(exc)], "error_count": 1, "warnings": [], "checked": {}}
1198
1199 if _locked or not settings["enabled"]:
1200 result = _test()
1201 else:
1202 with _destination_lock(Path(settings["destination"])):
1203 result = _test()
1204 updates: dict[str, Any] = {"last_restore_test": result,
1205 "event": {"kind": "restore_test", "ok": result["ok"],
1206 "at": result["tested_at"],
1207 "snapshot": result["snapshot"]}}
1208 if result["ok"]:
1209 updates["last_good_restore_test"] = result
1210 _record(data_dir, **updates)
1211 return result
1212
1213
1214def run_backup(
1215 data_dir: Path | str,
1216 *,
1217 env: Mapping[str, str] | None = None,
1218 objects_dir: Path | str | None = None,
1219 now: datetime | None = None,
1220) -> dict[str, Any]:
1221 """One full cycle: snapshot, prune, restore test, after-command, record.
1222
1223 Never raises for a failed backup -- it records the failure (that is the
1224 point) and returns it. Raises BackupScheduleError only when backups are
1225 off or another run holds the destination.
1226 """
1227 settings = config(env)
1228 if not settings["enabled"]:
1229 raise BackupScheduleError(f"scheduled backups are off; set {DESTINATION_ENV}")
1230 dest = Path(settings["destination"])
1231 started_at = now or _utc_now()
1232 started = time.monotonic()
1233 result: dict[str, Any] = {"started_at": _iso(started_at)}
1234
1235 refusals = destination_problems(dest, data_dir=data_dir,
1236 objects_dir=object_backup._objects_dir(objects_dir))
1237 if refusals:
1238 result.update(ok=False, error="; ".join(refusals), finished_at=_iso(_utc_now()))
1239 _record(data_dir, last_backup=result,
1240 event={"kind": "backup", "ok": False, "at": result["started_at"],
1241 "error": result["error"]})
1242 return result
1243
1244 with _destination_lock(dest):
1245 _record(data_dir, running={"kind": "backup", "started_at": result["started_at"],
1246 "pid": os.getpid()})
1247 try:
1248 previous = read_status(data_dir).get("last_good_backup") or {}
1249 summary = create_snapshot(dest, data_dir=data_dir, objects_dir=objects_dir,
1250 now=started_at)
1251 if previous.get("name") and not (dest / str(previous["name"])).is_dir() \
1252 and previous.get("destination") == str(dest):
1253 summary.setdefault("warnings", []).append(
1254 f"the previous snapshot {previous['name']} is no longer at the "
1255 "destination (was the disk replaced or unmounted?); this run was a full copy")
1256 summary["destination"] = str(dest)
1257 summary.setdefault("warnings", []).extend(
1258 destination_warnings(dest, data_dir=data_dir))
1259 result.update(ok=True, **summary)
1260 except Exception as exc: # noqa: BLE001 -- a failed backup is recorded, loudly
1261 result.update(ok=False, error=f"{type(exc).__name__}: {exc}"[:500])
1262 result["finished_at"] = _iso(_utc_now())
1263 result["total_seconds"] = round(time.monotonic() - started, 3)
1264 updates: dict[str, Any] = {
1265 "last_backup": result, "running": None,
1266 "event": {"kind": "backup", "ok": result["ok"], "at": result["started_at"],
1267 "name": result.get("name"), "error": result.get("error")}}
1268 if result["ok"]:
1269 updates["last_good_backup"] = result
1270 _record(data_dir, **updates)
1271 if not result["ok"]:
1272 return result
1273
1274 snapshot = dest / result["name"]
1275 _record(data_dir, running={"kind": "restore_test", "started_at": _iso(_utc_now()),
1276 "pid": os.getpid()})
1277 try:
1278 test = run_restore_test(data_dir, snapshot=snapshot, env=env,
1279 objects_dir=objects_dir, _locked=True)
1280 finally:
1281 _record(data_dir, running=None)
1282 result["restore_test"] = {"ok": test["ok"], "errors": test["errors"][:5]}
1283 try:
1284 result["pruned"] = prune_snapshots(dest, settings["keep"])
1285 except OSError as exc:
1286 result["prune_error"] = str(exc)
1287 if settings["after_command"]:
1288 if test["ok"]:
1289 after = _run_after_command(settings["after_command"], snapshot)
1290 else:
1291 after = {"ok": False, "at": _iso(_utc_now()), "snapshot": snapshot.name,
1292 "error": "not run: the snapshot failed its restore test"}
1293 result["after_command"] = after
1294 _record(data_dir, last_after_command=after)
1295 return result
1296
1297
1298def due(data_dir: Path | str, *, env: Mapping[str, str] | None = None,
1299 now: datetime | None = None) -> bool:
1300 """Is a scheduled run due? On the interval after the last attempt, or
1301 RETRY_AFTER_FAILURE_SECONDS after a failed one if that is sooner."""
1302 settings = config(env)
1303 if not settings["enabled"]:
1304 return False
1305 now = now or _utc_now()
1306 last = read_status(data_dir).get("last_backup") or {}
1307 age = _age_seconds(last.get("started_at"), now)
1308 if age is None:
1309 return True
1310 wait = settings["interval_seconds"]
1311 if last.get("ok") is False:
1312 wait = min(wait, RETRY_AFTER_FAILURE_SECONDS)
1313 return age >= wait
1314
1315
1316_BACKGROUND: dict[str, threading.Thread] = {}
1317
1318
1319def start_in_background(kind: str, data_dir: Path | str, *,
1320 objects_dir: Path | str | None = None,
1321 on_done=None) -> threading.Thread | None:
1322 """Run a backup ("backup") or restore test ("restore_test") on a thread.
1323
1324 Returns None when one is already running in this process. The daemon
1325 uses this so its poll loop (scheduler, queue, events) keeps turning
1326 while a large box is copied; the admin route uses it so a long backup
1327 is not an HTTP request a proxy will time out.
1328 """
1329 current = _BACKGROUND.get("run")
1330 if current is not None and current.is_alive():
1331 return None
1332
1333 def _work() -> None:
1334 try:
1335 if kind == "backup":
1336 outcome = run_backup(data_dir, objects_dir=objects_dir)
1337 else:
1338 outcome = run_restore_test(data_dir, objects_dir=objects_dir)
1339 except BackupScheduleError as exc:
1340 outcome = {"ok": False, "error": str(exc)}
1341 except Exception as exc: # noqa: BLE001 -- a thread must not die silently
1342 outcome = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
1343 try:
1344 _record(data_dir, running=None)
1345 except OSError:
1346 pass
1347 if on_done is not None:
1348 on_done(kind, outcome)
1349
1350 thread = threading.Thread(target=_work, name=f"dbbasic-{kind}", daemon=True)
1351 _BACKGROUND["run"] = thread
1352 thread.start()
1353 return thread
1354
1355
1356# --- CLI ----------------------------------------------------------------------------
1357
1358
1359def main(argv: list[str] | None = None) -> int:
1360 parser = argparse.ArgumentParser(
1361 description="Scheduled backups to a destination outside the box, and restore tests.")
1362 sub = parser.add_subparsers(dest="command", required=True)
1363 for name, text in (("run", "back up now (then restore-test the result)"),
1364 ("test", "restore-test a snapshot (the newest by default)"),
1365 ("status", "show the backup status"),
1366 ("list", "list snapshots at the destination")):
1367 command = sub.add_parser(name, help=text)
1368 command.add_argument("--data-dir", type=Path)
1369 command.add_argument("--objects-dir", type=Path)
1370 if name == "test":
1371 command.add_argument("snapshot", nargs="?", type=Path)
1372 restore = sub.add_parser("restore", help="copy a snapshot into object and data directories")
1373 restore.add_argument("snapshot", type=Path)
1374 restore.add_argument("--objects-dir", type=Path, required=True)
1375 restore.add_argument("--data-dir", type=Path, required=True)
1376 restore.add_argument("--overwrite", action="store_true")
1377 fingerprint = sub.add_parser("_fingerprint")
1378 fingerprint.add_argument("data_dir", type=Path)
1379 args = parser.parse_args(argv)
1380
1381 if args.command == "_fingerprint":
1382 print(json.dumps(_fingerprint_here(args.data_dir), sort_keys=True))
1383 return 0
1384 try:
1385 if args.command == "restore":
1386 output: Any = restore_snapshot(args.snapshot, objects_dir=args.objects_dir,
1387 data_dir=args.data_dir, overwrite=args.overwrite)
1388 code = 0
1389 else:
1390 data_dir = args.data_dir or object_backup._data_dir(None)
1391 if args.command == "run":
1392 output = run_backup(data_dir, objects_dir=args.objects_dir)
1393 code = 0 if output.get("ok") and (output.get("restore_test") or {}).get("ok") else 1
1394 elif args.command == "test":
1395 output = run_restore_test(data_dir, snapshot=args.snapshot,
1396 objects_dir=args.objects_dir)
1397 code = 0 if output["ok"] else 1
1398 elif args.command == "list":
1399 settings = config()
1400 output = [{"name": snap.name, "restore_test_ok": _restore_test_passed(snap)}
1401 for snap in list_snapshots(settings["destination"] or ".")] \
1402 if settings["enabled"] else []
1403 code = 0
1404 else:
1405 output = status(data_dir, objects_dir=args.objects_dir)
1406 code = 0 if output.get("healthy") or not output.get("enabled") else 1
1407 except BackupScheduleError as exc:
1408 print(json.dumps({"ok": False, "error": str(exc)}, indent=2))
1409 return 1
1410 print(json.dumps(output, indent=2, sort_keys=True, default=str))
1411 return code
1412
1413
1414if __name__ == "__main__":
1415 raise SystemExit(main())