askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_backup.py · 35.7 KB · 994 lines
| 1 | """Runtime backup and restore helpers for DBBASIC Object Server. |
| 2 | |
| 3 | The runtime backup format is intentionally narrow. It captures live object |
| 4 | source and runtime-owned data, but it does not include deployment secrets, |
| 5 | systemd units, provider metadata, virtualenvs, caches, or git history. |
| 6 | """ |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import argparse |
| 10 | import io |
| 11 | import json |
| 12 | import os |
| 13 | import re |
| 14 | import tarfile |
| 15 | from dataclasses import asdict, dataclass, field |
| 16 | from datetime import datetime, timezone |
| 17 | from pathlib import Path, PurePosixPath |
| 18 | from typing import Any, Callable, Sequence |
| 19 | |
| 20 | from object_namespace import DEFAULT_OBJECTS_DIR, OBJECTS_DIR_ENV |
| 21 | from object_versions import DEFAULT_DATA_DIR |
| 22 | |
| 23 | DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 24 | BACKUPS_DIR_ENV = "DBBASIC_BACKUPS_DIR" |
| 25 | BACKUP_FORMAT_VERSION = 1 |
| 26 | MANIFEST_NAME = "dbbasic-backup-manifest.json" |
| 27 | BACKUPS_DIR = "backups" |
| 28 | RUNTIME_DATA_DIRS = ( |
| 29 | "state", |
| 30 | "logs", |
| 31 | "versions", |
| 32 | "source_changes", |
| 33 | "schema_versions", |
| 34 | "record_changes", |
| 35 | "package_changes", |
| 36 | "package_baselines", |
| 37 | "reconciles", |
| 38 | "file_changes", |
| 39 | "files", |
| 40 | "user_files", |
| 41 | "permissions", |
| 42 | "schemas", |
| 43 | "collections", |
| 44 | ) |
| 45 | # Individual files (not whole directories) that ride along. The identity |
| 46 | # directory also holds credentials.tsv (password hashes), sessions.tsv and |
| 47 | # api_keys.tsv (token hashes) and service_keys.tsv (third-party provider |
| 48 | # secrets); a backup archive is downloadable and is stored beside the data |
| 49 | # it protects, so those stay out and ONLY the registry of people is kept: |
| 50 | # who the users and accounts are, their status and roles. A restored box |
| 51 | # therefore knows its users but nobody can sign in until credentials are |
| 52 | # re-issued (a password reset / new keys) -- documented in |
| 53 | # docs/http-api-contract.md "Backups". |
| 54 | RUNTIME_DATA_FILES = ( |
| 55 | "identity/users.tsv", |
| 56 | "identity/accounts.tsv", |
| 57 | ) |
| 58 | # The runtime roots that are a record of what happened rather than the state |
| 59 | # it left: per-object source versions and change logs, per-schema versions, |
| 60 | # per-collection record change logs (and their gzip archives), the package |
| 61 | # change log, per-object file change logs and object logs. A package |
| 62 | # rollback keeps every one of them as it is on disk and records itself as a |
| 63 | # new entry (object_server._record_package_restore_history); only a full |
| 64 | # CLI restore (disaster recovery) writes them back from the archive. |
| 65 | HISTORY_DATA_DIRS = ( |
| 66 | "versions", |
| 67 | "source_changes", |
| 68 | "schema_versions", |
| 69 | "record_changes", |
| 70 | "package_changes", |
| 71 | "file_changes", |
| 72 | "logs", |
| 73 | ) |
| 74 | USER_FILES_RECORDS_MEMBER = "data/collections/files/records.tsv" |
| 75 | USER_FILES_PREFIX = "data/user_files/" |
| 76 | SKIP_PARTS = {"__pycache__", ".git", ".venv", "node_modules"} |
| 77 | SKIP_SUFFIXES = (".pyc", ".pyo", ".tmp", ".lock") |
| 78 | RESTORE_POINT_LABEL_RE = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,127}$") |
| 79 | |
| 80 | |
| 81 | class BackupError(Exception): |
| 82 | """Base exception for backup operations.""" |
| 83 | |
| 84 | |
| 85 | class BackupRestoreError(BackupError): |
| 86 | """Raised when a backup cannot be safely restored.""" |
| 87 | |
| 88 | |
| 89 | @dataclass(frozen=True) |
| 90 | class BackupSummary: |
| 91 | path: str |
| 92 | format_version: int |
| 93 | created_at: str |
| 94 | files: int |
| 95 | bytes: int |
| 96 | entries: list[str] |
| 97 | warnings: list[str] |
| 98 | |
| 99 | def to_dict(self) -> dict[str, Any]: |
| 100 | return asdict(self) |
| 101 | |
| 102 | |
| 103 | @dataclass(frozen=True) |
| 104 | class BackupVerification: |
| 105 | path: str |
| 106 | ok: bool |
| 107 | format_version: int | None |
| 108 | files: int |
| 109 | bytes: int |
| 110 | entries: list[str] |
| 111 | errors: list[str] |
| 112 | warnings: list[str] |
| 113 | manifest: dict[str, Any] | None |
| 114 | # `files` records in the archive whose bytes are not in it, as |
| 115 | # "files/<id> (owner <owner>)". The archive can be sound (ok) and still |
| 116 | # restore to records that answer 404 "File bytes missing". |
| 117 | missing_file_bytes: list[str] = field(default_factory=list) |
| 118 | |
| 119 | def to_dict(self) -> dict[str, Any]: |
| 120 | return asdict(self) |
| 121 | |
| 122 | |
| 123 | @dataclass(frozen=True) |
| 124 | class RestoreSummary: |
| 125 | backup_path: str |
| 126 | objects_dir: str |
| 127 | data_dir: str |
| 128 | files: int |
| 129 | bytes: int |
| 130 | overwritten: bool |
| 131 | pruned_files: int = 0 |
| 132 | pruned_dirs: int = 0 |
| 133 | scoped: bool = False |
| 134 | selected: int = 0 |
| 135 | |
| 136 | def to_dict(self) -> dict[str, Any]: |
| 137 | return asdict(self) |
| 138 | |
| 139 | |
| 140 | def create_runtime_backup( |
| 141 | output_path: Path | str, |
| 142 | *, |
| 143 | objects_dir: Path | str | None = None, |
| 144 | data_dir: Path | str | None = None, |
| 145 | created_at: str | None = None, |
| 146 | ) -> BackupSummary: |
| 147 | """Create a tar/gzip archive containing object source and runtime data.""" |
| 148 | output = Path(output_path) |
| 149 | objects_path = _objects_dir(objects_dir) |
| 150 | data_path = _data_dir(data_dir) |
| 151 | timestamp = created_at or _utc_timestamp() |
| 152 | |
| 153 | members: list[tuple[Path, PurePosixPath]] = [] |
| 154 | warnings: list[str] = [] |
| 155 | entries: list[str] = [] |
| 156 | file_count = 0 |
| 157 | byte_count = 0 |
| 158 | |
| 159 | for source_path, archive_root in _runtime_sources(objects_path, data_path): |
| 160 | if not source_path.exists(): |
| 161 | continue |
| 162 | if archive_root.as_posix().removeprefix("data/") in RUNTIME_DATA_FILES: |
| 163 | if source_path.is_file(): |
| 164 | entries.append(archive_root.as_posix()) |
| 165 | members.append((source_path, archive_root)) |
| 166 | file_count += 1 |
| 167 | byte_count += source_path.stat().st_size |
| 168 | continue |
| 169 | if not source_path.is_dir(): |
| 170 | warnings.append(f"skipped non-directory source: {archive_root.as_posix()}") |
| 171 | continue |
| 172 | |
| 173 | entries.append(archive_root.as_posix()) |
| 174 | for path, archive_name in _iter_backup_members(source_path, archive_root): |
| 175 | members.append((path, archive_name)) |
| 176 | if path.is_file(): |
| 177 | file_count += 1 |
| 178 | byte_count += path.stat().st_size |
| 179 | |
| 180 | if file_count == 0: |
| 181 | warnings.append("backup contains no runtime files") |
| 182 | |
| 183 | manifest = { |
| 184 | "format_version": BACKUP_FORMAT_VERSION, |
| 185 | "created_at": timestamp, |
| 186 | "type": "dbbasic-runtime", |
| 187 | "entries": entries, |
| 188 | "files": file_count, |
| 189 | "bytes": byte_count, |
| 190 | "notes": [ |
| 191 | "deployment secrets are not included", |
| 192 | "identity: users.tsv and accounts.tsv only; credentials, sessions, " |
| 193 | "api keys and service keys are not included", |
| 194 | "systemd service files are not included", |
| 195 | "git history and virtualenvs are not included", |
| 196 | ], |
| 197 | "warnings": warnings, |
| 198 | } |
| 199 | |
| 200 | output.parent.mkdir(parents=True, exist_ok=True) |
| 201 | with tarfile.open(output, "w:gz", format=tarfile.PAX_FORMAT) as archive: |
| 202 | _add_manifest(archive, manifest) |
| 203 | for path, archive_name in members: |
| 204 | _add_path(archive, path, archive_name) |
| 205 | |
| 206 | return BackupSummary( |
| 207 | path=str(output), |
| 208 | format_version=BACKUP_FORMAT_VERSION, |
| 209 | created_at=timestamp, |
| 210 | files=file_count, |
| 211 | bytes=byte_count, |
| 212 | entries=entries, |
| 213 | warnings=warnings, |
| 214 | ) |
| 215 | |
| 216 | |
| 217 | def create_runtime_restore_point( |
| 218 | label: str, |
| 219 | *, |
| 220 | objects_dir: Path | str | None = None, |
| 221 | data_dir: Path | str | None = None, |
| 222 | backups_dir: Path | str | None = None, |
| 223 | created_at: str | None = None, |
| 224 | ) -> BackupSummary: |
| 225 | """Create a named runtime backup under the configured restore-point directory.""" |
| 226 | clean_label = _restore_point_label(label) |
| 227 | timestamp = created_at or _utc_timestamp() |
| 228 | output_dir = _backups_dir(backups_dir, data_dir=data_dir) |
| 229 | output_path = output_dir / f"{_backup_filename_timestamp(timestamp)}-{clean_label}.tar.gz" |
| 230 | return create_runtime_backup( |
| 231 | output_path, |
| 232 | objects_dir=objects_dir, |
| 233 | data_dir=data_dir, |
| 234 | created_at=timestamp, |
| 235 | ) |
| 236 | |
| 237 | |
| 238 | def verify_runtime_backup(backup_path: Path | str) -> BackupVerification: |
| 239 | """Inspect a runtime backup archive without extracting it.""" |
| 240 | path = Path(backup_path) |
| 241 | errors: list[str] = [] |
| 242 | warnings: list[str] = [] |
| 243 | manifest: dict[str, Any] | None = None |
| 244 | entries: set[str] = set() |
| 245 | file_count = 0 |
| 246 | byte_count = 0 |
| 247 | file_names: set[str] = set() |
| 248 | missing_file_bytes: list[str] = [] |
| 249 | |
| 250 | try: |
| 251 | with tarfile.open(path, "r:*") as archive: |
| 252 | manifest = _read_manifest(archive, errors) |
| 253 | for member in archive.getmembers(): |
| 254 | if member.name == MANIFEST_NAME: |
| 255 | continue |
| 256 | errors.extend(_validate_member(member)) |
| 257 | root = _member_entry(member.name) |
| 258 | if root is not None: |
| 259 | entries.add(root) |
| 260 | if member.isfile(): |
| 261 | file_count += 1 |
| 262 | byte_count += member.size |
| 263 | file_names.add(member.name) |
| 264 | if USER_FILES_RECORDS_MEMBER in file_names: |
| 265 | missing_file_bytes = _missing_file_bytes( |
| 266 | archive.extractfile(USER_FILES_RECORDS_MEMBER), file_names) |
| 267 | except (tarfile.TarError, OSError) as exc: |
| 268 | errors.append(f"cannot read backup archive: {exc}") |
| 269 | warnings.extend( |
| 270 | f"file record {name} has no bytes in this backup; a restore would " |
| 271 | f"answer 404 \"File bytes missing\" for it" |
| 272 | for name in missing_file_bytes) |
| 273 | |
| 274 | format_version = None |
| 275 | if manifest is not None: |
| 276 | format_version = _manifest_int(manifest.get("format_version")) |
| 277 | if format_version != BACKUP_FORMAT_VERSION: |
| 278 | errors.append(f"unsupported backup format version: {format_version}") |
| 279 | if _manifest_int(manifest.get("files")) != file_count: |
| 280 | errors.append("manifest file count does not match archive") |
| 281 | if _manifest_int(manifest.get("bytes")) != byte_count: |
| 282 | errors.append("manifest byte count does not match archive") |
| 283 | warnings.extend(str(warning) for warning in manifest.get("warnings", [])) |
| 284 | |
| 285 | return BackupVerification( |
| 286 | path=str(path), |
| 287 | ok=not errors, |
| 288 | format_version=format_version, |
| 289 | files=file_count, |
| 290 | bytes=byte_count, |
| 291 | entries=sorted(entries), |
| 292 | errors=errors, |
| 293 | warnings=warnings, |
| 294 | manifest=manifest, |
| 295 | missing_file_bytes=missing_file_bytes, |
| 296 | ) |
| 297 | |
| 298 | |
| 299 | def _missing_file_bytes(handle: Any, file_names: set[str]) -> list[str]: |
| 300 | """`files` records (from the archived records.tsv) with no |
| 301 | data/user_files/<owner>/<id> member in the archive.""" |
| 302 | if handle is None: |
| 303 | return [] |
| 304 | import object_backup_index |
| 305 | |
| 306 | try: |
| 307 | rows = object_backup_index._parse_tsv_by_id(handle.read()) |
| 308 | except Exception: # noqa: BLE001 -- an unparseable table is reported by its own checks |
| 309 | return [] |
| 310 | missing = [] |
| 311 | for record_id, row in sorted(rows.items()): |
| 312 | owner = str(row.get("owner_id") or "") |
| 313 | if f"{USER_FILES_PREFIX}{owner}/{record_id}" not in file_names: |
| 314 | missing.append(f"files/{record_id} (owner {owner})") |
| 315 | return missing |
| 316 | |
| 317 | |
| 318 | def read_backup_member(backup_path: Path | str, member_name: str) -> bytes | None: |
| 319 | """Return the bytes of one archive member, or None if it is not present. |
| 320 | |
| 321 | ``member_name`` is expected to be an internal archive relpath produced by |
| 322 | server code (e.g. "data/collections/notes/records.tsv"), not raw user |
| 323 | input — but it is still validated defensively against traversal. |
| 324 | """ |
| 325 | _safe_archive_path(member_name) |
| 326 | with tarfile.open(backup_path, "r:*") as archive: |
| 327 | try: |
| 328 | member = archive.getmember(member_name) |
| 329 | except KeyError: |
| 330 | return None |
| 331 | extracted = archive.extractfile(member) |
| 332 | if extracted is None: |
| 333 | return None |
| 334 | return extracted.read() |
| 335 | |
| 336 | |
| 337 | def _normalize_select(select: Sequence[str]) -> list[str]: |
| 338 | normalized: list[str] = [] |
| 339 | for raw in select: |
| 340 | cleaned = str(raw).strip("/") |
| 341 | if not (cleaned == "objects" or cleaned.startswith("objects/") |
| 342 | or cleaned == "data" or cleaned.startswith("data/")): |
| 343 | raise BackupRestoreError(f"invalid restore selector: {raw!r}") |
| 344 | normalized.append(cleaned) |
| 345 | return normalized |
| 346 | |
| 347 | |
| 348 | def _member_selected(name: str, selectors: list[str]) -> bool: |
| 349 | for selector in selectors: |
| 350 | if name == selector or name.startswith(selector + "/"): |
| 351 | return True |
| 352 | return False |
| 353 | |
| 354 | |
| 355 | def is_permission_audit_member(name: str) -> bool: |
| 356 | """True for data/permissions/audit.jsonl and its rotated segments. |
| 357 | |
| 358 | A rollback (package restore) keeps these as they are on disk: the audit |
| 359 | trail records what happened since the snapshot, the rollback included. |
| 360 | """ |
| 361 | parts = PurePosixPath(name).parts |
| 362 | return ( |
| 363 | len(parts) == 3 |
| 364 | and parts[:2] == ("data", "permissions") |
| 365 | and parts[2].startswith("audit") |
| 366 | ) |
| 367 | |
| 368 | |
| 369 | def is_identity_registry_member(name: str) -> bool: |
| 370 | """True for data/identity/users.tsv and data/identity/accounts.tsv. |
| 371 | |
| 372 | A package rollback keeps the registry as it is now: rolling it back |
| 373 | would re-activate a user disabled since the snapshot (whose password, |
| 374 | not in the archive, still works) and give back roles removed since. |
| 375 | """ |
| 376 | return name in {f"data/{member}" for member in RUNTIME_DATA_FILES} |
| 377 | |
| 378 | |
| 379 | def is_history_member(name: str) -> bool: |
| 380 | """True for a file under one of HISTORY_DATA_DIRS (data/versions/...). |
| 381 | |
| 382 | A package rollback keeps these as they are on disk: a history records |
| 383 | what happened since the snapshot, and the rollback is added to it as a |
| 384 | new entry instead of rewinding it. |
| 385 | """ |
| 386 | parts = PurePosixPath(name).parts |
| 387 | return len(parts) >= 3 and parts[0] == "data" and parts[1] in HISTORY_DATA_DIRS |
| 388 | |
| 389 | |
| 390 | def is_package_restore_preserved(name: str) -> bool: |
| 391 | """What POST /packages/{id}/restore leaves as it is on disk.""" |
| 392 | return ( |
| 393 | is_permission_audit_member(name) |
| 394 | or is_identity_registry_member(name) |
| 395 | or is_history_member(name) |
| 396 | ) |
| 397 | |
| 398 | |
| 399 | def restore_runtime_backup( |
| 400 | backup_path: Path | str, |
| 401 | *, |
| 402 | objects_dir: Path | str, |
| 403 | data_dir: Path | str, |
| 404 | overwrite: bool = False, |
| 405 | prune_extra: bool = False, |
| 406 | select: Sequence[str] | None = None, |
| 407 | preserve: Callable[[str], bool] | None = None, |
| 408 | on_change: Callable[[str, bytes | None, bytes | None], None] | None = None, |
| 409 | ) -> RestoreSummary: |
| 410 | """Restore a runtime backup into explicit object and data directories. |
| 411 | |
| 412 | ``select``, when provided, scopes the restore to archive members whose |
| 413 | name equals one of the selectors or is nested under one (e.g. |
| 414 | "data/collections/notes"). Combining ``select`` with ``prune_extra`` is |
| 415 | refused — pruning is a whole-instance operation. |
| 416 | |
| 417 | ``preserve``, when provided, names archive-relative files (e.g. |
| 418 | "data/permissions/audit.jsonl") that keep their current contents: the |
| 419 | archive's copy is not written and the file on disk is not pruned. |
| 420 | |
| 421 | ``on_change``, when provided, is called as ``on_change(name, before, |
| 422 | after)`` just before a file whose contents the restore actually changes |
| 423 | is written or pruned: ``name`` is archive-relative, ``before`` is what is |
| 424 | on disk (None when nothing is) and ``after`` the archive's copy (None |
| 425 | when the file is pruned). Files rewritten with identical bytes are not |
| 426 | reported. Callers use it to add the restore to the histories. |
| 427 | """ |
| 428 | if prune_extra and not overwrite: |
| 429 | raise BackupRestoreError("prune_extra requires overwrite=True") |
| 430 | if select is not None and prune_extra: |
| 431 | raise BackupRestoreError("select cannot be combined with prune_extra") |
| 432 | |
| 433 | selectors = _normalize_select(select) if select is not None else None |
| 434 | |
| 435 | backup = Path(backup_path) |
| 436 | objects_path = Path(objects_dir) |
| 437 | data_path = Path(data_dir) |
| 438 | verification = verify_runtime_backup(backup) |
| 439 | if not verification.ok: |
| 440 | raise BackupRestoreError("; ".join(verification.errors)) |
| 441 | |
| 442 | selected_count = 0 |
| 443 | planned: list[tuple[tarfile.TarInfo, Path]] = [] |
| 444 | with tarfile.open(backup, "r:*") as archive: |
| 445 | for member in archive.getmembers(): |
| 446 | if member.name == MANIFEST_NAME: |
| 447 | continue |
| 448 | if preserve is not None and member.isfile() and preserve(member.name): |
| 449 | continue |
| 450 | if selectors is not None: |
| 451 | if not _member_selected(member.name, selectors): |
| 452 | continue |
| 453 | selected_count += 1 |
| 454 | destination = _member_destination(member.name, objects_path, data_path) |
| 455 | planned.append((member, destination)) |
| 456 | if member.isdir(): |
| 457 | if destination.exists() and not destination.is_dir(): |
| 458 | raise BackupRestoreError(f"restore target is not a directory: {destination}") |
| 459 | continue |
| 460 | if destination.exists() and not overwrite: |
| 461 | raise BackupRestoreError(f"restore target already exists: {destination}") |
| 462 | |
| 463 | if selectors is not None and selected_count == 0: |
| 464 | raise BackupRestoreError( |
| 465 | f"no files in the backup match the selection: {', '.join(selectors)}" |
| 466 | ) |
| 467 | |
| 468 | pruned_files = 0 |
| 469 | pruned_dirs = 0 |
| 470 | if prune_extra: |
| 471 | keep_paths = {destination.resolve(strict=False) for _, destination in planned} |
| 472 | pruned_files, pruned_dirs = _prune_extra_runtime_paths( |
| 473 | objects_path, |
| 474 | data_path, |
| 475 | keep_paths, |
| 476 | preserve=preserve, |
| 477 | on_change=on_change, |
| 478 | ) |
| 479 | |
| 480 | restored_files = 0 |
| 481 | restored_bytes = 0 |
| 482 | for member, destination in planned: |
| 483 | if member.isdir(): |
| 484 | destination.mkdir(parents=True, exist_ok=True) |
| 485 | _chmod_from_member(destination, member) |
| 486 | continue |
| 487 | |
| 488 | extracted = archive.extractfile(member) |
| 489 | if extracted is None: |
| 490 | raise BackupRestoreError(f"cannot read archive member: {member.name}") |
| 491 | payload = extracted.read() |
| 492 | if on_change is not None: |
| 493 | before = _current_bytes(destination) |
| 494 | if before != payload: |
| 495 | on_change(member.name, before, payload) |
| 496 | destination.parent.mkdir(parents=True, exist_ok=True) |
| 497 | _write_restored_file(destination, payload, member) |
| 498 | restored_files += 1 |
| 499 | restored_bytes += member.size |
| 500 | |
| 501 | return RestoreSummary( |
| 502 | backup_path=str(backup), |
| 503 | objects_dir=str(objects_path), |
| 504 | data_dir=str(data_path), |
| 505 | files=restored_files, |
| 506 | bytes=restored_bytes, |
| 507 | overwritten=overwrite, |
| 508 | pruned_files=pruned_files, |
| 509 | pruned_dirs=pruned_dirs, |
| 510 | scoped=selectors is not None, |
| 511 | selected=selected_count, |
| 512 | ) |
| 513 | |
| 514 | |
| 515 | def _objects_dir(value: Path | str | None) -> Path: |
| 516 | if value is not None: |
| 517 | return Path(value) |
| 518 | return Path(os.environ.get(OBJECTS_DIR_ENV, DEFAULT_OBJECTS_DIR)) |
| 519 | |
| 520 | |
| 521 | def _data_dir(value: Path | str | None) -> Path: |
| 522 | if value is not None: |
| 523 | return Path(value) |
| 524 | return Path(os.environ.get(DATA_DIR_ENV, DEFAULT_DATA_DIR)) |
| 525 | |
| 526 | |
| 527 | def _backups_dir(value: Path | str | None, *, data_dir: Path | str | None) -> Path: |
| 528 | if value is not None: |
| 529 | return Path(value) |
| 530 | env_value = os.environ.get(BACKUPS_DIR_ENV) |
| 531 | if env_value: |
| 532 | return Path(env_value) |
| 533 | return _data_dir(data_dir) / BACKUPS_DIR |
| 534 | |
| 535 | |
| 536 | def _restore_point_label(value: str) -> str: |
| 537 | label = str(value).strip().lower() |
| 538 | if not RESTORE_POINT_LABEL_RE.fullmatch(label): |
| 539 | raise BackupRestoreError(f"invalid restore point label: {value!r}") |
| 540 | return label |
| 541 | |
| 542 | |
| 543 | def _backup_filename_timestamp(timestamp: str) -> str: |
| 544 | compact = timestamp.replace("+00:00", "Z") |
| 545 | compact = compact.replace("-", "").replace(":", "").replace(".", "") |
| 546 | compact = compact.replace("+", "") |
| 547 | if not compact.endswith("Z"): |
| 548 | compact = f"{compact}Z" |
| 549 | return compact |
| 550 | |
| 551 | |
| 552 | def _runtime_sources(objects_dir: Path, data_dir: Path) -> list[tuple[Path, PurePosixPath]]: |
| 553 | sources = [(objects_dir, PurePosixPath("objects"))] |
| 554 | for name in RUNTIME_DATA_DIRS: |
| 555 | sources.append((data_dir / name, PurePosixPath("data") / name)) |
| 556 | for name in RUNTIME_DATA_FILES: |
| 557 | sources.append((data_dir / name, PurePosixPath("data") / name)) |
| 558 | return sources |
| 559 | |
| 560 | |
| 561 | def _restore_roots(objects_dir: Path, data_dir: Path) -> list[Path]: |
| 562 | return [objects_dir, *(data_dir / name for name in RUNTIME_DATA_DIRS)] |
| 563 | |
| 564 | |
| 565 | def _prune_extra_runtime_paths( |
| 566 | objects_dir: Path, |
| 567 | data_dir: Path, |
| 568 | keep_paths: set[Path], |
| 569 | *, |
| 570 | preserve: Callable[[str], bool] | None = None, |
| 571 | on_change: Callable[[str, bytes | None, bytes | None], None] | None = None, |
| 572 | ) -> tuple[int, int]: |
| 573 | pruned_files = 0 |
| 574 | pruned_dirs = 0 |
| 575 | for root in _restore_roots(objects_dir, data_dir): |
| 576 | if not root.exists() or not root.is_dir(): |
| 577 | continue |
| 578 | archive_root = ( |
| 579 | PurePosixPath("objects") if root == objects_dir |
| 580 | else PurePosixPath("data") / root.relative_to(data_dir).as_posix() |
| 581 | ) |
| 582 | paths = sorted(root.rglob("*"), key=lambda path: len(path.parts), reverse=True) |
| 583 | for path in paths: |
| 584 | if path.resolve(strict=False) in keep_paths: |
| 585 | continue |
| 586 | if ( |
| 587 | preserve is not None |
| 588 | and not path.is_symlink() |
| 589 | and path.is_file() |
| 590 | and preserve((archive_root / path.relative_to(root).as_posix()).as_posix()) |
| 591 | ): |
| 592 | continue |
| 593 | if path.is_symlink() or path.is_file(): |
| 594 | if on_change is not None and not path.is_symlink(): |
| 595 | on_change( |
| 596 | (archive_root / path.relative_to(root).as_posix()).as_posix(), |
| 597 | _current_bytes(path), |
| 598 | None, |
| 599 | ) |
| 600 | path.unlink() |
| 601 | pruned_files += 1 |
| 602 | continue |
| 603 | if path.is_dir(): |
| 604 | try: |
| 605 | path.rmdir() |
| 606 | except OSError: |
| 607 | continue |
| 608 | pruned_dirs += 1 |
| 609 | return pruned_files, pruned_dirs |
| 610 | |
| 611 | |
| 612 | def _current_bytes(path: Path) -> bytes | None: |
| 613 | """What a regular file holds now; None for nothing, a link or a directory.""" |
| 614 | if path.is_symlink() or not path.is_file(): |
| 615 | return None |
| 616 | return path.read_bytes() |
| 617 | |
| 618 | |
| 619 | def _iter_backup_members( |
| 620 | source_root: Path, |
| 621 | archive_root: PurePosixPath, |
| 622 | ) -> list[tuple[Path, PurePosixPath]]: |
| 623 | members: list[tuple[Path, PurePosixPath]] = [(source_root, archive_root)] |
| 624 | children = sorted(source_root.rglob("*"), key=lambda path: path.relative_to(source_root).as_posix()) |
| 625 | for path in children: |
| 626 | if _should_skip(path, source_root): |
| 627 | continue |
| 628 | relative = path.relative_to(source_root).as_posix() |
| 629 | members.append((path, archive_root / relative)) |
| 630 | return members |
| 631 | |
| 632 | |
| 633 | def _should_skip(path: Path, source_root: Path) -> bool: |
| 634 | relative = path.relative_to(source_root) |
| 635 | parts = relative.parts |
| 636 | if any(part in SKIP_PARTS for part in parts): |
| 637 | return True |
| 638 | if any(part.startswith(".") for part in parts): |
| 639 | return True |
| 640 | if path.suffix in SKIP_SUFFIXES: |
| 641 | return True |
| 642 | return not (path.is_dir() or path.is_file()) |
| 643 | |
| 644 | |
| 645 | def _add_manifest(archive: tarfile.TarFile, manifest: dict[str, Any]) -> None: |
| 646 | payload = json.dumps(manifest, indent=2, sort_keys=True).encode("utf-8") |
| 647 | info = tarfile.TarInfo(MANIFEST_NAME) |
| 648 | info.size = len(payload) |
| 649 | info.mode = 0o644 |
| 650 | info.mtime = int(datetime.now(timezone.utc).timestamp()) |
| 651 | _normalize_tarinfo(info) |
| 652 | archive.addfile(info, io.BytesIO(payload)) |
| 653 | |
| 654 | |
| 655 | def _add_path(archive: tarfile.TarFile, path: Path, archive_name: PurePosixPath) -> None: |
| 656 | info = archive.gettarinfo(str(path), arcname=archive_name.as_posix()) |
| 657 | _normalize_tarinfo(info) |
| 658 | if path.is_dir(): |
| 659 | archive.addfile(info) |
| 660 | return |
| 661 | with path.open("rb") as file_obj: |
| 662 | archive.addfile(info, file_obj) |
| 663 | |
| 664 | |
| 665 | def _normalize_tarinfo(info: tarfile.TarInfo) -> None: |
| 666 | info.uid = 0 |
| 667 | info.gid = 0 |
| 668 | info.uname = "" |
| 669 | info.gname = "" |
| 670 | info.pax_headers = {} |
| 671 | |
| 672 | |
| 673 | def _read_manifest(archive: tarfile.TarFile, errors: list[str]) -> dict[str, Any] | None: |
| 674 | try: |
| 675 | member = archive.getmember(MANIFEST_NAME) |
| 676 | except KeyError: |
| 677 | errors.append("backup manifest is missing") |
| 678 | return None |
| 679 | |
| 680 | manifest_file = archive.extractfile(member) |
| 681 | if manifest_file is None: |
| 682 | errors.append("backup manifest cannot be read") |
| 683 | return None |
| 684 | |
| 685 | try: |
| 686 | payload = json.loads(manifest_file.read().decode("utf-8")) |
| 687 | except (UnicodeDecodeError, json.JSONDecodeError) as exc: |
| 688 | errors.append(f"backup manifest is invalid JSON: {exc}") |
| 689 | return None |
| 690 | |
| 691 | if not isinstance(payload, dict): |
| 692 | errors.append("backup manifest must be a JSON object") |
| 693 | return None |
| 694 | return payload |
| 695 | |
| 696 | |
| 697 | def _validate_member(member: tarfile.TarInfo) -> list[str]: |
| 698 | errors: list[str] = [] |
| 699 | try: |
| 700 | path = _safe_archive_path(member.name) |
| 701 | except BackupRestoreError as exc: |
| 702 | return [str(exc)] |
| 703 | |
| 704 | if member.issym() or member.islnk(): |
| 705 | errors.append(f"archive member uses links: {member.name}") |
| 706 | elif not (member.isfile() or member.isdir()): |
| 707 | errors.append(f"archive member has unsupported type: {member.name}") |
| 708 | |
| 709 | parts = path.parts |
| 710 | if not parts: |
| 711 | errors.append("archive member has empty name") |
| 712 | elif parts[0] == "objects": |
| 713 | pass |
| 714 | elif parts[0] == "data": |
| 715 | if len(parts) == 1: |
| 716 | pass |
| 717 | elif parts[1] in RUNTIME_DATA_DIRS: |
| 718 | pass |
| 719 | elif "/".join(parts[1:]) in RUNTIME_DATA_FILES or ( |
| 720 | member.isdir() and "/".join(parts[1:]) == "identity"): |
| 721 | pass |
| 722 | else: |
| 723 | errors.append(f"archive member uses unsupported data directory: {member.name}") |
| 724 | else: |
| 725 | errors.append(f"archive member is outside runtime backup roots: {member.name}") |
| 726 | |
| 727 | return errors |
| 728 | |
| 729 | |
| 730 | def _safe_archive_path(name: str) -> PurePosixPath: |
| 731 | path = PurePosixPath(name) |
| 732 | if not name or path.is_absolute(): |
| 733 | raise BackupRestoreError(f"unsafe archive member path: {name!r}") |
| 734 | if any(part in {"", ".", ".."} for part in path.parts): |
| 735 | raise BackupRestoreError(f"unsafe archive member path: {name!r}") |
| 736 | return path |
| 737 | |
| 738 | |
| 739 | def _member_entry(name: str) -> str | None: |
| 740 | try: |
| 741 | path = _safe_archive_path(name) |
| 742 | except BackupRestoreError: |
| 743 | return None |
| 744 | if path.parts[0] == "objects": |
| 745 | return "objects" |
| 746 | if path.parts[0] == "data" and len(path.parts) > 1: |
| 747 | return f"data/{path.parts[1]}" |
| 748 | return None |
| 749 | |
| 750 | |
| 751 | def _member_destination(name: str, objects_dir: Path, data_dir: Path) -> Path: |
| 752 | path = _safe_archive_path(name) |
| 753 | parts = path.parts |
| 754 | if parts[0] == "objects": |
| 755 | destination = objects_dir.joinpath(*parts[1:]) |
| 756 | _ensure_under(destination, objects_dir) |
| 757 | return destination |
| 758 | |
| 759 | if parts[0] == "data": |
| 760 | if len(parts) == 1: |
| 761 | destination = data_dir |
| 762 | elif parts[1] in RUNTIME_DATA_DIRS or "/".join(parts[1:]) in RUNTIME_DATA_FILES \ |
| 763 | or parts[1:] == ("identity",): |
| 764 | destination = data_dir.joinpath(*parts[1:]) |
| 765 | else: |
| 766 | raise BackupRestoreError(f"unsupported data directory in backup: {name}") |
| 767 | _ensure_under(destination, data_dir) |
| 768 | return destination |
| 769 | |
| 770 | raise BackupRestoreError(f"unsupported backup root: {name}") |
| 771 | |
| 772 | |
| 773 | def _ensure_under(path: Path, root: Path) -> None: |
| 774 | try: |
| 775 | path.resolve(strict=False).relative_to(root.resolve(strict=False)) |
| 776 | except ValueError as exc: |
| 777 | raise BackupRestoreError(f"restore target escapes runtime root: {path}") from exc |
| 778 | |
| 779 | |
| 780 | def _write_restored_file(destination: Path, payload: bytes, member: tarfile.TarInfo) -> None: |
| 781 | temp_path = destination.with_name(f".{destination.name}.restore.tmp") |
| 782 | # Whatever is at the temp path (a stale temp, or a planted symlink) is |
| 783 | # removed, never followed; O_EXCL|O_NOFOLLOW refuses one that reappears. |
| 784 | temp_path.unlink(missing_ok=True) |
| 785 | flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) |
| 786 | with os.fdopen(os.open(temp_path, flags, 0o600), "wb") as file_obj: |
| 787 | file_obj.write(payload) |
| 788 | temp_path.replace(destination) |
| 789 | _chmod_from_member(destination, member) |
| 790 | |
| 791 | |
| 792 | def _chmod_from_member(path: Path, member: tarfile.TarInfo) -> None: |
| 793 | mode = member.mode & 0o777 |
| 794 | if mode: |
| 795 | path.chmod(mode) |
| 796 | |
| 797 | |
| 798 | def _manifest_int(value: Any) -> int | None: |
| 799 | if isinstance(value, int): |
| 800 | return value |
| 801 | try: |
| 802 | return int(value) |
| 803 | except (TypeError, ValueError): |
| 804 | return None |
| 805 | |
| 806 | |
| 807 | def _utc_timestamp() -> str: |
| 808 | return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 809 | |
| 810 | |
| 811 | def main(argv: list[str] | None = None) -> int: |
| 812 | parser = argparse.ArgumentParser(description="Create, verify, and restore DBBASIC runtime backups.") |
| 813 | subcommands = parser.add_subparsers(dest="command", required=True) |
| 814 | |
| 815 | create = subcommands.add_parser("create", help="create a runtime backup") |
| 816 | create.add_argument("output", type=Path) |
| 817 | create.add_argument("--objects-dir", type=Path) |
| 818 | create.add_argument("--data-dir", type=Path) |
| 819 | create.add_argument("--json", action="store_true") |
| 820 | |
| 821 | verify = subcommands.add_parser("verify", help="verify a runtime backup") |
| 822 | verify.add_argument("backup", type=Path) |
| 823 | verify.add_argument("--json", action="store_true") |
| 824 | |
| 825 | restore = subcommands.add_parser("restore", help="restore a runtime backup") |
| 826 | restore.add_argument("backup", type=Path) |
| 827 | restore.add_argument("--objects-dir", type=Path, required=True) |
| 828 | restore.add_argument("--data-dir", type=Path, required=True) |
| 829 | restore.add_argument("--overwrite", action="store_true") |
| 830 | restore.add_argument("--prune-extra", action="store_true") |
| 831 | restore.add_argument("--collection", action="append", default=[]) |
| 832 | restore.add_argument("--only", action="append", default=[]) |
| 833 | restore.add_argument( |
| 834 | "--preview", action="store_true", |
| 835 | help="print what the restore would change and write nothing: with one " |
| 836 | "--collection, its records; otherwise the permission-policy difference", |
| 837 | ) |
| 838 | restore.add_argument( |
| 839 | "--yes", action="store_true", |
| 840 | help="apply an --overwrite restore that changes the permission policy " |
| 841 | "without asking (non-interactive use); the difference is still printed", |
| 842 | ) |
| 843 | restore.add_argument("--json", action="store_true") |
| 844 | |
| 845 | args = parser.parse_args(argv) |
| 846 | |
| 847 | try: |
| 848 | if args.command == "create": |
| 849 | result = create_runtime_backup( |
| 850 | args.output, |
| 851 | objects_dir=args.objects_dir, |
| 852 | data_dir=args.data_dir, |
| 853 | ) |
| 854 | _print_result(result.to_dict(), json_output=args.json) |
| 855 | return 0 |
| 856 | if args.command == "verify": |
| 857 | result = verify_runtime_backup(args.backup) |
| 858 | _print_result(result.to_dict(), json_output=args.json) |
| 859 | if not result.ok: |
| 860 | return 1 |
| 861 | # Sound but incomplete: file records whose bytes are not in it. |
| 862 | return 2 if result.missing_file_bytes else 0 |
| 863 | if args.command == "restore": |
| 864 | select = [f"data/collections/{name}" for name in args.collection] + list(args.only) |
| 865 | if args.preview and not args.collection and not args.only: |
| 866 | diff, diff_hash = _restore_policy_diff(args) |
| 867 | _print_policy_diff(diff, diff_hash, json_output=args.json) |
| 868 | return 0 |
| 869 | if args.preview: |
| 870 | if len(args.collection) != 1 or args.only: |
| 871 | raise BackupRestoreError( |
| 872 | "--preview requires exactly one --collection and no --only paths" |
| 873 | ) |
| 874 | import object_backup_index |
| 875 | import object_collections |
| 876 | |
| 877 | collection = args.collection[0] |
| 878 | if not object_collections.validate_collection_name(collection): |
| 879 | raise BackupRestoreError(f"invalid collection name: {collection!r}") |
| 880 | member_name = f"data/collections/{collection}/records.tsv" |
| 881 | archived_raw = read_backup_member(args.backup, member_name) |
| 882 | live_raw = object_backup_index._live_records_tsv(collection, data_dir=args.data_dir) |
| 883 | backup_rows = object_backup_index._parse_tsv_by_id(archived_raw) |
| 884 | live_rows = object_backup_index._parse_tsv_by_id(live_raw) |
| 885 | diff = object_backup_index._diff_records(backup_rows, live_rows) |
| 886 | result = { |
| 887 | "target": {"kind": "collection", "name": collection}, |
| 888 | "backup_id": str(args.backup), |
| 889 | "present_in_backup": archived_raw is not None, |
| 890 | **diff, |
| 891 | } |
| 892 | _print_result(result, json_output=args.json) |
| 893 | return 0 |
| 894 | policy_diff: dict[str, Any] | None = None |
| 895 | if args.overwrite: |
| 896 | # Only an overwrite can replace a live policy: show what it |
| 897 | # changes in who may do what, and apply it only when |
| 898 | # confirmed. Fail closed when it cannot be computed. |
| 899 | policy_diff, diff_hash = _restore_policy_diff(args, select=select or None) |
| 900 | if policy_diff["changed"]: |
| 901 | if not args.json: |
| 902 | _print_policy_diff(policy_diff, diff_hash, json_output=False) |
| 903 | if not args.yes and not _confirmed_interactively(args): |
| 904 | raise _PolicyNotConfirmed(policy_diff, diff_hash) |
| 905 | result = restore_runtime_backup( |
| 906 | args.backup, |
| 907 | objects_dir=args.objects_dir, |
| 908 | data_dir=args.data_dir, |
| 909 | overwrite=args.overwrite, |
| 910 | prune_extra=args.prune_extra, |
| 911 | select=select or None, |
| 912 | ) |
| 913 | output = result.to_dict() |
| 914 | if policy_diff is not None and args.json: |
| 915 | output["policy_diff"] = policy_diff |
| 916 | _print_result(output, json_output=args.json) |
| 917 | return 0 |
| 918 | except _PolicyNotConfirmed as exc: |
| 919 | if args.json: |
| 920 | print(json.dumps({"ok": False, "error": str(exc), "policy_diff": exc.diff, |
| 921 | "policy_diff_hash": exc.diff_hash}, indent=2)) |
| 922 | else: |
| 923 | print(f"ERROR: {exc}") |
| 924 | return 1 |
| 925 | except BackupError as exc: |
| 926 | if getattr(args, "json", False): |
| 927 | print(json.dumps({"ok": False, "error": str(exc)}, indent=2)) |
| 928 | else: |
| 929 | print(f"ERROR: {exc}") |
| 930 | return 1 |
| 931 | |
| 932 | return 1 |
| 933 | |
| 934 | |
| 935 | class _PolicyNotConfirmed(BackupError): |
| 936 | def __init__(self, diff: dict[str, Any], diff_hash: str): |
| 937 | loosens = " and LOOSENS it" if diff.get("loosens") else "" |
| 938 | super().__init__( |
| 939 | f"the restore changes the permission policy{loosens}; nothing was restored. " |
| 940 | "Check the difference (restore --preview) and re-run with --yes to apply it" |
| 941 | ) |
| 942 | self.diff = diff |
| 943 | self.diff_hash = diff_hash |
| 944 | |
| 945 | |
| 946 | def _restore_policy_diff( |
| 947 | args: argparse.Namespace, *, select: Sequence[str] | None = None |
| 948 | ) -> tuple[dict[str, Any], str]: |
| 949 | import object_policy_diff |
| 950 | |
| 951 | try: |
| 952 | diff = object_policy_diff.restore_policy_diff( |
| 953 | args.backup, args.data_dir, select=select, prune=bool(args.prune_extra), |
| 954 | ) |
| 955 | except object_policy_diff.PolicyDiffError as exc: |
| 956 | raise BackupRestoreError( |
| 957 | f"restore refused: the permission-policy difference cannot be computed ({exc})" |
| 958 | ) from exc |
| 959 | return diff, object_policy_diff.policy_diff_hash(diff, backup=Path(args.backup).name) |
| 960 | |
| 961 | |
| 962 | def _print_policy_diff(diff: dict[str, Any], diff_hash: str, *, json_output: bool) -> None: |
| 963 | import object_policy_diff |
| 964 | |
| 965 | if json_output: |
| 966 | print(json.dumps({"policy_diff": diff, "policy_diff_hash": diff_hash}, indent=2)) |
| 967 | return |
| 968 | print(object_policy_diff.format_policy_diff(diff)) |
| 969 | |
| 970 | |
| 971 | def _confirmed_interactively(args: argparse.Namespace) -> bool: |
| 972 | """Ask on a terminal; anything but "yes", or no terminal, is a no.""" |
| 973 | import sys |
| 974 | |
| 975 | if args.json or not sys.stdin.isatty(): |
| 976 | return False |
| 977 | try: |
| 978 | answer = input("Apply this restore and its policy change? Type 'yes' to continue: ") |
| 979 | except EOFError: |
| 980 | return False |
| 981 | return answer.strip().lower() == "yes" |
| 982 | |
| 983 | |
| 984 | def _print_result(result: dict[str, Any], *, json_output: bool) -> None: |
| 985 | if json_output: |
| 986 | print(json.dumps(result, indent=2)) |
| 987 | return |
| 988 | |
| 989 | for key, value in result.items(): |
| 990 | print(f"{key}: {value}") |
| 991 | |
| 992 | |
| 993 | if __name__ == "__main__": |
| 994 | raise SystemExit(main()) |