offgit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,401 @@
1
+ """Consistent snapshots and encrypted, versioned off-site backups via restic.
2
+
3
+ Flow (``offgit-server backup``):
4
+
5
+ 1. exclusive ``backup.lock`` (no overlapping backup/forget/restore)
6
+ 2. shared ``maintenance.lock`` only while the SQLite online-backup API copies
7
+ the live store into a private staging directory (no long write lock)
8
+ 3. verify the copy (integrity, foreign keys, schema, blob digests, manifests)
9
+ 4. write ``manifest.json`` (from the same snapshot) and publish the stage
10
+ 5. ``restic backup --json`` the stage; success only when restic exits 0 and
11
+ the reported snapshot is listed by ``restic snapshots``
12
+ 6. record health atomically (outside the DB); always remove the stage
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import json
19
+ import os
20
+ import re
21
+ import secrets
22
+ import shutil
23
+ import sqlite3
24
+ import subprocess
25
+ from collections.abc import Callable, Sequence
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ from offgit import __version__
30
+ from offgit.server.health import read_health, write_health
31
+ from offgit.server.locks import LockBusy, flock
32
+ from offgit.server.schema import connect, file_sha256, utcnow, verify_connection
33
+ from offgit.server.settings import ServerSettings
34
+
35
+ STAGE_DB = "store.sqlite3"
36
+ STAGE_MANIFEST = "manifest.json"
37
+ BACKUP_FORMAT = "offgit-backup-v1"
38
+
39
+ Runner = Callable[..., subprocess.CompletedProcess[str]]
40
+
41
+
42
+ class BackupError(Exception):
43
+ pass
44
+
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # snapshots
48
+
49
+
50
+ def create_snapshot(settings: ServerSettings, destination: Path) -> dict[str, Any]:
51
+ """Write a verified standalone copy of the store + manifest into an empty directory."""
52
+ destination.mkdir(mode=0o700, parents=True, exist_ok=True)
53
+ os.chmod(destination, 0o700)
54
+ if any(destination.iterdir()):
55
+ raise BackupError(f"snapshot destination {destination} is not empty")
56
+ if not settings.store_path.exists():
57
+ raise BackupError("store does not exist")
58
+ db_path = destination / STAGE_DB
59
+ old = os.umask(0o077)
60
+ try:
61
+ with flock(
62
+ settings.locks_dir / "maintenance.lock",
63
+ exclusive=False,
64
+ timeout=settings.lock_timeout_seconds,
65
+ ):
66
+ src = connect(settings.store_path, busy_timeout_ms=settings.busy_timeout_ms)
67
+ dst = sqlite3.connect(str(db_path))
68
+ try:
69
+ src.backup(dst, pages=256, sleep=0.005)
70
+ finally:
71
+ src.close()
72
+ dst.close()
73
+ except LockBusy as exc:
74
+ raise BackupError("store is in maintenance (restore/migrate running)") from exc
75
+ except sqlite3.Error as exc:
76
+ raise BackupError(f"SQLite online backup failed: {exc}") from exc
77
+ finally:
78
+ os.umask(old)
79
+
80
+ conn = connect(db_path)
81
+ try:
82
+ conn.execute("PRAGMA journal_mode = DELETE") # standalone file, no sidecars
83
+ report = verify_connection(conn)
84
+ if not report.ok:
85
+ raise BackupError("snapshot verification failed: " + "; ".join(report.problems[:5]))
86
+ projects = conn.execute(
87
+ "SELECT canonical_remote, revision FROM projects ORDER BY canonical_remote"
88
+ ).fetchall()
89
+ finally:
90
+ conn.close()
91
+ os.chmod(db_path, 0o600)
92
+ manifest = {
93
+ "format": BACKUP_FORMAT,
94
+ "offgit_version": __version__,
95
+ "schema_version": report.schema_version,
96
+ "server_id": report.server_id,
97
+ "server_epoch": report.server_epoch,
98
+ "captured_at": utcnow(),
99
+ "projects": len(projects),
100
+ "revisions": {c: r for c, r in projects},
101
+ "blobs": report.blobs,
102
+ "blob_bytes": report.blob_bytes,
103
+ "db_file": STAGE_DB,
104
+ "db_sha256": file_sha256(db_path),
105
+ "db_size": db_path.stat().st_size,
106
+ }
107
+ mpath = destination / STAGE_MANIFEST
108
+ fd = os.open(mpath, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
109
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
110
+ json.dump(manifest, fh, indent=2, sort_keys=True)
111
+ fh.write("\n")
112
+ fh.flush()
113
+ os.fsync(fh.fileno())
114
+ _fsync_dir(destination)
115
+ return manifest
116
+
117
+
118
+ def _fsync_dir(path: Path) -> None:
119
+ fd = os.open(path, os.O_RDONLY)
120
+ try:
121
+ os.fsync(fd)
122
+ finally:
123
+ os.close(fd)
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # restic plumbing
128
+
129
+ _SECRET_FIELD = re.compile(
130
+ r'(?i)("?(?:access_token|refresh_token|token|password|client_secret)"?\s*[:=]\s*)("[^"]*"|\S+)'
131
+ )
132
+ _URL_USERINFO = re.compile(r"(?i)(https?://)[^/@\s]+@")
133
+
134
+
135
+ def redact(text: str, limit: int = 2000) -> str:
136
+ text = _SECRET_FIELD.sub(lambda m: m.group(1) + "***", text)
137
+ text = _URL_USERINFO.sub(lambda m: m.group(1) + "***@", text)
138
+ text = text.strip()
139
+ return text[:limit] + ("…" if len(text) > limit else "")
140
+
141
+
142
+ def restic_env(settings: ServerSettings) -> dict[str, str]:
143
+ env = {
144
+ k: v
145
+ for k, v in os.environ.items()
146
+ if k in ("PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "XDG_CACHE_HOME")
147
+ }
148
+ env.setdefault("PATH", "/usr/local/bin:/usr/bin:/bin")
149
+ env["RESTIC_REPOSITORY"] = settings.backup.repository
150
+ env["RESTIC_PASSWORD_FILE"] = str(settings.password_file)
151
+ if settings.backup.rclone_config:
152
+ env["RCLONE_CONFIG"] = settings.backup.rclone_config
153
+ return env
154
+
155
+
156
+ def _restic(
157
+ settings: ServerSettings, args: Sequence[str], runner: Runner, *, timeout: int | None = None
158
+ ) -> subprocess.CompletedProcess[str]:
159
+ argv = [settings.backup.restic_bin, *args]
160
+ try:
161
+ return runner(
162
+ argv,
163
+ env=restic_env(settings),
164
+ capture_output=True,
165
+ text=True,
166
+ timeout=timeout or settings.backup.timeout_seconds,
167
+ check=False,
168
+ stdin=subprocess.DEVNULL,
169
+ )
170
+ except FileNotFoundError as exc:
171
+ raise BackupError(f"restic executable not found: {settings.backup.restic_bin}") from exc
172
+ except subprocess.TimeoutExpired as exc:
173
+ raise BackupError(f"restic {args[0]} timed out") from exc
174
+
175
+
176
+ def _check_password_file(settings: ServerSettings) -> None:
177
+ pf = settings.password_file
178
+ try:
179
+ st = pf.stat()
180
+ except FileNotFoundError as exc:
181
+ raise BackupError(
182
+ f"restic password file {pf} is missing; run 'offgit-server backup-init'"
183
+ ) from exc
184
+ if st.st_mode & 0o077:
185
+ raise BackupError(f"restic password file {pf} must be mode 0600")
186
+
187
+
188
+ def repository_id(settings: ServerSettings, runner: Runner) -> str:
189
+ proc = _restic(settings, ["cat", "config", "--json", "--no-lock"], runner, timeout=300)
190
+ if proc.returncode != 0:
191
+ raise BackupError("cannot read restic repository config: " + redact(proc.stderr))
192
+ try:
193
+ cfg = json.loads(proc.stdout)
194
+ rid = cfg["id"]
195
+ except (ValueError, KeyError, TypeError) as exc:
196
+ raise BackupError("unexpected output from 'restic cat config'") from exc
197
+ if not isinstance(rid, str) or not re.match(r"^[0-9a-f]{64}$", rid):
198
+ raise BackupError("unexpected restic repository id")
199
+ return rid
200
+
201
+
202
+ def check_repository(settings: ServerSettings, runner: Runner) -> str:
203
+ _check_password_file(settings)
204
+ try:
205
+ expected = settings.repo_id_path.read_text(encoding="utf-8").strip()
206
+ except FileNotFoundError as exc:
207
+ raise BackupError(
208
+ "backup repository identity not recorded; run 'offgit-server backup-init' "
209
+ "(or 'backup-init --adopt-existing' for an existing repository)"
210
+ ) from exc
211
+ actual = repository_id(settings, runner)
212
+ if actual != expected:
213
+ raise BackupError(
214
+ "restic repository identity does not match the recorded one; refusing to back up "
215
+ "to an unexpected destination"
216
+ )
217
+ return actual
218
+
219
+
220
+ def backup_init(
221
+ settings: ServerSettings, *, adopt_existing: bool, runner: Runner = subprocess.run
222
+ ) -> dict[str, Any]:
223
+ """Explicit one-time admin action: create password file (if absent) and init/adopt repo."""
224
+ with flock(settings.locks_dir / "backup.lock", exclusive=True, timeout=0):
225
+ pf = settings.password_file
226
+ created_password = False
227
+ if not pf.exists():
228
+ pf.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
229
+ fd = os.open(pf, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
230
+ with os.fdopen(fd, "w", encoding="ascii") as fh:
231
+ fh.write(secrets.token_urlsafe(48) + "\n")
232
+ fh.flush()
233
+ os.fsync(fh.fileno())
234
+ created_password = True
235
+ _check_password_file(settings)
236
+ if not adopt_existing:
237
+ proc = _restic(settings, ["init"], runner, timeout=600)
238
+ if proc.returncode != 0:
239
+ raise BackupError(
240
+ "restic init failed (use --adopt-existing if the repository already exists): "
241
+ + redact(proc.stderr)
242
+ )
243
+ rid = repository_id(settings, runner)
244
+ from offgit.config import atomic_write_private
245
+
246
+ atomic_write_private(settings.repo_id_path, rid + "\n")
247
+ return {
248
+ "repository_id": rid,
249
+ "created_password_file": created_password,
250
+ "password_file": str(pf),
251
+ }
252
+
253
+
254
+ def _parse_snapshot_id(stdout: str) -> str | None:
255
+ snapshot_id = None
256
+ for line in stdout.splitlines():
257
+ line = line.strip()
258
+ if not line.startswith("{"):
259
+ continue
260
+ try:
261
+ msg = json.loads(line)
262
+ except ValueError:
263
+ continue
264
+ if isinstance(msg, dict) and msg.get("message_type") == "summary":
265
+ sid = msg.get("snapshot_id")
266
+ if isinstance(sid, str) and re.match(r"^[0-9a-f]{8,64}$", sid):
267
+ snapshot_id = sid
268
+ return snapshot_id
269
+
270
+
271
+ def run_backup(settings: ServerSettings, *, runner: Runner = subprocess.run) -> dict[str, Any]:
272
+ try:
273
+ lock = flock(settings.locks_dir / "backup.lock", exclusive=True, timeout=0)
274
+ lock.__enter__()
275
+ except LockBusy as exc:
276
+ raise BackupError("another backup/maintenance job is running") from exc
277
+ health = read_health(settings.health_path)
278
+ if health.get("corrupt"):
279
+ health = {}
280
+ health["last_attempt_at"] = utcnow()
281
+ stage = settings.stage_dir
282
+ tmp = settings.data_dir / f"backup-stage.tmp-{secrets.token_hex(4)}"
283
+ try:
284
+ try:
285
+ repo_id = check_repository(settings, runner)
286
+ _cleanup_stage(settings)
287
+ manifest = create_snapshot(settings, tmp)
288
+ os.replace(tmp, stage)
289
+ _fsync_dir(settings.data_dir)
290
+ proc = _restic(
291
+ settings,
292
+ [
293
+ "backup",
294
+ "--json",
295
+ "--tag", settings.backup.tag,
296
+ "--host", settings.backup.host_tag,
297
+ str(stage),
298
+ ],
299
+ runner,
300
+ ) # fmt: skip
301
+ if proc.returncode != 0:
302
+ kind = "incomplete snapshot" if proc.returncode == 3 else f"exit {proc.returncode}"
303
+ raise BackupError(f"restic backup failed ({kind}): " + redact(proc.stderr))
304
+ snapshot_id = _parse_snapshot_id(proc.stdout)
305
+ if not snapshot_id:
306
+ raise BackupError("restic did not report a snapshot id")
307
+ verify = _restic(settings, ["snapshots", "--json", snapshot_id], runner, timeout=600)
308
+ if verify.returncode != 0:
309
+ raise BackupError("could not list the new snapshot: " + redact(verify.stderr))
310
+ try:
311
+ listed = json.loads(verify.stdout or "[]")
312
+ except ValueError as exc:
313
+ raise BackupError("unexpected output from 'restic snapshots'") from exc
314
+ if not any(
315
+ isinstance(s, dict)
316
+ and (s.get("id", "").startswith(snapshot_id) or s.get("short_id") == snapshot_id)
317
+ for s in listed
318
+ ):
319
+ raise BackupError("new snapshot is not listed by restic")
320
+ except BackupError as exc:
321
+ health.update({"last_result": "failed", "last_error": redact(str(exc))})
322
+ write_health(settings.health_path, health)
323
+ raise
324
+ except Exception as exc:
325
+ health.update(
326
+ {"last_result": "failed", "last_error": redact(f"{type(exc).__name__}: {exc}")}
327
+ )
328
+ write_health(settings.health_path, health)
329
+ raise BackupError(f"backup failed: {type(exc).__name__}") from exc
330
+ health.update(
331
+ {
332
+ "last_result": "ok",
333
+ "last_error": None,
334
+ "last_success_at": utcnow(),
335
+ "snapshot_id": snapshot_id,
336
+ "repository_id": repo_id,
337
+ "captured_at": manifest["captured_at"],
338
+ "captured_revisions": manifest["revisions"],
339
+ "db_sha256": manifest["db_sha256"],
340
+ "server_epoch": manifest["server_epoch"],
341
+ }
342
+ )
343
+ write_health(settings.health_path, health)
344
+ return {"snapshot_id": snapshot_id, "manifest": manifest}
345
+ finally:
346
+ _cleanup_stage(settings)
347
+ with contextlib.suppress(Exception):
348
+ shutil.rmtree(tmp, ignore_errors=True)
349
+ lock.__exit__(None, None, None)
350
+
351
+
352
+ def _cleanup_stage(settings: ServerSettings) -> None:
353
+ shutil.rmtree(settings.stage_dir, ignore_errors=True)
354
+ for leftover in settings.data_dir.glob("backup-stage.tmp-*"):
355
+ shutil.rmtree(leftover, ignore_errors=True)
356
+
357
+
358
+ def forget(
359
+ settings: ServerSettings, *, prune: bool, dry_run: bool, runner: Runner = subprocess.run
360
+ ) -> str:
361
+ health = read_health(settings.health_path)
362
+ if health.get("last_result") != "ok":
363
+ raise BackupError("refusing retention: the most recent backup did not succeed")
364
+ b = settings.backup
365
+ args = [
366
+ "forget",
367
+ "--tag", b.tag,
368
+ "--host", b.host_tag,
369
+ "--keep-hourly", str(b.keep_hourly),
370
+ "--keep-daily", str(b.keep_daily),
371
+ "--keep-weekly", str(b.keep_weekly),
372
+ "--keep-monthly", str(b.keep_monthly),
373
+ ] # fmt: skip
374
+ if dry_run:
375
+ args.append("--dry-run")
376
+ elif prune:
377
+ args.append("--prune")
378
+ if not any([b.keep_hourly, b.keep_daily, b.keep_weekly, b.keep_monthly]):
379
+ raise BackupError("retention policy keeps nothing; refusing")
380
+ with flock(settings.locks_dir / "backup.lock", exclusive=True, timeout=0):
381
+ check_repository(settings, runner)
382
+ proc = _restic(settings, args, runner)
383
+ if proc.returncode != 0:
384
+ raise BackupError("restic forget failed: " + redact(proc.stderr))
385
+ return proc.stdout
386
+
387
+
388
+ def check(
389
+ settings: ServerSettings, *, read_data_subset: str | None, runner: Runner = subprocess.run
390
+ ) -> str:
391
+ args = ["check"]
392
+ if read_data_subset:
393
+ if not re.match(r"^([0-9]{1,3}(\.[0-9]+)?%|[0-9]+/[0-9]+)$", read_data_subset):
394
+ raise BackupError("invalid --read-data-subset")
395
+ args.append(f"--read-data-subset={read_data_subset}")
396
+ with flock(settings.locks_dir / "backup.lock", exclusive=True, timeout=0):
397
+ check_repository(settings, runner)
398
+ proc = _restic(settings, args, runner)
399
+ if proc.returncode != 0:
400
+ raise BackupError("restic check failed: " + redact(proc.stderr + proc.stdout))
401
+ return proc.stdout