douyinWEB/backend/app/db_backup.py
hackrobot 1e8eb0130a Sync dylive production working tree to test3.
Include latest server fixes for yt-long/disk/ops and related frontend.
Exclude .bak scratch files.
2026-10-14 07:04:18 +00:00

215 lines
6.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""SQLite backup — copy-only, never modifies source DB.
Hardening (disk-safe):
- Cap file count (db_backup_keep_max), not only age
- Skip auto backup if last auto copy is fresher than interval
- Refuse new backup when free disk is below floor (leave headroom for live)
"""
from __future__ import annotations
import shutil
import time
from pathlib import Path
from typing import Any
from .config import settings
def _backup_dir() -> Path:
p = Path(settings.data_dir) / "backups"
p.mkdir(parents=True, exist_ok=True)
return p
def _db_path() -> Path:
return Path(settings.data_dir) / "monitor.db"
def _disk_free_gb(path: Path | None = None) -> float:
try:
usage = shutil.disk_usage(str(path or settings.data_dir))
return float(usage.free) / (1024.0 ** 3)
except Exception:
return 999.0
def _latest_auto_mtime() -> float:
newest = 0.0
for p in _backup_dir().glob("monitor_*_auto.db"):
try:
newest = max(newest, p.stat().st_mtime)
except OSError:
continue
return newest
def run_backup(*, label: str = "", force: bool = False) -> dict[str, Any]:
src = _db_path()
if not src.is_file():
return {"ok": False, "error": "db_not_found"}
free = _disk_free_gb()
# Need room for one full copy + ~2GB headroom
need_gb = max(3.0, (src.stat().st_size / (1024.0 ** 3)) * 1.15 + 2.0)
if (not force) and free < need_gb:
return {
"ok": False,
"error": "disk_too_low",
"disk_free_gb": round(free, 2),
"need_gb": round(need_gb, 2),
}
stamp = time.strftime("%Y%m%d_%H%M%S")
name = f"monitor_{stamp}{('_' + label) if label else ''}.db"
dest = _backup_dir() / name
try:
shutil.copy2(src, dest)
size = dest.stat().st_size
return {
"ok": True,
"path": str(dest),
"name": name,
"size": size,
"ts": time.time(),
"disk_free_gb": round(_disk_free_gb(), 2),
}
except Exception as exc:
return {"ok": False, "error": str(exc)[:200]}
def list_backups(*, limit: int = 20) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for p in sorted(_backup_dir().glob("monitor_*.db"), key=lambda x: x.stat().st_mtime, reverse=True):
try:
st = p.stat()
rows.append({"name": p.name, "size": st.st_size, "ts": st.st_mtime})
except OSError:
continue
if len(rows) >= max(1, limit):
break
return rows
def prune_backups(*, keep_days: float = 7.0, keep_max: int = 3) -> dict[str, Any]:
"""Remove aged backups, then enforce a hard max count (newest kept)."""
cutoff = time.time() - max(1.0, keep_days) * 86400.0
keep_max = max(1, min(30, int(keep_max)))
removed = 0
files: list[Path] = []
for p in _backup_dir().glob("monitor_*.db"):
try:
st = p.stat()
if st.st_mtime < cutoff:
p.unlink(missing_ok=True)
removed += 1
else:
files.append(p)
except OSError:
continue
files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
for p in files[keep_max:]:
try:
p.unlink(missing_ok=True)
removed += 1
except OSError:
continue
return {"ok": True, "removed": removed, "kept": min(keep_max, len(files))}
def prune_legacy_db_copies(*, keep_max: int = 2) -> dict[str, Any]:
"""Cull data/monitor.db.bak-* and pre-restore copies that sit beside live DB."""
root = Path(settings.data_dir)
removed = 0
cands: list[Path] = []
for p in root.glob("monitor.db.*"):
name = p.name.lower()
if p.name == "monitor.db":
continue
if any(x in name for x in (".bak", "pre-restore", ".old", ".copy")):
cands.append(p)
cands.sort(key=lambda x: x.stat().st_mtime, reverse=True)
for p in cands[max(0, keep_max) :]:
try:
p.unlink(missing_ok=True)
removed += 1
except OSError:
continue
return {"ok": True, "removed": removed}
async def backup_loop() -> None:
import asyncio
from . import db
await asyncio.sleep(90)
# One-shot cleanup of legacy piles left by old restarts / restores
try:
cfg0 = db.get_settings_map()
keep_days0 = float(cfg0.get("db_backup_keep_days") or 3)
keep_max0 = int(cfg0.get("db_backup_keep_max") or 3)
prune_backups(keep_days=keep_days0, keep_max=keep_max0)
prune_legacy_db_copies(keep_max=2)
except Exception:
pass
while True:
try:
cfg = db.get_settings_map()
if not cfg.get("db_backup_enabled", False):
await asyncio.sleep(300)
continue
try:
interval_h = float(cfg.get("db_backup_interval_hours") or 24)
except Exception:
interval_h = 24.0
interval_h = max(1.0, min(168.0, interval_h))
try:
keep_days = float(cfg.get("db_backup_keep_days") or 3)
except Exception:
keep_days = 3.0
try:
keep_max = int(cfg.get("db_backup_keep_max") or 3)
except Exception:
keep_max = 3
# Skip if an auto backup already exists within the interval.
# Prevents API restart storms from dumping 100+ copies/day.
last = _latest_auto_mtime()
age_h = (time.time() - last) / 3600.0 if last > 0 else 1e9
if age_h < interval_h * 0.95:
prune_backups(keep_days=keep_days, keep_max=keep_max)
await asyncio.sleep(min(3600.0, max(300.0, (interval_h - age_h) * 3600.0)))
continue
result = run_backup(label="auto", force=False)
prune_backups(keep_days=keep_days, keep_max=keep_max)
prune_legacy_db_copies(keep_max=2)
if result.get("ok"):
try:
db.add_event(
kind="db_backup",
level="info",
message=f"数据库已备份:{result.get('name')}",
meta={"size": result.get("size"), "name": result.get("name")},
)
except Exception:
pass
elif result.get("error") == "disk_too_low":
try:
db.add_event(
kind="db_backup",
level="warn",
message=f"磁盘不足,跳过备份(剩 {result.get('disk_free_gb')} GB)",
meta=result,
)
except Exception:
pass
await asyncio.sleep(interval_h * 3600.0)
except asyncio.CancelledError:
raise
except Exception:
await asyncio.sleep(600)