关于 promql-generator
promql-generator 是用于生成 PromQL 查询的技能,适用于仪表板、告警和指标分析。它先通过交互式规划确认目标、指标、标签和参数,再生成查询。
主要功能
- 01澄清监控目标与用途
- 02识别指标类型和可用标签
- 03交互式规划查询参数
- 04依据文档模式生成查询
- 05验证并改进查询结果
适用场景
- 01创建 PromQL 仪表板查询
- 02编写告警或记录规则表达式
- 03分析指标以排查问题或规划容量
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ akin-ozer/ cc-devops-skills --skill promql-generator安装后在 Claude Code 中输入/promql-generator确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
examples/alerting_rules.yamlcommon_queries.promqlkubernetes_patterns.promqlrecording_rules.yamlred_method.promqlslo_patterns.promqluse_method.promqlreferences/best_practices.mdmetric_types.mdpromql_functions.mdpromql_patterns.mdtests/test_service_down_portability.pytest_time_window_semantics.py详细介绍
PromQL 查询生成器
概述
此技能提供全面的交互式工作流,帮助生成符合生产要求且内置最佳实践的 PromQL 查询。可生成用于监控仪表板、告警规则和临时分析的查询,并注重用户协作以及在生成代码前进行规划。
何时使用此技能
遇到以下情况时,请调用此技能:
- 从头开始创建新的 PromQL 查询
- 构建监控仪表板(Grafana、Prometheus UI 等)
- 为 Prometheus Alertmanager 实现告警规则
- 分析指标以进行故障排查或容量规划
- 将监控需求转换为 PromQL 表达式
- 学习 PromQL 或教授他人
- 用户要求“创建”“生成”“构建”或“编写” PromQL 查询
- 使用 Prometheus 指标(计数器、仪表、直方图、摘要)
- 实现 RED(速率、错误、持续时间)或 USE(利用率、饱和度、错误)指标
交互式查询规划工作流
重要:此技能强调在生成查询前进行交互式规划。始终与用户协作规划,确保生成的查询符合其确切意图。
生成 PromQL 查询时,请遵循此工作流:
阶段 1:了解监控目标
首先了解用户想要监控或衡量什么。提出澄清问题以收集需求:
-
主要目标:你想监控或衡量什么?
- 请求速率(每秒请求数)
- 错误率(失败请求的百分比)
- 延迟/持续时间(响应时间、百分位数)
- 资源使用情况(CPU、内存、磁盘、网络)
- 可用性/正常运行时间
- 队列深度、饱和度、吞吐量
- 自定义业务指标
-
使用场景:此查询将用于什么?
- 仪表板可视化(Grafana、Prometheus UI)
- 告警规则(超过阈值时触发)
- 临时故障排查/分析
- 记录规则(预先计算的聚合)
- 容量规划或 SLO 跟踪
-
背景信息:还有其他背景信息吗?
- 服务/应用名称
- 团队或项目
- 优先级
- 现有指标或命名规范
如果用户未提供这些信息,请使用 AskUserQuestion 工具收集。
何时询问,何时推断:如果用户最初的请求已明确说明目标、使用场景和背景信息(例如,“为 payment-service 创建 P95 延迟 > 500ms 的告警”),你可以在回复中确认这些信息,而不必再次询问。仅针对缺失或含糊的信息提出澄清问题。
阶段 2:识别可用指标
确定有哪些可用且相关的指标:
-
指标发现:有哪些可用指标?
- 询问用户指标名称
- 如果不确定,建议常见的命名模式
- 检查名称中的指标类型标识:
_total后缀 → Counter_bucket、_sum、_count后缀 → Histogram- 无后缀 → 可能是 Gauge
_created后缀 → Counter 创建时间戳
-
指标类型识别:确认指标类型
- Counter:只会增加(或重置为零)的累积指标
- 示例:
http_requests_total、errors_total、bytes_sent_total - 搭配使用:
rate()、irate()、increase()
- 示例:
- Gauge:可随时间上升或下降的瞬时值
- 示例:
memory_usage_bytes、cpu_temperature_celsius、queue_length - 搭配使用:
avg_over_time()、min_over_time()、max_over_time(),或直接使用
- 示例:
- Histogram:包含累积计数的观测值分桶
- 示例:
http_request_duration_seconds_bucket、response_size_bytes_bucket - 搭配使用:
histogram_quantile()、rate()
- 示例:
- Summary:带有计数和总和的预计算分位数
- 示例:
rpc_duration_seconds{quantile="0.95"} - 使用
_sum和_count计算平均值;不要对分位数求平均值
- 示例:
- Counter:只会增加(或重置为零)的累积指标
-
标签发现:这些指标有哪些可用标签?
- 常见标签:
job、instance、environment、service、endpoint、status_code、method - 询问用户哪些标签对过滤或分组很重要
- 常见标签:
使用 AskUserQuestion 工具确认指标名称、类型和可用标签。
阶段 3:确定查询参数
收集查询的具体要求。
对用户提供参数的预先确认
IMPORTANT:如果用户已在初始请求中指定参数(例如“5 分钟窗口”、“500ms 阈值”、“错误率 > 5%”),你必须:
- 在回复中明确确认用户提供的值
- 在 AskUserQuestion 中将这些值设为预填默认选项,并将第一个选项设为“使用指定值”
- 允许用户快速确认,而不是重新询问已提供的信息
示例:如果用户说“P95 延迟超过 500ms 时触发告警”,请使用:
AskUserQuestion:
- Question: "Confirm the alert threshold?"
- Options:
1. "500ms (as specified)" - Use the threshold from your request
2. "Different threshold" - Let me specify a different value
这样既尊重用户的输入,也能加快工作流程,同时仍允许用户修改。
-
时间范围:查询应覆盖多长的时间窗口?
- 瞬时值(当前值)
- 一段时间内的速率(
[5m]、[1h]、[1d]) - 对于速率计算:实时场景通常使用
[1m]至[5m],趋势分析通常使用[1h]至[1d] - 经验法则:速率范围至少应为抓取间隔的 4 倍
-
标签过滤:使用哪些标签过滤数据?
- 精确匹配:
job="api-server"、status_code="200" - 反向匹配:
status_code!="200" - 正则匹配:
instance=~"prod-.*" - 多个条件:
{job="api", environment="production"}
- 精确匹配:
-
聚合:是否应聚合数据?
- 不聚合:按原样返回所有时间序列
- 按标签聚合:
sum by (job, endpoint)、avg by (instance) - 不按指定标签聚合:
sum without (instance, pod)、avg without (job) - 常见聚合函数:
sum、avg、max、min、count、topk、bottomk
-
阈值或条件:是否有特定条件?
- 对于告警:阈值(例如,错误率 > 5%)
- 对于过滤:仅显示高于或低于某个值的序列
- 对于比较:与历史数据进行比较(offset)
使用 AskUserQuestion 工具收集或确认这些参数。如果用户已提供数值(例如“5 分钟窗口”、“> 5%”),请将其作为默认选项供用户确认。
阶段 4:展示查询计划
生成任何代码之前,先用通俗易懂的语言展示查询计划,并请求用户确认:
## PromQL Query Plan
Based on your requirements, here's what the query will do:
**Goal**: [Describe the monitoring goal in plain English]
**Query Structure**:
1. Start with metric: `[metric_name]`
2. Filter by labels: `{label1="value1", label2="value2"}`
3. Apply function: `[function_name]([metric][time_range])`
4. Aggregate: `[aggregation] by ([label_list])`
5. Additional operations: [any calculations, ratios, or transformations]
**Expected Output**:
- Data type: [instant vector/scalar]
- Labels in result: [list of labels]
- Value represents: [what the number means]
- Typical range: [expected value range]
**Example Interpretation**:
If the query returns `0.05`, it means: [plain English explanation]
**Does this match your intentions?**
- If yes, I'll generate the query and validate it
- If no, let me know what needs to change
使用 AskUserQuestion 工具确认计划,提供以下选项:
- “是,生成此查询”
- “修改 [具体方面]”
- “展示其他方案”
用户选择后:
- “修改 [具体方面]”:提出一个聚焦的后续问题,询问要修改什么(指标、标签、函数、时间范围、阈值或输出形式),然后在生成前展示更新后的计划。
- “展示其他方案”:提供至少两个有效的查询计划,并说明各自的权衡(准确性、成本、基数、可读性),然后请用户在生成前选择一个。
阶段 5:生成 PromQL 查询
用户确认计划后,按照最佳实践生成实际的 PromQL 查询。
重要:生成前查阅参考文件
编写任何查询代码之前,必须:
-
首先确定查询类别(直方图、RED、USE、特定函数、优化等)。
-
使用 Read 工具只读取相关参考部分:
- 对于直方图查询 → 读取
references/metric_types.md(Histogram 部分) - 对于错误率/延迟模式 → 读取
references/promql_patterns.md(RED 方法部分) - 对于资源监控 → 读取
references/promql_patterns.md(USE 方法部分) - 对于优化问题 → 读取
references/best_practices.md - 对于特定函数 → 读取
references/promql_functions.md - 只有在需求发生变化,或当前对话中尚未查阅相关部分时,才重新读取该部分。
- 对于直方图查询 → 读取
-
如果无法读取所需参考资料,说明问题,并使用已有的最相关文档模式,尽力生成查询。
-
在回复中引用适用的模式或最佳实践:
As documented in references/promql_patterns.md (Pattern 3: Latency Percentile): # 95th percentile latency histogram_quantile(0.95, sum by (le) (rate(...))) -
生成类似查询时,参考示例文件:
Based on examples/red_method.promql (lines 64-82): # P95 latency with proper histogram_quantile usage
这样可以使生成的查询符合文档中的模式,同时避免在迭代式后续交流中不必要地重新读取整个文件。
查询生成最佳实践
-
始终使用标签筛选器
# Good: Specific filtering reduces cardinality rate(http_requests_total{job="api-server", environment="prod"}[5m]) # Bad: Matches all time series, high cardinality rate(http_requests_total[5m]) -
根据指标类型使用适当的函数
# Counter: Use rate() or increase() rate(http_requests_total[5m]) # Gauge: Use directly or with *_over_time() memory_usage_bytes avg_over_time(memory_usage_bytes[5m]) # Histogram: Use histogram_quantile() histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])) ) -
使用 by() 或 without() 进行聚合
# Aggregate by specific labels (keeps only these labels) sum by (job, endpoint) (rate(http_requests_total[5m])) # Aggregate without specific labels (removes these labels) sum without (instance, pod) (rate(http_requests_total[5m])) -
尽可能使用精确匹配,而非正则表达式
# Good: Faster exact match http_requests_total{status_code="200"} # Bad: Slower regex match when not needed http_requests_total{status_code=~"200"} -
正确计算比率
# Error rate: errors / total requests sum(rate(http_requests_total{status_code=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) -
复杂查询使用记录规则
- 如果查询频繁使用或计算开销较大
- 预聚合数据以减少查询负载
- 遵循命名约定:
level:metric:operations
-
采用便于阅读的格式
# Good: Multi-line for complex queries histogram_quantile(0.95, sum by (le, job) ( rate(http_request_duration_seconds_bucket{job="api-server"}[5m]) ) )
常见查询模式
模式 1:请求速率
# Requests per second
rate(http_requests_total{job="api-server"}[5m])
# Total requests per second across all instances
sum(rate(http_requests_total{job="api-server"}[5m]))
模式 2:错误率
# Error ratio (0 to 1)
sum(rate(http_requests_total{job="api-server", status_code=~"5.."}[5m]))
/
sum(rate(http_requests_total{job="api-server"}[5m]))
# Error percentage (0 to 100)
(
sum(rate(http_requests_total{job="api-server", status_code=~"5.."}[5m]))
/
sum(rate(http_requests_total{job="api-server"}[5m]))
) * 100
模式 3:延迟百分位数(直方图)
# 95th percentile latency
histogram_quantile(0.95,
sum by (le) (
rate(http_request_duration_seconds_bucket{job="api-server"}[5m])
)
)
模式 4:资源使用情况
# Current memory usage
process_resident_memory_bytes{job="api-server"}
# Average CPU usage over 5 minutes
avg_over_time(process_cpu_seconds_total{job="api-server"}[5m])
模式 5:可用性
# Percentage of up instances
(
count(up{job="api-server"} == 1)
/
count(up{job="api-server"})
) * 100
模式 6:饱和度/队列深度
# Average queue length
avg_over_time(queue_depth{job="worker"}[5m])
# Maximum queue depth in the last hour
max_over_time(queue_depth{job="worker"}[1h])
阶段 6:验证生成的查询
始终先尝试使用 devops-skills:promql-validator 技能验证生成的查询:
After generating the query, automatically invoke:
Skill(devops-skills:promql-validator)
The devops-skills:promql-validator skill will:
1. Check syntax correctness
2. Validate semantic logic (correct functions for metric types)
3. Identify anti-patterns and inefficiencies
4. Suggest optimizations
5. Explain what the query does
6. Verify it matches user intent
验证清单:
- 语法正确(括号配对、运算符有效)
- 指标类型与函数用法匹配
- 标签筛选足够具体
- 聚合方式合适
- 时间范围合理
- 不存在已知反模式
- 查询性能已优化
如果验证失败,请修复问题并重新验证,直到所有检查都通过。
如果验证器技能不可用、运行失败,或经过两轮修复/重新验证后仍无法完成:
- 简要说明验证器失败的原因(例如工具不可用、超时、解析错误等)。
- 执行手动后备检查(语法结构、指标与函数兼容性、标签筛选、聚合方式、时间范围合理性)。
- 将任何未检查的项目标记为 UNVERIFIED,并询问用户是要继续使用尽力而为的结果,还是提供更多上下文以便再次尝试验证。
重要:向用户显示验证结果
运行验证后,必须按以下格式向用户显示结构化结果:
## PromQL Validation Results
### Syntax Check
- Status: ✅ VALID / ⚠️ WARNING / ❌ ERROR / ⚠️ UNVERIFIED
- Issues: [list any syntax errors]
### Best Practices Check
- Status: ✅ OPTIMIZED / ⚠️ CAN BE IMPROVED / ❌ HAS ISSUES / ⚠️ UNVERIFIED
- Issues: [list any problems found]
- Suggestions: [list optimization opportunities]
### Validation Coverage
- Validator tool run: [successful / failed / unavailable]
- Checks completed: [syntax, semantics, anti-patterns, performance, intent-match]
- Checks skipped: [list any skipped checks, or "None"]
### Query Explanation
- **What it measures**: [plain English description]
- **Output labels**: [list labels in result, or "None (scalar)"]
- **Expected result structure**: [instant vector / scalar / etc.]
这种透明度有助于用户了解验证流程和相关建议。
阶段 7:提供使用说明
生成并验证(或执行手动后备验证)后,向用户提供:
-
最终查询:
[Generated and validated PromQL query] -
查询说明:
- 查询测量的内容
- 如何解读结果
- 预期值范围
- 输出中的标签
-
使用方法:
- 用于仪表板:复制到 Grafana/Prometheus UI 面板查询中
- 用于告警:将其与阈值集成到 Alertmanager 规则中
- 用于记录规则:将其添加到 Prometheus 记录规则配置中
- 用于临时查询:直接在 Prometheus 表达式浏览器中运行
-
自定义说明:
- 可能需要调整的时间范围
- 在不同环境中需要修改的标签
- 需要调整的阈值
- 需求变更时可用的替代函数
-
相关查询:
- 建议互补查询
- 提及记录规则的应用机会
- 推荐仪表板面板
原生直方图(Prometheus 3.x+)
原生直方图现已在 Prometheus 3.0+ 中稳定(于 2024 年 11 月发布)。与经典直方图相比,它们具有显著优势:
- 稀疏存储桶表示形式,空存储桶的开销近乎为零
- 插桩时无需配置存储桶边界
- 覆盖完整的 float64 范围
- 可在不同直方图之间高效合并
- 查询语法更简单
重要:从 Prometheus v3.8.0 开始,原生直方图已完全稳定。不过,抓取原生直方图仍需通过
scrape_native_histograms配置项显式启用。从 v3.9 开始,无需功能标志,但必须显式设置scrape_native_histograms。
原生直方图与经典直方图的语法
# Classic histogram (requires _bucket suffix and le label)
histogram_quantile(0.95,
sum by (job, le) (rate(http_request_duration_seconds_bucket[5m]))
)
# Native histogram (simpler - no _bucket suffix, no le label needed)
histogram_quantile(0.95,
sum by (job) (rate(http_request_duration_seconds[5m]))
)
原生直方图函数
# Get observation count rate from native histogram
histogram_count(rate(http_request_duration_seconds[5m]))
# Get sum of observations from native histogram
histogram_sum(rate(http_request_duration_seconds[5m]))
# Calculate fraction of observations between two values
histogram_fraction(0, 0.1, rate(http_request_duration_seconds[5m]))
# Average request duration from native histogram
histogram_sum(rate(http_request_duration_seconds[5m]))
/
histogram_count(rate(http_request_duration_seconds[5m]))
检测原生直方图与经典直方图
原生直方图具有以下特征:
- 指标名称没有
_bucket后缀 - 时间序列中没有
le标签 - 指标直接存储直方图数据(而非单独的存储桶计数器)
查询时,请检查 Prometheus 实例是否已启用原生直方图:
# prometheus.yml - Enable native histogram scraping
scrape_configs:
- job_name: 'my-app'
scrape_native_histogram: true # Prometheus 3.x+
自定义桶原生直方图(NHCB)
Prometheus 3.4+ 支持自定义桶原生直方图(schema -53),可将经典直方图转换为原生直方图。这是已有经典直方图的用户的重要迁移路径。
NHCB 的优势:
- 保留现有插桩(无需更改代码)
- 将经典直方图存储为原生直方图,降低成本
- 使用原生直方图语法进行查询
- 提高可靠性和压缩率
配置(Prometheus 3.4+):
# prometheus.yml - Convert classic histograms to NHCB on scrape
global:
scrape_configs:
- job_name: 'my-app'
convert_classic_histograms_to_nhcb: true # Prometheus 3.4+
查询 NHCB:
# Query NHCB metrics the same way as native histograms
histogram_quantile(0.95, sum by (job) (rate(http_request_duration_seconds[5m])))
# histogram_fraction also works with NHCB (Prometheus 3.4+)
histogram_fraction(0, 0.2, rate(http_request_duration_seconds[5m]))
注意:Schema -53 表示自定义桶边界。具有不同自定义桶边界的直方图通常无法相互合并。
SLO、错误预算和消耗速率模式
服务级别目标(SLO)是现代 SRE 实践的关键。这些模式有助于实现基于 SLO 的监控和告警。
错误预算计算
# Error budget remaining (for 99.9% SLO over 30 days)
# Returns value between 0 and 1 (1 = full budget, 0 = exhausted)
1 - (
sum(rate(http_requests_total{job="api", status_code=~"5.."}[30d]))
/
sum(rate(http_requests_total{job="api"}[30d]))
) / 0.001 # 0.001 = 1 - 0.999 (allowed error rate)
# Simplified: Availability over 30 days
sum(rate(http_requests_total{job="api", status_code!~"5.."}[30d]))
/
sum(rate(http_requests_total{job="api"}[30d]))
消耗速率计算
消耗速率衡量错误预算的消耗速度。消耗速率为 1 表示预算将在 SLO 窗口结束时恰好耗尽。
# Current burn rate (1 hour window, 99.9% SLO)
# Burn rate = (current error rate) / (allowed error rate)
(
sum(rate(http_requests_total{job="api", status_code=~"5.."}[1h]))
/
sum(rate(http_requests_total{job="api"}[1h]))
) / 0.001 # 0.001 = allowed error rate for 99.9% SLO
# Burn rate > 1 means consuming budget faster than allowed
# Burn rate of 14.4 consumes 2% of monthly budget in 1 hour
多窗口、多消耗速率告警(Google SRE 标准)
SLO 告警推荐使用多窗口方法,以平衡检测速度和精确度:
# Page-level alert: 2% budget in 1 hour (burn rate 14.4)
# Long window (1h) AND short window (5m) must both exceed threshold
(
(
sum(rate(http_requests_total{job="api", status_code=~"5.."}[1h]))
/
sum(rate(http_requests_total{job="api"}[1h]))
) > 14.4 * 0.001
)
and
(
(
sum(rate(http_requests_total{job="api", status_code=~"5.."}[5m]))
/
sum(rate(http_requests_total{job="api"}[5m]))
) > 14.4 * 0.001
)
# Ticket-level alert: 5% budget in 6 hours (burn rate 6)
(
(
sum(rate(http_requests_total{job="api", status_code=~"5.."}[6h]))
/
sum(rate(http_requests_total{job="api"}[6h]))
) > 6 * 0.001
)
and
(
(
sum(rate(http_requests_total{job="api", status_code=~"5.."}[30m]))
/
sum(rate(http_requests_total{job="api"}[30m]))
) > 6 * 0.001
)
SLO 记录规则
预先计算 SLO 指标,以提高告警效率:
# Recording rules for SLO calculations
groups:
- name: slo_recording_rules
interval: 30s
rules:
# Error ratio over different windows
- record: job:slo_errors_per_request:ratio_rate1h
expr: |
sum by (job) (rate(http_requests_total{status_code=~"5.."}[1h]))
/
sum by (job) (rate(http_requests_total[1h]))
- record: job:slo_errors_per_request:ratio_rate5m
expr: |
sum by (job) (rate(http_requests_total{status_code=~"5.."}[5m]))
/
sum by (job) (rate(http_requests_total[5m]))
# Availability (success ratio)
- record: job:slo_availability:ratio_rate1h
expr: |
1 - job:slo_errors_per_request:ratio_rate1h
延迟 SLO 查询
# Percentage of requests faster than SLO target (200ms)
(
sum(rate(http_request_duration_seconds_bucket{le="0.2", job="api"}[5m]))
/
sum(rate(http_request_duration_seconds_count{job="api"}[5m]))
) * 100
# Requests violating latency SLO (slower than 500ms)
(
sum(rate(http_request_duration_seconds_count{job="api"}[5m]))
-
sum(rate(http_request_duration_seconds_bucket{le="0.5", job="api"}[5m]))
)
/
sum(rate(http_request_duration_seconds_count{job="api"}[5m]))
消耗速率参考表
| 消耗速率 | 预算消耗量 | 耗尽 30 天预算所需时间 | 告警严重级别 |
|---|---|---|---|
| 1 | 30 天内 100% | 30 天 | 无 |
| 2 | 15 天内 100% | 15 天 | 低 |
| 6 | 6 小时内 5% | 5 天 | 工单 |
| 14.4 | 1 小时内 2% | ~2 天 | 页面告警 |
| 36 | 1 小时内 5% | ~20 小时 | 页面告警(紧急) |
高级查询技巧
使用子查询
子查询支持复杂的时间计算:
# Maximum 5-minute rate over the past 30 minutes
max_over_time(
rate(http_requests_total[5m])[30m:1m]
)
语法:<query>[<range>:<resolution>]
<range>:要评估的时间窗口<resolution>:各次评估之间的步长
使用 Offset 修饰符
将当前数据与历史数据进行比较:
# Compare current rate with rate from 1 week ago
rate(http_requests_total[5m])
-
rate(http_requests_total[5m] offset 1w)
使用 @ 修饰符
在指定时间戳查询指标:
# Rate at the end of the range query
rate(http_requests_total[5m] @ end())
# Rate at specific Unix timestamp
rate(http_requests_total[5m] @ 1609459200)
二元运算符和向量匹配
使用运算符组合指标并控制标签匹配:
# One-to-one matching (default)
metric_a + metric_b
# Many-to-one with group_left
rate(http_requests_total[5m])
* on (job, instance) group_left (version)
app_version_info
# Ignoring specific labels
metric_a + ignoring(instance) metric_b
逻辑运算符
根据条件筛选时间序列:
# Return series only where value > 100
http_requests_total > 100
# Return series present in both
metric_a and metric_b
# Return series in A but not in B
metric_a unless metric_b
文档查找
如果用户询问特定的 Prometheus 功能、运算符或自定义指标:
-
优先尝试 context7 MCP:
Use mcp__context7__resolve-library-id with "prometheus" Then use mcp__context7__get-library-docs with: - context7CompatibleLibraryID: /prometheus/docs - topic: [specific feature, function, or operator] - page: 1 (fetch additional pages if needed) -
回退到 WebSearch:
Search query pattern: "Prometheus PromQL [function/operator/feature] documentation [version] examples" Examples: "Prometheus PromQL rate function documentation examples" "Prometheus PromQL histogram_quantile documentation best practices" "Prometheus PromQL aggregation operators documentation"
常见监控场景
RED 方法(适用于请求驱动型服务)
-
速率:请求吞吐量
sum(rate(http_requests_total{job="api"}[5m])) by (endpoint) -
错误:错误率
sum(rate(http_requests_total{job="api", status_code=~"5.."}[5m])) / sum(rate(http_requests_total{job="api"}[5m])) -
持续时间:延迟百分位数
histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{job="api"}[5m])) )
USE 方法(适用于资源)
-
利用率:资源使用百分比
( avg(rate(node_cpu_seconds_total{mode!="idle"}[5m])) / count(node_cpu_seconds_total{mode="idle"}) ) * 100 -
饱和度:队列深度或资源争用
avg_over_time(node_load1[5m]) -
错误:错误计数器
rate(node_network_receive_errs_total[5m])
告警规则
生成用于告警的查询时:
-
包含阈值:明确给出条件
# Alert when error rate exceeds 5% ( sum(rate(http_requests_total{status_code=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) ) > 0.05 -
使用布尔运算符:返回 1(触发)或 0(不告警)
# Returns 1 when memory usage > 90% (process_resident_memory_bytes / node_memory_MemTotal_bytes) > 0.9 -
考虑持续时间:告警通常使用
for子句alert: HighErrorRate expr: | ( sum(rate(http_requests_total{status_code=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) ) > 0.05 for: 10m # Only fire after 10 minutes of continuous violation
记录规则
生成用于记录规则的查询时:
-
遵循命名约定:
level:metric:operations# level: aggregation level (job, instance, etc.) # metric: base metric name # operations: functions applied - record: job:http_requests:rate5m expr: sum by (job) (rate(http_requests_total[5m])) -
预先聚合开销较大的查询:
# Recording rule for frequently-used latency query - record: job_endpoint:http_request_duration_seconds:p95 expr: | histogram_quantile(0.95, sum by (job, endpoint, le) ( rate(http_request_duration_seconds_bucket[5m]) ) ) -
在仪表板中使用记录的指标:
# Instead of expensive query, use pre-recorded metric job_endpoint:http_request_duration_seconds:p95{job="api-server"}
错误处理
常见问题与解决方案
-
结果为空:
- 检查指标是否存在:
up{job="your-job"} - 确认标签筛选条件正确
- 检查时间范围是否合适
- 确认指标正在被抓取
- 检查指标是否存在:
-
序列过多(高基数):
- 添加更具体的标签筛选条件
- 使用聚合减少序列数量
- 考虑使用记录规则
- 检查是否存在标签爆炸(动态标签)
-
数值不正确:
- 确认指标类型(计数器还是仪表)
- 检查函数用法(对计数器使用 rate,而不是对仪表使用)
- 确认时间范围是否合适
- 检查计数器是否重置
-
性能问题:
- 缩短范围向量的时间范围
- 添加标签筛选条件以降低基数
- 对复杂查询使用记录规则
- 避免使用开销大的正则表达式
- 考虑查询超时设置
沟通指南
生成查询时:
- 说明计划:生成查询前,始终先用通俗语言说明计划
- 提出问题:使用 AskUserQuestion 工具收集需求
- 确认意图:定稿前确认查询符合用户目标
- 讲解:说明使用特定函数或模式的原因
- 提供背景信息:展示如何解读结果
- 建议改进:提供优化或替代方案
- 主动验证:始终验证并修复问题
- 后续跟进:询问是否需要调整
AskUserQuestion 不可用时的备用方案
如果无法使用结构化提问工具,请改用纯文本明确列出问题:
- 在一条简短提示中询问目标、指标名称/类型、标签、时间范围、聚合方式和使用场景。
- 如果用户只提供了部分答案,请采用保守的默认值继续,并明确标注假设。
- 如果核心输入仍不明确,请提供 2-3 个具体的查询计划选项,让用户选择。
- 不要因为等待完美的上下文而无限期阻止生成;请生成尽力而为的查询,并附上假设说明。
相关参考标准与简单情形跳过规则
确定性地使用参考资料,但对于简单请求,避免不必要的读取。
满足以下任一条件时,读取参考资料:
- 请求直方图或摘要分位数
- 查询使用连接/向量匹配、子查询、偏移量或记录/告警规则
- 查询用于 SLO/燃耗率/错误预算工作流
- 查询涉及优化或基数问题
- 指标类型未知或存在争议
仅当以下条件全部满足时,跳过读取参考资料:
- 单指标、单函数查询(
rate、increase、sum、avg、max、min) - 不使用连接、记录/告警规则或高级函数
- 用户明确提供了指标类型和标签
跳过时,请明确说明:Reference read skipped (trivial case),并且仍必须进行验证。
与 devops-skills:promql-validator 集成
生成任何 PromQL 查询后,自动调用 devops-skills:promql-validator 技能以确保质量:
Steps:
1. Generate the PromQL query based on user requirements
2. Invoke devops-skills:promql-validator skill with the generated query
3. Review validation results (syntax, semantics, performance)
4. Fix any issues identified by the validator
5. Re-validate until all checks pass
6. Provide the final validated query with usage instructions
7. Ask user if further refinements are needed
这样可以确保所有生成的查询都遵循最佳实践,并满足生产环境的要求。
资源
重要:明确查阅参考资料
生成查询时,应使用 Read 工具明确读取相关参考文件,并引用适用的最佳实践。这样可以确保生成的查询遵循已记录的模式,也有助于用户理解为何推荐特定方法。
references/
promql_functions.md
- 全面介绍所有 PromQL 函数
- 按类别分组(聚合、数学、时间、直方图等)
- 每个函数均附有用法示例
- 在以下情况下阅读此文件:实现特定函数需求,或用户询问函数行为时
promql_patterns.md
- 适用于常见监控场景的查询模式
- RED 方法模式(速率、错误、持续时间)
- USE 方法模式(利用率、饱和度、错误)
- 告警和记录规则模式
- 在以下情况下阅读此文件:实现错误率、延迟或资源使用量等标准监控模式时
best_practices.md
- PromQL 最佳实践和反模式
- 性能优化指南
- 基数管理
- 查询结构建议
- 在以下情况下阅读此文件:优化查询、检查反模式或出现基数问题时
metric_types.md
- Prometheus 指标类型详细指南
- Counter、Gauge、Histogram、Summary
- 每种类型的适用场景
- 每种类型适用的函数
- 在以下情况下阅读此文件:解答指标类型相关问题,或确定某个指标适用的函数时
examples/
common_queries.promql
- 常用 PromQL 查询集
- 请求速率、错误率、延迟查询
- 资源使用量查询
- 可用性和运行时间查询
- 可复制并进行自定义
red_method.promql
- 完整的 RED 方法实现
- 请求速率查询
- 错误率查询
- 持续时间/延迟查询
use_method.promql
- 完整的 USE 方法实现
- 利用率查询
- 饱和度查询
- 错误查询
alerting_rules.yaml
- Prometheus 告警规则示例
- 各种基于阈值的告警
- 告警表达式最佳实践
recording_rules.yaml
- Prometheus 记录规则示例
- 预聚合指标
- 命名约定
slo_patterns.promql
- SLO、错误预算和燃烧速率查询
- 多窗口、多燃烧速率告警模式
- 延迟 SLO 合规性查询
kubernetes_patterns.promql
- Kubernetes 监控模式
- kube-state-metrics 查询(Pod、部署、节点)
- cAdvisor 容器指标(CPU、内存)
- Kubernetes 的向量匹配和连接
重要说明
- 始终进行交互式规划:未经用户确认计划,切勿生成查询
- 使用 AskUserQuestion:利用该工具收集需求并确认计划
- 验证所有内容:生成后始终调用 devops-skills:promql-validator
- 向用户说明:解释查询的作用及其结构设计原因
- 考虑使用场景:根据查询用于仪表板、告警还是分析来定制
- 考虑性能:始终包含标签筛选条件,并考虑基数
- 遵循指标类型:对 Counter、Gauge 和 Histogram 使用适当的函数
- 确保格式清晰易读:复杂查询使用多行格式
成功标准
成功的查询生成过程应满足以下可衡量的检查点:
- 完成需求收集:记录目标/使用场景/指标/时间范围/聚合方式。
- 完成计划确认:用户已批准计划,或已记录明确的假设。
- 记录参考资料决策:记录
consulted及文件名,或记录skipped (trivial case)及原因。 - 完成查询有效性检查:语法通过验证器检查,或通过手动备用检查。
- 完成语义合理性检查:函数选择符合指标类型(counter/gauge/histogram/summary)。
- 完成基数防护:查询包含明确的筛选条件,或说明聚合理由。
- 完成交付:提供最终查询、解读以及后续自定义指导。
请记住
目标是协作规划并生成与用户意图完全一致的 PromQL 查询。始终优先考虑清晰度、正确性和性能。交互式规划阶段是此技能中最重要的部分——绝不能跳过!