Files
agent_management/HEALTH_CHECK_FIX.md
T
2026-01-06 09:26:11 +00:00

3.7 KiB
Raw Blame History

健康检查修复说明

问题描述

之前的健康检查实现存在一个严重问题:即使 agent 的容器已经崩溃(crashed),查询状态时仍然会显示为健康(healthy)。

根本原因

原实现只检查了 Pod 的 phase(如 Running、Pending 等),但没有检查容器的实际状态。即使容器崩溃或处于等待/终止状态,Pod 的 phase 可能仍然是 "Running"。

修复内容

1. 修改 k8s_manager.py 的 get_pod_status 方法

主要改进:

  • ✅ 检查容器实际状态(running、waiting、terminated)
  • ✅ 检查容器就绪状态(ready)
  • ✅ 检查容器重启次数
  • ✅ 新增 health_status 字段,返回真实健康状态

健康状态分类:

  • healthy: 所有容器运行正常且就绪
  • unhealthy: 容器崩溃、终止或未就绪
  • degraded: 容器重启次数过多(>5次)

新增字段:

  • health_status: 真实健康状态
  • containers: 容器详细信息数组,包含:
    • name: 容器名称
    • ready: 是否就绪
    • restart_count: 重启次数
    • state: 当前状态(running/waiting/terminated)
    • reason: 状态原因(如果有)
    • exit_code: 退出码(如果已终止)

2. 修改 k8s_manager_new.py 的 get_deployment_status 方法

对于基于 Deployment 的实现,同样增加了对底层 Pod 容器的健康检查。

3. 更新 app.py 的 PodStatusResponse 模型

添加了新字段以支持响应中的健康状态信息。

使用方法

查询 Agent 状态

curl http://localhost:8000/agents/my-mysql-agenty/status

示例响应(健康状态)

{
  "name": "my-mysql-agenty",
  "namespace": "ai-agents",
  "status": "Running",
  "health_status": "healthy",
  "containers": [
    {
      "name": "mysql-agent",
      "ready": true,
      "restart_count": 0,
      "state": "running",
      "started_at": "2026-01-06T10:00:00Z"
    }
  ],
  ...
}

示例响应(崩溃状态)

{
  "name": "my-mysql-agenty",
  "namespace": "ai-agents",
  "status": "Terminated",
  "health_status": "unhealthy",
  "containers": [
    {
      "name": "mysql-agent",
      "ready": false,
      "restart_count": 3,
      "state": "terminated",
      "reason": "Error",
      "exit_code": 1,
      "message": "Connection refused",
      "finished_at": "2026-01-06T10:30:00Z"
    }
  ],
  ...
}

示例响应(等待状态)

{
  "name": "my-mysql-agenty",
  "namespace": "ai-agents",
  "status": "Waiting",
  "health_status": "unhealthy",
  "containers": [
    {
      "name": "mysql-agent",
      "ready": false,
      "restart_count": 2,
      "state": "waiting",
      "reason": "CrashLoopBackOff",
      "message": "Back-off restarting failed container"
    }
  ],
  ...
}

测试

运行测试脚本验证修复:

# 设置环境变量
export API_URL="http://localhost:8000"
export AGENT_NAME="my-mysql-agenty"

# 运行测试
./test_health_check.sh

重启服务

修复后需要重启 agent-manager 服务以应用更改:

# 如果使用 systemd
sudo systemctl restart agent-manager

# 或者如果直接运行
pkill -f "uvicorn.*app:app"
uvicorn app:app --host 0.0.0.0 --port 8000 --reload

注意事项

  1. 向后兼容性:

    • 原有的 status 字段保持不变
    • 新增的 health_status 字段不会影响现有客户端
  2. 建议:

    • 在监控和告警系统中使用 health_status 而非 status
    • 检查 containers 数组获取详细的失败原因
  3. 健康状态判断优先级:

    • 任何容器 unhealthy → 整体 unhealthy
    • 任何容器 degraded(且无 unhealthy)→ 整体 degraded
    • 所有容器 healthy → 整体 healthy