mcpField
I
incident-response

incident-response

github.com/hieutrtr云与 DevOps857 次安装38 周前更新
代码仓库

关于 incident-response

incident-response 面向处理生产故障的工程团队,覆盖初步分级、排查、缓解和复盘。它提供响应流程、沟通模板及报告脚本。

主要功能

  1. 01按严重程度划分故障
  2. 02执行五分钟分诊流程
  3. 03排查应用与服务故障
  4. 04协调响应并发布状态更新
  5. 05生成复盘报告和运行手册

适用场景

  1. 01分诊生产中断或错误激增
  2. 02调查服务性能下降
  3. 03协调失败部署后的回滚
  4. 04记录根因与后续行动

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/hieutrtr/ai1-skills --skill incident-response

安装后在 Claude Code 中输入/incident-response确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
escalation-contacts.md
post-mortem-template.md
scripts/
fetch-logs.sh
generate-incident-report.py
health-check-all-services.sh

详细介绍

事件响应

适用场景

在以下情况启用此技能:

  • 生产服务宕机或向用户返回错误
  • 错误率飙升,超出正常阈值
  • 性能显著下降(延迟增加、超时)
  • 监控系统触发了告警
  • 用户报告的问题表明存在系统性故障
  • 需要调查并修复部署失败
  • 事件发生后进行复盘或根因分析

输出: 将运行手册写入 docs/runbooks/<service>-runbook.md,将事后复盘报告写入 postmortem-YYYY-MM-DD.md。

请勿在以下情况使用此技能:

  • 配置监控或告警规则(使用 monitoring-setup)
  • 执行常规部署(使用 deployment-pipeline)
  • Docker 镜像或基础设施问题(使用 docker-best-practices)
  • 功能开发或代码变更(使用 python-backend-expert 或 react-frontend-expert)

说明

严重级别分类

立即对每起事件进行分类。严重级别决定响应紧迫性、沟通频率和升级路径。

严重级别影响示例响应时间更新频率
SEV1 (P1)完全宕机,所有用户受影响服务宕机、数据丢失、安全漏洞立即(< 5 分钟)每 15 分钟
SEV2 (P2)严重降级,大多数用户受影响核心功能故障、延迟严重< 15 分钟每 30 分钟
SEV3 (P3)部分降级,部分用户受影响非关键功能故障、间歇性错误< 1 小时每 2 小时
SEV4 (P4)轻微问题,少数用户受影响外观问题、边缘情况错误< 4 小时每天

升级规则:

  • SEV1:立即呼叫值班工程师和工程经理
  • SEV2:呼叫值班工程师,并通知工程经理
  • SEV3:通过 Slack 通知值班工程师
  • SEV4:创建工单,在正常工作时间处理

联系人矩阵请参阅 references/escalation-contacts.md。

5 分钟分诊工作流

检测到事件时,请在最初的 5 分钟内按照此分诊工作流操作。

┌─────────────────────────────────────────────────────────┐
│  MINUTE 0-1: Acknowledge and Classify                   │
│  • Acknowledge the alert or report                      │
│  • Assign severity (SEV1-SEV4)                          │
│  • Designate incident commander                         │
├─────────────────────────────────────────────────────────┤
│  MINUTE 1-2: Assess Scope                               │
│  • Check health endpoints for all services              │
│  • Check error rate and latency dashboards              │
│  • Determine: which services are affected?              │
├─────────────────────────────────────────────────────────┤
│  MINUTE 2-3: Identify Recent Changes                    │
│  • Check: was there a recent deployment?                │
│  • Check: any infrastructure changes?                   │
│  • Check: any external dependency issues?               │
├─────────────────────────────────────────────────────────┤
│  MINUTE 3-4: Initial Communication                      │
│  • Post in #incidents channel                           │
│  • Update status page if SEV1/SEV2                      │
│  • Page additional responders if needed                 │
├─────────────────────────────────────────────────────────┤
│  MINUTE 4-5: Begin Investigation or Mitigate            │
│  • If recent deploy: consider immediate rollback        │
│  • If not deploy-related: begin diagnostic commands     │
│  • Start incident timeline log                          │
└─────────────────────────────────────────────────────────┘

快速健康检查命令:

./skills/incident-response/scripts/health-check-all-services.sh \
  --output-dir ./incident-triage/
事件指挥官职责

事件指挥官(IC)负责协调响应。他们不直接进行调查。

IC 职责:

  1. 协调 —— 为响应人员分配任务,避免重复工作
  2. 沟通 —— 定期向相关方发布更新
  3. 决策 —— 决定是否回滚、升级或沟通
  4. 跟踪 —— 维护事件时间线
  5. 结束 —— 宣布事件已解决并安排事后复盘

IC 沟通模板(初始):

INCIDENT DECLARED: [Title]
Severity: [SEV1/SEV2/SEV3/SEV4]
Commander: [Name]
Start time: [UTC timestamp]
Impact: [What users are experiencing]
Status: Investigating
Next update: [Time]

IC 沟通模板(更新):

INCIDENT UPDATE: [Title]
Severity: [SEV level]
Duration: [Time since start]
Status: [Investigating/Identified/Mitigating/Resolved]
Current findings: [What we know]
Actions in progress: [What we are doing]
Next update: [Time]
调查步骤

根据问题类型执行以下诊断步骤。

应用错误(FastAPI)
# 1. Check application logs for errors
./skills/incident-response/scripts/fetch-logs.sh \
  --service backend \
  --since "15 minutes ago" \
  --output-dir ./incident-logs/

# 2. Check error rate from logs
docker logs app-backend --since 15m 2>&1 | grep -c "ERROR"

# 3. Check active connections and request patterns
curl -s http://localhost:8000/health/ready | jq .

# 4. Check if the issue is in a specific endpoint
docker logs app-backend --since 15m 2>&1 | \
  grep "ERROR" | \
  grep -oP '"path":"[^"]*"' | sort | uniq -c | sort -rn

# 5. Check Python process status
docker exec app-backend ps aux
docker exec app-backend python -c "import sys; print(sys.version)"
数据库问题(PostgreSQL)
# 1. Check database connectivity
docker exec app-db pg_isready -U postgres

# 2. Check active connections (connection pool exhaustion?)
docker exec app-db psql -U postgres -d app_prod -c "
  SELECT count(*), state FROM pg_stat_activity
  GROUP BY state ORDER BY count DESC;
"

# 3. Check for long-running queries (locks, deadlocks?)
docker exec app-db psql -U postgres -d app_prod -c "
  SELECT pid, now() - pg_stat_activity.query_start AS duration,
         query, state
  FROM pg_stat_activity
  WHERE (now() - pg_stat_activity.query_start) > interval '30 seconds'
  AND state != 'idle'
  ORDER BY duration DESC;
"

# 4. Check for lock contention
docker exec app-db psql -U postgres -d app_prod -c "
  SELECT blocked_locks.pid AS blocked_pid,
         blocking_locks.pid AS blocking_pid,
         blocked_activity.query AS blocked_query
  FROM pg_catalog.pg_locks blocked_locks
  JOIN pg_catalog.pg_stat_activity blocked_activity
    ON blocked_activity.pid = blocked_locks.pid
  JOIN pg_catalog.pg_locks blocking_locks
    ON blocking_locks.locktype = blocked_locks.locktype
    AND blocking_locks.relation = blocked_locks.relation
    AND blocking_locks.pid != blocked_locks.pid
  JOIN pg_catalog.pg_stat_activity blocking_activity
    ON blocking_activity.pid = blocking_locks.pid
  WHERE NOT blocked_locks.granted;
"

# 5. Check disk space
docker exec app-db df -h /var/lib/postgresql/data
Redis 问题
# 1. Check Redis connectivity
docker exec app-redis redis-cli ping

# 2. Check memory usage
docker exec app-redis redis-cli info memory | grep used_memory_human

# 3. Check connected clients
docker exec app-redis redis-cli info clients | grep connected_clients

# 4. Check slow log
docker exec app-redis redis-cli slowlog get 10

# 5. Check keyspace
docker exec app-redis redis-cli info keyspace
网络和基础设施
# 1. Check DNS resolution
nslookup api.example.com

# 2. Check SSL certificate expiry
echo | openssl s_client -servername api.example.com -connect api.example.com:443 2>/dev/null | \
  openssl x509 -noout -dates

# 3. Check container resource usage
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}"

# 4. Check disk space on host
df -h /

# 5. Check if dependent services are reachable
curl -sf https://external-api.example.com/health || echo "External API unreachable"
修复措施
立即缓解措施(几分钟内执行)
问题缓解措施命令
错误部署回滚./scripts/deploy.sh --rollback --env production --version $PREV_SHA --output-dir ./results/
连接池耗尽重启后端docker restart app-backend
长时间运行的查询终止查询SELECT pg_terminate_backend(<pid>);
内存泄漏重启服务docker restart app-backend
Redis 空间已满清除非关键键redis-cli --scan --pattern "cache:*" | xargs redis-cli del
SSL 证书过期应用新证书在负载均衡器中更新证书
磁盘空间已满清理日志/临时文件docker system prune -f
较长期的修复措施(稳定后实施)
  1. 修复代码中的根本原因 —— 创建分支、修复问题、测试,并通过常规流水线部署
  2. 添加监控 —— 如果现有告警未能发现问题,则添加新的告警规则
  3. 添加测试 —— 针对故障场景编写回归测试
  4. 更新运行手册 —— 记录新的故障模式和补救步骤
沟通协议
内部沟通

频道:

  • #incidents —— 活跃事件协调(SEV1/SEV2)
  • #incidents-low —— SEV3/SEV4 跟踪
  • #engineering —— 事件后总结

规则:

  1. 所有沟通均在指定的事件频道中进行
  2. 使用线程讨论调查细节,主频道仅用于状态更新
  3. IC 按照规定的频率发布更新(参见严重级别表)
  4. 明确标记相关人员,不要假定他们正在关注
  5. 为所有重要发现和操作添加时间戳
外部沟通(SEV1/SEV2)

状态页更新模板:

[Investigating] We are investigating reports of [issue description].
Users may experience [user-visible impact].
We will provide an update within [time].
[Identified] The issue has been identified as [brief description].
We are working on a fix. Estimated resolution: [time estimate].
[Resolved] The issue affecting [service] has been resolved.
The root cause was [brief description].
We apologize for the disruption and will publish a detailed post-mortem.
事后复盘 / RCA 框架

每次 SEV1/SEV2 事件发生后 48 小时内进行无责备的事后复盘。SEV3 事件进行轻量级复盘。

完整模板请参见 references/post-mortem-template.md。

事后复盘原则:

  1. 不归咎于个人 —— 关注系统和流程,而非个人
  2. 全面彻底 —— 找出所有促成因素,而不只是触发因素
  3. 可执行 —— 每项发现都必须转化为有负责人的具体行动项
  4. 及时 —— 在 48 小时内进行,趁细节仍记忆犹新
  5. 共享 —— 向整个工程团队发布

事后复盘结构:

  1. 摘要 —— 发生了什么、何时发生,以及造成了什么影响
  2. 时间线 —— 按分钟记录发现、调查和缓解过程
  3. 根本原因 —— 导致事件发生的根本原因
  4. 促成因素 —— 使事件恶化的其他情况
  5. 进展顺利之处 —— 响应过程中有效的部分
  6. 可改进之处 —— 检测、响应或工具方面的不足
  7. 行动项 —— 明确具体任务、负责人和截止日期

用于根因分析的五个为什么技巧:

Why did users see 500 errors?
  -> Because the backend service returned errors to the load balancer.
Why did the backend service return errors?
  -> Because database connections timed out.
Why did database connections time out?
  -> Because the connection pool was exhausted.
Why was the connection pool exhausted?
  -> Because a new endpoint opened connections without releasing them.
Why were connections not released?
  -> Because the endpoint was missing the async context manager for sessions.

Root cause: Missing async context manager for database sessions in new endpoint.

生成结构化事件报告:

python skills/incident-response/scripts/generate-incident-report.py \
  --title "Database connection pool exhaustion" \
  --severity SEV2 \
  --start-time "2024-01-15T14:30:00Z" \
  --end-time "2024-01-15T15:15:00Z" \
  --output-dir ./post-mortems/
事件响应脚本
脚本用途用法
scripts/fetch-logs.sh从服务中获取近期日志./scripts/fetch-logs.sh --service backend --since "30m" --output-dir ./logs/
scripts/health-check-all-services.sh检查所有服务的运行状况./scripts/health-check-all-services.sh --output-dir ./health/
scripts/generate-incident-report.py生成结构化事件报告python scripts/generate-incident-report.py --title "..." --severity SEV1 --output-dir ./reports/
快速参考:常见事件模式
模式症状可能原因首要操作
502/503 错误用户看到错误页面后端崩溃或过载检查 docker ps,必要时重启
响应缓慢延迟高、超时数据库查询、外部 API检查慢查询日志和数据库连接
部分故障部分端点无法使用单个依赖服务宕机检查各服务的运行状况
内存增长OOM 终止、重启内存泄漏检查 docker stats,然后重启
部署后错误激增错误恰好从部署时开始出现新代码存在 Bug立即回滚
逐渐降级指标逐渐恶化资源耗尽、连接泄漏检查资源使用趋势
输出文件

运行手册: 写入 docs/runbooks/<service>-runbook.md:

# Runbook: [Service Name]

## Service Overview
- Purpose, dependencies, critical paths

## Common Issues
### Issue 1: [Description]
- **Symptoms:** [What you see]
- **Diagnosis:** [Commands to run]
- **Resolution:** [Steps to fix]

## Escalation
- On-call: #ops-oncall
- Service owner: @team-name

事后复盘: 写入 postmortem-YYYY-MM-DD.md:

# Post-Mortem: [Incident Title]

## Summary
- **Date:** YYYY-MM-DD
- **Severity:** SEV1-4
- **Duration:** X hours
- **Impact:** [Users/revenue affected]

## Timeline
- HH:MM - [Event]

## Root Cause
[Technical explanation]

## Action Items
- [ ] [Preventive measure] - Owner: @name - Due: YYYY-MM-DD

评论

支持 Markdown