Installation
Install as Agent Plugin
Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-monitoring-promql-query@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin cloud-monitoring-promql-query v1.0.0 follows the Agent Plugins spec.
Install with the gh extension
gh skills-hub install cloud-monitoring-promql-query Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/cloud-monitoring-promql-query/ Extract the ZIP to .github/skills/ in your repo. The folder name must match cloud-monitoring-promql-query for Copilot to auto-discover it.
Skill Files (6)
SKILL.md 10.6 KB
---
name: cloud-monitoring-promql-query
metadata:
version: "1.0.1"
category: CloudObservabilityAndMonitoring
description: >-
Generates valid PromQL queries from Cloud Monitoring metric descriptors and
resource parameters. Use when asked to create, generate, write, or format
PromQL queries, PromQL strings, or PromQL aggregations for Cloud Monitoring
metrics and resources. Don't use for raw metric discovery or metric selection.
---
# Cloud Monitoring PromQL Generator
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.
## Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-promql-query)"`
and append `agent-skills/1.0 (skill:cloud-monitoring-promql-query)` to `User-Agent` headers.
## Workflow
### Resolve Project ID (CRITICAL & BLOCKING)
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:
1. **Check Prompt/Payload**: Look for the Project ID in the user's prompt or
input.
2. **Check Environment**: If the Project ID is not present in the prompt, you
MUST run `gcloud config get-value project` to attempt to resolve it from the
environment.
3. **Ask for Clarification (BLOCKING)**: If the Project ID is not in the prompt
AND the `gcloud` 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 `YOUR_PROJECT_ID`). You
must refuse to proceed and ask the user to provide the Project ID.
### Inspect Metric and Resource Descriptors
1. **Use Provided Descriptors First**: If the user's prompt already includes
metric descriptor details (such as `metric.type`, `metricKind`, `valueType`,
or `monitoredResourceTypes`) or specific resource filter values, use those
values directly instead of calling the Cloud Monitoring API.
2. **Discover Missing Descriptors**: If exact metric descriptors
(`metric.type`, `metricKind`, `valueType`) are missing or underspecified,
resolve the target metric type's descriptor using one of these paths:
* **Vague Query**: If the prompt is vague (for example, `"VM CPU usage"`),
use the `cloud-monitoring-metric-selection` skill first to identify the
specific metric type.
* **Known Metric Type**: If you already have the specific metric type name
(for example, `compute.googleapis.com/instance/cpu/utilization`) but
need its descriptor, call the
`google-cloud-monitoring:list_metric_descriptors` MCP tool. If the tool
is missing, refer to the `cloud-monitoring-metric-selection` skill to
configure the Cloud Monitoring MCP server.
* **Fallback**: If the MCP tool cannot be configured, fall back to making
a direct Cloud Monitoring API call.
3. **Identify Key Fields**: From the retrieved descriptor, identify four key
schema attributes:
* **`type`**: The Cloud Monitoring metric type string.
* **`metricKind`**: `GAUGE`, `DELTA`, or `CUMULATIVE`.
* **`valueType`**: `INT64`, `DOUBLE`, `DISTRIBUTION`, or `BOOL`.
* **`monitoredResourceTypes`**: Compatible `resource.type` strings
required for resource scoping and grouping.
### Resolve Resource Filters & Discovery Protocol
To filter data by a specific resource instance, apply these resource rules and
discovery protocols:
1. **Monitored Resource Filter**: Always include the
`monitored_resource="<type>"` filter in your query to prevent collisions
across services that share metric names.
* **Example**: `monitored_resource="gae_app"`
2. **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.
3. **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 `"instance-1"`), but the resource schema uses numeric IDs (like
`instance_id`), use PromQL string name labels instead of numeric ID
labels. **Example**: `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 `project_id` and sub-resource
labels. **Example**: `database_id="{project_id}:{instance_name}"`.
4. **Resource Label Discovery**: The
`google-cloud-monitoring:list_metric_descriptors` tool 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 (`projects.monitoredResourceDescriptors.get`):
```bash
TOKEN=$(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 the `MonitoredResourceDescriptor` object
containing the `labels` array with the exact resource label keys for that
resource.
### Choose Aggregation Structure & Defaults
The query structure and aggregation functions (such as `rate`,
`histogram_quantile`, `sum`, or `avg`) depend on the metric type and how it is
visualized.
1. **Consult the Reference**: Consult the
[Cloud Monitoring to PromQL Basic Aggregations Reference](references/basic_aggregations.md)
as the single source of truth to map Cloud Monitoring properties (Metric
Kind, Value Type, Aligner, Reducer) to their PromQL structures.
2. **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
`agent.googleapis.com/memory/percent_used` and
`agent.googleapis.com/disk/percent_used` require `{state!="free"}`. Do
**NOT** filter by `{state="used"}`.
### Format & Validate Query
Before presenting any PromQL queries, validate them using the linter:
#### Python Dependencies
Before executing the validation script (`scripts/validate_promql.py`), install
the required Python dependencies:
```bash
python3 -c "import promql_parser" || pip install promql-parser
```
#### Validation Procedure
1. **Format Constraints**:
* **Metric Name Normalization**: Convert Cloud Monitoring metric types to
PromQL metric names using this recipe:
1. **Split Domain and Path**: Split the Cloud Monitoring metric type by
the first slash (`/`) to separate the domain from the path.
* **Example**:
`storage.googleapis.com/network/received_bytes_count` -> domain
`storage.googleapis.com`, path `network/received_bytes_count`
2. **Normalize Domain**: Replace all periods (`.`) in the domain with
underscores (`_`).
* **Example**: `storage.googleapis.com` ->
`storage_googleapis_com`
3. **Normalize Path**: Replace all periods (`.`) and slashes (`/`) in
the path with underscores (`_`).
* **Example**: `network/received_bytes_count` ->
`network_received_bytes_count`
4. **Join with Colon**: Join the normalized domain and normalized path
with a colon (`:`).
* **Example**:
`storage_googleapis_com:network_received_bytes_count`
5. **Native Prometheus Metrics**: If the metric type has no slash, keep
it as-is.
* **Example**: `up` -> `up`, `http_requests_total` ->
`http_requests_total`
6. **Distribution Suffix**: If the metric's `valueType` is
`DISTRIBUTION`, append `_bucket` to the end of the normalized name.
* **Example**:
`cloudfunctions.googleapis.com/function/execution_times` ->
`cloudfunctions_googleapis_com:function_execution_times_bucket`
* 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 `by
(label)`) only follow aggregation operators (such as `sum`, `avg`,
`min`, `max`, or `count`). Never place a grouping clause directly after
a metric selector.
* **Incorrect**: `metric{...} by (label)`
* **Correct**: `sum(rate(metric{...}[5m])) by (label)`
* **Fenced Output Code Block**: ALWAYS wrap the final verified PromQL
query in a fenced `promql` code block in your final response.
2. **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](references/promql_error_recovery.md) to
diagnose and fix common type mismatches and syntax errors before
repeating the loop.
## References
* [Cloud Monitoring PromQL Basic Aggregations Reference](references/basic_aggregations.md)
* [Cloud Monitoring PromQL Error Recovery Guide](references/promql_error_recovery.md)
* [Cloud Monitoring PromQL Documentation](https://docs.cloud.google.com/monitoring/promql.md.txt)
* [Cloud Monitoring Monitored Resource Types Reference](https://docs.cloud.google.com/monitoring/api/resources.md.txt)
references/
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-promql-query)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include `agent-skills/1.0 (skill:cloud-monitoring-promql-query)` in the `User-Agent`
header. If a `User-Agent` header is already specified, append this string to
the end of it rather than overwriting existing `User-Agent` data — the
collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
tokens, so any rewording breaks attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:cloud-monitoring-promql-query)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
basic_aggregations.md 12.8 KB
# Cloud Monitoring to PromQL Basic Aggregations Reference
This document maps Cloud Monitoring metric concepts to their PromQL query
equivalents. Use this matrix to determine the correct PromQL query structure and
default aggregation functions based on Cloud Monitoring metric properties.
## Table of Contents
- [Translation Matrix](#translation-matrix) (~Line 26)
- [Default Aggregations and Visualization Rules](#default-aggregations-and-visualization-rules)
(~Line 112)
- [CPU and Memory Utilization (Ratios / Percentages)](#cpu-and-memory-utilization-ratios-percentages)
(~Line 117)
- [Rate of Events / Throughput (Counters)](#rate-of-events-throughput-counters)
(~Line 139)
- [Distribution Metrics (Quantiles / Latency)](#distribution-metrics-quantiles-latency)
(~Line 156)
- [Boolean & Status Metrics (BOOL Value-Type)](#boolean-status-metrics-bool-value-type)
(~Line 167)
- [Ranking & Sorting (Top N / Bottom N)](#ranking-sorting-top-n-bottom-n)
(~Line 179)
- [Sampling Intervals vs. Rate Windows ([5m] vs. Coarser Metrics)](#sampling-intervals-vs-rate-windows-5m-vs-coarser-metrics)
(~Line 189)
- [Backlog Age & Processing Lag](#backlog-age-processing-lag) (~Line 204)
## Translation Matrix
To use this matrix:
- **Inputs**:
- Identify the metric type's `metricKind` and `valueType` from its
`MetricDescriptor`.
- Infer the target calculation goal from the user's prompt (for example,
Sum, Mean, 95th Percentile) under **Aggregation Intent**.
- **Output PromQL Structure**:
- Extract the template from the **PromQL Query Structure** column for the
matching row.
- Replace `<metric>` with the translated metric name (for example, mapping
`compute.googleapis.com/instance/cpu/utilization` to
`compute_googleapis_com:instance_cpu_utilization`).
When the user's aggregation preference is underspecified, use the row marked
**(default)**.
| Metric Kind | Value Type | Aggregation Intent | PromQL Query Structure |
| :----------- | :------------- | :------------------ | :------------------------------ |
| `GAUGE` | `NUMERIC` | Raw / Unaggregated | `<metric>` |
: : (`INT64` / : (default for : :
: : `DOUBLE`) : ratios/utilization) : :
| `GAUGE` | `NUMERIC` | **Sum (default for | `sum(<metric>)` |
: : : counts/gauges)** : :
| `GAUGE` | `NUMERIC` | Mean / Average | `avg(<metric>)` |
| `GAUGE` | `NUMERIC` | Min | `min(<metric>)` |
| `GAUGE` | `NUMERIC` | Max | `max(<metric>)` |
| `GAUGE` | `NUMERIC` | Count time series | `count(<metric>)` |
| `GAUGE` | `NUMERIC` | 99th percentile | `quantile(0.99, <metric>)` |
| `GAUGE` | `NUMERIC` | 95th percentile | `quantile(0.95, <metric>)` |
| `GAUGE` | `NUMERIC` | 50th percentile | `quantile(0.50, <metric>)` |
: : : (Median) : :
| `GAUGE` | `DISTRIBUTION` | **Distribution | `sum(rate(<metric>_bucket[5m])) |
: : : Buckets (default)** : by (le, <group_labels>)` :
| `GAUGE` | `DISTRIBUTION` | 99th percentile | `histogram_quantile(0.99, |
: : : : sum(rate(<metric>_bucket[5m])) :
: : : : by (le, <group_labels>))` :
| `GAUGE` | `DISTRIBUTION` | 95th percentile | `histogram_quantile(0.95, |
: : : : sum(rate(<metric>_bucket[5m])) :
: : : : by (le, <group_labels>))` :
| `GAUGE` | `DISTRIBUTION` | 50th percentile | `histogram_quantile(0.50, |
: : : (Median) : sum(rate(<metric>_bucket[5m])) :
: : : : by (le, <group_labels>))` :
| `GAUGE` | `BOOL` | Raw / Unaggregated | `<metric>` |
: : : Points : :
| `GAUGE` | `BOOL` | **Fraction true / | `avg(<metric>) * 100` *(or |
: : : Availability : `avg(<metric>)` in `[0.0, :
: : : (default)** : 1.0]`)* :
| `GAUGE` | `BOOL` | Count true | `sum(<metric>)` |
| `GAUGE` | `BOOL` | Filter Unhealthy / | `<metric> == 0` |
: : : Down : :
| `DELTA` / | `NUMERIC` | Raw / Per-Series | `rate(<metric>[5m])` |
: `CUMULATIVE` : (`INT64` / : Rate : :
: : `DOUBLE`) : : :
| `DELTA` / | `NUMERIC` | **Sum Rate / | `sum(rate(<metric>[5m]))` |
: `CUMULATIVE` : : Throughput : :
: : : (default)** : :
| `DELTA` / | `NUMERIC` | Mean Rate | `avg(rate(<metric>[5m]))` |
: `CUMULATIVE` : : : :
| `DELTA` / | `NUMERIC` | Min Rate | `min(rate(<metric>[5m]))` |
: `CUMULATIVE` : : : :
| `DELTA` / | `NUMERIC` | Max Rate | `max(rate(<metric>[5m]))` |
: `CUMULATIVE` : : : :
| `DELTA` / | `NUMERIC` | 99th percentile | `quantile(0.99, |
: `CUMULATIVE` : : Rate : rate(<metric>[5m]))` :
| `DELTA` / | `NUMERIC` | 95th percentile | `quantile(0.95, |
: `CUMULATIVE` : : Rate : rate(<metric>[5m]))` :
| `DELTA` / | `NUMERIC` | Total Cumulative | `sum(increase(<metric>[1h]))` |
: `CUMULATIVE` : : Volume (over 1h) : :
| `DELTA` / | `DISTRIBUTION` | **Distribution | `sum(rate(<metric>_bucket[5m])) |
: `CUMULATIVE` : : Buckets (default)** : by (le, <group_labels>)` :
| `DELTA` / | `DISTRIBUTION` | 99th percentile | `histogram_quantile(0.99, |
: `CUMULATIVE` : : Latency : sum(rate(<metric>_bucket[5m])) :
: : : : by (le, <group_labels>))` :
| `DELTA` / | `DISTRIBUTION` | 95th percentile | `histogram_quantile(0.95, |
: `CUMULATIVE` : : Latency : sum(rate(<metric>_bucket[5m])) :
: : : : by (le, <group_labels>))` :
| `DELTA` / | `DISTRIBUTION` | 50th percentile | `histogram_quantile(0.50, |
: `CUMULATIVE` : : Latency (Median) : sum(rate(<metric>_bucket[5m])) :
: : : : by (le, <group_labels>))` :
| `ANY` | `ANY` | Top N Outliers | `topk(<N>, <metric_or_rate>)` |
| `ANY` | `ANY` | Bottom N Outliers | `bottomk(<N>, |
: : : : <metric_or_rate>)` :
## Default Aggregations and Visualization Rules
Apply these standard defaults when generating queries or when the user's
aggregation preference is underspecified:
### CPU and Memory Utilization (Ratios / Percentages)
* **Use when**: Querying CPU or memory utilization metrics (ratios or
percentages) for any service or agent (for example,
`compute_googleapis_com:instance_cpu_utilization` or
`agent_googleapis_com:memory_percent_used`).
* **Default Query Structure**: Reference the metric name directly without
wrapping it in an aggregator (such as `avg` or `sum`) to return all
individual time series (unaggregated). This is the preferred default to
monitor all instances.
* **Example**:
`agent_googleapis_com:memory_percent_used{monitored_resource="gce_instance",
state!="free"}`
* **Aggregation Constraints**:
* **No Summing**: Do NOT use `sum()`. Utilization metrics represent ratios
or percentages; summing them yields mathematically invalid values.
* **No Averaging for Resource Limits**: Avoid averaging utilization across
instances (such as `avg(metric)`) for resource limits (like memory
limits or disk space utilization) because it masks outliers. Instead,
group by the resource instance (such as `by (pod_name)`) or use
`topk(30, ...)` to highlight outliers.
### Rate of Events / Throughput (Counters)
* **Use when**: Querying `DELTA` or `CUMULATIVE` event counter metrics (for
example, request count or disk bytes count).
* **Throughput Rule**: Convert event counts to a rate by applying `rate(...)`
over a window (default `[5m]`).
* *Default*: Sum the rates across relevant groupings:
`sum(rate(compute_googleapis_com:instance_disk_read_bytes_count{...}[5m]))`
* **Volume Rule (`increase` vs `rate`)**: Use `rate()` for per-second
throughput (such as requests per second). Use `increase()` when the user
asks for total cumulative event volume over a specific time window.
* **Example**: Total errors in the last 1h: `sum(increase(<metric>[1h]))`
* **DELTA vs. CUMULATIVE Handling**: Trust Cloud Monitoring PromQL to
automatically handle both `DELTA` and `CUMULATIVE` metric kinds natively
when using `rate()`, `irate()`, or `increase()`. Do not perform manual
type-casting.
### Distribution Metrics (Quantiles / Latency)
* **Use when**: Querying `DISTRIBUTION` metrics (such as request latencies).
* **Rule**: Append `_bucket` to the metric name, wrap it in
`histogram_quantile()`, and ensure you group by the `le`
(less-than-or-equal) bucket boundary label.
* **Default Query Structure**:
* **Example (p95)**: `histogram_quantile(0.95,
sum(rate(spanner_googleapis_com:query_latency_bucket{...}[5m])) by (le,
instance_id))`
### Boolean & Status Metrics (`BOOL` Value-Type)
* **Use when**: Querying `BOOL` value-type metrics (such as endpoint health or
binary uptime checks).
* **Rule**: Represent boolean metrics numerically where `1` is true/up and `0`
is false/down.
* **Default Query Structures**:
* *Filter for Unhealthy/Down Instances*: `<metric> == 0`
* *Count Healthy Instances*: `sum(<metric>)`
* *Cluster Availability Percentage*: `avg(<metric>) * 100` (or
`avg(<metric>)` for `[0.0, 1.0]`)
### Ranking & Sorting (Top N / Bottom N)
* **Use when**: Identifying the highest- or lowest-consuming instances
(commonly used for sorting).
* **Rule**: Use `topk()` or `bottomk()` to filter results.
* **Default Query Structure**: Wrap the rate or gauge in the ranking function.
* **Example (Top 10)**: `topk(10, avg_over_time(<metric>[5m]))`
* **Example (Top 5 rate)**: `topk(5, sum(rate(<metric>[5m])) by
(instance_id))`
### Sampling Intervals vs. Rate Windows (`[5m]` vs. Coarser Metrics)
* **Use when**: Determining the correct range window (for example, `[5m]`) for
rate functions.
* **Rule**: Ensure the rate window spans at least **twice the scrape
interval** (sampling period) of the underlying metric to avoid chart gaps
and zero-scraping artifacts.
* **Default Query Structure**:
* Use `[5m]` as a safe default for standard 1-minute resolution metrics.
* Increase the rate window (for example, to `[15m]` or `[30m]`) for
coarser metrics (emitted every 5m or 10m) to cover at least 2
consecutive samples.
* Use `[${__interval}]` as the default range window if the sampling period
is unknown.
### Backlog Age & Processing Lag
* **Use when**: Querying metrics tracking maximum age, lag, or oldest
unacknowledged items (for example,
`pubsub.googleapis.com/subscription/oldest_unacked_message_age` or
`dataflow.googleapis.com/job/system_lag`).
* **Rule**: Use `max()` to aggregate across instances to surface the peak
delay. Do NOT use `sum()` or `avg()`.
* **Default Query Structure**:
* **Example**:
`max(pubsub_googleapis_com:subscription_oldest_unacked_message_age{monitored_resource="pubsub_subscription"})`
promql_error_recovery.md 5.1 KB
# PromQL Error Recovery Guide
When `validate_promql.py` or Cloud Monitoring query execution reports a syntax
or type error, use this reference to diagnose and fix the query before repeating
the validation loop.
## Table of Contents
- [Common Error Diagnoses & Solutions](#common-error-diagnoses-solutions)
(~Line 24)
- [Range Vector vs. Instant Vector Type Mismatch](#range-vector-vs-instant-vector-type-mismatch)
(~Line 26)
- [Invalid Grouping Clause Placement (`by` / `without`)](#invalid-grouping-clause-placement-by-without)
(~Line 45)
- [Histogram Quantile Bucket & Label Mismatch](#histogram-quantile-bucket-label-mismatch)
(~Line 63)
- [Vector Matching & Binary Operator Collision](#vector-matching-binary-operator-collision)
(~Line 81)
- [Unquoted Literals & Equality Operators](#unquoted-literals-equality-operators)
(~Line 99)
- [Trailing Comments or Multiline Collisions](#trailing-comments-or-multiline-collisions)
(~Line 115)
## Common Error Diagnoses & Solutions
### Range Vector vs. Instant Vector Type Mismatch
* **Error**: `expected type range vector in call to function "rate", got
instant vector` (or `irate`, `increase`).
* **Cause**: Calling `rate()` without a time duration window (such as
`rate(metric)`), or placing an aggregation operator inside the rate (such as
`rate(sum(metric)[5m])`). In PromQL, functions like `sum()` or `avg()`
return an instant vector, which cannot be passed to `rate()`.
* **Fix**: Ensure `rate()`, `irate()`, and `increase()` wrap the raw metric
with a duration window, and place aggregation operators on the outside:
```
# Wrong
rate(sum(compute_googleapis_com:instance_network_sent_bytes_count)[5m])
# Correct
sum(rate(compute_googleapis_com:instance_network_sent_bytes_count[5m]))
```
### Invalid Grouping Clause Placement (`by` / `without`)
* **Error**: `syntax error: unexpected BY` or `invalid label grouping`.
* **Cause**: Attaching a grouping clause directly to a raw metric selector or
rate function. In PromQL, `by (...)` and `without (...)` can only attach to
aggregation operators (`sum`, `avg`, `min`, `max`, `count`, `topk`,
`bottomk`, `quantile`, `stddev`, `stdvar`).
* **Fix**: Move the grouping clause to attach directly to the aggregation
operator:
```
# Wrong
rate(bigtable_googleapis_com:server_read_count[5m]) by (table_id)
# Correct
sum(rate(bigtable_googleapis_com:server_read_count[5m])) by (table_id)
```
### Histogram Quantile Bucket & Label Mismatch
* **Error**: `histogram_quantile requires a "le" label in the input vector` or
empty/NaN distribution calculation.
* **Cause**: Using `histogram_quantile()` without grouping by the `le`
(less-than-or-equal) bucket boundary label, or forgetting to append the
`_bucket` suffix to the distribution metric name.
* **Fix**: Append `_bucket` to the metric name and ensure `le` is included in
the `by (...)` clause alongside any target instance labels:
```
# Wrong
histogram_quantile(0.95, sum(rate(cloudfunctions_googleapis_com:function_execution_times[5m])) by (function_name))
# Correct
histogram_quantile(0.95, sum(rate(cloudfunctions_googleapis_com:function_execution_times_bucket[5m])) by (le, function_name))
```
### Vector Matching & Binary Operator Collision
* **Error**: `multiple matches for labels: many-to-one matching must be
explicit (group_left/group_right)`.
* **Cause**: Performing arithmetic between two different time series (for
example, dividing the error count by the total request count) when the label
sets do not match 1-to-1 across both sides of the operator.
* **Fix**: Use `ignoring(...)` or `on(...)` to specify the exact label subset
for matching, and append `group_left` or `group_right` for many-to-one or
one-to-many ratios:
```
# Correcting a many-to-one ratio
sum(rate(error_metric[5m])) by (method, service)
/ on (service) group_left(method)
sum(rate(total_requests[5m])) by (service)
```
### Unquoted Literals & Equality Operators
* **Error**: `unexpected identifier` or `invalid label matcher`.
* **Cause**: Using unquoted strings in label selectors, or using a single `=`
instead of `==` for boolean comparisons outside label selectors.
* **Fix**: Quote all string literals inside label matchers, and use double
equals `==` for value comparisons:
```
# Wrong
http_requests_total{environment=prod} = 0
# Correct
http_requests_total{environment="prod"} == 0
```
### Trailing Comments or Multiline Collisions
* **Error**: Silently ignored filters, syntax errors at the end of the query,
or unexpected end of input.
* **Cause**: Including comments (`# ...`) or line breaks when transmitting
queries to single-line Cloud Monitoring translation APIs. Cloud Monitoring's
parser collapses whitespace and treats everything after `#` on the same line
as a comment.
* **Fix**: Strip all markdown formatting, line breaks, and `#` comments before
passing the string to validation or execution.
scripts/
validate_promql.py 7.5 KB
#!/usr/bin/env python3
"""PromQL query validator for Google Cloud Monitoring metric queries.
Validates PromQL syntax and Cloud Monitoring specific semantic requirements
using the
promql-parser Python library:
- Requires 'monitored_resource' label matchers on metric selectors.
- Requires rate(), increase(), or irate() wrapping around counter metrics
(_count, _total, usage_time).
- Requires histogram_quantile() wrapping around distribution bucket metrics
(_bucket).
"""
import argparse
import re
import sys
try:
import promql_parser # pylint: disable=g-import-not-at-top
except ImportError:
print(
"Error: 'promql-parser' Python package is not installed.",
file=sys.stderr,
)
print(
"Please install it using: pip install promql-parser",
file=sys.stderr,
)
sys.exit(1)
# Google Cloud Monitoring semantic requirement: counter metrics must be
# evaluated using a rate, increase, or irate function.
COUNTER_WRAPPERS = (
"rate",
"increase",
"irate",
)
# Metric name suffixes identifying Google Cloud Monitoring counter metrics.
COUNTER_METRIC_SUFFIXES = (
"_count",
"_total",
"usage_time",
)
# Metric names that require specific state label filtering.
STATE_FILTERED_METRICS = (
"agent_googleapis_com:memory_percent_used",
"agent_googleapis_com:disk_percent_used",
)
def extract_query(content: str) -> str:
"""Extracts a PromQL query from markdown and sanitizes macro variables."""
pattern = re.compile(r"(?s)```(?:[a-zA-Z0-9_-]+)?\s*\r?\n(.*?)\r?\n```")
matches = pattern.findall(content)
if matches:
content = matches[0]
# Sanitize template variables like ${__interval} to [5m] for validation.
content = re.sub(r"\[\s*\$\{?__interval\}?\s*\]", "[5m]", content)
return content.strip()
def validate_promql_query(query: str) -> tuple[list[str], list[str]]:
"""Validates syntax and Cloud Monitoring semantics using the promql-parser AST."""
try:
ast = promql_parser.parse(query)
except Exception as e: # pylint: disable=broad-exception-caught
return [f"Syntax Error: {e}"], []
errors = []
warnings = []
def get_func_name(node) -> str:
"""Returns function name or aggregation operator name from an AST node."""
if hasattr(node, "func"): # Matches Call nodes (rate, histogram_quantile)
f = node.func
return getattr(f, "name", str(f))
if hasattr(node, "op"): # Matches AggregateExpr nodes (sum, avg)
o = node.op
return getattr(o, "name", str(o))
if hasattr(node, "name"): # Matches VectorSelector nodes
return str(node.name)
return str(node)
def walk(node, ancestors):
if node is None:
return
# Check VectorSelector AST nodes (has matchers or label_matchers)
matchers_obj = getattr(node, "matchers", None) or getattr(
node, "label_matchers", None
)
if matchers_obj is not None:
metric_name = getattr(node, "name", "") or "{...}"
if hasattr(matchers_obj, "matchers"):
matcher_list = matchers_obj.matchers
elif isinstance(matchers_obj, (list, tuple)):
matcher_list = matchers_obj
else:
matcher_list = []
# Rule 1: monitored_resource filter requirement
matcher_names = [getattr(m, "name", "") for m in matcher_list]
if "monitored_resource" not in matcher_names:
errors.append(
f"Metric selector '{metric_name}' is missing the"
" 'monitored_resource' type filter."
)
# Rule 2: Counter metric wrapping requirement
is_counter = any(metric_name.endswith(s) for s in COUNTER_METRIC_SUFFIXES)
if is_counter:
has_rate_wrapper = any(
get_func_name(a) in COUNTER_WRAPPERS for a in ancestors
)
if not has_rate_wrapper:
warnings.append(
f"Counter metric '{metric_name}' is not wrapped in rate() or"
" increase()."
)
# Rule 3: Histogram bucket metric wrapping requirement
if metric_name.endswith("_bucket"):
has_histogram_wrapper = any(
get_func_name(a) == "histogram_quantile" for a in ancestors
)
if not has_histogram_wrapper:
errors.append(
f"Histogram bucket metric '{metric_name}' is not wrapped in"
" histogram_quantile()."
)
# Rule 4: GCE Agent memory/disk utilization state label filtering
if metric_name in STATE_FILTERED_METRICS:
has_state_not_free = False
has_state_used = False
for m in matcher_list:
m_name = getattr(m, "name", "")
m_value = getattr(m, "value", "")
m_op = getattr(m, "op", None)
if m_name == "state":
if m_op == promql_parser.MatchOp.NotEqual and m_value == "free":
has_state_not_free = True
if m_op == promql_parser.MatchOp.Equal and m_value == "used":
has_state_used = True
if not has_state_not_free:
errors.append(
f"Metric selector '{metric_name}' is missing the"
" 'state!=\"free\"' filter to exclude free memory/disk state."
)
if has_state_used:
errors.append(
f"Metric selector '{metric_name}' must not use 'state=\"used\"'"
" as it ignores cached and buffered memory/disk."
)
# Recurse children AST nodes
children = []
for attr in (
"expressions",
"expression",
"vector_selector",
"vector",
"args",
"lhs",
"rhs",
"expr",
):
val = getattr(node, attr, None)
if val:
children.extend(val if isinstance(val, (list, tuple)) else [val])
for child in children:
if child and isinstance(child, object):
walk(child, ancestors + [node])
walk(ast, [])
return errors, warnings
def main():
parser = argparse.ArgumentParser(
description="Validate PromQL queries for Google Cloud Monitoring."
)
parser.add_argument(
"--file",
type=str,
default="",
help="Path to the file containing the PromQL query.",
)
parser.add_argument(
"--query",
type=str,
nargs="*",
default=[],
help="Direct PromQL query string(s) to validate.",
)
args = parser.parse_args()
if args.file:
try:
with open(args.file, "r", encoding="utf-8") as f:
queries = [extract_query(f.read())]
except OSError as e:
print(f"Error reading file: {e}", file=sys.stderr)
sys.exit(1)
elif args.query:
queries = [extract_query(q) for q in args.query if q.strip()]
else:
print("Error: Must specify either --file or --query.", file=sys.stderr)
parser.print_help(file=sys.stderr)
sys.exit(1)
if not queries:
print("Error: Empty query.", file=sys.stderr)
sys.exit(1)
has_errors = False
for i, query in enumerate(queries, 1):
errors, warnings = validate_promql_query(query)
prefix = f"[{i}/{len(queries)}] " if len(queries) > 1 else ""
if warnings:
print(f"{prefix}Validation Warnings for '{query}':", file=sys.stderr)
for warn in warnings:
print(f" - {warn}", file=sys.stderr)
if errors:
has_errors = True
print(f"{prefix}Validation Failed for '{query}':", file=sys.stderr)
for err in errors:
print(f" - {err}", file=sys.stderr)
if has_errors:
sys.exit(1)
if len(queries) == 1:
print(
"OK: PromQL query passed all syntax and Cloud Monitoring validation"
" checks."
)
else:
print(f"OK: All {len(queries)} PromQL queries passed validation checks.")
sys.exit(0)
if __name__ == "__main__":
main()
validate_promql_test.py 9.6 KB
#!/usr/bin/env python3
"""Unit tests and stress tests for validate_promql.py."""
import unittest
import validate_promql
class ValidatePromqlTest(unittest.TestCase):
# --- Valid PromQL Query Tests ---
def test_valid_counter_query(self):
query = (
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m]))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_increase_counter_query(self):
query = (
'sum(increase(spanner_googleapis_com:api_request_count'
'{monitored_resource="spanner_instance"}[1h]))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_irate_counter_query(self):
query = (
'sum(irate(loadbalancing_googleapis_com:https_request_count'
'{monitored_resource="https_lb_rule"}[5m]))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_histogram_query(self):
query = (
'histogram_quantile(0.95,'
' sum(rate(spanner_googleapis_com:query_latency_bucket'
'{monitored_resource="spanner_instance"}[5m])) by (le, instance_id))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_binary_expression(self):
query = (
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m])) /'
' sum(rate(compute_googleapis_com:instance_disk_write_bytes_count'
'{monitored_resource="gce_instance"}[5m]))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_subquery(self):
query = (
'rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m])[30m:1m]'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_boolean_query(self):
query = (
'pubsub_googleapis_com:subscription_delivery_latency_health_score{monitored_resource="pubsub_subscription",'
' subscription_id="sub-1"} == 0'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_topk_aggregation(self):
query = (
'topk(10,'
' avg_over_time(agent_googleapis_com:memory_percent_used'
'{monitored_resource="gce_instance", state!="free"}[5m]))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_bottomk_aggregation(self):
query = (
'bottomk(5,'
' sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m])) by (instance_id))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_regex_label_matcher(self):
query = (
'sum(rate(compute_googleapis_com:instance_cpu_utilization_count'
'{monitored_resource="gce_instance", instance_name=~"web-.*"}[5m]))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_offset_modifier(self):
query = (
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m] offset 1d))'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
def test_valid_group_left_matching(self):
query = (
'sum(rate(error_count{monitored_resource="k8s_container"}[5m])) by'
' (method, service) / on (service) group_left(method)'
' sum(rate(total_requests{monitored_resource="k8s_container"}[5m]))'
' by (service)'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
# --- Invalid & Edge Case Tests ---
def test_missing_monitored_resource(self):
query = (
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{instance_id="123"}[5m]))'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('monitored_resource' in err for err in errors),
f'Expected monitored_resource error, got: {errors}',
)
def test_counter_not_wrapped(self):
query = (
'compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}'
)
errors, warnings = validate_promql.validate_promql_query(query)
self.assertFalse(errors, f'Expected no errors, got: {errors}')
self.assertTrue(
any('wrapped in rate() or increase()' in warn for warn in warnings),
f'Expected counter wrapping warning, got: {warnings}',
)
def test_histogram_bucket_not_wrapped(self):
query = (
'spanner_googleapis_com:query_latency_bucket'
'{monitored_resource="spanner_instance"}'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('wrapped in histogram_quantile()' in err for err in errors),
f'Expected histogram wrapping error, got: {errors}',
)
def test_invalid_grouping_clause(self):
query = (
'compute_googleapis_com:instance_cpu_utilization'
'{monitored_resource="gce_instance"} by (instance_id)'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('Syntax Error' in err for err in errors),
f'Expected syntax error, got: {errors}',
)
def test_unclosed_bracket_syntax_error(self):
query = (
'compute_googleapis_com:instance_cpu_utilization'
'{monitored_resource="gce_instance"'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('Syntax Error' in err for err in errors),
f'Expected syntax error, got: {errors}',
)
def test_multiple_selectors_one_missing_monitored_resource(self):
query = (
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m])) + '
'sum(rate(compute_googleapis_com:instance_disk_write_bytes_count[5m]))'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('monitored_resource' in err for err in errors),
f'Expected monitored_resource error, got: {errors}',
)
def test_state_filtered_metric_missing_state_filter(self):
# Test memory metric missing state filter
query = (
'avg(agent_googleapis_com:memory_percent_used'
'{monitored_resource="gce_instance"})'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('missing the \'state!="free"\'' in err for err in errors),
f'Expected state filter missing error, got: {errors}',
)
# Test disk metric missing state filter
query = (
'avg(agent_googleapis_com:disk_percent_used'
'{monitored_resource="gce_instance"})'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('missing the \'state!="free"\'' in err for err in errors),
f'Expected state filter missing error, got: {errors}',
)
def test_state_filtered_metric_using_state_used(self):
# Test memory metric using state="used"
query = (
'avg(agent_googleapis_com:memory_percent_used'
'{monitored_resource="gce_instance", state="used"})'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('must not use \'state="used"\'' in err for err in errors),
f'Expected state="used" error, got: {errors}',
)
# Test disk metric using state="used"
query = (
'avg(agent_googleapis_com:disk_percent_used'
'{monitored_resource="gce_instance", state="used"})'
)
errors, _ = validate_promql.validate_promql_query(query)
self.assertTrue(
any('must not use \'state="used"\'' in err for err in errors),
f'Expected state="used" error, got: {errors}',
)
def test_state_filtered_metric_valid_disk(self):
query = (
'avg(agent_googleapis_com:disk_percent_used'
'{monitored_resource="gce_instance", state!="free"})'
)
self.assertEqual(validate_promql.validate_promql_query(query), ([], []))
# --- Query Extractor Markdown & Macro Parsing Tests ---
def test_extract_query(self):
markdown = (
'Here is the query:\n'
'```promql\n'
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m]))\n'
'```\n'
'Hope this helps!'
)
expected = (
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m]))'
)
self.assertEqual(validate_promql.extract_query(markdown), expected)
def test_extract_query_with_interval_macro(self):
raw_query = (
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[${__interval}]))'
)
expected = (
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count'
'{monitored_resource="gce_instance"}[5m]))'
)
extracted = validate_promql.extract_query(raw_query)
self.assertEqual(extracted, expected)
self.assertEqual(validate_promql.validate_promql_query(extracted), ([], []))
def test_multi_query_validation(self):
queries = [
'compute_googleapis_com:instance_cpu_utilization{monitored_resource="gce_instance"}',
'sum(rate(compute_googleapis_com:instance_disk_read_bytes_count{monitored_resource="gce_instance"}[5m]))',
]
for q in queries:
self.assertEqual(validate_promql.validate_promql_query(q), ([], []))
if __name__ == '__main__':
unittest.main()
License (Apache-2.0)
Apache-2.0
Source: google/skills
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE