eatback / py /backup.py
kritpakin's picture
Add 3D flow page, safety fixes, evidence rules; rebuild static demo
052adbf verified
Raw History Blame Contribute Delete
8.85 kB
"""Backups of the school database (Python standard library only).
Made automatically when the server starts, after every finished round, and before anything that
replaces data (demo reset, starting real use, restoring a backup). Every file is checked with
PRAGMA integrity_check before it counts. Kept: the newest 30 files plus the last one of each of the
past 30 days. Copy the backups folder to a USB drive or cloud folder from time to time.
python server/backup.py make a backup now
python server/backup.py list list backups, newest first
python server/backup.py restore NAME put a backup back (the current data is backed up first)
Restoring from the command line: stop the server first, then start it again afterwards.
"""
from __future__ import annotations
import json
import os
import re
import sqlite3
import sys
from datetime import date, datetime, timedelta
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from db import DB_PATH, LOCK, conn, log_event, migrate # noqa: E402
BACKUP_DIR = Path(os.environ.get("EATBACK_BACKUP_DIR") or DB_PATH.parent / "backups")
KEEP_RECENT, KEEP_DAYS = 30, 30
NAME = re.compile(r"^eatback-(\d{8})-(\d{6})(?:-(\d+))?-([a-z-]+)\.sqlite3$")
REASONS = {
"start": ("เปิดเซิร์ฟเวอร์", "Server start"), "close": ("จบรอบ", "Round ended"), "manual": ("กดสำรองเอง", "Manual"),
"before-reset": ("ก่อนรีเซ็ตเดโม", "Before demo reset"), "before-reseed": ("ก่อนโหลดเดโมชุดใหม่", "Before new demo data"),
"before-real": ("ก่อนเริ่มใช้งานจริง", "Before starting real use"), "before-restore": ("ก่อนกู้คืน", "Before restore"),
}
class BackupError(Exception):
pass
def enabled() -> bool:
"""The in-browser demo keeps its data in the visitor's browser; there is nothing to back up there."""
return not os.environ.get("EATBACK_BROWSER")
def _open_ro(path: Path) -> sqlite3.Connection:
return sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True)
def inspect(path: Path, full: bool = True) -> dict:
"""Open a backup read-only: is it a whole, readable EatBack database, and what is in it?"""
try:
c = _open_ro(path)
try:
ok = c.execute("PRAGMA integrity_check" if full else "PRAGMA quick_check").fetchone()[0] == "ok"
tables = {r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type = 'table'")}
if not ok or not {"settings", "menus", "meals", "events"} <= tables:
return {"ok": False}
n, closed, last = c.execute(
"SELECT COUNT(*), COALESCE(SUM(status = 'closed'), 0), MAX(CASE WHEN status = 'closed' THEN date END) FROM meals").fetchone()
meta = dict(c.execute("SELECT key, value FROM settings WHERE key IN ('data_mode', 'school_name')").fetchall())
return {"ok": True, "meals": n, "closed_rounds": closed, "last_round": last,
"data_mode": "real" if meta.get("data_mode") == "real" else "demo",
"school_name": json.loads(meta["school_name"]) if "school_name" in meta else None}
finally:
c.close()
except (sqlite3.Error, ValueError):
return {"ok": False}
def _files() -> list[tuple[datetime, int, Path, str]]:
"""(time, counter, path, reason) for every backup file, newest first."""
out = []
if BACKUP_DIR.is_dir():
for p in BACKUP_DIR.iterdir():
m = NAME.match(p.name)
if m and p.is_file():
out.append((datetime.strptime(m[1] + m[2], "%Y%m%d%H%M%S"), int(m[3] or 1), p, m[4]))
return sorted(out, key=lambda f: (f[0], f[1]), reverse=True)
def listing() -> list[dict]:
return [{"name": p.name, "created_at": t.isoformat(timespec="seconds"), "reason": reason,
"reason_th": REASONS.get(reason, (reason,))[0], "reason_en": REASONS.get(reason, (reason, reason))[1],
"size": p.stat().st_size, **inspect(p, full=False)} for t, _, p, reason in _files()]
def path_of(name: str) -> Path:
"""The backup file for a name from listing(); anything else (paths, other files) is refused."""
if not isinstance(name, str) or not NAME.match(name):
raise BackupError("ไม่พบไฟล์สำรองนี้")
p = BACKUP_DIR / name
if p.parent.resolve() != BACKUP_DIR.resolve() or not p.is_file():
raise BackupError("ไม่พบไฟล์สำรองนี้")
return p
def prune() -> list[str]:
files = _files()
keep = {p.name for _, _, p, _ in files[:KEEP_RECENT]}
days: set[date] = set()
oldest = date.today() - timedelta(days=KEEP_DAYS)
for t, _, p, _ in files: # newest first, so this keeps the last backup of each day
if t.date() >= oldest and t.date() not in days:
days.add(t.date())
keep.add(p.name)
removed = []
for _, _, p, _ in files:
if p.name not in keep:
p.unlink(missing_ok=True)
removed.append(p.name)
return removed
def make(reason: str) -> dict:
"""Copy the live database into a new, checked backup file."""
if not enabled():
raise BackupError("ลิงก์ออนไลน์เก็บข้อมูลไว้ในเบราว์เซอร์ ไม่มีการสำรองข้อมูล")
if reason not in REASONS:
raise BackupError("unknown backup reason")
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
now = datetime.now()
stamp = now.strftime("%Y%m%d-%H%M%S")
name, i = f"eatback-{stamp}-{reason}.sqlite3", 2
while (BACKUP_DIR / name).exists():
name, i = f"eatback-{stamp}-{i}-{reason}.sqlite3", i + 1
part = BACKUP_DIR / f"{name}.part"
dest = sqlite3.connect(part)
try:
with LOCK:
conn.backup(dest)
dest.execute("PRAGMA journal_mode = DELETE") # one self-contained file, no -wal/-shm beside it
finally:
dest.close()
info = inspect(part)
if not info["ok"]:
part.unlink(missing_ok=True)
raise BackupError("สำรองข้อมูลไม่สำเร็จ ไฟล์ที่ได้ตรวจไม่ผ่าน")
os.replace(part, BACKUP_DIR / name)
prune()
return {"name": name, "created_at": now.isoformat(timespec="seconds"), "reason": reason,
"size": (BACKUP_DIR / name).stat().st_size, **info}
def restore(name: str) -> dict:
"""Replace the live data with a backup. The current data is backed up first, so a restore can be undone."""
if not enabled():
raise BackupError("ลิงก์ออนไลน์เก็บข้อมูลไว้ในเบราว์เซอร์ ไม่มีการสำรองข้อมูล")
path = path_of(name)
info = inspect(path)
if not info["ok"]:
raise BackupError("ไฟล์สำรองนี้เสียหรือไม่ใช่ข้อมูล EatBack กู้คืนไม่ได้")
with LOCK:
safety = make("before-restore")
src = _open_ro(path)
try:
src.backup(conn)
finally:
src.close()
migrate() # an older backup gets today's columns and indexes
log_event("backup_restored", name=name, safety_backup=safety["name"])
return {"restored": name, "safety_backup": safety["name"], **info}
def _cli(argv: list[str]) -> int:
cmd = argv[0] if argv else "make"
try:
if cmd == "make":
b = make("manual")
print(f"สำรองแล้ว: {BACKUP_DIR / b['name']} ({b['closed_rounds']} รอบที่จบแล้ว)")
elif cmd == "list":
rows = listing()
print(f"โฟลเดอร์: {BACKUP_DIR}")
for r in rows:
state = "ok" if r["ok"] else "เสีย"
print(f" {r['name']:<48} {r['reason_th']:<22} {r.get('closed_rounds', '-'):>5} รอบ {state}")
if not rows:
print(" (ยังไม่มีไฟล์สำรอง)")
elif cmd == "restore" and len(argv) == 2:
r = restore(argv[1])
print(f"กู้คืนแล้ว: {r['restored']}\nข้อมูลก่อนกู้คืนเก็บไว้ที่: {r['safety_backup']}")
else:
print(__doc__)
return 2
except BackupError as e:
print(f"ไม่สำเร็จ: {e}")
return 1
return 0
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
raise SystemExit(_cli(sys.argv[1:]))