32e - AI辅助监控与事件响应
本文是《AI Agent 实战手册》第 32 章第 5 节。 上一节:32d-AI辅助容器化 | 下一节:32f-DevOps-Steering规则与反模式
概述
监控与事件响应是生产系统可靠性的最后一道防线,而 AI 正在将这一领域从”被动告警-人工排查”推向”智能预测-自动响应-自主修复”的新范式。2025-2026 年,Grafana Labs 推出了 Grafana Assistant(已 GA),支持自然语言创建仪表板、编写 PromQL/LogQL 查询和 AI 驱动的事件调查;PagerDuty 发布了业界首个端到端 AI Agent 套件,其 SRE Agent 可自动生成自更新运行手册;incident.io 的 AI SRE 可自动化高达 80% 的事件响应流程;BigPanda 的 Agentic ITOps 平台实现了从检测到解决的全链路 AI 自动化。本节深入覆盖 AI 辅助 Prometheus 告警规则生成、Grafana 仪表板创建、运行手册自动生成、事后分析(Postmortem)AI 辅助、AIOps 平台与工具、异常检测、On-Call 自动化与 AI 辅助分诊等核心主题,提供完整的 Prompt 模板库和实战案例。
1. AI 辅助监控与事件响应工具全景
1.1 监控与可观测性 AI 工具对比
| 工具 | 用途 | 价格 | 适用场景 |
|---|---|---|---|
| Grafana Assistant | 自然语言创建仪表板、编写查询、AI 事件调查 | Grafana Cloud Free 免费(有限额);Pro $29/月起;Advanced 联系销售 | 已有 Grafana 栈的团队,自然语言驱动可观测性 |
| Datadog AI(Watchdog/Bits AI) | 自动异常检测、根因分析、AI 驱动告警 | Infrastructure $15/主机/月起;APM $31/主机/月起;Log Management $0.10/GB/月起 | 全栈可观测性,企业级 AI 异常检测 |
| New Relic AI | 跨遥测数据关联、自然语言查询、AI 告警 | 免费层 100GB/月;Standard $0.30/GB 起;Pro/Enterprise 联系销售 | 应用性能监控,全栈关联分析 |
| PagerDuty AI Agent Suite | AI SRE Agent、自动分诊、自更新运行手册、智能路由 | Professional $21/用户/月;Business $41/用户/月;Enterprise 联系销售(AI 功能额外付费) | 企业级事件管理,On-Call 自动化 |
| BigPanda AIOps | 事件关联、噪声消除、根因分析、自动化工作流 | 联系销售(企业定价) | 大规模 IT 运维,多工具事件聚合 |
| incident.io | AI SRE 自动响应、Slack 原生事件管理、自动 Postmortem | Team 免费(最多 10 用户);Pro $16/用户/月;Enterprise 联系销售 | Slack 原生团队,现代事件管理 |
| Rootly | AI 事件管理、Slack 工作流、自动 Postmortem | Starter 免费;Pro $19/用户/月;Enterprise 联系销售 | 中小团队 Slack 原生事件管理 |
| FireHydrant | 事件管理自动化、运行手册、状态页 | Free 免费;Pro $35/用户/月;Enterprise 联系销售 | 需要强工作流自定义的团队 |
| Claude Code / GPT | 通用 AI 辅助生成 PromQL、告警规则、仪表板 JSON、运行手册 | Claude Pro $20/月;GPT Plus $20/月 | 灵活的 AI 辅助配置生成 |
| GitHub Copilot | IDE 内 YAML/JSON 配置补全 | Individual $10/月;Business $19/月 | 日常监控配置编写 |
1.2 AI 辅助监控能力层次模型
┌─────────────────────────────────────────────────────┐
│ Level 5: 自主修复(Self-Healing) │
│ AI 自动执行修复操作,人工仅审查 │
├─────────────────────────────────────────────────────┤
│ Level 4: 智能响应(Intelligent Response) │
│ AI 自动分诊、路由、执行运行手册、生成 Postmortem │
├─────────────────────────────────────────────────────┤
│ Level 3: 预测分析(Predictive Analytics) │
│ AI 预测故障、趋势预警、容量规划 │
├─────────────────────────────────────────────────────┤
│ Level 2: 智能检测(Smart Detection) │
│ AI 异常检测、噪声消除、事件关联 │
├─────────────────────────────────────────────────────┤
│ Level 1: AI 辅助配置(AI-Assisted Config) │
│ AI 生成告警规则、仪表板、查询语句 │
├─────────────────────────────────────────────────────┤
│ Level 0: 手动配置(Manual Configuration) │
│ 手写 PromQL、手动创建仪表板、人工排查 │
└─────────────────────────────────────────────────────┘2. AI 辅助 Prometheus 告警规则生成
2.1 Prometheus 告警规则基础
Prometheus 告警规则由 PromQL 表达式定义,存储在 YAML 文件中,由 Prometheus 周期性评估。当条件满足指定持续时间后触发告警,发送到 Alertmanager 进行路由、分组和通知。
告警规则的核心结构:
groups:
- name: example_alerts
rules:
- alert: HighErrorRate # 告警名称
expr: | # PromQL 表达式
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m])) > 0.05
for: 5m # 持续时间阈值
labels:
severity: critical # 告警标签
annotations:
summary: "高错误率告警" # 摘要
description: | # 详细描述
HTTP 5xx 错误率超过 5%,当前值 {{ $value | printf "%.2f" }}%
runbook_url: "https://wiki.example.com/runbooks/high-error-rate"2.2 AI 生成 PromQL 查询的 Prompt 模板
模板 1:基础指标查询生成
你是一位 Prometheus 和 PromQL 专家。请根据以下需求生成 PromQL 查询:
## 监控需求
- 监控目标:[例如:Nginx 反向代理]
- 指标类型:[例如:请求延迟 P99]
- 时间窗口:[例如:5 分钟]
- 聚合维度:[例如:按服务名和状态码]
## 可用指标
[列出已知的 Prometheus 指标名称,例如:
- nginx_http_request_duration_seconds_bucket
- nginx_http_requests_total
- nginx_connections_active]
## 输出要求
1. 提供完整的 PromQL 查询
2. 解释查询逻辑
3. 说明适用的可视化类型(Graph/Stat/Table)
4. 给出合理的告警阈值建议模板 2:Recording Rules 生成
你是 Prometheus 运维专家。请为以下高频查询生成 Recording Rules:
## 原始查询
[粘贴当前使用的 PromQL 查询]
## 上下文
- 查询执行频率:[例如:每 15 秒]
- 数据保留期:[例如:30 天]
- Prometheus 实例数:[例如:3 个联邦节点]
## 输出要求
1. 生成 recording rule YAML 配置
2. 遵循命名规范:level:metric:operations
3. 说明预计的性能提升
4. 包含依赖的 recording rules(如有层级依赖)模板 3:完整告警规则集生成
你是 SRE 专家,精通 Prometheus 告警最佳实践。请为以下服务生成完整的告警规则集:
## 服务信息
- 服务名称:[例如:payment-service]
- 服务类型:[例如:REST API 微服务]
- 技术栈:[例如:Go + gRPC + PostgreSQL]
- SLO 目标:[例如:可用性 99.9%,P99 延迟 < 500ms]
## 已暴露的指标
[列出服务暴露的 Prometheus 指标]
## 要求
1. 按 USE 方法(Utilization/Saturation/Errors)和 RED 方法(Rate/Errors/Duration)组织
2. 包含 severity 分级(info/warning/critical/page)
3. 每条规则包含 runbook_url annotation
4. 包含合理的 for 持续时间(避免误报)
5. 包含 recording rules 预计算复杂查询
6. 输出完整的 YAML 配置文件2.3 AI 生成告警规则实战示例
示例:为 Web 应用生成 SLO 驱动的告警规则
使用 Claude Code 或 GPT 生成:
# 文件:alerts/web-app-slo-alerts.yml
# AI 生成 + 人工审查
groups:
# ============================================
# Recording Rules - 预计算高频查询
# ============================================
- name: web_app_recording_rules
interval: 30s
rules:
# 请求速率(按服务和状态码)
- record: service:http_requests:rate5m
expr: sum by (service, status_code) (rate(http_requests_total[5m]))
# 错误率
- record: service:http_errors:ratio5m
expr: |
sum by (service) (rate(http_requests_total{status_code=~"5.."}[5m]))
/
sum by (service) (rate(http_requests_total[5m]))
# P99 延迟
- record: service:http_latency:p99_5m
expr: |
histogram_quantile(0.99,
sum by (service, le) (rate(http_request_duration_seconds_bucket[5m]))
)
# P50 延迟
- record: service:http_latency:p50_5m
expr: |
histogram_quantile(0.50,
sum by (service, le) (rate(http_request_duration_seconds_bucket[5m]))
)
# ============================================
# SLO 驱动的告警规则
# ============================================
- name: web_app_slo_alerts
rules:
# --- 可用性 SLO(目标 99.9%)---
- alert: SLOErrorBudgetBurnRateHigh
expr: |
(
service:http_errors:ratio5m > (14.4 * 0.001)
and
sum by (service) (rate(http_requests_total{status_code=~"5.."}[1h]))
/
sum by (service) (rate(http_requests_total[1h])) > (14.4 * 0.001)
)
for: 2m
labels:
severity: page
slo: availability
annotations:
summary: "SLO 错误预算快速消耗 - {{ $labels.service }}"
description: |
服务 {{ $labels.service }} 的错误预算消耗速率过高。
5 分钟错误率:{{ $value | printf "%.4f" }}
按当前速率,错误预算将在 1 小时内耗尽。
runbook_url: "https://wiki.example.com/runbooks/slo-error-budget"
- alert: SLOErrorBudgetBurnRateMedium
expr: |
(
service:http_errors:ratio5m > (6 * 0.001)
and
sum by (service) (rate(http_requests_total{status_code=~"5.."}[6h]))
/
sum by (service) (rate(http_requests_total[6h])) > (6 * 0.001)
)
for: 15m
labels:
severity: critical
slo: availability
annotations:
summary: "SLO 错误预算中速消耗 - {{ $labels.service }}"
description: |
服务 {{ $labels.service }} 的错误预算消耗速率偏高。
按当前速率,错误预算将在 6 小时内耗尽。
runbook_url: "https://wiki.example.com/runbooks/slo-error-budget"
# --- 延迟 SLO(P99 < 500ms)---
- alert: SLOLatencyP99High
expr: service:http_latency:p99_5m > 0.5
for: 5m
labels:
severity: critical
slo: latency
annotations:
summary: "P99 延迟超过 SLO 目标 - {{ $labels.service }}"
description: |
服务 {{ $labels.service }} 的 P99 延迟为 {{ $value | printf "%.3f" }}s,
超过 500ms SLO 目标。
runbook_url: "https://wiki.example.com/runbooks/high-latency"
- alert: SLOLatencyP50Degraded
expr: service:http_latency:p50_5m > 0.2
for: 10m
labels:
severity: warning
slo: latency
annotations:
summary: "P50 延迟异常升高 - {{ $labels.service }}"
description: |
服务 {{ $labels.service }} 的 P50 延迟为 {{ $value | printf "%.3f" }}s,
中位数延迟异常升高,可能影响用户体验。
runbook_url: "https://wiki.example.com/runbooks/latency-degradation"
# --- 流量异常 ---
- alert: TrafficDropSudden
expr: |
(
sum by (service) (rate(http_requests_total[5m]))
/
sum by (service) (rate(http_requests_total[1h] offset 1d))
) < 0.5
for: 10m
labels:
severity: warning
annotations:
summary: "流量骤降 - {{ $labels.service }}"
description: |
服务 {{ $labels.service }} 当前流量较昨日同期下降超过 50%。
可能原因:上游故障、DNS 问题、部署异常。
runbook_url: "https://wiki.example.com/runbooks/traffic-drop"
- alert: TrafficSpike
expr: |
(
sum by (service) (rate(http_requests_total[5m]))
/
sum by (service) (rate(http_requests_total[1h] offset 1d))
) > 3
for: 5m
labels:
severity: warning
annotations:
summary: "流量激增 - {{ $labels.service }}"
description: |
服务 {{ $labels.service }} 当前流量较昨日同期增长超过 3 倍。
可能原因:营销活动、爬虫、DDoS。
runbook_url: "https://wiki.example.com/runbooks/traffic-spike"
# ============================================
# 基础设施告警
# ============================================
- name: web_app_infra_alerts
rules:
- alert: HighCPUUsage
expr: |
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 85
for: 10m
labels:
severity: warning
annotations:
summary: "CPU 使用率过高 - {{ $labels.instance }}"
description: "实例 {{ $labels.instance }} CPU 使用率 {{ $value | printf \"%.1f\" }}%"
runbook_url: "https://wiki.example.com/runbooks/high-cpu"
- alert: HighMemoryUsage
expr: |
(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100 > 90
for: 5m
labels:
severity: critical
annotations:
summary: "内存使用率过高 - {{ $labels.instance }}"
description: "实例 {{ $labels.instance }} 内存使用率 {{ $value | printf \"%.1f\" }}%"
runbook_url: "https://wiki.example.com/runbooks/high-memory"
- alert: DiskSpaceLow
expr: |
(1 - node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100 > 85
for: 15m
labels:
severity: warning
annotations:
summary: "磁盘空间不足 - {{ $labels.instance }}"
description: "实例 {{ $labels.instance }} 根分区使用率 {{ $value | printf \"%.1f\" }}%"
runbook_url: "https://wiki.example.com/runbooks/disk-space"
- alert: PodRestartingFrequently
expr: |
increase(kube_pod_container_status_restarts_total[1h]) > 5
for: 5m
labels:
severity: warning
annotations:
summary: "Pod 频繁重启 - {{ $labels.pod }}"
description: |
Pod {{ $labels.namespace }}/{{ $labels.pod }} 在过去 1 小时内重启 {{ $value }} 次。
runbook_url: "https://wiki.example.com/runbooks/pod-restart"2.4 Alertmanager 路由配置 AI 生成
Prompt 模板:Alertmanager 配置生成
你是 Prometheus Alertmanager 配置专家。请根据以下团队结构和通知需求生成 Alertmanager 配置:
## 团队结构
[描述团队和 On-Call 轮值安排]
## 通知渠道
- Slack:[频道列表]
- PagerDuty:[服务列表]
- 邮件:[邮件组列表]
- Webhook:[自定义 webhook URL]
## 路由规则
- page 级别 → PagerDuty + Slack #incidents
- critical 级别 → Slack #alerts + 邮件
- warning 级别 → Slack #monitoring
- info 级别 → 仅记录
## 要求
1. 包含合理的 group_by、group_wait、group_interval、repeat_interval
2. 包含抑制规则(critical 抑制 warning)
3. 包含静默时间窗口配置示例
4. 输出完整的 alertmanager.ymlAI 生成的 Alertmanager 配置示例
# alertmanager.yml - AI 生成 + 人工审查
global:
resolve_timeout: 5m
slack_api_url: 'https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK'
# 通知模板
templates:
- '/etc/alertmanager/templates/*.tmpl'
# 路由树
route:
receiver: 'default-slack'
group_by: ['alertname', 'service', 'severity']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
# Page 级别 → PagerDuty + Slack #incidents
- match:
severity: page
receiver: 'pagerduty-critical'
group_wait: 10s
repeat_interval: 5m
continue: true
- match:
severity: page
receiver: 'slack-incidents'
group_wait: 10s
# Critical 级别 → Slack #alerts + 邮件
- match:
severity: critical
receiver: 'slack-alerts'
group_wait: 30s
repeat_interval: 1h
continue: true
- match:
severity: critical
receiver: 'email-oncall'
# Warning 级别 → Slack #monitoring
- match:
severity: warning
receiver: 'slack-monitoring'
group_wait: 1m
repeat_interval: 4h
# 抑制规则
inhibit_rules:
# critical 抑制同服务的 warning
- source_match:
severity: 'critical'
target_match:
severity: 'warning'
equal: ['alertname', 'service']
# page 抑制同服务的 critical 和 warning
- source_match:
severity: 'page'
target_match_re:
severity: 'critical|warning'
equal: ['alertname', 'service']
# 接收器定义
receivers:
- name: 'default-slack'
slack_configs:
- channel: '#monitoring'
send_resolved: true
title: '{{ .GroupLabels.alertname }}'
text: >-
{{ range .Alerts }}
*{{ .Labels.severity | toUpper }}* - {{ .Annotations.summary }}
{{ .Annotations.description }}
{{ end }}
- name: 'pagerduty-critical'
pagerduty_configs:
- service_key: 'YOUR_PAGERDUTY_SERVICE_KEY'
severity: 'critical'
description: '{{ .GroupLabels.alertname }}: {{ .CommonAnnotations.summary }}'
- name: 'slack-incidents'
slack_configs:
- channel: '#incidents'
send_resolved: true
color: '{{ if eq .Status "firing" }}danger{{ else }}good{{ end }}'
- name: 'slack-alerts'
slack_configs:
- channel: '#alerts'
send_resolved: true
- name: 'slack-monitoring'
slack_configs:
- channel: '#monitoring'
send_resolved: true
- name: 'email-oncall'
email_configs:
- to: 'oncall-team@example.com'
send_resolved: true3. AI 辅助 Grafana 仪表板创建
3.1 Grafana Assistant:自然语言驱动的可观测性
2025 年,Grafana Labs 推出了 Grafana Assistant,这是一个内置于 Grafana Cloud 的上下文感知 AI Agent。它支持:
- 自然语言查询:用自然语言提问,Assistant 自动生成 PromQL、LogQL、TraceQL 查询
- 仪表板创建与修改:通过对话创建和修改仪表板面板
- 事件调查:AI 引导的多步骤事件调查,支持并行调查多个线索
- 上下文感知:基于 Grafana 文档、博客和社区知识提供最佳实践建议
Grafana Assistant 使用示例
# 自然语言 → PromQL
用户:"显示过去 24 小时内 payment-service 的 P95 延迟趋势"
Assistant 生成:
histogram_quantile(0.95,
sum by (le) (rate(http_request_duration_seconds_bucket{service="payment-service"}[5m]))
)
# 自然语言 → 仪表板面板
用户:"创建一个面板显示各服务的错误率排行榜"
Assistant 生成:包含 PromQL 查询的 Bar Gauge 面板配置
# 事件调查
用户:"payment-service 延迟升高,帮我排查"
Assistant:
1. 检查错误率变化 → 生成查询
2. 检查上游依赖延迟 → 生成查询
3. 检查资源使用率 → 生成查询
4. 关联最近部署事件 → 提供分析3.2 AI 生成 Grafana 仪表板 JSON 的 Prompt 模板
模板 1:服务概览仪表板
你是 Grafana 仪表板设计专家。请为以下服务生成完整的 Grafana 仪表板 JSON:
## 服务信息
- 服务名称:[例如:order-service]
- 数据源:[例如:Prometheus]
- 技术栈:[例如:Node.js + Express + PostgreSQL + Redis]
## 仪表板要求
### 第一行:关键指标概览(Stat 面板)
- 当前 QPS
- 错误率(%)
- P99 延迟(ms)
- 活跃连接数
### 第二行:趋势图(Time Series 面板)
- 请求速率(按状态码分组)
- 延迟分布(P50/P90/P99)
### 第三行:资源使用(Time Series 面板)
- CPU 使用率
- 内存使用率
- 数据库连接池使用率
### 第四行:依赖健康(Table 面板)
- 上游服务延迟和错误率
## 输出要求
1. 完整的 Grafana Dashboard JSON(可直接导入)
2. 包含模板变量($service, $namespace, $interval)
3. 包含合理的阈值颜色(绿/黄/红)
4. 面板使用合适的可视化类型
5. 包含 annotations 显示部署事件模板 2:SLO 仪表板
你是 SRE 和 Grafana 专家。请生成一个 SLO 监控仪表板:
## SLO 定义
- 可用性 SLO:[例如:99.9%(月度)]
- 延迟 SLO:[例如:P99 < 500ms]
- 错误预算周期:[例如:30 天滚动窗口]
## 仪表板面板要求
1. 错误预算剩余百分比(Gauge)
2. 错误预算消耗趋势(Time Series)
3. 错误预算消耗速率(Stat)
4. SLI 实际值 vs SLO 目标(Time Series + 阈值线)
5. 预计错误预算耗尽时间(Stat)
6. 按端点的 SLI 分解(Table)
## 输出要求
1. 完整的 Grafana Dashboard JSON
2. 使用 recording rules 中的预计算指标
3. 包含合理的颜色阈值3.3 AI 生成的仪表板 JSON 示例(核心片段)
以下是 AI 生成的服务概览仪表板核心面板配置:
{
"dashboard": {
"title": "Order Service - 服务概览",
"tags": ["service", "order-service", "ai-generated"],
"timezone": "browser",
"refresh": "30s",
"time": { "from": "now-6h", "to": "now" },
"templating": {
"list": [
{
"name": "service",
"type": "query",
"query": "label_values(http_requests_total, service)",
"current": { "text": "order-service", "value": "order-service" }
},
{
"name": "namespace",
"type": "query",
"query": "label_values(kube_pod_info{pod=~\".*order.*\"}, namespace)"
},
{
"name": "interval",
"type": "interval",
"query": "1m,5m,15m,30m,1h",
"current": { "text": "5m", "value": "5m" }
}
]
},
"panels": [
{
"title": "当前 QPS",
"type": "stat",
"gridPos": { "h": 4, "w": 6, "x": 0, "y": 0 },
"targets": [
{
"expr": "sum(rate(http_requests_total{service=\"$service\"}[$interval]))",
"legendFormat": "QPS"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps",
"thresholds": {
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 1000 },
{ "color": "red", "value": 5000 }
]
}
}
}
},
{
"title": "错误率",
"type": "stat",
"gridPos": { "h": 4, "w": 6, "x": 6, "y": 0 },
"targets": [
{
"expr": "sum(rate(http_requests_total{service=\"$service\",status_code=~\"5..\"}[$interval])) / sum(rate(http_requests_total{service=\"$service\"}[$interval])) * 100",
"legendFormat": "Error Rate"
}
],
"fieldConfig": {
"defaults": {
"unit": "percent",
"thresholds": {
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 1 },
{ "color": "red", "value": 5 }
]
}
}
}
},
{
"title": "P99 延迟",
"type": "stat",
"gridPos": { "h": 4, "w": 6, "x": 12, "y": 0 },
"targets": [
{
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{service=\"$service\"}[$interval]))) * 1000",
"legendFormat": "P99"
}
],
"fieldConfig": {
"defaults": {
"unit": "ms",
"thresholds": {
"steps": [
{ "color": "green", "value": null },
{ "color": "yellow", "value": 200 },
{ "color": "red", "value": 500 }
]
}
}
}
},
{
"title": "请求速率(按状态码)",
"type": "timeseries",
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 4 },
"targets": [
{
"expr": "sum by (status_code) (rate(http_requests_total{service=\"$service\"}[$interval]))",
"legendFormat": "{{status_code}}"
}
],
"fieldConfig": {
"overrides": [
{
"matcher": { "id": "byRegexp", "options": "5.." },
"properties": [{ "id": "color", "value": { "fixedColor": "red", "mode": "fixed" } }]
},
{
"matcher": { "id": "byRegexp", "options": "2.." },
"properties": [{ "id": "color", "value": { "fixedColor": "green", "mode": "fixed" } }]
}
]
}
},
{
"title": "延迟分布",
"type": "timeseries",
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 4 },
"targets": [
{
"expr": "histogram_quantile(0.50, sum by (le) (rate(http_request_duration_seconds_bucket{service=\"$service\"}[$interval]))) * 1000",
"legendFormat": "P50"
},
{
"expr": "histogram_quantile(0.90, sum by (le) (rate(http_request_duration_seconds_bucket{service=\"$service\"}[$interval]))) * 1000",
"legendFormat": "P90"
},
{
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{service=\"$service\"}[$interval]))) * 1000",
"legendFormat": "P99"
}
],
"fieldConfig": {
"defaults": { "unit": "ms" }
}
}
]
}
}3.4 Grafana Dashboard as Code 工作流
使用 AI + Grafonnet(Jsonnet 库)实现仪表板版本化管理:
Prompt 模板:Grafonnet 代码生成
你是 Grafana 和 Grafonnet(Jsonnet)专家。请将以下仪表板需求转换为 Grafonnet 代码:
## 仪表板需求
[描述仪表板面板和查询]
## 输出要求
1. 使用 Grafonnet v11+ 库语法
2. 代码模块化(变量、面板、行分离)
3. 包含 Makefile 或脚本用于构建和部署
4. 支持多环境(dev/staging/prod)参数化Grafonnet 示例(AI 生成)
// dashboards/service-overview.jsonnet
local grafana = import 'github.com/grafana/grafonnet/gen/grafonnet-latest/main.libsonnet';
local dashboard = grafana.dashboard;
local panel = grafana.panel;
local query = grafana.query;
local variables = {
service: dashboard.variable.query.new('service')
+ dashboard.variable.query.withDatasource('prometheus')
+ dashboard.variable.query.queryTypes.withLabelValues('service', 'http_requests_total'),
interval: dashboard.variable.interval.new('interval', ['1m', '5m', '15m', '30m', '1h'])
+ dashboard.variable.interval.withCurrent('5m'),
};
local panels = {
qps: panel.stat.new('当前 QPS')
+ panel.stat.queryOptions.withTargets([
query.prometheus.new('prometheus',
'sum(rate(http_requests_total{service="$service"}[$interval]))')
+ query.prometheus.withLegendFormat('QPS'),
])
+ panel.stat.standardOptions.withUnit('reqps'),
errorRate: panel.stat.new('错误率')
+ panel.stat.queryOptions.withTargets([
query.prometheus.new('prometheus',
'sum(rate(http_requests_total{service="$service",status_code=~"5.."}[$interval])) / sum(rate(http_requests_total{service="$service"}[$interval])) * 100')
+ query.prometheus.withLegendFormat('Error Rate'),
])
+ panel.stat.standardOptions.withUnit('percent'),
requestRate: panel.timeSeries.new('请求速率')
+ panel.timeSeries.queryOptions.withTargets([
query.prometheus.new('prometheus',
'sum by (status_code) (rate(http_requests_total{service="$service"}[$interval]))')
+ query.prometheus.withLegendFormat('{{status_code}}'),
]),
};
dashboard.new('Service Overview - $service')
+ dashboard.withTags(['service', 'ai-generated'])
+ dashboard.withRefresh('30s')
+ dashboard.withVariables([variables.service, variables.interval])
+ dashboard.withPanels(
grafana.util.grid.makeGrid([
panels.qps + { gridPos: { h: 4, w: 6, x: 0, y: 0 } },
panels.errorRate + { gridPos: { h: 4, w: 6, x: 6, y: 0 } },
panels.requestRate + { gridPos: { h: 8, w: 12, x: 0, y: 4 } },
])
)4. AI 辅助运行手册(Runbook)生成
4.1 运行手册的重要性与 AI 革新
运行手册是 SRE 团队的核心知识资产,记录了事件响应的标准操作流程。传统运行手册面临的挑战:
- 文档腐化:系统变更后运行手册未同步更新
- 知识孤岛:关键操作知识存在于个人经验中
- 执行不一致:不同工程师对同一问题的处理方式不同
- 编写成本高:编写和维护高质量运行手册耗时巨大
2025-2026 年,AI 正在从根本上改变运行手册的生命周期:
| 传统方式 | AI 辅助方式 |
|---|---|
| 手动编写,容易过时 | AI 根据告警规则和系统架构自动生成 |
| 静态文档,需人工执行 | 可执行运行手册,AI 辅助自动执行步骤 |
| 事后补写,经常遗漏 | 事件过程中实时生成和更新 |
| 单一版本,缺乏上下文 | 上下文感知,根据当前系统状态动态调整 |
PagerDuty 的 SRE Agent 已经能够自动生成”自更新运行手册”——运行手册会根据每次事件的处理经验自动优化和更新。
4.2 AI 生成运行手册的 Prompt 模板
模板 1:告警驱动的运行手册生成
你是一位资深 SRE,精通事件响应和运行手册编写。请为以下告警生成完整的运行手册:
## 告警信息
- 告警名称:[例如:SLOErrorBudgetBurnRateHigh]
- 告警表达式:[粘贴 PromQL 表达式]
- 严重级别:[例如:page]
- 触发条件:[例如:错误预算消耗速率超过 14.4x]
## 系统上下文
- 服务名称:[例如:payment-service]
- 架构:[例如:Go 微服务 → PostgreSQL + Redis → Kafka]
- 依赖服务:[列出上下游依赖]
- 部署方式:[例如:Kubernetes + ArgoCD]
## 运行手册要求
1. **概述**:告警含义和影响范围
2. **严重性评估**:如何判断影响程度
3. **诊断步骤**:按优先级排列的排查步骤,每步包含:
- 具体命令或查询
- 预期输出和判断标准
- 下一步决策树
4. **缓解措施**:按场景的缓解操作
5. **升级路径**:何时升级、联系谁
6. **恢复验证**:如何确认问题已解决
7. **事后跟进**:需要创建的后续任务
## 格式要求
- 使用 Markdown 格式
- 命令使用代码块
- 包含决策树(if/then 结构)
- 预计处理时间标注模板 2:服务级运行手册集生成
你是 SRE 专家。请为以下服务生成完整的运行手册集合:
## 服务信息
- 服务名称:[服务名]
- 技术栈:[技术栈详情]
- 关键依赖:[依赖列表]
- SLO:[SLO 定义]
## 需要覆盖的场景
1. 服务完全不可用
2. 延迟异常升高
3. 错误率突增
4. 数据库连接池耗尽
5. 内存泄漏 / OOM
6. 磁盘空间不足
7. 证书过期
8. 依赖服务故障
9. 部署回滚
10. 流量激增应对
## 每个运行手册包含
- 触发条件(对应的告警规则)
- 影响评估
- 诊断命令
- 缓解步骤
- 升级路径
- 恢复验证4.3 AI 生成的运行手册示例
# 运行手册:SLO 错误预算快速消耗
## 概述
当服务的错误预算消耗速率超过正常水平 14.4 倍时触发此告警。
按当前速率,月度错误预算将在约 1 小时内耗尽。
这是 **page 级别** 告警,需要立即响应。
## 影响评估(预计 2 分钟)
### 步骤 1:确认影响范围
```bash
# 检查受影响的端点
kubectl exec -it $(kubectl get pod -l app=payment-service -o name | head -1) \
-- curl -s localhost:9090/metrics | grep http_requests_total | grep 'status_code="5'
# 在 Grafana 中查看错误分布
# 打开:https://grafana.example.com/d/payment-overview判断标准
- 如果仅单个端点受影响 → 转到「单端点故障」
- 如果多个端点受影响 → 转到「全局故障排查」
- 如果错误率 > 50% → 立即升级到 P1
诊断步骤(预计 5-10 分钟)
步骤 2:检查最近部署
# 查看最近部署历史
kubectl rollout history deployment/payment-service -n production
# 查看最近 30 分钟的部署事件
kubectl get events -n production --sort-by='.lastTimestamp' | grep payment | tail -20如果最近 30 分钟内有部署 → 转到「部署回滚」
步骤 3:检查依赖服务健康
# 检查 PostgreSQL 连接
kubectl exec -it $(kubectl get pod -l app=payment-service -o name | head -1) \
-- pg_isready -h postgres-primary -p 5432
# 检查 Redis 连接
kubectl exec -it $(kubectl get pod -l app=payment-service -o name | head -1) \
-- redis-cli -h redis-primary ping
# 检查 Kafka 消费者延迟
kubectl exec -it kafka-0 -- kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe --group payment-consumer如果依赖服务不健康 → 转到对应依赖的运行手册
步骤 4:检查资源使用
# Pod 资源使用
kubectl top pods -l app=payment-service -n production
# 检查 OOM 事件
kubectl get events -n production --field-selector reason=OOMKilling | grep payment
# 检查节点资源
kubectl top nodes如果资源不足 → 转到「资源扩容」
缓解措施
场景 A:部署回滚(预计 3 分钟)
# 回滚到上一个版本
kubectl rollout undo deployment/payment-service -n production
# 验证回滚状态
kubectl rollout status deployment/payment-service -n production --timeout=120s
# 验证错误率恢复
# 等待 2 分钟后检查 Grafana 仪表板场景 B:依赖故障降级(预计 5 分钟)
# 启用降级模式(feature flag)
kubectl set env deployment/payment-service \
DEGRADED_MODE=true \
CACHE_FALLBACK=true \
-n production
# 或通过 feature flag 服务
curl -X POST https://flags.example.com/api/flags/payment-degraded-mode \
-H "Authorization: Bearer $FLAG_TOKEN" \
-d '{"enabled": true}'场景 C:流量限制(预计 2 分钟)
# 调整 Istio 限流
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
name: payment-rate-limit
namespace: production
spec:
workloadSelector:
labels:
app: payment-service
configPatches:
- applyTo: HTTP_FILTER
match:
context: SIDECAR_INBOUND
patch:
operation: INSERT_BEFORE
value:
name: envoy.filters.http.local_ratelimit
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit
stat_prefix: http_local_rate_limiter
token_bucket:
max_tokens: 100
tokens_per_fill: 100
fill_interval: 1s
EOF升级路径
| 条件 | 升级目标 | 联系方式 |
|---|---|---|
| 错误率 > 50% 持续 5 分钟 | P1 事件指挥官 | Slack #incident-command |
| 影响支付功能 | 支付团队 Tech Lead | PagerDuty @payment-oncall |
| 数据一致性问题 | 数据团队 | Slack #data-oncall |
| 需要基础设施变更 | 平台团队 | PagerDuty @platform-oncall |
恢复验证(预计 5 分钟)
# 1. 确认错误率恢复正常
# PromQL: service:http_errors:ratio5m{service="payment-service"} < 0.001
# 2. 确认延迟恢复正常
# PromQL: service:http_latency:p99_5m{service="payment-service"} < 0.5
# 3. 确认无积压请求
# 检查 Kafka 消费者延迟是否恢复
# 4. 确认告警已自动恢复
# 检查 Alertmanager:https://alertmanager.example.com事后跟进
- 创建事件 Postmortem 文档
- 更新此运行手册(如有新发现)
- 创建改进 Jira ticket
- 安排事件回顾会议
---
## 5. AI 辅助事后分析(Postmortem)
### 5.1 AI 驱动的 Postmortem 工具对比
| 工具 | AI Postmortem 能力 | 价格 | 特色 |
|------|-------------------|------|------|
| **incident.io Scribe** | 实时转录通话、自动捕获 Slack 时间线、AI 在 15 分钟内生成 Postmortem 草稿 | Pro $16/用户/月起 | 自动化程度最高,减少 60-90 分钟手动整理 |
| **Rootly** | AI 自动生成 Postmortem、时间线提取、行动项建议 | Pro $19/用户/月起 | Slack 原生,模板灵活 |
| **FireHydrant** | 自动时间线、Postmortem 模板、工作流自定义 | Pro $35/用户/月起 | 工作流自定义能力强 |
| **PagerDuty** | 基础 Postmortem 功能,AI 辅助有限 | Business $41/用户/月起 | 告警强但 Postmortem 功能较弱 |
| **Claude/GPT** | 通用 AI 辅助编写 Postmortem | $20/月起 | 灵活,适合自定义模板 |
| **River Editor** | 免费 AI Postmortem 生成器 | 免费 | 粘贴时间线即可生成完整报告 |
### 5.2 AI 生成 Postmortem 的 Prompt 模板
#### 模板 1:完整 Postmortem 报告生成
你是一位资深 SRE,精通无指责(blameless)事后分析方法论。 请根据以下事件信息生成完整的 Postmortem 报告:
事件基本信息
- 事件 ID:[例如:INC-2025-0142]
- 事件标题:[例如:Payment Service 全面不可用]
- 严重级别:[例如:P1]
- 影响时长:[例如:2025-07-15 14:23 UTC 至 15:47 UTC(84 分钟)]
- 影响范围:[例如:所有支付交易失败,影响约 12,000 用户]
事件时间线
[按时间顺序列出关键事件,例如:
- 14:23 - Prometheus 告警触发:payment-service 错误率 > 50%
- 14:25 - PagerDuty 通知 On-Call 工程师
- 14:28 - On-Call 确认告警,开始排查
- 14:35 - 发现 PostgreSQL 连接池耗尽
- 14:42 - 确认根因:数据库迁移脚本锁表
- 14:50 - 执行回滚迁移
- 15:10 - 连接池恢复,错误率开始下降
- 15:47 - 完全恢复,告警解除]
根因分析线索
[提供已知的技术细节]
Postmortem 报告要求
- 执行摘要(3-5 句话,面向管理层)
- 影响分析(用户影响、业务影响、财务影响)
- 详细时间线(含检测、响应、缓解、恢复各阶段)
- 根因分析(使用 5 Whys 方法)
- 贡献因素(非直接原因但加剧了问题的因素)
- 做得好的地方(What went well)
- 需要改进的地方(What went poorly)
- 行动项(具体、可执行、有负责人和截止日期)
- 经验教训(Lessons learned)
格式要求
- 无指责语气(blameless)
- 行动项使用 P0/P1/P2 优先级
- 每个行动项包含:描述、负责人占位符、截止日期建议
#### 模板 2:根因分析(RCA)深度分析
你是根因分析专家。请对以下事件进行深度 RCA:
事件描述
[事件概述]
已知事实
[列出所有已知的技术事实和时间线]
分析要求
- 使用 5 Whys 方法追溯根因
- 使用 鱼骨图(Ishikawa) 分析贡献因素
- 人员(People)
- 流程(Process)
- 技术(Technology)
- 环境(Environment)
- 区分 直接原因 和 系统性原因
- 提出 预防措施(防止再次发生)和 检测措施(更快发现)
- 评估每个措施的 投入产出比
### 5.3 AI 生成的 Postmortem 示例
```markdown
# Postmortem: Payment Service 全面不可用
## 事件 ID: INC-2025-0142
### 执行摘要
2025 年 7 月 15 日 14:23-15:47 UTC,Payment Service 经历了 84 分钟的全面不可用。
根因是一个数据库迁移脚本在生产环境执行时对核心交易表加了排他锁,
导致所有数据库连接被阻塞,连接池耗尽。约 12,000 名用户受到影响,
预计收入损失约 $45,000。事件在 5 分钟内被检测到,但根因定位耗时 14 分钟。
### 影响分析
| 维度 | 影响 |
|------|------|
| 用户影响 | ~12,000 用户无法完成支付,错误页面展示 |
| 业务影响 | 所有支付交易失败,订单转化率降至 0% |
| 财务影响 | 预计收入损失 ~$45,000(基于历史同期流量) |
| SLO 影响 | 月度可用性 SLO 从 99.95% 降至 99.81%,错误预算消耗 63% |
| 声誉影响 | 社交媒体出现约 50 条用户投诉 |
### 详细时间线
| 时间 (UTC) | 事件 | 阶段 |
|-----------|------|------|
| 14:20 | 数据库迁移脚本开始执行(ALTER TABLE ADD COLUMN) | 触发 |
| 14:23 | Prometheus 告警触发:payment-service 错误率 > 50% | 检测 |
| 14:23 | Grafana 仪表板显示数据库连接池使用率 100% | 检测 |
| 14:25 | PagerDuty 通知 On-Call 工程师 Alice | 通知 |
| 14:28 | Alice 确认告警,开始排查 | 响应 |
| 14:30 | Alice 检查 Pod 状态,发现所有 Pod 健康但请求超时 | 诊断 |
| 14:33 | Alice 检查数据库连接,发现连接池耗尽 | 诊断 |
| 14:35 | Alice 查看 pg_stat_activity,发现大量 waiting 连接 | 诊断 |
| 14:38 | Alice 发现 ALTER TABLE 持有 AccessExclusiveLock | 诊断 |
| 14:42 | 确认根因:迁移脚本锁表。Alice 联系 DBA Bob | 根因确认 |
| 14:45 | Bob 取消迁移事务:SELECT pg_cancel_backend(pid) | 缓解 |
| 14:48 | 连接池开始恢复,部分请求成功 | 恢复中 |
| 15:10 | 错误率降至 1% 以下 | 恢复中 |
| 15:47 | 完全恢复,所有告警解除 | 恢复 |
### 根因分析(5 Whys)
1. **Why** 支付服务不可用?
→ 所有数据库连接被阻塞,连接池耗尽
2. **Why** 数据库连接被阻塞?
→ ALTER TABLE 语句持有 AccessExclusiveLock,阻塞所有查询
3. **Why** ALTER TABLE 在生产高峰期执行?
→ 迁移脚本通过 CI/CD 自动执行,未设置执行时间窗口
4. **Why** CI/CD 未限制迁移执行时间?
→ 迁移管线缺少"维护窗口"检查和锁超时配置
5. **Why** 迁移脚本未使用在线 DDL?
→ 团队未建立数据库迁移安全审查流程,未要求使用 pg_repack 或 CREATE INDEX CONCURRENTLY 等在线方式
### 贡献因素
- **缺少迁移预检**:CI/CD 管线未检查迁移脚本是否包含锁表操作
- **连接池无保护**:未配置连接获取超时和最大等待队列
- **监控盲区**:缺少数据库锁等待时间的专项监控
- **运行手册缺失**:无"数据库连接池耗尽"专项运行手册
### 做得好的地方 ✅
1. 告警在 3 分钟内触发,检测速度快
2. On-Call 工程师 3 分钟内响应
3. 诊断过程系统化,14 分钟定位根因
4. 团队协作顺畅,DBA 快速介入
### 需要改进的地方 ❌
1. 迁移脚本未经安全审查直接在生产执行
2. 缺少数据库锁监控告警
3. 连接池耗尽后无降级机制
4. 运行手册未覆盖此场景
### 行动项
| 优先级 | 行动项 | 负责人 | 截止日期 |
|--------|--------|--------|---------|
| P0 | 为 CI/CD 添加迁移安全检查(检测 ALTER TABLE、锁类型) | [DBA 团队] | 1 周内 |
| P0 | 配置数据库连接获取超时(5s)和锁等待超时(10s) | [后端团队] | 3 天内 |
| P1 | 添加 pg_stat_activity 锁等待监控告警 | [SRE 团队] | 2 周内 |
| P1 | 编写"数据库连接池耗尽"运行手册 | [SRE 团队] | 2 周内 |
| P1 | 建立数据库迁移安全审查清单和流程 | [DBA 团队] | 2 周内 |
| P2 | 实现支付服务降级模式(缓存兜底) | [后端团队] | 1 个月内 |
| P2 | 迁移管线添加维护窗口检查 | [平台团队] | 1 个月内 |
### 经验教训
1. **数据库迁移是高风险操作**:所有生产迁移必须经过安全审查,使用在线 DDL 方式
2. **连接池需要保护机制**:超时、队列限制、断路器缺一不可
3. **监控需要覆盖数据库内部状态**:不仅监控应用层指标,还需监控数据库锁、连接、查询性能6. AIOps 平台与智能异常检测
6.1 AIOps 平台深度对比
AIOps(AI for IT Operations)市场在 2025 年估值已达 164 亿美元,预计 2030 年将达 366 亿美元。以下是主流 AIOps 平台的深度对比:
| 维度 | Datadog Watchdog/Bits AI | New Relic AI | PagerDuty AIOps | BigPanda | incident.io AI SRE |
|---|---|---|---|---|---|
| 核心能力 | 自动异常检测、根因分析、AI 告警 | 跨遥测关联、NL 查询、AI 告警 | AI SRE Agent、智能路由、自更新运行手册 | 事件关联、噪声消除、自动化工作流 | AI 自动响应、自动 Postmortem |
| 异常检测 | Watchdog 自动检测,无需配置阈值 | Applied Intelligence 异常检测 | 事件关联和模式识别 | 跨工具事件关联 | 基于历史模式的异常识别 |
| 噪声消除 | 智能告警分组和去重 | 事件关联和智能分组 | AIOps 事件关联,减少 90%+ 噪声 | 核心能力,跨工具事件聚合 | 智能告警路由 |
| 自动化程度 | 中(检测+建议) | 中(检测+查询辅助) | 高(SRE Agent 自动执行) | 高(自动化工作流) | 最高(80% 自动响应) |
| 集成生态 | 750+ 集成 | 600+ 集成 | 700+ 集成 | 广泛的监控工具集成 | Slack/Teams 原生 |
| 自托管 | 否 | 否 | 否 | 否 | 否 |
| 起步价 | $15/主机/月 | 免费层 100GB/月 | $21/用户/月 | 联系销售 | 免费(≤10 用户) |
| 适用规模 | 中大型 | 各规模 | 中大型 | 大型企业 | 中小到中大型 |
6.2 Datadog Watchdog 与 Bits AI
Datadog 的 AI 能力分为两个核心组件:
Watchdog(自动异常检测):
- 自动监控所有指标,无需手动配置阈值
- 使用机器学习检测异常模式(突变、趋势变化、季节性偏差)
- 自动关联异常事件,提供根因分析建议
- 支持 APM、基础设施、日志的跨域关联
Bits AI(生成式 AI 助手):
- 自然语言查询监控数据
- AI 辅助事件调查和根因分析
- 自动生成事件摘要和建议
- 与 Slack/Teams 集成的 AI 助手
使用 AI 配置 Datadog Monitor 的 Prompt 模板
你是 Datadog 监控配置专家。请为以下需求生成 Datadog Monitor 配置(Terraform 格式):
## 监控需求
- 服务:[服务名]
- 监控类型:[metric/log/APM/composite]
- 条件:[描述告警条件]
- 通知:[通知渠道和升级策略]
## 输出要求
1. Terraform datadog_monitor 资源定义
2. 包含合理的 evaluation_delay 和 new_group_delay
3. 包含 warning 和 critical 双阈值
4. 包含 notify_no_data 配置
5. 消息模板包含 runbook 链接和上下文信息Terraform 配置示例(AI 生成)
# Datadog Monitor - AI 生成
resource "datadog_monitor" "payment_error_rate" {
name = "[Payment] Error Rate Exceeds SLO Threshold"
type = "query alert"
message = <<-EOT
## Payment Service Error Rate Alert
{{#is_alert}}
🔴 **CRITICAL**: Error rate is {{value}}%, exceeding 5% threshold.
{{/is_alert}}
{{#is_warning}}
🟡 **WARNING**: Error rate is {{value}}%, approaching threshold.
{{/is_warning}}
**Runbook**: https://wiki.example.com/runbooks/payment-error-rate
**Dashboard**: https://app.datadoghq.com/dashboard/payment-overview
{{#is_alert}}
@pagerduty-payment-oncall
@slack-incidents
{{/is_alert}}
{{#is_warning}}
@slack-monitoring
{{/is_warning}}
EOT
query = <<-EOQ
sum(last_5m):
sum:http.requests{service:payment-service,status_code:5xx}.as_count()
/
sum:http.requests{service:payment-service}.as_count()
* 100 > 5
EOQ
monitor_thresholds {
critical = 5
warning = 2
}
evaluation_delay = 60
new_group_delay = 60
notify_no_data = true
no_data_timeframe = 10
renotify_interval = 30
tags = [
"service:payment-service",
"team:payments",
"env:production",
"managed-by:terraform"
]
}6.3 AI 异常检测实现模式
模式 1:基于 Prometheus + Python 的简单异常检测
你是 AIOps 工程师。请生成一个基于 Prometheus 指标的异常检测脚本:
## 需求
- 从 Prometheus 查询指标数据
- 使用统计方法检测异常(Z-Score / IQR / 移动平均偏差)
- 检测到异常时发送告警到 Slack
- 支持季节性调整(按小时/天/周的周期性)
## 技术要求
- Python 3.11+
- 使用 prometheus_api_client 库
- 异常检测使用 scipy 或 sklearn
- 可配置的灵敏度参数AI 生成的异常检测脚本核心逻辑
# anomaly_detector.py - AI 生成 + 人工审查
import numpy as np
from prometheus_api_client import PrometheusConnect
from scipy import stats
from datetime import datetime, timedelta
import requests
import json
class MetricAnomalyDetector:
"""基于统计方法的 Prometheus 指标异常检测器"""
def __init__(self, prometheus_url: str, slack_webhook: str):
self.prom = PrometheusConnect(url=prometheus_url, disable_ssl=True)
self.slack_webhook = slack_webhook
def detect_zscore_anomaly(
self,
query: str,
lookback_hours: int = 24,
threshold: float = 3.0
) -> list[dict]:
"""使用 Z-Score 方法检测异常"""
# 查询历史数据
end_time = datetime.now()
start_time = end_time - timedelta(hours=lookback_hours)
result = self.prom.custom_query_range(
query=query,
start_time=start_time,
end_time=end_time,
step="5m"
)
anomalies = []
for series in result:
values = np.array([float(v[1]) for v in series["values"]])
timestamps = [v[0] for v in series["values"]]
if len(values) < 10:
continue
# 计算 Z-Score
z_scores = np.abs(stats.zscore(values))
# 检测异常点
for i, (z, val, ts) in enumerate(zip(z_scores, values, timestamps)):
if z > threshold:
anomalies.append({
"metric": series.get("metric", {}),
"timestamp": datetime.fromtimestamp(ts).isoformat(),
"value": val,
"z_score": z,
"mean": np.mean(values),
"std": np.std(values),
})
return anomalies
def detect_iqr_anomaly(
self,
query: str,
lookback_hours: int = 168, # 1 周
multiplier: float = 1.5
) -> list[dict]:
"""使用 IQR(四分位距)方法检测异常,对季节性数据更鲁棒"""
end_time = datetime.now()
start_time = end_time - timedelta(hours=lookback_hours)
result = self.prom.custom_query_range(
query=query,
start_time=start_time,
end_time=end_time,
step="15m"
)
anomalies = []
for series in result:
values = np.array([float(v[1]) for v in series["values"]])
if len(values) < 20:
continue
q1 = np.percentile(values, 25)
q3 = np.percentile(values, 75)
iqr = q3 - q1
lower_bound = q1 - multiplier * iqr
upper_bound = q3 + multiplier * iqr
# 检查最近的值是否异常
recent_values = values[-12:] # 最近 3 小时
for i, val in enumerate(recent_values):
if val < lower_bound or val > upper_bound:
anomalies.append({
"metric": series.get("metric", {}),
"value": val,
"bounds": {"lower": lower_bound, "upper": upper_bound},
"direction": "high" if val > upper_bound else "low",
})
return anomalies
def alert_slack(self, anomalies: list[dict], alert_name: str):
"""发送异常告警到 Slack"""
if not anomalies:
return
blocks = [
{
"type": "header",
"text": {"type": "plain_text", "text": f"🚨 异常检测告警: {alert_name}"}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"检测到 *{len(anomalies)}* 个异常数据点"
}
}
]
for a in anomalies[:5]: # 最多显示 5 个
blocks.append({
"type": "section",
"text": {
"type": "mrkdwn",
"text": (
f"• 指标: `{json.dumps(a.get('metric', {}))}`\n"
f" 值: *{a['value']:.2f}* | Z-Score: {a.get('z_score', 'N/A'):.2f}"
)
}
})
requests.post(self.slack_webhook, json={"blocks": blocks})
# 使用示例
if __name__ == "__main__":
detector = MetricAnomalyDetector(
prometheus_url="http://prometheus:9090",
slack_webhook="https://hooks.slack.com/services/YOUR/WEBHOOK"
)
# 检测 HTTP 错误率异常
anomalies = detector.detect_zscore_anomaly(
query='sum by (service) (rate(http_requests_total{status_code=~"5.."}[5m]))',
lookback_hours=24,
threshold=3.0
)
detector.alert_slack(anomalies, "HTTP 错误率异常")7. On-Call 自动化与 AI 辅助分诊
7.1 AI 驱动的 On-Call 工作流
2025-2026 年,AI 正在重塑 On-Call 工程师的工作方式:
传统 On-Call 流程:
告警触发 → 人工确认 → 人工排查 → 人工缓解 → 人工恢复 → 人工写 Postmortem
↓ ↓ ↓ ↓ ↓ ↓
2分钟 5分钟 15-60分钟 10-30分钟 5分钟 60-90分钟
AI 辅助 On-Call 流程:
告警触发 → AI 自动分诊 → AI 建议诊断 → AI 辅助缓解 → AI 验证恢复 → AI 生成 Postmortem
↓ ↓ ↓ ↓ ↓ ↓
即时 30秒 2-5分钟 5-10分钟 自动 15分钟7.2 AI 分诊系统架构
┌──────────────────────────────────────────────────────────────┐
│ AI 分诊系统架构 │
├──────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────┐ ┌──────────────┐ ┌───────────────────┐ │
│ │ 告警源 │───→│ AI 分诊引擎 │───→│ 响应编排器 │ │
│ │ │ │ │ │ │ │
│ │Prometheus│ │ 1.告警分类 │ │ • 自动执行运行手册 │ │
│ │Datadog │ │ 2.严重性评估 │ │ • 通知正确的人 │ │
│ │CloudWatch│ │ 3.影响范围 │ │ • 创建事件频道 │ │
│ │自定义 │ │ 4.根因推测 │ │ • 收集诊断信息 │ │
│ └─────────┘ │ 5.建议操作 │ └───────────────────┘ │
│ └──────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ 知识库 │ │
│ │ │ │
│ │ • 历史事件数据 │ │
│ │ • 运行手册 │ │
│ │ • 系统架构图 │ │
│ │ • 变更日志 │ │
│ │ • On-Call 排班 │ │
│ └──────────────────┘ │
└──────────────────────────────────────────────────────────────┘7.3 PagerDuty AI Agent Suite 实践
PagerDuty 在 2025 年发布了业界首个端到端 AI Agent 套件,核心组件包括:
SRE Agent:
- 从相关历史事件中学习
- 自动收集上下文信息和诊断数据
- 推荐并执行诊断和修复操作
- 生成自更新运行手册
Operational Insights Agent:
- 跨服务的智能事件关联
- 趋势分析和预测性告警
- 自动识别重复性事件模式
Scheduling Optimization Agent:
- 智能 On-Call 排班优化
- 基于技能和经验的告警路由
- 工作负载均衡
配置 PagerDuty 智能路由的 Prompt 模板
你是 PagerDuty 配置专家。请为以下团队设计智能告警路由策略:
## 团队结构
[描述团队成员、技能专长、时区分布]
## 服务列表
[列出需要监控的服务及其技术栈]
## 路由需求
1. 按服务技术栈路由到对应专家
2. 按严重级别设置不同的升级策略
3. 工作时间和非工作时间使用不同路由
4. 包含跨团队升级路径
## 输出要求
1. PagerDuty Service 配置
2. Escalation Policy 配置
3. Event Orchestration 规则
4. 智能路由决策逻辑7.4 使用 AI 构建自定义分诊 Bot
Prompt 模板:Slack 分诊 Bot 设计
你是 SRE 工具开发专家。请设计一个 Slack 事件分诊 Bot:
## 功能需求
1. 接收 Alertmanager/PagerDuty webhook
2. AI 分析告警内容,自动分类和评估严重性
3. 在 Slack 创建事件频道
4. 自动收集相关诊断信息(最近部署、相关指标、日志片段)
5. 推荐运行手册和缓解步骤
6. 跟踪事件状态和时间线
7. 事件结束后自动生成 Postmortem 草稿
## 技术栈
- 语言:[例如:Python/TypeScript]
- Slack SDK
- OpenAI/Claude API
- Prometheus API
- PagerDuty API
## 输出要求
1. 系统架构图
2. 核心模块设计
3. Slack 交互流程
4. AI Prompt 设计(分诊、诊断建议、Postmortem 生成)AI 生成的分诊 Bot 核心逻辑(TypeScript)
// incident-triage-bot.ts - AI 生成 + 人工审查
import { App } from "@slack/bolt";
import Anthropic from "@anthropic-ai/sdk";
interface AlertPayload {
alertname: string;
severity: string;
service: string;
description: string;
labels: Record<string, string>;
annotations: Record<string, string>;
}
interface TriageResult {
severity: "P1" | "P2" | "P3" | "P4";
category: string;
impactAssessment: string;
suggestedActions: string[];
runbookUrl: string | null;
shouldPage: boolean;
suggestedOwner: string;
}
class IncidentTriageBot {
private slack: App;
private ai: Anthropic;
constructor(slackToken: string, anthropicKey: string) {
this.slack = new App({
token: slackToken,
signingSecret: process.env.SLACK_SIGNING_SECRET!,
});
this.ai = new Anthropic({ apiKey: anthropicKey });
}
/**
* AI 驱动的告警分诊
*/
async triageAlert(alert: AlertPayload): Promise<TriageResult> {
const recentDeployments = await this.getRecentDeployments(alert.service);
const relatedIncidents = await this.getRelatedIncidents(alert.service);
const response = await this.ai.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
system: `你是一位资深 SRE,负责对生产告警进行分诊。
基于告警信息、最近部署和历史事件,评估严重性并推荐响应操作。
以 JSON 格式返回分诊结果。`,
messages: [
{
role: "user",
content: `## 告警信息
${JSON.stringify(alert, null, 2)}
## 最近部署(过去 2 小时)
${JSON.stringify(recentDeployments, null, 2)}
## 相关历史事件
${JSON.stringify(relatedIncidents, null, 2)}
## 请返回 JSON 格式的分诊结果:
{
"severity": "P1|P2|P3|P4",
"category": "分类(如:性能退化/服务不可用/资源不足/依赖故障)",
"impactAssessment": "影响评估描述",
"suggestedActions": ["建议操作1", "建议操作2"],
"runbookUrl": "相关运行手册 URL 或 null",
"shouldPage": true/false,
"suggestedOwner": "建议负责团队"
}`,
},
],
});
const text =
response.content[0].type === "text" ? response.content[0].text : "";
return JSON.parse(text) as TriageResult;
}
/**
* 创建事件 Slack 频道并发布分诊结果
*/
async createIncidentChannel(
alert: AlertPayload,
triage: TriageResult
): Promise<string> {
const timestamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const channelName = `inc-${timestamp}-${alert.service}-${triage.severity.toLowerCase()}`;
const channel = await this.slack.client.conversations.create({
name: channelName,
is_private: false,
});
const channelId = channel.channel!.id!;
// 发布分诊摘要
await this.slack.client.chat.postMessage({
channel: channelId,
blocks: [
{
type: "header",
text: {
type: "plain_text",
text: `🚨 ${triage.severity} - ${alert.alertname}`,
},
},
{
type: "section",
fields: [
{ type: "mrkdwn", text: `*服务:* ${alert.service}` },
{ type: "mrkdwn", text: `*严重级别:* ${triage.severity}` },
{ type: "mrkdwn", text: `*分类:* ${triage.category}` },
{ type: "mrkdwn", text: `*建议负责:* ${triage.suggestedOwner}` },
],
},
{
type: "section",
text: {
type: "mrkdwn",
text: `*影响评估:*\n${triage.impactAssessment}`,
},
},
{
type: "section",
text: {
type: "mrkdwn",
text: `*建议操作:*\n${triage.suggestedActions.map((a, i) => `${i + 1}. ${a}`).join("\n")}`,
},
},
],
});
return channelId;
}
private async getRecentDeployments(service: string): Promise<unknown[]> {
// 从 ArgoCD/GitHub API 获取最近部署
// 实现省略
return [];
}
private async getRelatedIncidents(service: string): Promise<unknown[]> {
// 从事件管理系统获取历史事件
// 实现省略
return [];
}
}8. 日志模式检测与 AI 辅助日志分析
8.1 AI 辅助日志查询
Grafana Assistant 支持自然语言生成 LogQL 查询,大幅降低日志分析门槛:
# 自然语言 → LogQL 示例
用户:"显示 payment-service 过去 1 小时的错误日志,按错误类型分组"
Assistant 生成:
{app="payment-service"} |= "error" | json | line_format "{{.level}} {{.msg}}"
| label_format level=level | count_over_time({app="payment-service"} |= "error" | json [1h]) by (error_type)
用户:"找出导致 500 错误最多的请求路径"
Assistant 生成:
topk(10,
sum by (path) (
count_over_time({app="payment-service"} | json | status_code = 500 [1h])
)
)8.2 AI 日志模式检测 Prompt 模板
你是日志分析专家。请分析以下日志样本,识别异常模式:
## 日志样本
[粘贴 50-100 行日志]
## 分析要求
1. 识别错误模式和频率
2. 检测异常的日志模式(新出现的错误类型、频率突变)
3. 关联分析(同一请求 ID 的日志链路)
4. 提取关键指标(错误率、延迟分布、异常堆栈)
5. 生成 LogQL/Elasticsearch 查询用于持续监控
6. 建议告警规则
## 输出格式
- 模式摘要表
- 异常发现列表
- 建议的监控查询
- 建议的告警规则8.3 使用 AI 构建日志异常检测管线
# log_anomaly_pipeline.py - AI 辅助设计
from collections import Counter
from datetime import datetime, timedelta
import re
class LogAnomalyDetector:
"""基于模式频率变化的日志异常检测"""
def __init__(self):
self.baseline_patterns: Counter = Counter()
self.current_patterns: Counter = Counter()
def extract_pattern(self, log_line: str) -> str:
"""将日志行转换为模式(替换变量部分)"""
# 替换 IP 地址
pattern = re.sub(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', '<IP>', log_line)
# 替换数字
pattern = re.sub(r'\b\d+\b', '<NUM>', pattern)
# 替换 UUID
pattern = re.sub(
r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',
'<UUID>', pattern
)
# 替换时间戳
pattern = re.sub(
r'\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}',
'<TIMESTAMP>', pattern
)
return pattern
def build_baseline(self, log_lines: list[str]):
"""从历史日志构建基线模式分布"""
for line in log_lines:
pattern = self.extract_pattern(line)
self.baseline_patterns[pattern] += 1
def detect_anomalies(
self,
current_logs: list[str],
new_pattern_threshold: int = 5,
frequency_change_ratio: float = 3.0
) -> dict:
"""检测日志模式异常"""
self.current_patterns = Counter()
for line in current_logs:
pattern = self.extract_pattern(line)
self.current_patterns[pattern] += 1
anomalies = {
"new_patterns": [], # 新出现的模式
"frequency_spikes": [], # 频率激增的模式
"disappeared": [], # 消失的模式
}
# 检测新模式
for pattern, count in self.current_patterns.items():
if pattern not in self.baseline_patterns and count >= new_pattern_threshold:
anomalies["new_patterns"].append({
"pattern": pattern,
"count": count,
"sample": next(
(l for l in current_logs if self.extract_pattern(l) == pattern),
None
)
})
# 检测频率激增
total_baseline = sum(self.baseline_patterns.values()) or 1
total_current = sum(self.current_patterns.values()) or 1
for pattern, count in self.current_patterns.items():
if pattern in self.baseline_patterns:
baseline_ratio = self.baseline_patterns[pattern] / total_baseline
current_ratio = count / total_current
if baseline_ratio > 0 and current_ratio / baseline_ratio > frequency_change_ratio:
anomalies["frequency_spikes"].append({
"pattern": pattern,
"baseline_ratio": f"{baseline_ratio:.4f}",
"current_ratio": f"{current_ratio:.4f}",
"change_factor": f"{current_ratio / baseline_ratio:.1f}x",
})
return anomalies实战案例:从零构建 AI 辅助监控体系
案例背景
一个电商平台的 SRE 团队需要为新上线的微服务架构建立完整的监控体系。技术栈:
- 应用层:Node.js + Go 微服务(8 个服务)
- 数据层:PostgreSQL + Redis + Kafka
- 基础设施:Kubernetes on AWS EKS
- 现有工具:Prometheus + Grafana(基础配置)
步骤 1:使用 AI 生成监控策略
Prompt 给 Claude Code:
我们是一个电商平台,有 8 个微服务运行在 Kubernetes 上。
请帮我设计完整的监控策略,包括:
1. 每个服务层级需要监控的关键指标(USE/RED 方法)
2. SLO 定义建议
3. 告警分级策略
4. 仪表板组织结构AI 输出的监控策略摘要:
## 监控策略
### SLO 定义
| 服务 | 可用性 SLO | 延迟 SLO (P99) | 错误预算/月 |
|------|-----------|---------------|-----------|
| API Gateway | 99.95% | 200ms | 21.6 分钟 |
| Order Service | 99.9% | 500ms | 43.2 分钟 |
| Payment Service | 99.99% | 300ms | 4.3 分钟 |
| User Service | 99.9% | 200ms | 43.2 分钟 |
| Inventory Service | 99.9% | 300ms | 43.2 分钟 |
### 告警分级
| 级别 | 条件 | 响应时间 | 通知方式 |
|------|------|---------|---------|
| Page | SLO 错误预算 1h 内耗尽 | 5 分钟 | PagerDuty + Slack |
| Critical | 错误率 > 5% 或 P99 > 2x SLO | 15 分钟 | Slack #alerts |
| Warning | 错误率 > 1% 或资源 > 80% | 1 小时 | Slack #monitoring |
| Info | 趋势变化、部署事件 | 下个工作日 | Slack #monitoring |
### 仪表板结构
1. 全局概览(所有服务 SLO 状态)
2. 服务详情(每个服务一个仪表板)
3. 基础设施(K8s 集群、节点、Pod)
4. 数据层(PostgreSQL、Redis、Kafka)
5. SLO 错误预算(月度追踪)
6. On-Call 概览(当前告警、事件统计)步骤 2:AI 批量生成告警规则
Prompt:
基于上述监控策略,请为所有 8 个服务生成完整的 Prometheus 告警规则。
使用模板化方式,通过 label 区分不同服务。
包含 recording rules 预计算。
输出完整的 YAML 文件。步骤 3:AI 生成 Grafana 仪表板
Prompt:
请为"全局概览"仪表板生成 Grafana Dashboard JSON。
要求:
- 顶部:8 个服务的 SLO 状态卡片(绿/黄/红)
- 中部:错误预算消耗趋势图
- 底部:最近事件列表(来自 annotation)
- 支持 $namespace 和 $interval 变量步骤 4:AI 生成运行手册集
Prompt:
为以下 5 个最常见的告警场景生成运行手册:
1. Payment Service 错误率突增
2. 数据库连接池耗尽
3. Kafka 消费者延迟过高
4. K8s Pod OOM Killed
5. API Gateway 延迟 P99 超标
每个运行手册包含:诊断步骤、缓解措施、升级路径、恢复验证。步骤 5:配置 AI 分诊自动化
Prompt:
请设计一个基于 Alertmanager webhook 的 AI 分诊系统:
1. 接收 Alertmanager 告警
2. 使用 Claude API 进行自动分诊
3. 在 Slack 创建事件频道
4. 自动关联最近部署和相关指标
5. 推荐运行手册
请提供 Python 实现的核心代码。案例成果
| 指标 | 实施前 | 实施后 | 改善 |
|---|---|---|---|
| 告警规则数量 | 12 条(手写) | 86 条(AI 生成 + 人工审查) | 7x |
| 仪表板数量 | 3 个(基础) | 15 个(全覆盖) | 5x |
| 运行手册覆盖率 | 20%(仅核心场景) | 85%(主要场景全覆盖) | 4.25x |
| MTTD(平均检测时间) | 15 分钟 | 3 分钟 | 80% ↓ |
| MTTR(平均恢复时间) | 45 分钟 | 18 分钟 | 60% ↓ |
| 配置编写时间 | 3 周(人工) | 3 天(AI 辅助) | 85% ↓ |
案例分析
关键成功因素:
- AI 生成 + 人工审查:AI 负责批量生成,人工负责审查和调优
- 模板化思维:使用参数化模板而非逐个服务手写
- SLO 驱动:以 SLO 为核心组织告警,避免告警疲劳
- 渐进式部署:先 warning 观察,再调整为 critical/page
注意事项:
- AI 生成的阈值需要根据实际流量模式调整
- Recording rules 需要验证计算正确性
- 运行手册需要在实际事件中验证和迭代
9. 监控即代码(Monitoring as Code)与 AI
9.1 监控配置的版本化管理
将监控配置纳入 Git 版本控制是现代 SRE 的最佳实践。AI 可以加速这一流程:
项目结构示例:
monitoring/
├── prometheus/
│ ├── recording-rules/
│ │ ├── web-services.yml
│ │ ├── data-layer.yml
│ │ └── infrastructure.yml
│ ├── alerting-rules/
│ │ ├── slo-alerts.yml
│ │ ├── infra-alerts.yml
│ │ └── business-alerts.yml
│ └── alertmanager.yml
├── grafana/
│ ├── dashboards/
│ │ ├── global-overview.json
│ │ ├── service-detail.jsonnet
│ │ └── slo-tracking.json
│ └── provisioning/
│ ├── datasources.yml
│ └── dashboards.yml
├── runbooks/
│ ├── high-error-rate.md
│ ├── high-latency.md
│ ├── db-connection-pool.md
│ └── pod-oom-killed.md
├── scripts/
│ ├── anomaly-detector.py
│ └── triage-bot.ts
├── terraform/
│ ├── datadog-monitors.tf
│ ├── pagerduty-services.tf
│ └── grafana-dashboards.tf
└── Makefile9.2 CI/CD 集成:监控配置的自动验证
Prompt 模板:监控 CI/CD 管线生成
你是 DevOps 专家。请为监控配置仓库生成 CI/CD 管线:
## 仓库结构
[描述监控配置仓库结构]
## 管线要求
1. PR 阶段:
- 验证 Prometheus 规则语法(promtool check rules)
- 验证 Alertmanager 配置(amtool check-config)
- 验证 Grafana Dashboard JSON 格式
- 运行单元测试(promtool test rules)
- AI 审查告警规则质量(阈值合理性、标签完整性)
2. 合并后:
- 自动部署到 staging 环境
- 运行集成测试
- 部署到 production
## 输出要求
- GitHub Actions workflow YAML
- 包含所有验证步骤
- 包含 Slack 通知AI 生成的 GitHub Actions 工作流
# .github/workflows/monitoring-ci.yml
name: Monitoring Configuration CI/CD
on:
pull_request:
paths:
- 'prometheus/**'
- 'grafana/**'
- 'alertmanager.yml'
push:
branches: [main]
paths:
- 'prometheus/**'
- 'grafana/**'
- 'alertmanager.yml'
jobs:
validate:
name: Validate Monitoring Config
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install promtool
run: |
PROM_VERSION="2.53.0"
wget -q "https://github.com/prometheus/prometheus/releases/download/v${PROM_VERSION}/prometheus-${PROM_VERSION}.linux-amd64.tar.gz"
tar xzf "prometheus-${PROM_VERSION}.linux-amd64.tar.gz"
sudo mv "prometheus-${PROM_VERSION}.linux-amd64/promtool" /usr/local/bin/
- name: Validate Prometheus Rules
run: |
echo "=== 验证 Recording Rules ==="
for f in prometheus/recording-rules/*.yml; do
echo "检查: $f"
promtool check rules "$f"
done
echo "=== 验证 Alerting Rules ==="
for f in prometheus/alerting-rules/*.yml; do
echo "检查: $f"
promtool check rules "$f"
done
- name: Run Rule Unit Tests
run: |
if [ -d "prometheus/tests" ]; then
for f in prometheus/tests/*_test.yml; do
echo "运行测试: $f"
promtool test rules "$f"
done
fi
- name: Install amtool
run: |
AM_VERSION="0.27.0"
wget -q "https://github.com/prometheus/alertmanager/releases/download/v${AM_VERSION}/alertmanager-${AM_VERSION}.linux-amd64.tar.gz"
tar xzf "alertmanager-${AM_VERSION}.linux-amd64.tar.gz"
sudo mv "alertmanager-${AM_VERSION}.linux-amd64/amtool" /usr/local/bin/
- name: Validate Alertmanager Config
run: amtool check-config prometheus/alertmanager.yml
- name: Validate Grafana Dashboards
run: |
echo "=== 验证 Dashboard JSON ==="
for f in grafana/dashboards/*.json; do
echo "检查: $f"
python3 -c "import json; json.load(open('$f'))" || exit 1
done
- name: Check Alert Quality
run: |
python3 scripts/check-alert-quality.py \
--rules-dir prometheus/alerting-rules/ \
--check-labels severity,service \
--check-annotations summary,description,runbook_url \
--check-for-duration \
--min-for-duration 1m
deploy-staging:
name: Deploy to Staging
needs: validate
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v4
- name: Deploy Prometheus Rules to Staging
run: |
kubectl --context staging apply -f prometheus/recording-rules/ -n monitoring
kubectl --context staging apply -f prometheus/alerting-rules/ -n monitoring
- name: Deploy Grafana Dashboards to Staging
run: |
for f in grafana/dashboards/*.json; do
curl -X POST "https://grafana-staging.example.com/api/dashboards/db" \
-H "Authorization: Bearer ${{ secrets.GRAFANA_STAGING_TOKEN }}" \
-H "Content-Type: application/json" \
-d "{\"dashboard\": $(cat $f), \"overwrite\": true}"
done
- name: Notify Slack
uses: slackapi/slack-github-action@v2
with:
webhook: ${{ secrets.SLACK_WEBHOOK }}
payload: |
{
"text": "✅ 监控配置已部署到 Staging 环境",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "监控配置更新已部署到 *Staging*\n提交: `${{ github.sha }}`\n作者: ${{ github.actor }}"
}
}
]
}
deploy-production:
name: Deploy to Production
needs: deploy-staging
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- name: Deploy to Production
run: |
kubectl --context production apply -f prometheus/recording-rules/ -n monitoring
kubectl --context production apply -f prometheus/alerting-rules/ -n monitoring
- name: Deploy Grafana Dashboards
run: |
for f in grafana/dashboards/*.json; do
curl -X POST "https://grafana.example.com/api/dashboards/db" \
-H "Authorization: Bearer ${{ secrets.GRAFANA_PROD_TOKEN }}" \
-H "Content-Type: application/json" \
-d "{\"dashboard\": $(cat $f), \"overwrite\": true}"
done9.3 Prometheus 规则单元测试
AI 可以帮助生成告警规则的单元测试:
Prompt 模板
你是 Prometheus 测试专家。请为以下告警规则生成 promtool 单元测试:
## 告警规则
[粘贴告警规则 YAML]
## 测试要求
1. 测试告警在正确条件下触发
2. 测试告警在正常条件下不触发
3. 测试 for 持续时间的行为
4. 测试 recording rules 的计算正确性
5. 测试标签和 annotation 的正确性AI 生成的测试示例
# prometheus/tests/slo_alerts_test.yml
rule_files:
- ../alerting-rules/slo-alerts.yml
- ../recording-rules/web-services.yml
evaluation_interval: 1m
tests:
# 测试 1:错误率超过阈值时触发告警
- interval: 1m
input_series:
- series: 'http_requests_total{service="payment-service",status_code="200"}'
values: '0+95x20' # 每分钟 95 个成功请求
- series: 'http_requests_total{service="payment-service",status_code="500"}'
values: '0+10x20' # 每分钟 10 个错误请求(~9.5% 错误率)
alert_rule_test:
- eval_time: 10m
alertname: SLOErrorBudgetBurnRateHigh
exp_alerts:
- exp_labels:
severity: page
slo: availability
service: payment-service
exp_annotations:
summary: "SLO 错误预算快速消耗 - payment-service"
# 测试 2:正常错误率不触发告警
- interval: 1m
input_series:
- series: 'http_requests_total{service="payment-service",status_code="200"}'
values: '0+999x20' # 每分钟 999 个成功请求
- series: 'http_requests_total{service="payment-service",status_code="500"}'
values: '0+1x20' # 每分钟 1 个错误请求(0.1% 错误率)
alert_rule_test:
- eval_time: 10m
alertname: SLOErrorBudgetBurnRateHigh
exp_alerts: [] # 不应触发
# 测试 3:Recording Rule 计算正确性
- interval: 1m
input_series:
- series: 'http_requests_total{service="order-service",status_code="200"}'
values: '0+100x10'
- series: 'http_requests_total{service="order-service",status_code="500"}'
values: '0+5x10'
promql_expr_test:
- expr: 'service:http_errors:ratio5m{service="order-service"}'
eval_time: 10m
exp_samples:
- labels: 'service:http_errors:ratio5m{service="order-service"}'
value: 0.0476 # 5/(100+5) ≈ 0.047610. AI 辅助容量规划与趋势预测
10.1 使用 AI 进行容量规划
Prompt 模板:容量规划分析
你是 SRE 容量规划专家。请基于以下指标数据进行容量规划分析:
## 当前资源使用
- CPU:[当前使用率和趋势]
- 内存:[当前使用率和趋势]
- 存储:[当前使用量和增长率]
- 网络:[当前带宽使用]
## 业务增长预期
- 用户增长率:[例如:月增 15%]
- 流量增长率:[例如:月增 20%]
- 数据增长率:[例如:月增 10GB]
## 分析要求
1. 基于当前趋势预测未来 3/6/12 个月的资源需求
2. 识别瓶颈资源和预计耗尽时间
3. 提供扩容建议(垂直/水平/架构优化)
4. 成本估算
5. 生成 PromQL 查询用于持续监控容量趋势10.2 Prometheus 趋势预测查询
AI 可以帮助生成基于 predict_linear 的容量预测查询:
# 容量预测告警规则 - AI 生成
groups:
- name: capacity_prediction
rules:
# 磁盘空间预测:7 天内耗尽
- alert: DiskWillFillIn7Days
expr: |
predict_linear(
node_filesystem_avail_bytes{mountpoint="/"}[7d], 7 * 24 * 3600
) < 0
for: 1h
labels:
severity: warning
annotations:
summary: "磁盘空间预计 7 天内耗尽 - {{ $labels.instance }}"
description: |
基于过去 7 天的趋势,实例 {{ $labels.instance }} 的根分区
预计将在 7 天内耗尽。当前可用空间:
{{ with printf "node_filesystem_avail_bytes{instance='%s',mountpoint='/'}" $labels.instance | query }}
{{ . | first | value | humanize1024 }}B
{{ end }}
runbook_url: "https://wiki.example.com/runbooks/disk-capacity"
# 内存趋势:24 小时内可能 OOM
- alert: MemoryWillExhaustIn24h
expr: |
predict_linear(
node_memory_MemAvailable_bytes[6h], 24 * 3600
) < 0
for: 30m
labels:
severity: warning
annotations:
summary: "内存预计 24 小时内耗尽 - {{ $labels.instance }}"
runbook_url: "https://wiki.example.com/runbooks/memory-capacity"
# PVC 存储预测
- alert: PVCWillFillIn14Days
expr: |
predict_linear(
kubelet_volume_stats_available_bytes[14d], 14 * 24 * 3600
) < 0
for: 1h
labels:
severity: warning
annotations:
summary: "PVC 存储预计 14 天内耗尽 - {{ $labels.persistentvolumeclaim }}"
runbook_url: "https://wiki.example.com/runbooks/pvc-capacity"避坑指南
❌ 常见错误
-
盲目信任 AI 生成的阈值
- 问题:AI 生成的告警阈值基于通用经验,可能不适合你的业务场景。例如 AI 可能将错误率阈值设为 1%,但你的服务正常错误率就有 0.8%
- 正确做法:先以 warning 级别部署 AI 生成的告警,观察 1-2 周的实际触发情况,再根据基线数据调整阈值。使用
for持续时间避免瞬时波动触发
-
告警规则缺少
for持续时间- 问题:AI 有时生成的告警规则没有设置
for字段,导致瞬时指标波动就触发告警,造成告警风暴 - 正确做法:所有告警规则必须设置合理的
for持续时间。Page 级别至少 2 分钟,Warning 级别至少 5-10 分钟。在 AI 生成后人工检查每条规则的for值
- 问题:AI 有时生成的告警规则没有设置
-
仪表板面板过多导致性能问题
- 问题:AI 倾向于生成大量面板以”全面覆盖”,但一个仪表板包含 50+ 面板会导致加载缓慢,Prometheus 查询压力大
- 正确做法:每个仪表板控制在 15-20 个面板以内。使用 recording rules 预计算复杂查询。按层级组织仪表板(概览→详情→调试)
-
运行手册中的命令未验证
- 问题:AI 生成的运行手册中的 kubectl、SQL 等命令可能包含语法错误或不适用于你的环境
- 正确做法:在非生产环境验证所有运行手册命令。使用
--dry-run标志测试危险操作。定期进行”运行手册演练”(Game Day)
-
Postmortem 模板过于模板化
- 问题:AI 生成的 Postmortem 可能过于格式化,缺少真正有价值的深度分析和团队特定的上下文
- 正确做法:将 AI 生成的 Postmortem 作为草稿起点,团队在事件回顾会议中补充真实的讨论和洞察。确保行动项具体、可执行、有明确负责人
-
过度依赖 AI 异常检测而忽略基础监控
- 问题:团队投入大量精力配置 AI 异常检测,却忽略了基础的阈值告警和健康检查
- 正确做法:先建立完善的基础监控(健康检查、资源阈值、SLO 告警),再叠加 AI 异常检测作为补充。AI 异常检测是锦上添花,不是替代品
-
告警标签和 Annotation 不完整
- 问题:AI 生成的告警规则可能缺少关键标签(severity、service、team)或 annotation(runbook_url、description),导致告警路由失败或 On-Call 工程师缺少上下文
- 正确做法:建立告警规则质量检查清单,在 CI/CD 中自动验证必需的标签和 annotation。使用本节提供的 CI 脚本进行自动化检查
-
Recording Rules 命名不规范
- 问题:AI 生成的 recording rules 命名不遵循 Prometheus 命名规范(
level:metric:operations),导致后续维护困难 - 正确做法:在 Prompt 中明确要求遵循命名规范,并在 CI 中检查。正确示例:
service:http_requests:rate5m,错误示例:my_custom_metric
- 问题:AI 生成的 recording rules 命名不遵循 Prometheus 命名规范(
✅ 最佳实践
- SLO 驱动告警设计:以 SLO 和错误预算为核心组织告警,而非为每个指标设置独立阈值。使用多窗口多燃烧率(Multi-Window Multi-Burn-Rate)告警策略
- 告警分级明确:严格区分 page(需要立即响应)、critical(15 分钟内响应)、warning(工作时间处理)、info(仅记录),避免所有告警都是 critical
- 监控即代码:所有监控配置纳入 Git 版本控制,通过 CI/CD 部署,禁止手动修改生产环境配置
- 运行手册与告警绑定:每条 page/critical 告警必须有对应的 runbook_url annotation,指向经过验证的运行手册
- 定期演练:每季度进行一次”Game Day”,模拟故障场景,验证告警、运行手册和响应流程的有效性
- AI 生成后必须人工审查:AI 生成的所有监控配置都必须经过有经验的 SRE 审查,特别关注阈值合理性、标签完整性和查询性能
- 渐进式部署告警:新告警先以 warning 级别部署观察,确认无误后再提升为 critical/page
- 噪声管理:定期审查告警触发频率,消除噪声告警。目标:每个 On-Call 轮值期间的 page 告警不超过 2-3 次
相关资源与延伸阅读
- Grafana Assistant 官方文档 — Grafana AI 助手的完整使用指南,包含自然语言查询和仪表板创建功能
- Prometheus Alerting Best Practices — Prometheus 官方告警最佳实践指南,涵盖告警设计原则和常见模式
- PagerDuty AI Agent Suite — PagerDuty 的 AI SRE Agent、智能路由和自更新运行手册功能介绍
- incident.io AI SRE — 现代事件管理平台,AI 自动化高达 80% 的事件响应流程
- BigPanda AIOps Platform — 企业级 AIOps 平台,专注事件关联和噪声消除
- Awesome Prometheus Alerts — GitHub 上最全面的 Prometheus 告警规则集合,覆盖各类中间件和基础设施
- Grafonnet(Grafana Jsonnet 库) — 使用 Jsonnet 编写 Grafana 仪表板的官方库,实现 Dashboard as Code
- SLO Generator — Google 开源的 SLO 计算和告警生成工具
- Prometheus Alert Rule Generator — 在线 Prometheus 告警规则生成器和 PromQL 速查表
- KodeKloud AIOps Foundations Course — AIOps 基础课程,结合 Prometheus、Grafana 和 Python 构建 AI 驱动的监控系统
参考来源
- Grafana Labs — Introducing Grafana Assistant (2025-05)
- Grafana Labs — Grafana Assistant GA and Assistant Investigations Preview (2025-10)
- Grafana Labs — The Year in AI at Grafana Labs (2025-12)
- Grafana Labs — Going Beyond AI Chat: Building an Agentic System (2025-06)
- PagerDuty — First End-to-End AI Agent Suite Launch (2025-10)
- PagerDuty — Spring 2025 Product Launch: Agentic AI for SRE (2025-02)
- incident.io — 5 Best AI-Powered Incident Management Platforms 2026 (2026-02)
- incident.io — Automated Post-Mortems Compared (2026-02)
- incident.io — Incident Management Trends 2026 (2026-01)
- BigPanda — Agentic AI for IT Operations (2025)
- DZone — AIOps Monitoring Dashboard with Prometheus and Grafana (2025-08)
- SparkCo AI — Integrating Grafana and Prometheus with AI (2026-01)
- C# Corner — Generative AI for Incident Triage & Runbooks (2025-10)
- Cutover — AI-Powered Runbooks in Incident Management (2025-08)
- TechCloudUp — 7 Essential Prometheus Alerting Rules Best Practices (2025-08)
- Last9 — Prometheus Alerting Examples for Developers (2025-06)
- Last9 — Datadog Pricing 2026 Full Cost Breakdown (2026-01)
📖 返回 总览与导航 | 上一节:32d-AI辅助容器化 | 下一节:32f-DevOps-Steering规则与反模式