# -*- coding: utf-8 -*- """SQLite backup — copy-only, never modifies source DB.""" 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 run_backup(*, label: str = "") -> dict[str, Any]: src = _db_path() if not src.is_file(): return {"ok": False, "error": "db_not_found"} 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()} 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) -> dict[str, Any]: cutoff = time.time() - max(1.0, keep_days) * 86400.0 removed = 0 for p in _backup_dir().glob("monitor_*.db"): try: if p.stat().st_mtime < cutoff: 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(60) 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 7) except Exception: keep_days = 7.0 result = run_backup(label="auto") if result.get("ok"): prune_backups(keep_days=keep_days) 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 await asyncio.sleep(interval_h * 3600.0) except asyncio.CancelledError: raise except Exception: await asyncio.sleep(600)