Files
AgentScript/agent/backend/app/services/backup_service.py
T
HenryandClaude Code 26e13ff032 feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。
排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。

Co-Authored-By: Claude Code <[email protected]>
2026-11-13 13:48:41 +08:00

145 lines
4.8 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.
"""
自动备份服务
============
【功能说明】
定时备份 SQLite 数据库、配置文件、向量库元数据到指定目录。
支持手动触发和定时调度。
【技术选型理由】
1. 选 SQLite 版本化备份(.backup):在线备份不锁库;
2. 备份文件用时间戳命名:便于保留多个版本;
3. 自动清理过期备份(保留最近 N 天)。
【实现思路】
- backup_now():立即执行备份;
- auto_backup_loop():后台定时循环(每 N 小时);
- 清理超过保留期的旧备份。
"""
from __future__ import annotations
import logging
import shutil
import sqlite3
import time
from datetime import datetime
from pathlib import Path
from app.config.settings import load_settings
logger = logging.getLogger("agent.backup")
# 备份配置
BACKUP_DIR = Path(r"D:\Agent\agent\data\backups\auto")
RETENTION_DAYS = 30 # 保留最近 30 天
BACKUP_INTERVAL_SECONDS = 12 * 3600 # 每 12 小时一次
def backup_now() -> dict:
"""
立即执行全量备份。
【备份内容】SQLite + .env + 配置 + 向量库元数据
【返回】{success, backup_path, files, size_bytes}
"""
settings = load_settings()
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = BACKUP_DIR / f"backup_{timestamp}"
backup_path.mkdir(parents=True, exist_ok=True)
files_copied = []
total_bytes = 0
try:
# 1. SQLite 数据库(在线备份,不锁库)
db_path = settings.sqlite_db_path
if db_path.exists():
dest = backup_path / "agent.db"
# 用 SQLite .backup API(安全在线备份)
src_conn = sqlite3.connect(str(db_path))
dest_conn = sqlite3.connect(str(dest))
try:
src_conn.backup(dest_conn)
finally:
# 【修复】close 必须在 finally,否则 backup 抛异常时两个连接都泄漏
dest_conn.close()
src_conn.close()
size = dest.stat().st_size
total_bytes += size
files_copied.append({"name": "agent.db", "size": size})
# 2. .env 配置
env_path = Path(r"D:\Agent\agent\backend\.env")
if env_path.exists():
dest = backup_path / ".env"
shutil.copy2(env_path, dest)
size = dest.stat().st_size
total_bytes += size
files_copied.append({"name": ".env", "size": size})
# 3. 备注文件
remarks_path = Path(r"D:\Agent\agent\backend\.env.remarks.json")
if remarks_path.exists():
dest = backup_path / ".env.remarks.json"
shutil.copy2(remarks_path, dest)
size = dest.stat().st_size
total_bytes += size
files_copied.append({"name": ".env.remarks.json", "size": size})
# 4. 向量库元数据(只备 SQLite,不备大文件)
chroma_db = settings.chroma_dir / "chroma.sqlite3"
if chroma_db.exists():
dest = backup_path / "chroma.sqlite3"
shutil.copy2(chroma_db, dest)
size = dest.stat().st_size
total_bytes += size
files_copied.append({"name": "chroma.sqlite3", "size": size})
# 5. 清理过期备份
cleaned = _cleanup_old_backups()
logger.info("备份完成:%s(%d 个文件,%.1fKB)", backup_path, len(files_copied), total_bytes / 1024)
return {
"success": True,
"backup_path": str(backup_path),
"files": files_copied,
"size_bytes": total_bytes,
"cleaned_old": cleaned,
}
except Exception as exc: # noqa: BLE001
logger.exception("备份失败")
return {"success": False, "message": f"备份失败:{exc}"}
def _cleanup_old_backups() -> int:
"""清理超过保留期的旧备份。"""
if not BACKUP_DIR.exists():
return 0
cutoff = time.time() - RETENTION_DAYS * 86400
cleaned = 0
for item in BACKUP_DIR.iterdir():
if item.is_dir() and item.stat().st_mtime < cutoff:
shutil.rmtree(item, ignore_errors=True)
cleaned += 1
return cleaned
def list_backups() -> list[dict]:
"""列出所有备份(供前端展示)。"""
if not BACKUP_DIR.exists():
return []
items = []
for item in sorted(BACKUP_DIR.iterdir(), reverse=True):
if item.is_dir():
total_size = sum(f.stat().st_size for f in item.rglob("*") if f.is_file())
file_count = sum(1 for f in item.rglob("*") if f.is_file())
items.append({
"name": item.name,
"path": str(item),
"size_bytes": total_size,
"file_count": file_count,
"created_at": datetime.fromtimestamp(item.stat().st_mtime).isoformat(),
})
return items