cloud-monitoring-promql-query
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloud Monitoring PromQL Generator
Cloud Monitoring PromQL 生成器
Use this skill to generate a valid PromQL query from any Cloud Monitoring metric
type. This guide applies to all Cloud Monitoring metric types by mapping Cloud
Monitoring metric and resource descriptors to PromQL structures.
使用此技能可从任意Cloud Monitoring指标类型生成有效的PromQL查询。本指南通过将Cloud Monitoring指标和资源描述符映射到PromQL结构,适用于所有Cloud Monitoring指标类型。
Workflow
工作流程
Resolve Project ID (CRITICAL & BLOCKING)
解析项目ID(关键且阻塞步骤)
Before performing any other actions (such as searching code, reading references,
or running validation), you MUST verify whether the Google Cloud Project ID is
available:
- Check Prompt/Payload: Look for the Project ID in the user's prompt or input.
- Check Environment: If the Project ID is not present in the prompt, you
MUST run to attempt to resolve it from the environment.
gcloud config get-value project - Ask for Clarification (BLOCKING): If the Project ID is not in the prompt
AND the command fails, returns an empty string, or is unavailable, you MUST immediately stop. Do NOT generate a PromQL query, do not run the validation script, and do not use placeholders (like
gcloud). You must refuse to proceed and ask the user to provide the Project ID.YOUR_PROJECT_ID
在执行任何其他操作(如搜索代码、查阅参考资料或运行验证)之前,您必须验证Google Cloud项目ID是否可用:
- 检查提示/负载: 在用户的提示或输入中查找项目ID。
- 检查环境: 如果提示中没有项目ID,您必须运行 尝试从环境中解析。
gcloud config get-value project - 请求澄清(阻塞步骤): 如果提示中没有项目ID,且命令执行失败、返回空字符串或不可用,您必须立即停止操作。请勿生成PromQL查询、不要运行验证脚本、也不要使用占位符(如
gcloud)。您必须拒绝继续并要求用户提供项目ID。YOUR_PROJECT_ID
Inspect Metric and Resource Descriptors
检查指标和资源描述符
- Use Provided Descriptors First: If the user's prompt already includes
metric descriptor details (such as ,
metric.type,metricKind, orvalueType) or specific resource filter values, use those values directly instead of calling the Cloud Monitoring API.monitoredResourceTypes - Discover Missing Descriptors: If exact metric descriptors
(,
metric.type,metricKind) are missing or underspecified, resolve the target metric type's descriptor using one of these paths:valueType- Vague Query: If the prompt is vague (for example, ), use the
"VM CPU usage"skill first to identify the specific metric type.cloud-monitoring-metric-selection - Known Metric Type: If you already have the specific metric type name
(for example, ) but need its descriptor, call the
compute.googleapis.com/instance/cpu/utilizationMCP tool. If the tool is missing, refer to thegoogle-cloud-monitoring:list_metric_descriptorsskill to configure the Cloud Monitoring MCP server.cloud-monitoring-metric-selection - Fallback: If the MCP tool cannot be configured, fall back to making a direct Cloud Monitoring API call.
- Vague Query: If the prompt is vague (for example,
- Identify Key Fields: From the retrieved descriptor, identify four key
schema attributes:
- : The Cloud Monitoring metric type string.
type - :
metricKind,GAUGE, orDELTA.CUMULATIVE - :
valueType,INT64,DOUBLE, orDISTRIBUTION.BOOL - : Compatible
monitoredResourceTypesstrings required for resource scoping and grouping.resource.type
- 优先使用提供的描述符: 如果用户的提示已包含指标描述符详情(如、
metric.type、metricKind或valueType)或特定资源过滤值,请直接使用这些值,无需调用Cloud Monitoring API。monitoredResourceTypes - 发现缺失的描述符: 如果缺少或未明确指定确切的指标描述符(、
metric.type、metricKind),请通过以下路径之一解析目标指标类型的描述符:valueType- 模糊查询: 如果提示内容模糊(例如),请先使用
"VM CPU使用率"技能确定具体的指标类型。cloud-monitoring-metric-selection - 已知指标类型: 如果您已知道具体的指标类型名称(例如)但需要其描述符,请调用
compute.googleapis.com/instance/cpu/utilizationMCP工具。如果该工具缺失,请参考google-cloud-monitoring:list_metric_descriptors技能配置Cloud Monitoring MCP服务器。cloud-monitoring-metric-selection - 备选方案: 如果无法配置MCP工具,请退而直接调用Cloud Monitoring API。
- 模糊查询: 如果提示内容模糊(例如
- 识别关键字段: 从检索到的描述符中识别四个关键架构属性:
- : Cloud Monitoring指标类型字符串。
type - :
metricKind、GAUGE或DELTA。CUMULATIVE - :
valueType、INT64、DOUBLE或DISTRIBUTION。BOOL - : 资源范围界定和分组所需的兼容
monitoredResourceTypes字符串。resource.type
Resolve Resource Filters & Discovery Protocol
解析资源过滤器与发现协议
To filter data by a specific resource instance, apply these resource rules and
discovery protocols:
-
Monitored Resource Filter: Always include thefilter in your query to prevent collisions across services that share metric names.
monitored_resource="<type>"- Example:
monitored_resource="gae_app"
- Example:
-
Preserve User Literals (CRITICAL): ALWAYS use the literal resource names, namespaces, and IDs provided in the user's prompt. Do NOT override or replace these values with active resource names found during Cloud Monitoring discovery unless the user explicitly asked you to find active resources. Telemetry discovery must only be used to identify metric type names and label keys, not to override user input.
-
Resource Identifier Mapping:
- Direct & Specific Keys: Use the most specific resource identifier
available. Example: ,
version_id.cluster_name - Name-to-ID Resolution: If the user filters by a resource name
(such as ), but the resource schema uses numeric IDs (like
"instance-1"), use PromQL string name labels instead of numeric ID labels. Example:instance_id,instance_name.metadata_system_name - Composite Identifiers: For resources with hierarchical identifiers
(such as Cloud SQL databases), format the filter as a single composite
key. Do NOT split them into separate and sub-resource labels. Example:
project_id.database_id="{project_id}:{instance_name}"
- Direct & Specific Keys: Use the most specific resource identifier
available. Example:
-
Resource Label Discovery: Thetool only returns metric-specific labels. If the label schema for a monitored resource is unknown, fetch the resource descriptor directly from the Cloud Monitoring v3 REST API (
google-cloud-monitoring:list_metric_descriptors):projects.monitoredResourceDescriptors.getbashTOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || gcloud auth print-access-token) curl -s -H "Authorization: Bearer ${TOKEN}" \ "https://monitoring.googleapis.com/v3/projects/{project_id}/monitoredResourceDescriptors/{monitored_resource_type}"An HTTP 200 OK response returns theobject containing theMonitoredResourceDescriptorarray with the exact resource label keys for that resource.labels
要按特定资源实例过滤数据,请应用以下资源规则和发现协议:
-
受监控资源过滤器: 请始终在查询中包含过滤器,以防止共享指标名称的服务之间发生冲突。
monitored_resource="<type>"- 示例:
monitored_resource="gae_app"
- 示例:
-
保留用户字面量(关键): 请始终使用用户提示中提供的字面资源名称、命名空间和ID。除非用户明确要求查找活动资源,否则请勿用Cloud Monitoring发现过程中找到的活动资源名称覆盖或替换这些值。遥测发现仅应用于识别指标类型名称和标签键,而非覆盖用户输入。
-
资源标识符映射:
- 直接且特定的键: 使用可用的最具体资源标识符。示例: 、
version_id。cluster_name - 名称到ID的解析: 如果用户按资源名称(如)过滤,但资源架构使用数字ID(如
"instance-1"),请使用PromQL字符串名称标签而非数字ID标签。示例:instance_id、instance_name。metadata_system_name - 复合标识符: 对于具有分层标识符的资源(如Cloud SQL数据库),请将过滤器格式化为单个复合键。请勿将其拆分为单独的和子资源标签。示例:
project_id。database_id="{project_id}:{instance_name}"
- 直接且特定的键: 使用可用的最具体资源标识符。示例:
-
资源标签发现:工具仅返回特定于指标的标签。如果受监控资源的标签架构未知,请直接从Cloud Monitoring v3 REST API (
google-cloud-monitoring:list_metric_descriptors)获取资源描述符:projects.monitoredResourceDescriptors.getbashTOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || gcloud auth print-access-token) curl -s -H "Authorization: Bearer ${TOKEN}" \ "https://monitoring.googleapis.com/v3/projects/{project_id}/monitoredResourceDescriptors/{monitored_resource_type}"HTTP 200 OK响应会返回包含数组的labels对象,其中包含该资源的确切资源标签键。MonitoredResourceDescriptor
Choose Aggregation Structure & Defaults
选择聚合结构与默认值
The query structure and aggregation functions (such as ,
, , or ) depend on the metric type and how it is
visualized.
ratehistogram_quantilesumavg- Consult the Reference: Consult the Cloud Monitoring to PromQL Basic Aggregations Reference as the single source of truth to map Cloud Monitoring properties (Metric Kind, Value Type, Aligner, Reducer) to their PromQL structures.
- SRE Aggregation & Visualization Rules:
- Do NOT sum or average ratio/percentage utilization metrics (like CPU
% or Memory limit utilization) across resource instances. Instead, keep
them unaggregated (raw metric), group by instance, or wrap in .
topk(30, avg_over_time(...)) - State Label Filtering (CRITICAL): Only the metrics
and
agent.googleapis.com/memory/percent_usedrequireagent.googleapis.com/disk/percent_used. Do NOT filter by{state!="free"}.{state="used"}
- Do NOT sum or average ratio/percentage utilization metrics (like CPU
% or Memory limit utilization) across resource instances. Instead, keep
them unaggregated (raw metric), group by instance, or wrap in
查询结构和聚合函数(如、、或)取决于指标类型及其可视化方式。
ratehistogram_quantilesumavg- 查阅参考资料: 请查阅Cloud Monitoring 到 PromQL 基础聚合参考作为单一可信来源,将Cloud Monitoring属性(指标类型、值类型、对齐器、归约器)映射到对应的PromQL结构。
- SRE聚合与可视化规则:
- 请勿对比率/百分比利用率指标(如CPU使用率或内存限制利用率)跨资源实例求和或取平均值。相反,请保持其未聚合状态(原始指标)、按实例分组,或使用包裹。
topk(30, avg_over_time(...)) - 状态标签过滤(关键): 仅和
agent.googleapis.com/memory/percent_used这两个指标需要agent.googleapis.com/disk/percent_used过滤。请勿使用{state!="free"}进行过滤。{state="used"}
- 请勿对比率/百分比利用率指标(如CPU使用率或内存限制利用率)跨资源实例求和或取平均值。相反,请保持其未聚合状态(原始指标)、按实例分组,或使用
Format & Validate Query
格式化与验证查询
Before presenting any PromQL queries, validate them using the linter:
在展示任何PromQL查询之前,请使用校验器进行验证:
Python Dependencies
Python依赖项
Before executing the validation script (), install
the required Python dependencies:
scripts/validate_promql.pybash
python3 -c "import promql_parser" || pip install promql-parser在执行验证脚本()之前,请安装所需的Python依赖项:
scripts/validate_promql.pybash
python3 -c "import promql_parser" || pip install promql-parserValidation Procedure
验证流程
- Format Constraints:
- Metric Name Normalization: Convert Cloud Monitoring metric types to
PromQL metric names using this recipe:
- Split Domain and Path: Split the Cloud Monitoring metric type by
the first slash () to separate the domain from the path.
/- Example:
-> domain
storage.googleapis.com/network/received_bytes_count, pathstorage.googleapis.comnetwork/received_bytes_count
- Example:
- Normalize Domain: Replace all periods () in the domain with underscores (
.)._- Example: ->
storage.googleapis.comstorage_googleapis_com
- Example:
- Normalize Path: Replace all periods () and slashes (
.) in the path with underscores (/)._- Example: ->
network/received_bytes_countnetwork_received_bytes_count
- Example:
- Join with Colon: Join the normalized domain and normalized path
with a colon ().
:- Example:
storage_googleapis_com:network_received_bytes_count
- Example:
- Native Prometheus Metrics: If the metric type has no slash, keep
it as-is.
- Example: ->
up,up->http_requests_totalhttp_requests_total
- Example:
- Distribution Suffix: If the metric's is
valueType, appendDISTRIBUTIONto the end of the normalized name._bucket- Example:
->
cloudfunctions.googleapis.com/function/execution_timescloudfunctions_googleapis_com:function_execution_times_bucket
- Example:
- Split Domain and Path: Split the Cloud Monitoring metric type by
the first slash (
- Ensure the final query is a single line with no comments (no or
#). Cloud Monitoring query translation collapses whitespace and can cause code trailing a comment to be ignored or throw parsing errors.// - Grouping Clause Syntax: Ensure grouping clauses (such as ) only follow aggregation operators (such as
by (label),sum,avg,min, ormax). Never place a grouping clause directly after a metric selector.count- Incorrect:
metric{...} by (label) - Correct:
sum(rate(metric{...}[5m])) by (label)
- Incorrect:
- Fenced Output Code Block: ALWAYS wrap the final verified PromQL
query in a fenced code block in your final response.
promql
- Metric Name Normalization: Convert Cloud Monitoring metric types to
PromQL metric names using this recipe:
- Linter Verification:
- Validate all generated queries in a single batch:
python3 <path_to_skill>/scripts/validate_promql.py --query '<q1>' '<q2>' - If validation fails, read PromQL Error Recovery Guide to diagnose and fix common type mismatches and syntax errors before repeating the loop.
- Validate all generated queries in a single batch:
- 格式约束:
- 指标名称规范化: 使用以下规则将Cloud Monitoring指标类型转换为PromQL指标名称:
- 拆分域名和路径: 将Cloud Monitoring指标类型按第一个斜杠()拆分,以分离域名和路径。
/- 示例:
-> 域名
storage.googleapis.com/network/received_bytes_count,路径storage.googleapis.comnetwork/received_bytes_count
- 示例:
- 规范化域名: 将域名中的所有点()替换为下划线(
.)。_- 示例: ->
storage.googleapis.comstorage_googleapis_com
- 示例:
- 规范化路径: 将路径中的所有点()和斜杠(
.)替换为下划线(/)。_- 示例: ->
network/received_bytes_countnetwork_received_bytes_count
- 示例:
- 用冒号连接: 使用冒号()连接规范化后的域名和路径。
:- 示例:
storage_googleapis_com:network_received_bytes_count
- 示例:
- 原生Prometheus指标: 如果指标类型没有斜杠,请保持原样。
- 示例: ->
up,up->http_requests_totalhttp_requests_total
- 示例:
- 分布后缀: 如果指标的为
valueType,请在规范化名称末尾追加DISTRIBUTION。_bucket- 示例:
->
cloudfunctions.googleapis.com/function/execution_timescloudfunctions_googleapis_com:function_execution_times_bucket
- 示例:
- 拆分域名和路径: 将Cloud Monitoring指标类型按第一个斜杠(
- 确保最终查询为无注释的单行内容(无或
#)。Cloud Monitoring查询转换会折叠空白字符,可能导致注释后的代码被忽略或抛出解析错误。// - 分组子句语法: 确保分组子句(如)仅跟随聚合运算符(如
by (label)、sum、avg、min或max)。切勿将分组子句直接放在指标选择器之后。count- 错误示例:
metric{...} by (label) - 正确示例:
sum(rate(metric{...}[5m])) by (label)
- 错误示例:
- 围栏式输出代码块: 请始终将最终验证通过的PromQL查询包裹在围栏式代码块中作为最终响应。
promql
- 指标名称规范化: 使用以下规则将Cloud Monitoring指标类型转换为PromQL指标名称:
- 校验器验证:
- 批量验证所有生成的查询:
python3 <path_to_skill>/scripts/validate_promql.py --query '<q1>' '<q2>' - 如果验证失败,请查阅PromQL错误恢复指南诊断并修复常见的类型不匹配和语法错误,然后重复验证流程。
- 批量验证所有生成的查询:
References
参考资料
- Cloud Monitoring PromQL Basic Aggregations Reference
- Cloud Monitoring PromQL Error Recovery Guide
- Cloud Monitoring PromQL Documentation
- Cloud Monitoring Monitored Resource Types Reference
- Cloud Monitoring PromQL基础聚合参考
- Cloud Monitoring PromQL错误恢复指南
- Cloud Monitoring PromQL文档
- Cloud Monitoring受监控资源类型参考