"""运行时补丁:进行系统备份时执行Rclone备份脚本""" from __future__ import annotations import functools import inspect import subprocess import sys import traceback import routers.system print("正在加载 bootstrap.py...") def _log(message: str) -> None: print(f"[Hook] {message}", file=sys.stderr) def _make_patched_endpoint(original_endpoint): @functools.wraps(original_endpoint) async def new_endpoint(*args, **kwargs): _log("开始后台触发备份脚本") try: log = open("/tmp/browserflow-backup.log", "ab") subprocess.Popen( ["/bin/bash", "/app/backup.sh"], stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True, close_fds=True, ) except Exception as exc: _log(f"启动备份脚本失败: {exc}") return await original_endpoint(*args, **kwargs) new_endpoint.__signature__ = inspect.signature(original_endpoint) new_endpoint._backup_patched = True return new_endpoint def _install_patch() -> None: for route in routers.system.router.routes: if getattr(route, "path", None) == "/api/system/backup" and "GET" in getattr(route, "methods", set()): if getattr(route.endpoint, "_backup_patched", False): continue original_endpoint = route.endpoint route.endpoint = _make_patched_endpoint(original_endpoint) _log("备份补丁已安装") try: _install_patch() except Exception: _log("补丁安装失败") traceback.print_exc()