Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install gke-alert-configuration@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin gke-alert-configuration v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install gke-alert-configuration

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/gke-alert-configuration/

Extract the ZIP to .github/skills/ in your repo. The folder name must match gke-alert-configuration for Copilot to auto-discover it.

Skill Files (6)

SKILL.md 21.2 KB
---
name: gke-alert-configuration
metadata:
  version: "1.0.3"
  category: CloudInfrastructure
  canonical_source: https://github.com/google/skills/tree/main/skills/cloud/gke-alert-configuration
description: >-
  Configures alerting policies in Terraform for Google Kubernetes Engine (GKE)
  clusters, workloads, and services using PromQL and Google Cloud Managed Service
  for Prometheus. Use when writing, analyzing, validating, or deploying Terraform
  alerting policies to monitor GKE service latency, traffic, error rates using
  Multi-Window Multi-Burn-Rate SLO alerts, memory saturation, and cluster health
  such as CrashLoopBackOff and Node NotReady conditions.
  Don't use for non-GKE compute runtimes such as standalone Compute Engine VMs or
  standalone Cloud Run services without GKE.
---

# GKE Alert Configuration

This skill provides guidelines and best practices for creating robust,
high-signal alerting policies for Google Kubernetes Engine workloads using
Google Cloud Managed Service for Prometheus and Terraform. It ensures
comprehensive coverage of the **4 Golden Signals** and key cluster health
metrics while minimizing alert noise.

--------------------------------------------------------------------------------

## 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:gke-alert-configuration)"`
and append `agent-skills/1.0 (skill:gke-alert-configuration)` to `User-Agent` headers.

## Critical Rules

*   **Negative Triggers and Scope Redirection for Non-GKE Standalone Runtimes**:
    *   This skill is strictly scoped to Google Kubernetes Engine (GKE)
        workloads, clusters, and services using PromQL and Google Cloud Managed
        Service for Prometheus.
    *   **Do not use for non-GKE compute runtimes**, such as standalone Compute
        Engine virtual machines or standalone Cloud Run services without GKE.
    *   **STOP AND RESPOND DIRECTLY (Do Not Edit Files)**: When the user
        requests alert configuration for non-GKE compute infrastructure:
        1.  **Do not write, create, edit, or validate any Terraform files on
            disk**.
        2.  **Immediately stop and respond directly to the user in chat**:
            *   **Explicitly Clarify Out-of-Scope**: State clearly that
                standalone Compute Engine virtual machine monitoring or
                standalone Cloud Run monitoring is out of scope for this
                GKE-specific PromQL alerting skill, which is designed
                specifically for GKE workloads using Google Cloud Managed
                Service for Prometheus and PromQL.
            *   **Do Not Generate GKE PromQL Alerts**: Do not create or generate
                Kubernetes PromQL alert policies or fabricate Kubernetes
                container, pod, or node resources for non-GKE infrastructure.
            *   **Redirect the User**: Guide and redirect the user to standard
                Google Cloud Monitoring metrics, such as
                `compute.googleapis.com/instance/cpu/utilization` or
                `run.googleapis.com/request_latencies`, using standard
                `google_monitoring_alert_policy` with `condition_threshold` or
                MQL, or recommend the relevant specialized Cloud observability
                skill.
*   **Mandatory `kube-state-metrics` (KSM) Cost Guardrail**:
    *   Deploying open-source `kube-state-metrics` in Google Cloud Managed
        Service for Prometheus incurs billable metric ingestion costs.
    *   **STOP AND ASK PERMISSION FIRST (Do Not Edit Files)**: When a requested
        alert rule relies on **Tier 2 KSM metrics** (such as `kube_cronjob_*`,
        `kube_pod_status_phase`, `kube_persistentvolume_*`, `kube_deployment_*`,
        `kube_statefulset_*`, `kube_job_*`, or `kube_daemonset_*`), **do not
        write, create, edit, or validate any Terraform files or generate alert
        policies before obtaining user approval**.
    *   Instead, you **must immediately stop and respond directly to the user**
        to:
        1.  **Alert the user** that the requested alert requires
            `kube-state-metrics`.
        2.  **Explain the cost impact**: Detail that `kube-state-metrics` incurs
            billable sample ingestion costs in Google Cloud Managed Service for
            Prometheus.
        3.  **Ask for explicit permission**: Ask the user for explicit
            permission before assuming, enabling, or generating KSM-dependent
            alert configurations.
        4.  **Recommend filtering or allowlisting**: Suggest and recommend
            filtering or allowlisting only the specific required metrics, such
            as using a `PodMonitoring` resource with `metricRelabeling`
            (`action: keep`) or KSM `--metric-allowlist` to minimize ingestion
            costs. Provide a concrete allowlist example.
    *   **Always prefer Non-KSM Native Alternatives** (Tier 1 cAdvisor or native
        GKE metrics documented in
        [metrics_and_alerts_catalog.md](references/metrics_and_alerts_catalog.md))
        whenever possible, such as using `container_memory_working_set_bytes`
        and `container_spec_memory_limit_bytes` instead of
        `kube_pod_container_resource_limits`.
    *   **Explicit Tier and Cost Surcharge Identification in Response**: In
        every response where you generate or recommend an alerting policy, you
        **must explicitly state its classification tier and cost impact**:
        *   **Tier 1 native or standard metric** (GKE built-in metrics, cAdvisor
            `container_*`, kubelet volume stats, kubelet node conditions, and
            control-plane metrics; see
            [metrics_and_alerts_catalog.md](references/metrics_and_alerts_catalog.md)):
            State that it is a **Tier 1 native or standard metric with zero KSM
            cost surcharge**.
        *   **Tier 2 KSM metric**: State that it is a **Tier 2 KSM-dependent
            metric** and follow the permission and allowlisting guardrail above.
            *(Tip: Generally, metrics with the `kube_` prefix that represent
            resource state or metadata belong to Tier 2).*
*   **Plan-Validate-Execute Loop for Approved File Edits**: When modifying,
    adding, or merging approved Terraform files on disk in a workspace, follow
    the three-phase workflow:
    1.  **Plan**: Draft a structured change plan (`changes.json`) containing
        proposed policy resource names, PromQL expressions, grouping labels, and
        durations.
    2.  **Validate**: Run the pre-edit validation script (`python3
        scripts/validate_config.py --plan changes.json`) to verify PromQL
        grammar, lookback windows, duration rules, and ensure no duplicate
        signals exist.
    3.  **Execute**: After the plan passes validation, apply or merge changes
        in-place into the target Terraform configuration (`alerts.tf`).
    4.  *Note*: When answering questions or providing Terraform snippets
        directly in chat where no disk modification is requested, output the
        complete, valid Terraform HCL block in your response.
*   **Configure the 4 Golden Signals and Cluster Health**: Always ensure the
    target Kubernetes workload or service has the following alerting coverage:
    1.  **Latency** (P95 response time)
    2.  **Errors** (Multi-Window Multi-Burn-Rate SLO alerts, such as Fast Burn 1
        hour / 5 minutes with factor 14.4, Slow Burn 6 hours / 30 minutes with
        factor 6.0; do not use simple static ratios)
    3.  **Traffic** (Sudden drop or complete metric disappearance using
        `absent()` or `default 0` syntax, or overload spikes)
    4.  **Saturation (Memory Limit Utilization Only)**: When describing or
        configuring alert policies for a cluster or project, include ONLY
        **Memory Saturation** (`container_memory_working_set_bytes` /
        `container_spec_memory_limit_bytes`). Do **NOT** include CPU saturation
        alerts or list `container_cpu_usage_seconds_total` as an alert metric
        because CPU is compressible and throttled by CFS quotas rather than
        causing uncompressible fatal termination (OOM).
    5.  **Cluster Health** (Pod CrashLooping, Node NotReady)
*   **PromQL Only (Managed Prometheus)**: You must use
    `condition_prometheus_query_language` with PromQL. Do **NOT** use MQL or
    standard `condition_threshold` unless explicitly requested. Google Cloud
    Managed Service for Prometheus is the standard telemetry ingestion path for
    GKE.
*   **Terraform Only**: Write the generated observability configuration ONLY as
    Terraform (`.tf`) files, such as `alerts.tf` and `variables.tf`.
*   **Dynamic Multi-Resource Alerting (No Hardcoding)**: You must not hardcode
    specific pod names, node names, or service names in alerting conditions
    unless explicitly requested. Alerting policies must be written to cover
    resources dynamically:
    *   Always use grouping aggregations (`by (cluster, namespace, service, pod,
        container)`) instead of filtering to a single instance. This allows a
        single alert policy to dynamically track each service or pod separately.
    *   Always declare and use Terraform variables for `project_id`,
        `cluster_name`, and `namespace` (`var.project_id`, `var.cluster_name`,
        `var.namespace`) to make the configuration reusable across environments.
        Always define these variables in `variables.tf` (or within the
        configuration) and reference all three in policies or PromQL label
        matchers.
*   **No Redundant Duration Windows on Lookbacks**:
    *   When PromQL expressions already use an aggregated lookback window (such
        as `increase(...[15m]) > 3` or multi-window SLO burn rates), the query
        time window already smooths out transient spikes.
    *   Adding a Terraform duration on top of a PromQL lookback window increases
        the Mean Time to Detect (MTTD) without providing additional smoothing
        benefits.
    *   In these cases, set Terraform `duration = "0s"` (or `"60s"`). Do not
        enforce `duration = "300s"` on top of `[15m]`, which delays critical
        crashloop alerts by up to 20 minutes total (15 minutes + 5 minutes).
    *   Use `duration = "300s"` only on instantaneous gauge conditions, such as
        `kube_node_status_condition == 0`.
*   **Use SLO Burn Rates Instead of Simple Ratios**: For error rate alerting,
    always generate Multi-Window Multi-Burn-Rate (MWMBR) SLO alerts (such as
    14.4x burn rate over 1 hour and 5 minute windows for a 99% SLO) rather than
    simple error rate ratios (`rate(5xx)/rate(total) > 0.05`), which produce
    excessive false alarms on low traffic.
*   **Robust Traffic Drop Detection (`absent()` / `default 0`)**: When
    monitoring for traffic drops to zero, do not use `rate(...) == 0` alone
    because Prometheus time series disappear completely when no requests occur
    (evaluating to an empty vector rather than 0). Use `default 0` syntax, such
    as `sum(rate(...[5m])) default 0 == 0`, or `absent(...) == 1`.
*   **Notification Channels**: By default, never configure any notification
    channels without user input. If the user explicitly provides a notification
    channel, configure the alerts to use it. Otherwise, you must prompt the user
    in your response to ask if they would like to configure one.
*   **Consult GKE Metrics and Open-Source Alerts Catalog**: When designing or
    generating evaluation suites or alerting policies, consult
    [metrics_and_alerts_catalog.md](references/metrics_and_alerts_catalog.md)
    for public GKE metrics (`kubernetes.io/`) and open-source Kubernetes alerts
    (`awesome-prometheus-alerts`).
*   **Plain English Response**: You must include a plain English explanation for
    what the alerts do in your response. Explain what the alert measures, what
    the threshold represents, and what a trigger indicates.
*   **User Labels**: Include a `user_labels` block in all
    `google_monitoring_alert_policy` resources to track policies created by this
    skill:

    ```terraform
    user_labels = {
      created-with-google-skill = "gke-alert-configuration"
    }
    ```

--------------------------------------------------------------------------------

## Alerting Policy Structure in Terraform

Alerting policies must be defined using the `google_monitoring_alert_policy`
resource with `condition_prometheus_query_language`. Always declare variables in
`variables.tf` for `project_id`, `cluster_name`, and `namespace`.

```hcl
# variables.tf
variable "project_id" {
  type        = string
  description = "Google Cloud Project ID"
}

variable "cluster_name" {
  type        = string
  description = "GKE Cluster Name"
}

variable "namespace" {
  type        = string
  description = "Target Kubernetes Namespace"
  default     = "default"
}

variable "slo_target" {
  type        = number
  description = "SLO Target fraction (for example 0.99 for 99%)"
  default     = 0.99
}
```

```hcl
# alerts.tf
# Example: Multi-Window Multi-Burn-Rate (MWMBR) SLO Alert (Fast Burn: 14.4x, 1h & 5m windows)
resource "google_monitoring_alert_policy" "k8s_service_error_rate_slo" {
  project      = var.project_id
  display_name = "[K8s] ${var.cluster_name} - Service Error Rate SLO Fast Burn"
  combiner     = "OR"

  conditions {
    display_name = "Error Budget Fast Burn (14.4x over 1h and 5m)"
    condition_prometheus_query_language {
      query    = <<-EOT
        (
          (
            sum(
              rate(
                http_requests_total{
                  cluster="${var.cluster_name}",
                  namespace="${var.namespace}",
                  status=~"5.."
                }[5m]
              )
            ) by (service, namespace, cluster)
            /
            sum(
              rate(
                http_requests_total{
                  cluster="${var.cluster_name}",
                  namespace="${var.namespace}"
                }[5m]
              )
            ) by (service, namespace, cluster)
          ) > (1 - ${var.slo_target}) * 14.4
        )
        and
        (
          (
            sum(
              rate(
                http_requests_total{
                  cluster="${var.cluster_name}",
                  namespace="${var.namespace}",
                  status=~"5.."
                }[1h]
              )
            ) by (service, namespace, cluster)
            /
            sum(
              rate(
                http_requests_total{
                  cluster="${var.cluster_name}",
                  namespace="${var.namespace}"
                }[1h]
              )
            ) by (service, namespace, cluster)
          ) > (1 - ${var.slo_target}) * 14.4
        )
      EOT
      duration = "0s"
    }
  }
}
```

--------------------------------------------------------------------------------

## Telemetry Metrics and PromQL Examples

For GKE metrics (`kubernetes.io/`), community open-source alerts
(`awesome-prometheus-alerts`), KSM cost guardrails, and non-KSM native
alternatives, you must read and follow:

*   [metrics_and_alerts_catalog.md](references/metrics_and_alerts_catalog.md)

For specific PromQL queries corresponding to each of the Golden Signals, you
must read and follow:

*   [promql_queries.md](references/promql_queries.md)

For GKE cluster prerequisites, enabling Google Cloud Managed Service for
Prometheus collection, configuring PodMonitoring custom scraping, and enabling
control plane metrics collection (API Server, Controller Manager, Scheduler),
you must read and follow:

*   [gke_configuration_prerequisites.md](references/gke_configuration_prerequisites.md)

--------------------------------------------------------------------------------

## Tooling Scripts and Validation Loop

Use the `validate_config.py` script to validate change plans and Terraform
configurations when working in a repository:

*   **Pre-Edit Plan Validation**: Draft a `changes.json` plan specifying the
    proposed policies, queries, and durations, and validate it before editing:
    *   Command: `python3 scripts/validate_config.py --plan changes.json`
*   **Post-Edit and Directory Validation**: Scan existing or modified Terraform
    files in a directory to ensure no duplicates or syntax errors exist:
    *   Command: `python3 scripts/validate_config.py --directory [TARGET_TF_DIR]
        --cluster-var "${var.cluster_name}"`
    *   Single file validation: `python3 scripts/validate_config.py --file
        [PATH_TO_TF_FILE]`

--------------------------------------------------------------------------------

## Technical Considerations and Gotchas

*   **Lookback Windows versus Duration Buffers**:
    *   Do not add large `duration = "300s"` buffers to alerts that already use
        aggregated lookback windows like `increase(...[15m])` or multi-window
        SLO rates.
    *   The `[15m]` window in `increase(...[15m]) > 3` already smooths spikes.
        Adding `duration = "300s"` increases MTTD by forcing the restart count
        to remain above 3 for an extra 5 continuous minutes, delaying alerts by
        up to 20 minutes total.
    *   Use `duration = "0s"` or `"60s"` when using lookback window functions.
        Reserve `duration = "300s"` for raw instantaneous gauge conditions, such
        as `kube_node_status_condition == 0`.
*   **Memory Saturation Only for Cluster Alerting**:
    *   Do not configure CPU saturation alerts for cluster or workload
        monitoring. CPU is compressible (throttled by the CFS scheduler), while
        memory is uncompressible (triggers OOMKills).
    *   Configure Memory Saturation using `container_memory_working_set_bytes` /
        `container_spec_memory_limit_bytes`.
*   **Missing Resource Limits Blind Spot (Mandatory Explanation)**: Saturation
    alerts that compare usage to limits (such as
    `container_spec_memory_limit_bytes`) will **fail to resolve** or return
    `NaN` if workloads do not have explicit Memory limits configured in their
    Kubernetes manifests.
    *   **Mandatory Instruction**: Whenever you generate, discuss, or recommend
        any memory saturation alert comparing usage against limits (including
        non-KSM cAdvisor alternatives using
        `container_spec_memory_limit_bytes`), you **must explicitly explain and
        warn the user in your response** that container memory limits must be
        explicitly configured in the Kubernetes pod specs or manifests
        (`resources.limits.memory`) for the saturation query to resolve (and not
        return `NaN` or fail to resolve).
*   **Linear Disk Predictions (`predict_linear`)**: When forecasting volume
    exhaustion using
    `predict_linear(kubelet_volume_stats_available_bytes[6h:5m], 4 * 24 * 3600)
    < 0`, explain that `predict_linear` uses linear regression over the recent
    lookback window (for example, 6 hours) to project when available disk will
    drop below 0 (for example, within 4 days). Identify
    `kubelet_volume_stats_available_bytes` as a Tier 1 native kubelet metric
    with zero KSM surcharge.
*   **API Server Error and Client Metrics**:
    *   `apiserver_request_total` and `rest_client_requests_total` are Tier 1
        Control Plane metrics with zero KSM cost surcharge. Explain that
        `apiserver_request_total` monitors 5xx HTTP error rates across API
        server endpoints, while `rest_client_requests_total` monitors 4xx and
        5xx requests sent by REST clients communicating with the API server.
*   **Traffic Disappearance Gotcha (`absent()` / `default 0`)**:
    *   When traffic drops completely to zero, Prometheus and GMP stop emitting
        the `http_requests_total` time series.
    *   `sum(rate(...[5m])) == 0` evaluates to an empty vector, preventing the
        alert from triggering.
    *   Always use `sum(rate(...[5m])) default 0 == 0` or `absent(...) == 1` to
        reliably detect total traffic loss.
*   **CrashLooping versus Normal Restarts**: A container restarting occasionally
    might be normal, for example job completion or a minor rolling update. Alert
    on **frequent** restarts (such as more than 3 restarts in 15 minutes with
    `duration = "0s"`) using `kube_pod_container_status_restarts_total` rather
    than a single restart to avoid noise.
*   **Node Upgrades**: During GKE cluster upgrades, nodes are drained and
    restarted, which can trigger "Node NotReady" alerts. Warn the user that
    these alerts might fire during maintenance windows, or suggest configuring
    maintenance windows if supported.

--------------------------------------------------------------------------------

## Additional Resources

*   [Google Cloud Managed Service for Prometheus Documentation](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus.md.txt)
*   [GKE Observability and Monitoring Concepts](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/observability.md.txt)
*   [Google Cloud Alerting Policies in Terraform](https://docs.cloud.google.com/monitoring/alerts/terraform.md.txt)
*   [Google Cloud Monitoring Pricing](https://cloud.google.com/products/observability/pricing)
*   [Google SRE Workbook: Alerting on SLOs](https://sre.google/workbook/alerting-on-slos/)
*   [Awesome Prometheus Alerts Repository](https://github.com/samber/awesome-prometheus-alerts)
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:gke-alert-configuration)" \
    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:gke-alert-configuration)` 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:gke-alert-configuration)
    ```

-   **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.
gke_configuration_prerequisites.md 10.6 KB
# GKE Configuration & Telemetry Prerequisites for Alerting Policies

This document details the Google Kubernetes Engine (GKE) and Google Cloud
configurations required to support the 16 critical alerting policies defined in
the reference catalog. It provides cluster operators with the setup commands,
configuration parameters, and verification queries to ensure telemetry flows
correctly for each alert.

--------------------------------------------------------------------------------

## Table of Contents

*   [Telemetry Ingestion Architecture](#telemetry-ingestion-architecture)
    (~line 38)
*   [Prerequisite Matrix by Alert](#prerequisite-matrix-by-alert) (~line 64)
*   [GKE Control Plane Metrics (Tier 1)](#gke-control-plane-metrics-tier-1)
    (~line 90)
    *   [Enable Control Plane Metrics](#enable-control-plane-metrics) (~line 96)
    *   [Verification Query](#verification-query) (~line 112)
*   [Kube-State-Metrics (KSM) (Tier 2)](#kube-state-metrics-ksm-tier-2)
    (~line 122)
    *   [KSM Scrape Configuration](#ksm-scrape-configuration) (~line 127)
    *   [Filtered PodMonitoring Resource (Cost-Optimized)](#filtered-podmonitoring-resource-cost-optimized)
        (~line 134)
*   [Workload Instrumentation (Golden Signals)](#workload-instrumentation-golden-signals)
    (~line 160)
    *   [Prometheus Metrics Exporter](#prometheus-metrics-exporter) (~line 165)
    *   [Workload PodMonitoring Configuration](#workload-podmonitoring-configuration)
        (~line 173)
*   [Google Cloud IAM and API Prerequisites](#google-cloud-iam-and-api-prerequisites)
    (~line 195)
    *   [Required APIs](#required-apis) (~line 200)
    *   [Required IAM Roles](#required-iam-roles) (~line 211)
*   [Verification Runbook](#verification-runbook) (~line 221)

--------------------------------------------------------------------------------

## Telemetry Ingestion Architecture

The following diagram illustrates how metrics for each alert category are
scraped from the cluster and ingested into Google Cloud Monitoring / Managed
Service for Prometheus (GMP).

```mermaid
graph TD
    subgraph GKE Cluster
        subgraph Master Node (Google Managed)
            APIServer[Kubernetes API Server] -->|Exposes apiserver_* & rest_*| GMP_CP[GKE Control Plane Metrics collector]
        end
        subgraph Worker Nodes
            subgraph Kubelet
                cAdvisor[cAdvisor] -->|Exposes container_*| GMP_Operator[GMP Operator / PodMonitoring]
                KubeletVol[Volume Stats] -->|Exposes kubelet_volume_*| GMP_Operator
            end
            KSM[kube-state-metrics pod] -->|Exposes kube_*| GMP_Operator
        end
    end
    GMP_CP -->|Writes to| Google_Cloud_Monitoring[Google Cloud Monitoring / GMP]
    GMP_Operator -->|Writes to| Google_Cloud_Monitoring
```

--------------------------------------------------------------------------------

## Prerequisite Matrix by Alert

This table lists the GKE and Google Cloud prerequisites and configuration
requirements for each of the 16 critical alerts.

Alert Name                                     | Cost Tier       | Required Metrics                                        | GKE Cluster Requirement       | Workload/Resource Requirement
:--------------------------------------------- | :-------------- | :------------------------------------------------------ | :---------------------------- | :----------------------------
**Kubernetes Node not ready**                  | Tier 1 (Native) | `kube_node_status_condition`                            | System Monitoring Enabled     | GKE Nodes running standard Kubelet
**Kubernetes Node memory pressure**            | Tier 1 (Native) | `kube_node_status_condition`                            | System Monitoring Enabled     | GKE Nodes running standard Kubelet
**Kubernetes Node disk pressure**              | Tier 1 (Native) | `kube_node_status_condition`                            | System Monitoring Enabled     | GKE Nodes running standard Kubelet
**Kubernetes Node network unavailable**        | Tier 1 (Native) | `kube_node_status_condition`                            | System Monitoring Enabled     | GKE Nodes running standard Kubelet
**Kubernetes Volume full in four days**        | Tier 1 (Native) | `kubelet_volume_stats_available_bytes`                  | System Monitoring Enabled     | Pods with attached volumes (CSI Driver supported)
**Kubernetes API server errors**               | Tier 1 (Native) | `apiserver_request_total`                               | Control Plane Metrics Enabled | GKE Master nodes active
**Kubernetes API client errors**               | Tier 1 (Native) | `rest_client_requests_total`                            | Control Plane Metrics Enabled | API Clients communicating with API Server
**Kubernetes client certificate expires soon** | Tier 1 (Native) | `apiserver_client_certificate_expiration_seconds_count` | Control Plane Metrics Enabled | Client certificate authentication enabled
**Kubernetes CronJob failing**                 | Tier 2 (KSM)    | `kube_cronjob_status_*`, `kube_cronjob_spec_*`          | `kube-state-metrics` Scraped  | Active CronJobs in cluster
**Kubernetes PersistentVolume error**          | Tier 2 (KSM)    | `kube_persistentvolume_status_phase`                    | `kube-state-metrics` Scraped  | PersistentVolume resources configured
**Kubernetes StatefulSet down**                | Tier 2 (KSM)    | `kube_statefulset_*`                                    | `kube-state-metrics` Scraped  | StatefulSets deployed
**Kubernetes Pod not healthy**                 | Tier 2 (KSM)    | `kube_pod_status_phase`                                 | `kube-state-metrics` Scraped  | Pods running in target namespaces
**Kubernetes Deployment generation mismatch**  | Tier 2 (KSM)    | `kube_deployment_*`                                     | `kube-state-metrics` Scraped  | Deployments deployed
**Kubernetes StatefulSet generation mismatch** | Tier 2 (KSM)    | `kube_statefulset_*`                                    | `kube-state-metrics` Scraped  | StatefulSets deployed
**Kubernetes DaemonSet misscheduled**          | Tier 2 (KSM)    | `kube_daemonset_*`                                      | `kube-state-metrics` Scraped  | DaemonSets deployed
**Kubernetes Job slow completion**             | Tier 2 (KSM)    | `kube_job_*`                                            | `kube-state-metrics` Scraped  | Jobs deployed

--------------------------------------------------------------------------------

## GKE Control Plane Metrics (Tier 1)

The control plane alerts (`KubernetesAPIServerErrors`,
`KubernetesAPIClientErrors`, and `KubernetesClientCertificateExpiresSoon`)
require API server and API client telemetry.

### Enable Control Plane Metrics

By default, GKE master metrics are not scraped. You must explicitly enable them
in the GKE cluster configuration using `gcloud`:

```bash
gcloud container clusters update CLUSTER_NAME \
    --zone=COMPUTE_ZONE \
    --monitoring=SYSTEM,API_SERVER,CONTROLLER_MANAGER,SCHEDULER
```

*   **API_SERVER**: Exposes API server request volumes, error rates, and client
    request metrics.
*   **CONTROLLER_MANAGER & SCHEDULER**: (Optional but recommended) Exposes
    scheduler queue metrics and controller manager execution states.

### Verification Query

Verify that API server telemetry is flowing to Cloud Monitoring:

```promql
sum(rate(apiserver_request_total[5m])) by (code)
```

--------------------------------------------------------------------------------

## Kube-State-Metrics (KSM) (Tier 2)

All workload, replica mismatch, and CronJob alerts require cluster state metrics
(`kube_*` metrics).

### KSM Scrape Configuration

To collect KSM metrics in Google Cloud Managed Service for Prometheus (GMP):

1.  Deploy `kube-state-metrics` to the `kube-system` namespace.
2.  Deploy a GMP `PodMonitoring` custom resource targeting the KSM deployment.

### Filtered PodMonitoring Resource (Cost-Optimized)

To avoid high sample ingestion charges, use `metricRelabeling` to drop all
unused metrics:

```yaml
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  name: kube-state-metrics-filtered
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  endpoints:
  - port: http-metrics
    interval: 30s
    metricRelabeling:
    - action: keep
      sourceLabels: [__name__]
      regex: "^(kube_deployment_.*|kube_statefulset_.*|kube_daemonset_.*|kube_cronjob_.*|kube_job_.*|kube_pod_status_phase|kube_pod_info|kube_pod_container_status_.*|kube_persistentvolume_status_phase)$"
```

--------------------------------------------------------------------------------

## Workload Instrumentation (Golden Signals)

For Latency, Traffic, Error Rates, and Saturation monitoring, target workloads
must expose application and runtime telemetry.

### Prometheus Metrics Exporter

Ensure application containers expose standard Prometheus metrics endpoints (such
as `/metrics` on port 8080 or 9090) emitting:

*   `http_requests_total` (Traffic & Errors)
*   `http_request_duration_seconds_bucket` (Latency)

### Workload PodMonitoring Configuration

Create a `PodMonitoring` resource in the workload's namespace:

```yaml
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  name: app-metrics-monitoring
  namespace: default
spec:
  selector:
    matchLabels:
      app: my-app
  endpoints:
  - port: http-metrics
    path: /metrics
    interval: 15s
```

--------------------------------------------------------------------------------

## Google Cloud IAM and API Prerequisites

To deploy and evaluate Terraform alerting policies, the following Google Cloud
prerequisites are required:

### Required APIs

Enable the required Google Cloud APIs:

```bash
gcloud services enable \
    monitoring.googleapis.com \
    container.googleapis.com \
    cloudresourcemanager.googleapis.com
```

### Required IAM Roles

The service account or user deploying the Terraform configuration requires:

*   `roles/monitoring.alertPolicyEditor` (or `roles/monitoring.editor`)
*   `roles/monitoring.viewer` (for validating existing policies)
*   `roles/container.viewer` (for querying cluster metadata)

--------------------------------------------------------------------------------

## Verification Runbook

After deploying alerting policies, run the following verification steps:

1.  **Validate Terraform Syntax**:

    ```bash
    terraform init
    terraform validate
    ```

2.  **Validate PromQL Rules**:

    ```bash
    python3 scripts/validate_config.py --file alerts.tf
    ```

3.  **Inspect Cloud Monitoring Alert Policies**:

    ```bash
    gcloud alpha monitoring policies list \
        --filter="displayName ~ '^\[K8s\]'" \
        --format="table(name,displayName,enabled)"
    ```
metrics_and_alerts_catalog.md 24.4 KB
# Comprehensive GKE Metrics & Kubernetes Alerting Catalog

This catalog compiles public Google Kubernetes Engine (GKE) telemetry metrics
from the
[Google Cloud Managed Service for Prometheus Documentation](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus.md.txt),
the
[GKE Observability Documentation](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/observability.md.txt),
and the
[Google Cloud Monitoring Pricing Documentation](https://cloud.google.com/products/observability/pricing),
along with critical alerting rules from the open-source
[Awesome Prometheus Alerts for Kubernetes](https://samber.github.io/awesome-prometheus-alerts/rules/orchestrators/kubernetes/)
catalog.

It serves as the reference catalog for the `gke-alert-configuration` skill when
generating evaluation suites and production alerting policies in Google Cloud
Managed Service for Prometheus and Cloud Monitoring.

--------------------------------------------------------------------------------

## Table of Contents

*   [Telemetry Decision Hierarchy and KSM Cost Guardrails](#telemetry-decision-hierarchy-and-ksm-cost-guardrails)
    (~line 61)
    *   [Classification Tiers and Cost Optimization](#classification-tiers-and-cost-optimization)
        (~line 84)
    *   [Tier 2 Allowlist Template (PodMonitoring)](#tier-2-allowlist-template-podmonitoring-with-metricrelabeling)
        (~line 92)
*   [GKE Public Metrics Catalog (kubernetes.io/)](#gke-public-metrics-catalog-kubernetesio)
    (~line 119)
    *   [Container and Pod Core Metrics](#container-and-pod-core-metrics)
        (~line 123)
    *   [Node and Infrastructure Core Metrics](#node-and-infrastructure-core-metrics)
        (~line 143)
    *   [Autoscaling and Hardware Accelerator Metrics](#autoscaling-and-hardware-accelerator-metrics)
        (~line 157)
*   [Open Source Kubernetes Alerts Catalog (awesome-prometheus-alerts)](#open-source-kubernetes-alerts-catalog-awesome-prometheus-alerts)
    (~line 169)
    *   [Node Health and Capacity Alerts](#node-health-and-capacity-alerts)
        (~line 173)
    *   [Workload and Container Reliability Alerts](#workload-and-container-reliability-alerts)
        (~line 184)
    *   [Jobs, CronJobs, and Storage Alerts](#jobs-cronjobs-and-storage-alerts)
        (~line 199)
    *   [API Server and Control Plane Alerts](#api-server-and-control-plane-alerts)
        (~line 210)
*   [Non-KSM Native Alternative Implementations](#non-ksm-native-alternative-implementations)
    (~line 221)
    *   [Container Memory Saturation and OOM Risk](#container-memory-saturation-and-oom-risk-primary-saturation-alert)
        (~line 227)
    *   [Pod CrashLoopBackOff and Restarts](#pod-crashloopbackoff-and-restarts-non-ksm-alternative)
        (~line 257)
    *   [Node Readiness and Health](#node-readiness-and-health-non-ksm-alternative)
        (~line 277)
    *   [Multi-Window Multi-Burn-Rate SLO Error Rate Alerts](#multi-window-multi-burn-rate-mwmbr-slo-error-rate-alerts)
        (~line 287)
    *   [Traffic Outage Detection (absent() / default 0)](#traffic-outage-detection-absent--default-0)
        (~line 310)

--------------------------------------------------------------------------------

## Telemetry Decision Hierarchy and KSM Cost Guardrails

> [!IMPORTANT] **Cost Warning on `kube-state-metrics` (KSM)**: In Google Cloud
> Managed Service for Prometheus, billing is based on **metric samples
> ingested**. Deploying open-source `kube-state-metrics` unmodified scrapes
> state for every object across the cluster, generating high time-series volume
> and significant ingestion cost.
>
> **Mandatory Agent Guardrail**: When a user requests an alert that requires
> `kube-state-metrics`, you **must alert the user** that the policy requires
> KSM, ask for explicit permission before assuming or enabling KSM ingestion,
> and prefer **Non-KSM Native Alternatives** where possible.

```mermaid
flowchart TD
    A[User Request for Alert Policy] --> B{Can alert be served via Native GKE or cAdvisor?}
    B -->|Yes - Tier 1| C[Use Native GKE / cAdvisor Metric with Zero KSM Surcharge]
    B -->|No - Requires KSM| D[Alert User on KSM Cost and Ask Permission]
    D --> E{User Approved KSM?}
    E -->|No| F[Fall back to closest Native API / cAdvisor Approximation]
    E -->|Yes - Tier 2| G[Generate KSM Alert Policy and Recommend Filtered PodMonitoring Allowlist]
```

### Classification Tiers and Cost Optimization

*   **Tier 1: Native GKE Built-ins / cAdvisor (Zero KSM Cost)**: Metrics
    collected natively by GKE or cAdvisor without `kube-state-metrics`.
*   **Tier 2: Filtered KSM (Requires Consent & Allowlist)**: Rules requiring
    Kubernetes control-plane state (such as Deployment spec versus ready
    replicas) that require `kube-state-metrics`.

#### Tier 2 Allowlist Template (`PodMonitoring` with `metricRelabeling`)

When KSM is required and authorized, always recommend configuring a filtered
`PodMonitoring` resource to scrape only the required metrics and drop all
others:

```yaml
apiVersion: monitoring.googleapis.com/v1
kind: PodMonitoring
metadata:
  name: kube-state-metrics-filtered
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: kube-state-metrics
  endpoints:
  - port: http-metrics
    interval: 30s
    metricRelabeling:
    - action: keep
      sourceLabels: [__name__]
      regex: "^(kube_deployment_.*|kube_statefulset_.*|kube_daemonset_.*|kube_cronjob_.*|kube_job_.*|kube_pod_status_phase|kube_pod_info|kube_pod_container_status_.*|kube_persistentvolume_status_phase)$"
```

--------------------------------------------------------------------------------

## GKE Public Metrics Catalog (`kubernetes.io/`)

Below are the public native GKE telemetry metrics available in Cloud Monitoring.

### Container and Pod Core Metrics

Metric Path                                             | Unit | Description                                         | Cost Tier
:------------------------------------------------------ | :--- | :-------------------------------------------------- | :--------
`kubernetes.io/container/cpu/core_usage_time`           | `s`  | Cumulative CPU time consumed by the container.      | Tier 1 (Native)
`kubernetes.io/container/cpu/limit_cores`               | `1`  | CPU core limit configured for the container.        | Tier 1 (Native)
`kubernetes.io/container/cpu/request_cores`             | `1`  | CPU core request configured for the container.      | Tier 1 (Native)
`kubernetes.io/container/memory/used_bytes`             | `By` | Total memory currently used by the container.       | Tier 1 (Native)
`kubernetes.io/container/memory/limit_bytes`            | `By` | Memory limit configured for the container.          | Tier 1 (Native)
`kubernetes.io/container/memory/request_bytes`          | `By` | Memory request configured for the container.        | Tier 1 (Native)
`kubernetes.io/container/memory/page_fault_count`       | `1`  | Cumulative count of memory page faults.             | Tier 1 (Native)
`kubernetes.io/container/restart_count`                 | `1`  | Number of times the container has restarted.        | Tier 1 (Native)
`kubernetes.io/container/uptime`                        | `s`  | Duration the container has been running.            | Tier 1 (Native)
`kubernetes.io/container/ephemeral_storage/used_bytes`  | `By` | Local ephemeral storage used by container.          | Tier 1 (Native)
`kubernetes.io/container/ephemeral_storage/limit_bytes` | `By` | Ephemeral storage limit for container.              | Tier 1 (Native)
`kubernetes.io/pod/network/received_bytes_count`        | `By` | Cumulative bytes received by pod network interface. | Tier 1 (Native)
`kubernetes.io/pod/network/sent_bytes_count`            | `By` | Cumulative bytes sent by pod network interface.     | Tier 1 (Native)
`kubernetes.io/pod/volume/used_bytes`                   | `By` | Persistent volume storage used by pod.              | Tier 1 (Native)
`kubernetes.io/pod/volume/total_bytes`                  | `By` | Total persistent volume storage capacity.           | Tier 1 (Native)

### Node and Infrastructure Core Metrics

Metric Path                                       | Unit | Description                                             | Cost Tier
:------------------------------------------------ | :--- | :------------------------------------------------------ | :--------
`kubernetes.io/node/cpu/allocatable_cores`        | `1`  | Total allocatable CPU cores on the node.                | Tier 1 (Native)
`kubernetes.io/node/cpu/total_cores`              | `1`  | Total physical CPU cores on the node.                   | Tier 1 (Native)
`kubernetes.io/node/cpu/core_usage_time`          | `s`  | Cumulative CPU core seconds used across node.           | Tier 1 (Native)
`kubernetes.io/node/memory/allocatable_bytes`     | `By` | Total allocatable memory on the node.                   | Tier 1 (Native)
`kubernetes.io/node/memory/used_bytes`            | `By` | Total memory currently used on the node.                | Tier 1 (Native)
`kubernetes.io/node/status`                       | `1`  | Current operational status of the node.                 | Tier 1 (Native)
`kubernetes.io/node/status_condition`             | `1`  | Condition status (Ready, MemoryPressure, DiskPressure). | Tier 1 (Native)
`kubernetes.io/node/ephemeral_storage/used_bytes` | `By` | Ephemeral storage bytes used on node filesystem.        | Tier 1 (Native)
`kubernetes.io/node/pid_used` / `pid_limit`       | `1`  | PIDs used vs. maximum PID limit on node.                | Tier 1 (Native)

### Autoscaling and Hardware Accelerator Metrics

Metric Path                                                                       | Unit | Description                                 | Cost Tier
:-------------------------------------------------------------------------------- | :--- | :------------------------------------------ | :--------
`kubernetes.io/autoscaler/container/cpu/per_replica_recommended_request_cores`    | `1`  | VPA recommended CPU request per replica.    | Tier 1 (Native)
`kubernetes.io/autoscaler/container/memory/per_replica_recommended_request_bytes` | `By` | VPA recommended memory request per replica. | Tier 1 (Native)
`kubernetes.io/autoscaler/recommenders/horizontal/target_value`                   | `1`  | HPA target metric value for autoscaling.    | Tier 1 (Native)
`kubernetes.io/container/accelerator/duty_cycle`                                  | `%`  | GPU/TPU accelerator execution duty cycle.   | Tier 1 (Native)
`kubernetes.io/container/accelerator/memory_used`                                 | `By` | GPU/TPU accelerator memory allocated.       | Tier 1 (Native)

--------------------------------------------------------------------------------

## Open Source Kubernetes Alerts Catalog (`awesome-prometheus-alerts`)

Compiled from the open-source community catalog.

### Node Health and Capacity Alerts

Alert Name                              | Open Source PromQL Rule                                                                                                                                                                                                   | Severity | KSM Required? | Non-KSM Native Alternative Available?
:-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------- | :------------ | :------------------------------------
**Kubernetes Node not ready**           | `kube_node_status_condition{condition="Ready",status="true"} == 0`                                                                                                                                                        | Critical | No (Standard) | Yes (Tier 1 PromQL / native node status)
**Kubernetes Node scheduling disabled** | `kube_node_spec_taint{key="node.kubernetes.io/unschedulable"} == 1`                                                                                                                                                       | Warning  | No (Standard) | Yes
**Kubernetes Node memory pressure**     | `kube_node_status_condition{condition="MemoryPressure",status="true"} == 1`                                                                                                                                               | Critical | No (Standard) | Yes
**Kubernetes Node disk pressure**       | `kube_node_status_condition{condition="DiskPressure",status="true"} == 1`                                                                                                                                                 | Critical | No (Standard) | Yes
**Kubernetes Node network unavailable** | `kube_node_status_condition{condition="NetworkUnavailable",status="true"} == 1`                                                                                                                                           | Critical | No (Standard) | Yes
**Kubernetes Node out of pod capacity** | `sum by (node) ((kube_pod_status_phase{phase="Running"} == 1) + on(uid, instance) group_left(node) (0 * kube_pod_info{pod_template_hash=""})) / sum by (node) (kube_node_status_allocatable{resource="pods"}) * 100 > 90` | Warning  | **Yes (KSM)** | Yes (Approximate via cAdvisor pod count)

### Workload and Container Reliability Alerts

Alert Name                                       | Open Source PromQL Rule                                                                                                                                                                                                     | Severity | KSM Required? | Non-KSM Native Alternative Available?
:----------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :------------ | :------------------------------------
**Kubernetes Pod crash looping**                 | `increase(kube_pod_container_status_restarts_total[15m]) > 3`                                                                                                                                                               | Warning  | No (cAdvisor) | Yes (`kubernetes.io/container/restart_count`)
**Kubernetes Pod not healthy**                   | `sum by (namespace, pod) (kube_pod_status_phase{phase=~"Pending\|Unknown\|Failed"}) > 0`                                                                                                                                    | Critical | **Yes (KSM)** | Partial (Native pod availability checks)
**Kubernetes Container OOMKiller**               | `(kube_pod_container_status_restarts_total - kube_pod_container_status_restarts_total offset 10m >= 1) and ignoring (reason) min_over_time(kube_pod_container_status_last_terminated_reason{reason="OOMKilled"}[10m]) == 1` | Warning  | **Yes (KSM)** | Yes (Memory usage > 95% of container limit)
**Kubernetes Deployment replicas mismatch**      | `kube_deployment_spec_replicas != kube_deployment_status_replicas_available`                                                                                                                                                | Warning  | **Yes (KSM)** | No exact match without KSM (Control Plane state)
**Kubernetes StatefulSet replicas mismatch**     | `kube_statefulset_status_replicas_ready != kube_statefulset_status_replicas`                                                                                                                                                | Warning  | **Yes (KSM)** | No exact match without KSM
**Kubernetes StatefulSet down**                  | `kube_statefulset_replicas != kube_statefulset_status_replicas_ready > 0`                                                                                                                                                   | Critical | **Yes (KSM)** | No exact match without KSM
**Kubernetes Deployment generation mismatch**    | `kube_deployment_status_observed_generation != kube_deployment_metadata_generation`                                                                                                                                         | Critical | **Yes (KSM)** | Requires KSM
**Kubernetes StatefulSet update not rolled out** | `max without (revision) (kube_statefulset_status_current_revision unless kube_statefulset_status_update_revision) * (kube_statefulset_replicas != kube_statefulset_status_replicas_updated)`                                | Warning  | **Yes (KSM)** | Requires KSM
**Kubernetes DaemonSet rollout stuck**           | `(kube_daemonset_status_number_ready / kube_daemonset_status_desired_number_scheduled * 100 < 100) or (kube_daemonset_status_desired_number_scheduled - kube_daemonset_status_current_number_scheduled > 0)`                | Warning  | **Yes (KSM)** | Requires KSM
**Kubernetes DaemonSet misscheduled**            | `kube_daemonset_status_number_misscheduled > 0`                                                                                                                                                                             | Critical | **Yes (KSM)** | Requires KSM

### Jobs, CronJobs, and Storage Alerts

Alert Name                              | Open Source PromQL Rule                                                                                                                                          | Severity | KSM Required? | Non-KSM Native Alternative Available?
:-------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :------------ | :------------------------------------
**Kubernetes Job failed**               | `kube_job_status_failed > 0`                                                                                                                                     | Warning  | **Yes (KSM)** | Requires KSM
**Kubernetes Job not starting**         | `kube_job_status_active == 0 and kube_job_status_failed == 0 and kube_job_status_succeeded == 0 and (time() - kube_job_status_start_time) > 600`                 | Warning  | **Yes (KSM)** | Requires KSM
**Kubernetes CronJob failing**          | `(kube_cronjob_status_last_schedule_time > kube_cronjob_status_last_successful_time) AND (kube_cronjob_status_active == 0) AND (kube_cronjob_spec_suspend == 0)` | Critical | **Yes (KSM)** | Requires KSM
**Kubernetes Volume out of disk space** | `kubelet_volume_stats_available_bytes / kubelet_volume_stats_capacity_bytes * 100 < 10 and kubelet_volume_stats_capacity_bytes > 0`                              | Warning  | No (Kubelet)  | Yes (`kubernetes.io/pod/volume/...`)
**Kubernetes Volume full in four days** | `predict_linear(kubelet_volume_stats_available_bytes[6h:5m], 4 * 24 * 3600) < 0`                                                                                 | Critical | No (Kubelet)  | Yes
**Kubernetes PersistentVolume error**   | `kube_persistentvolume_status_phase{phase=~"Failed\|Pending"} > 0`                                                                                               | Critical | **Yes (KSM)** | Requires KSM

### API Server and Control Plane Alerts

Alert Name                                     | Open Source PromQL Rule                                                                                                                                                                                                                                                | Severity | KSM Required? | Non-KSM Native Alternative Available?
:--------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :------------ | :------------------------------------
**Kubernetes API server errors**               | `sum(rate(apiserver_request_total{job="apiserver",code=~"(?:5..)"}[1m])) by (instance, job) / sum(rate(apiserver_request_total{job="apiserver"}[1m])) by (instance, job) * 100 > 3 and sum(rate(apiserver_request_total{job="apiserver"}[1m])) by (instance, job) > 0` | Critical | No            | Yes (Native Control Plane PromQL)
**Kubernetes API client errors**               | `(sum(rate(rest_client_requests_total{code=~"(4\|5).."}[1m])) by (instance, job) / sum(rate(rest_client_requests_total[1m])) by (instance, job)) * 100 > 1 and sum(rate(rest_client_requests_total[1m])) by (instance, job) > 0`                                       | Critical | No            | Yes (Native Control Plane PromQL)
**Kubernetes client certificate expires soon** | `apiserver_client_certificate_expiration_seconds_count{job="apiserver"} > 0 and on(job) histogram_quantile(0.01, sum by (job, le) (rate(apiserver_client_certificate_expiration_seconds_bucket{job="apiserver"}[5m]))) < 24*60*60`                                     | Critical | No            | Yes (Native Control Plane PromQL)
**Kubernetes API server latency**              | `histogram_quantile(0.99, sum(rate(apiserver_request_duration_seconds_bucket{verb!~"(?:CONNECT\|WATCHLIST\|WATCH\|PROXY)"}[10m])) WITHOUT (subresource)) > 1`                                                                                                          | Warning  | No            | Yes (Native Control Plane PromQL)

--------------------------------------------------------------------------------

## Non-KSM Native Alternative Implementations

When a user requests open-source catalog alerts that normally rely on
`kube-state-metrics`, the skill must first offer these **Tier 1 (Non-KSM)**
equivalents to avoid customer ingestion costs:

### Container Memory Saturation and OOM Risk (Primary Saturation Alert)

Instead of `container_memory_working_set_bytes /
kube_pod_container_resource_limits`, use native cAdvisor limits:

```promql
sum(
  container_memory_working_set_bytes{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}",
    container!=""
  }
) by (pod, container)
/
sum(
  container_spec_memory_limit_bytes{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}",
    container!=""
  }
) by (pod, container) > 0.90
```

> [!NOTE] **Memory versus CPU Saturation**: In Kubernetes, CPU is compressible
> and throttled by the CFS scheduler without killing containers. Memory is
> uncompressible and triggers fatal OOMKilled events. Therefore, cluster
> saturation alerting focuses on **Memory Saturation**, and CPU saturation
> alerts (and `container_cpu_usage_seconds_total`) are excluded from the
> recommended cluster alert suite.

### Pod CrashLoopBackOff and Restarts (Non-KSM Alternative)

Use native GKE Cloud Monitoring metric `kubernetes.io/container/restart_count`
or cAdvisor restart counter:

```promql
sum(
  increase(
    kube_pod_container_status_restarts_total{
      cluster="${var.cluster_name}",
      namespace="${var.namespace}"
    }[15m]
  )
) by (pod, container) > 3
```

*   **Duration Rule**: Set Terraform `duration = "0s"` (or `"60s"`). The `[15m]`
    lookback window already smooths transient spikes; adding `duration = "300s"`
    delays critical crashloop alerts by 20 minutes total.

### Node Readiness and Health (Non-KSM Alternative)

```promql
kube_node_status_condition{
  cluster="${var.cluster_name}",
  condition="Ready",
  status="true"
} == 0
```

### Multi-Window Multi-Burn-Rate (MWMBR) SLO Error Rate Alerts

For service error rate monitoring, use multi-window burn rate alerts instead of
simple static ratios:

```promql
(
  (
    sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}", status=~"5.."}[5m])) by (service)
    /
    sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}"}[5m])) by (service)
  ) > (1 - 0.99) * 14.4
)
and
(
  (
    sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}", status=~"5.."}[1h])) by (service)
    /
    sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}"}[1h])) by (service)
  ) > (1 - 0.99) * 14.4
)
```

### Traffic Outage Detection (`absent()` / `default 0`)

Avoid brittle `== 0` checks. Use `default 0` or `absent()` to detect total
traffic loss:

```promql
(sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}"}[5m])) by (service) default 0) == 0
and
(sum(rate(http_requests_total{cluster="${var.cluster_name}", namespace="${var.namespace}"}[5m] offset 1w)) by (service)) > 1
```
promql_queries.md 11.6 KB
# PromQL Queries Reference for Kubernetes Alerting

This document provides best-practice PromQL queries for monitoring Kubernetes
clusters and services, organized by the Golden Signals and key Cluster Health
metrics.

All queries are designed to be used with **Google Cloud Managed Service for
Prometheus (GMP)** and can be deployed via Cloud Monitoring alerting policies
using `condition_prometheus_query_language`.

--------------------------------------------------------------------------------

## Table of Contents

*   [Latency Alerts (P95 Response Time)](#latency-alerts-p95-response-time)
    (~line 47)
    *   [Query (Standard Prometheus HTTP Metrics)](#query-standard-prometheus-http-metrics)
        (~line 51)
    *   [Query (OpenTelemetry Semantic Conventions)](#query-opentelemetry-semantic-conventions)
        (~line 66)
*   [Traffic Alerts (Request Rate and Outage Detection)](#traffic-alerts-request-rate-and-outage-detection)
    (~line 90)
    *   [Query (Request Rate QPS)](#query-request-rate-qps) (~line 95)
    *   [Traffic Drop and Outage Detection (absent() or default 0)](#traffic-drop-and-outage-detection-absent-or-default-0)
        (~line 108)
*   [Error Alerts (Multi-Window Multi-Burn-Rate SLO)](#error-alerts-multi-window-multi-burn-rate-slo)
    (~line 179)
    *   [Fast Burn Rate Alert (14.4x over 1 hour and 5 minutes)](#fast-burn-rate-alert-144x-over-1-hour-and-5-minutes)
        (~line 188)
    *   [Medium Burn Rate Alert (6.0x over 6 hours and 30 minutes)](#medium-burn-rate-alert-60x-over-6-hours-and-30-minutes)
        (~line 243)
    *   [Slow Burn Rate Alert (1.0x over 3 days and 6 hours)](#slow-burn-rate-alert-10x-over-3-days-and-6-hours)
        (~line 296)
*   [Saturation Alerts (Memory Limit Utilization)](#saturation-alerts-memory-limit-utilization)
    (~line 352)
    *   [Query (cAdvisor Memory Limit Saturation)](#query-cadvisor-memory-limit-saturation)
        (~line 362)
*   [Cluster and Workload Health Alerts](#cluster-and-workload-health-alerts)
    (~line 392)
    *   [Pod CrashLooping and Frequent Restarts](#pod-crashlooping-and-frequent-restarts)
        (~line 396)
    *   [Node NotReady Condition](#node-notready-condition) (~line 416)
    *   [API Server Request Errors](#api-server-request-errors) (~line 432)

--------------------------------------------------------------------------------

## Latency Alerts (P95 Response Time)

Monitors the 95th percentile of HTTP request duration to detect slow responses.

### Query (Standard Prometheus HTTP Metrics)

```promql
histogram_quantile(0.95,
  sum(
    rate(
      http_request_duration_seconds_bucket{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m]
    )
  ) by (le, service, ingress)
) > 2.0
```

### Query (OpenTelemetry Semantic Conventions)

If your application is instrumented with OpenTelemetry, it might use
`http_server_request_duration_milliseconds`:

```promql
histogram_quantile(0.95,
  sum(
    rate(
      http_server_request_duration_milliseconds_bucket{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m]
    )
  ) by (le, service)
) > 2000
```

*   **Threshold**: `2.0` seconds (or `2000` ms). Adjust based on latency target.
*   **Buffer**: Use `duration = "300s"` in the alert policy for instantaneous
    percentiles or `duration = "0s"` when multi-window smoothing is applied.

--------------------------------------------------------------------------------

## Traffic Alerts (Request Rate and Outage Detection)

Monitors the volume of requests to detect sudden drops (indicating outage) or
overload spikes.

### Query (Request Rate QPS)

```promql
sum(
  rate(
    http_requests_total{
      cluster="${var.cluster_name}",
      namespace="${var.namespace}"
    }[5m]
  )
) by (service)
```

### Traffic Drop and Outage Detection (`absent()` or `default 0`)

> [!WARNING] **The `== 0` Metric Disappearance Gotcha**: When a service
> experiences a total traffic outage, HTTP requests stop entirely and Prometheus
> stops emitting the `http_requests_total` metric series. Evaluating
> `rate(...) == 0` returns an **empty vector** (no data) rather than a `0`
> value, so the alert will **fail to fire**.

To reliably detect a complete traffic loss, use **`default 0`** or
**`absent()`**:

#### Option A: `default 0` Anomaly Comparison (Recommended)

Fires if current 5m traffic is zero when historical traffic 1 week ago was
active (> 1 QPS):

```promql
(
  sum(
    rate(
      http_requests_total{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m]
    )
  ) by (service) default 0
) == 0
and
(
  sum(
    rate(
      http_requests_total{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m] offset 1w
    )
  ) by (service)
) > 1
```

#### Option B: Complete Metric Disappearance (`absent()`)

Fires if the `http_requests_total` time series disappears entirely from the
cluster or namespace:

```promql
absent(
  http_requests_total{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}"
  }
) == 1
```

#### Option C: Instantaneous Zero Traffic (`default 0`)

```promql
(
  sum(
    rate(
      http_requests_total{
        cluster="${var.cluster_name}",
        namespace="${var.namespace}"
      }[5m]
    )
  ) by (service) default 0
) == 0
```

--------------------------------------------------------------------------------

## Error Alerts (Multi-Window Multi-Burn-Rate SLO)

Multi-Window Multi-Burn-Rate (MWMBR) alerting evaluates error budget consumption
across two simultaneous lookback windows (short-window and long-window). Both
windows must exceed the burn rate threshold for the alert to fire, eliminating
false alerts from short bursts while rapidly catching critical outages.

Formula: `Burn Rate = (Errors / Total Requests in Lookback) / (1 - SLO Target)`

### Fast Burn Rate Alert (14.4x over 1 hour and 5 minutes)

*   **Severity**: Critical (Page on-call). Consumes 2% of 30-day budget in 1
    hour (100% budget consumed in 2 days).
*   **Duration**: Set `duration = "0s"` (lookback windows already smooth
    spikes).

```promql
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[5m]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[5m]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 14.4
)
and
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[1h]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[1h]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 14.4
)
```

### Medium Burn Rate Alert (6.0x over 6 hours and 30 minutes)

*   **Severity**: High (Page / Ticket). Consumes 5% of 30-day budget in 6 hours.
*   **Duration**: Set `duration = "0s"`.

```promql
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[30m]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[30m]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 6.0
)
and
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[6h]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[6h]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 6.0
)
```

### Slow Burn Rate Alert (1.0x over 3 days and 6 hours)

*   **Severity**: Warning (Ticket / Email). Consumes 10% of 30-day budget in 3
    days.
*   **Duration**: Set `duration = "0s"`.

```promql
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[6h]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[6h]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 1.0
)
and
(
  (
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}",
          status=~"5.."
        }[3d]
      )
    ) by (service)
    /
    sum(
      rate(
        http_requests_total{
          cluster="${var.cluster_name}",
          namespace="${var.namespace}"
        }[3d]
      )
    ) by (service)
  ) > (1 - ${var.slo_target}) * 1.0
)
```

--------------------------------------------------------------------------------

## Saturation Alerts (Memory Limit Utilization)

Monitors how close workloads are to their allocated memory resource limits.

> [!NOTE] **Memory Saturation versus CPU Saturation**: In Kubernetes, CPU is
> compressible and throttled by CFS quotas. Memory is uncompressible and causes
> immediate `OOMKilled` termination. For cluster alerting suites, only **Memory
> Saturation** is included. CPU saturation alerts and
> `container_cpu_usage_seconds_total` are excluded.

### Query (cAdvisor Memory Limit Saturation)

```promql
sum(
  container_memory_working_set_bytes{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}",
    container!=""
  }
) by (pod, container)
/
sum(
  container_spec_memory_limit_bytes{
    cluster="${var.cluster_name}",
    namespace="${var.namespace}",
    container!=""
  }
) by (pod, container) > 0.90
```

*   **Metric**: `container_memory_working_set_bytes` divided by
    `container_spec_memory_limit_bytes`.
*   **Threshold**: `0.90` (90% limit utilization).
*   **Duration**: `duration = "300s"` in Terraform alert policy.
*   **Mandatory User Warning**: Memory limits must be explicitly configured in
    the container pod specifications (`resources.limits.memory`) for this PromQL
    expression to resolve (and avoid `NaN`).

--------------------------------------------------------------------------------

## Cluster and Workload Health Alerts

Alerts that monitor the foundational health of nodes and pods.

### Pod CrashLooping and Frequent Restarts

Detects containers restarting repeatedly (CrashLoopBackOff).

```promql
sum(
  increase(
    kube_pod_container_status_restarts_total{
      cluster="${var.cluster_name}",
      namespace="${var.namespace}"
    }[15m]
  )
) by (pod, container) > 3
```

*   **Window**: `[15m]` lookback with threshold `> 3`.
*   **Duration**: **`duration = "0s"`** (or `"60s"`). The `[15m]` window already
    provides time smoothing; adding `duration = "300s"` unnecessarily delays
    alerts.

### Node NotReady Condition

Detects nodes that have transitioned to a NotReady state.

```promql
kube_node_status_condition{
  cluster="${var.cluster_name}",
  condition="Ready",
  status="true"
} == 0
```

*   **Condition**: `condition="Ready", status="true" == 0`
*   **Duration**: `duration = "300s"` to prevent alerting during transient node
    restarts or scheduled cluster upgrades.

### API Server Request Errors

Detects elevated error rates on the Kubernetes API Server control plane.

```promql
sum(
  rate(
    apiserver_request_total{
      job="apiserver",
      code=~"5.."
    }[1m]
  )
) by (instance, job)
/
sum(
  rate(
    apiserver_request_total{
      job="apiserver"
    }[1m]
  )
) by (instance, job) * 100 > 3
```
scripts/
validate_config.py 13.0 KB
#!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""HCL configuration and PromQL validation script for GKE alert policies.

Parses Terraform HCL alert policy resource blocks or pre-edit change plans
(such as changes.json), detects duplicate targets for Kubernetes resources,
and lints Prometheus queries for correct syntax, time windows, and essential
label filters.
"""

import argparse
import glob
import json
import os
import re
import sys


class PromQLLinter:
  """Linter for PromQL query strings inside alert policies."""

  @classmethod
  def check_balanced_chars(cls, query, open_char, close_char):
    """Checks if parenthesis or braces are balanced."""
    count = 0
    for i, char in enumerate(query):
      if char == open_char:
        count += 1
      elif char == close_char:
        count -= 1
        if count < 0:
          return f"Unbalanced '{close_char}' at position {i}"
    if count != 0:
      return f"Unbalanced '{open_char}' (net count: {count})"
    return None

  @classmethod
  def lint_query(cls, query):
    """Runs a suite of sanity lint checks on a PromQL query.

    Args:
        query: The PromQL query string to lint.

    Returns:
        A list of string lint error messages. Empty if valid.
    """
    errors = []

    # 1. Balanced parentheses
    paren_err = cls.check_balanced_chars(query, "(", ")")
    if paren_err:
      errors.append(f"Parentheses error: {paren_err}")

    # 2. Balanced curly braces
    brace_err = cls.check_balanced_chars(query, "{", "}")
    if brace_err:
      errors.append(f"Curly braces error: {brace_err}")

    # 3. Time window validations (such as [5m], [1w:5m], [3d], [1h])
    window_matches = re.finditer(r"\[([^\]]+)\]", query)
    for match in window_matches:
      window_str = match.group(1)
      if not re.fullmatch(r"\d+[smhdw](:(\d+[smhdw])?)?", window_str):
        errors.append(
            "Invalid Prometheus time window/subquery interval:"
            f" '[{window_str}]' at position {match.start()}"
        )

    # 4. Lookback offset range validation (such as offset 1w, offset 1d)
    offset_matches = re.finditer(r"\boffset\s+(\S+)", query)
    for match in offset_matches:
      offset_str = match.group(1)
      if not re.fullmatch(r"\d+[smhdw]", offset_str):
        errors.append(
            f"Invalid lookback offset format: 'offset {offset_str}' at position"
            f" {match.start()}"
        )

    # 5. Ensure the query references Kubernetes relevant labels in a label filter
    # or grouping aggregation.
    k8s_labels = [
        "cluster",
        "cluster_name",
        "namespace",
        "namespace_name",
        "pod",
        "pod_name",
        "container",
        "container_name",
        "service",
        "job",
        "node",
        "instance",
    ]

    has_k8s_reference = False
    for label in k8s_labels:
      if label in query:
        has_k8s_reference = True
        break

    if not has_k8s_reference:
      errors.append(
          "Query is missing Kubernetes-relevant resource references. It should "
          "reference at least one standard label like 'cluster', 'namespace', "
          "'pod', 'container', 'service', or 'job' in filters or groupings."
      )

    return errors


class HCLScanner:
  """Scanner for HCL alert policies."""

  @classmethod
  def extract_alert_policies(cls, hcl_content):
    """Extracts resource 'google_monitoring_alert_policy' blocks and metadata."""
    policies = []
    pattern = re.compile(
        r'resource\s+"google_monitoring_alert_policy"\s+"([^"]+)"\s*\{'
    )

    for match in pattern.finditer(hcl_content):
      resource_name = match.group(1)
      start_pos = match.start()

      brace_count = 0
      end_pos = -1
      in_string = False
      escape = False

      for i in range(match.end() - 1, len(hcl_content)):
        char = hcl_content[i]
        if escape:
          escape = False
          continue
        if char == "\\":
          escape = True
          continue
        if char == '"':
          in_string = not in_string
          continue
        if not in_string:
          if char == "{":
            brace_count += 1
          elif char == "}":
            brace_count -= 1
            if brace_count == 0:
              end_pos = i + 1
              break

      if end_pos == -1:
        continue

      block_content = hcl_content[start_pos:end_pos]

      # Extract display_name
      display_name_match = re.search(
          r'display_name\s*=\s*"([^"]+)"', block_content
      )
      display_name = display_name_match.group(1) if display_name_match else ""

      # Extract PromQL queries
      queries = [
          q.group(1)
          for q in re.finditer(
              r"query\s*=\s*<<-?EOT\n(.*?)\n\s*EOT",
              block_content,
              re.DOTALL,
          )
      ]
      if not queries:
        for q_match in re.finditer(
            r'query\s*=\s*"((?:[^"\\]|\\.)*)"', block_content
        ):
          raw_query = q_match.group(1)
          clean_query = re.sub(r'\\+"', '"', raw_query).replace("\\\\", "\\")
          queries.append(clean_query)

      # Extract threshold filters
      filters = []
      filter_matches = re.finditer(
          r'filter\s*=\s*"((?:[^"\\]|\\.)*)"', block_content
      )
      for f_match in filter_matches:
        filters.append(f_match.group(1))

      # Infer signal type
      signal_type = "unknown"
      res_lower, disp_lower = resource_name.lower(), display_name.lower()
      rules = [
          ("latency", "latency", "latency"),
          ("error", "error", "errors"),
          ("traffic", "traffic", "traffic"),
          ("saturation", "saturation", "saturation"),
          ("cpu", "cpu", "saturation_cpu"),
          ("memory", "memory", "saturation_memory"),
          ("crash", "crash", "health_crashloop"),
          ("ready", "ready", "health_ready"),
      ]
      for res_pat, disp_pat, sig in rules:
        if res_pat in res_lower or disp_pat in disp_lower:
          signal_type = sig
          break

      policies.append({
          "resource_name": resource_name,
          "display_name": display_name,
          "signal_type": signal_type,
          "queries": queries,
          "filters": filters,
          "start_pos": start_pos,
          "end_pos": end_pos,
          "block_content": block_content,
      })

    return policies


def validate_plan_file(plan_path):
  """Validates a pre-edit Plan JSON file (such as changes.json)."""
  errors = []
  try:
    with open(plan_path, "r") as f:
      plan_data = json.load(f)
  except Exception as e:
    return {
        "valid": False,
        "errors": [f"Failed to parse plan JSON file '{plan_path}': {e}"],
        "policies_scanned_count": 0,
        "duplicates_found": [],
    }

  policies = plan_data.get("policies", [])
  if not isinstance(policies, list) or not policies:
    errors.append(
        "Plan file must contain a non-empty 'policies' array of planned alert"
        " policy objects."
    )
    return {
        "valid": False,
        "errors": errors,
        "policies_scanned_count": 0,
        "duplicates_found": [],
    }

  target_map = {}
  duplicates = []

  for idx, p in enumerate(policies):
    res_name = p.get("resource_name", f"policy_{idx}")
    query = p.get("query", "")
    signal_type = p.get("signal_type", "unknown")
    duration = str(p.get("duration", "0s"))

    if not query:
      errors.append(f"Policy '{res_name}' is missing a required 'query' field.")
      continue

    # Lint query syntax
    lint_errs = PromQLLinter.lint_query(query)
    for err in lint_errs:
      errors.append(f"Lint error in planned policy '{res_name}': {err}")

    # Lookback vs Duration rule validation
    if re.search(r"\[(15m|30m|1h|6h|3d)\]", query) and duration not in [
        "0s",
        "60s",
        "0",
        "60",
    ]:
      errors.append(
          f"Duration warning in planned policy '{res_name}': Query uses"
          f" lookback aggregation but enforces long duration '{duration}'."
          " Expected '0s' or '60s' to prevent redundant delay."
      )

    # Check duplicates
    if signal_type != "unknown":
      if signal_type not in target_map:
        target_map[signal_type] = []
      target_map[signal_type].append(res_name)

  for signal_type, matched_names in target_map.items():
    if len(matched_names) > 1:
      duplicates.append({
          "signal_type": signal_type,
          "policies": matched_names,
      })
      errors.append(
          "Duplicate Plan Target: Multiple planned policies target"
          f" '{signal_type}': {matched_names}. Please consolidate them."
      )

  return {
      "valid": len(errors) == 0,
      "errors": errors,
      "policies_scanned_count": len(policies),
      "duplicates_found": duplicates,
  }


def validate_directory_tf_files(directory, expected_cluster_var=None):
  """Scans and validates all *.tf files in a given directory."""
  tf_files = glob.glob(os.path.join(directory, "*.tf"))
  all_errors = []
  all_policies = []
  duplicates = []
  target_map = {}

  for filepath in tf_files:
    filename = os.path.basename(filepath)
    try:
      with open(filepath, "r") as f:
        content = f.read()
    except Exception as e:
      all_errors.append(f"File error in '{filename}': {e}")
      continue

    policies = HCLScanner.extract_alert_policies(content)
    for policy in policies:
      policy["filename"] = filename
      all_policies.append(policy)

      for query in policy["queries"]:
        lint_errs = PromQLLinter.lint_query(query)
        for err in lint_errs:
          all_errors.append(
              f"Lint error in '{filename}' -> resource"
              f" '{policy['resource_name']}': {err}"
          )

      key = policy["signal_type"]
      if key not in target_map:
        target_map[key] = []
      target_map[key].append(policy)

  for signal_type, matches in target_map.items():
    if len(matches) > 1 and signal_type != "unknown":
      duplicates.append({
          "signal_type": signal_type,
          "policies": [
              {
                  "filename": p["filename"],
                  "resource_name": p["resource_name"],
                  "display_name": p["display_name"],
              }
              for p in matches
          ],
      })

  for dup in duplicates:
    policy_list = ", ".join(
        f"'{p['resource_name']}' in '{p['filename']}'" for p in dup["policies"]
    )
    all_errors.append(
        "Duplicate Target Error: Multiple alert policies are targeting the"
        f" same signal '{dup['signal_type']}': [{policy_list}]."
        " Please merge them or ensure they target different resources/labels."
    )

  return {
      "valid": len(all_errors) == 0,
      "errors": all_errors,
      "policies_scanned_count": len(all_policies),
      "duplicates_found": duplicates,
  }


def main():
  parser = argparse.ArgumentParser(
      description=(
          "Lints HCL alerts, pre-edit change plans, and PromQL query targets in"
          " Kubernetes tf templates."
      )
  )
  parser.add_argument(
      "--plan",
      type=str,
      help="Path to pre-edit change plan JSON file (such as changes.json).",
  )
  parser.add_argument(
      "--directory",
      type=str,
      default=".",
      help="Directory containing *.tf files to scan.",
  )
  parser.add_argument(
      "--cluster-var",
      type=str,
      default="${var.cluster_name}",
      help="The expected variable or literal for the cluster name.",
  )
  parser.add_argument(
      "--file",
      type=str,
      help="Validate a single specific HCL file instead of scanning directory.",
  )
  args = parser.parse_args()

  if args.plan:
    results = validate_plan_file(args.plan)
    print(json.dumps(results, indent=2))
    if not results["valid"]:
      sys.exit(1)
    sys.exit(0)

  if args.file:
    try:
      with open(args.file, "r") as f:
        content = f.read()
      policies = HCLScanner.extract_alert_policies(content)
      errors = []
      for p in policies:
        for q in p["queries"]:
          errors.extend(PromQLLinter.lint_query(q))
      if errors:
        print(f"Validation failed for '{args.file}':", file=sys.stderr)
        for err in errors:
          print(f"  - {err}", file=sys.stderr)
        sys.exit(1)
      else:
        print(f"Validation passed for '{args.file}'!")
        sys.exit(0)
    except Exception as e:
      print(f"Error reading file '{args.file}': {e}", file=sys.stderr)
      sys.exit(1)

  results = validate_directory_tf_files(args.directory, args.cluster_var)
  print(json.dumps(results, indent=2))
  if not results["valid"]:
    sys.exit(1)


if __name__ == "__main__":
  main()

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE