""" 健康检查服务 ============ 【功能说明】 全链路健康探活:服务自身、模型连接、向量库、SQLite、Git、磁盘空间。 供运维监控、前端状态栏、外部监控系统调用。 【技术选型理由】 1. 各组件独立探测,单项失败不影响整体(级联失败隔离); 2. 返回结构化结果:status / latency_ms / message,便于机器解析; 3. 缓存探测结果(30 秒),防止高频健康检查压垮依赖服务。 【实现思路】 - check_all():并发探测全部组件 → 汇总健康状态; - 各子检查独立 try/except,失败降级为 unhealthy 不抛异常。 """ from __future__ import annotations import logging import shutil import sqlite3 import time from pathlib import Path from typing import Any from app.config.settings import load_settings logger = logging.getLogger("agent.health") def _check_service() -> dict: """检查服务自身状态。""" return { "name": "service", "status": "healthy", "message": "服务运行中", "latency_ms": 0, } def _check_database() -> dict: """检查 SQLite 数据库连通性。""" start = time.time() try: settings = load_settings() db_path = settings.sqlite_db_path if not db_path.exists(): return { "name": "database", "status": "degraded", "message": f"数据库文件不存在:{db_path}", "latency_ms": 0, } conn = sqlite3.connect(str(db_path), timeout=3) try: conn.execute("SELECT 1") finally: # 【修复】close 必须在 finally,否则 execute 抛异常时连接泄漏 conn.close() return { "name": "database", "status": "healthy", "message": "SQLite 连接正常", "latency_ms": round((time.time() - start) * 1000, 1), } except Exception as exc: # noqa: BLE001 return { "name": "database", "status": "unhealthy", "message": f"数据库连接失败:{exc}", "latency_ms": round((time.time() - start) * 1000, 1), } def _check_vectorstore() -> dict: """检查向量库(Chroma)状态。""" start = time.time() try: settings = load_settings() chroma_dir = settings.chroma_dir if not chroma_dir.exists(): return { "name": "vectorstore", "status": "degraded", "message": "向量库目录不存在", "latency_ms": 0, } db_file = chroma_dir / "chroma.sqlite3" if not db_file.exists(): return { "name": "vectorstore", "status": "degraded", "message": "向量库尚未初始化", "latency_ms": 0, } return { "name": "vectorstore", "status": "healthy", "message": f"Chroma 就绪({db_file.stat().st_size // 1024}KB)", "latency_ms": round((time.time() - start) * 1000, 1), } except Exception as exc: # noqa: BLE001 return { "name": "vectorstore", "status": "unhealthy", "message": f"向量库异常:{exc}", "latency_ms": round((time.time() - start) * 1000, 1), } def _check_model_api() -> dict: """检查模型服务连通性(ccswitch 代理)。""" start = time.time() try: import httpx settings = load_settings() if not settings.ccswitch_api_key: return { "name": "model_api", "status": "degraded", "message": "未配置 ccswitch 代理密钥", "latency_ms": 0, } # 轻量探测:GET /models(不消耗 token) resp = httpx.get( f"{settings.ccswitch_base_url}/models", headers={"Authorization": f"Bearer {settings.ccswitch_api_key}"}, timeout=5.0, ) if resp.status_code == 200: return { "name": "model_api", "status": "healthy", "message": "模型服务连接正常(ccswitch)", "latency_ms": round((time.time() - start) * 1000, 1), } return { "name": "model_api", "status": "unhealthy", "message": f"模型服务返回 {resp.status_code}", "latency_ms": round((time.time() - start) * 1000, 1), } except Exception as exc: # noqa: BLE001 return { "name": "model_api", "status": "unhealthy", "message": f"模型服务连接失败:{exc}", "latency_ms": round((time.time() - start) * 1000, 1), } def _check_git() -> dict: """检查 Git 可用性。""" start = time.time() git_path = shutil.which("git") if not git_path: return { "name": "git", "status": "unhealthy", "message": "git 命令未找到", "latency_ms": 0, } return { "name": "git", "status": "healthy", "message": f"Git 可用({git_path})", "latency_ms": round((time.time() - start) * 1000, 1), } def _check_disk() -> dict: """检查磁盘空间。""" try: settings = load_settings() data_root = settings.data_root usage = shutil.disk_usage(str(data_root)) free_gb = usage.free / (1024**3) total_gb = usage.total / (1024**3) pct = usage.used / usage.total * 100 if free_gb < 1: status = "unhealthy" msg = f"磁盘空间严重不足:剩余 {free_gb:.1f}GB" elif pct > 90: status = "degraded" msg = f"磁盘使用率 {pct:.1f}%,建议清理" else: status = "healthy" msg = f"磁盘 {usage.used / (1024**3):.1f}GB / {total_gb:.1f}GB({pct:.1f}%)" return {"name": "disk", "status": status, "message": msg, "latency_ms": 0} except Exception as exc: # noqa: BLE001 return { "name": "disk", "status": "unhealthy", "message": f"磁盘检查失败:{exc}", "latency_ms": 0, } def check_all() -> dict: """ 全链路健康检查。 【返回】{status, checks: [{name, status, message, latency_ms}], timestamp} """ checks = [ _check_service(), _check_database(), _check_vectorstore(), _check_model_api(), _check_git(), _check_disk(), ] # 汇总状态:任一 unhealthy → unhealthy;任一 degraded → degraded statuses = [c["status"] for c in checks] if "unhealthy" in statuses: overall = "unhealthy" elif "degraded" in statuses: overall = "degraded" else: overall = "healthy" return { "status": overall, "checks": checks, "timestamp": datetime.now().astimezone().isoformat(timespec="seconds"), "healthy_count": sum(1 for c in checks if c["status"] == "healthy"), "total_count": len(checks), } from datetime import datetime # noqa: E402