Installation

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

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

Install with the gh extension
gh skills-hub install gke-observability

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

Download and extract to your repository:

.github/skills/gke-observability/

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

Skill Files (5)

SKILL.md 13.3 KB
---
name: gke-observability
description: >-
  Configures GKE observability, including Cloud Logging, Cloud Monitoring, and
  managed Prometheus. Use when configuring GKE monitoring, setting up GKE
  logging, or configuring Prometheus metrics collection, to diagnose GKE control
  plane, API server, admission webhook, etcd storage, node registration or
  label, and pod eviction, preemption, or scheduling issues using GKE metrics,
  Kubernetes events, and Cloud Logging, and to troubleshoot Managed Service for
  Prometheus (GMP) issues such as missing metrics, unhealthy scrape targets,
  PodMonitoring misconfiguration, rule/alert evaluation failures, and monitoring
  permission errors. Don't use to configure local application logging frameworks
  or external APMs outside GKE.
metadata:
  version: "1.2.1"
  category: CloudObservabilityAndMonitoring
---

# GKE Observability

This reference covers monitoring, logging, and metrics configuration and
troubleshooting for Google Kubernetes Engine (GKE). The golden path enables
comprehensive observability including control-plane metrics and Managed Service
for Prometheus (GMP).

> **MCP Tools:** `get_cluster`, `list_k8s_events`, `get_k8s_logs`,
> `get_k8s_cluster_info`, `describe_k8s_resource`. **CLI-only:** `gcloud
> container clusters update --monitoring=...`, `gcloud logging read`

## Usage Attribution

Do not run live `kubectl`, `gcloud`, or `curl` commands unless the user names a
target cluster/project or asks to inspect a live cluster (output commands and
queries with placeholders, and skip [Usage Attribution](references/attribution.md)).
Before running any live command, read [Usage Attribution](references/attribution.md),
prefix `gcloud` with `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gke-observability)"`,
and append `agent-skills/1.0 (skill:gke-observability)` to `User-Agent` headers
(never in generated scripts, Terraform, or user-facing code).

## Sub-Skill Reference Routing (Progressive Disclosure)

> **Complete Reference Index** (no `scripts/` directory or unlisted reference
> files exist — do not run `ls` on the skill folder; read only the matching
> reference below when answering deep diagnostic, metric, log, or GMP questions):

1.  **[Control-Plane Metrics, Storage, Webhooks & Capacity](references/control-plane-metrics-and-storage.md)**:
    Read for GKE control-plane (KCP) VM CPU or RAM/memory usage questions (not
    publicly exposed) and customer-visible alternatives; cluster etcd /
    etcd-compatible storage left, quota & per-resource scalability limits;
    admission webhook latency, system namespace/Lease/upgrade exclusions,
    `APIService` discovery bloat, client discovery caching bursts
    (`/apis/custom.metrics.k8s.io`, `/apis/metrics.k8s.io`) & proactive GKE
    Recommender insights; watch storms; controller-manager workqueue & scheduler
    lag; or control-plane headroom, VM autoscaling & node-count pre-scaling,
    network egress, connections (`65k`, no per-replica metric) & Protobuf.
2.  **[Cloud Logging, Audit Attribution, APF & API Server Traces](references/logging-audit-and-apiserver-traces.md)**:
    Read for `kube-apiserver` slow-request `Trace[` logs (`trace.go` & KEP-647);
    `httplog.go` client load (`user_agent`, `verb`, `apf_iseats`); Cloud Audit
    Log noisy-neighbor, heavy `LIST` & unindexed CRD `fieldSelector` scan
    tail-latency attribution; API Priority and Fairness (APF) `429`/`504`/`404`
    throttling; `409 Conflict` hot objects (`ConfigMap` -> `Lease` heartbeats) &
    `RenewDeadline / 2` leader-election timeouts; `pods/exec` saturation,
    Konnectivity (`No agent available`), disabled Cloud KMS keys, or in-cluster
    GCP IAM OAuth token webhook authorizer saturation.
3.  **[Cluster/Node/Pod Health, Maintenance & Managed Prometheus (GMP)](references/cluster-node-pod-health-and-gmp.md)**:
    Read for control-plane availability (`kubernetes.io/cluster/kcp_healthchecks`
    rate ratio & ruling out KCP outages); maintenance windows
    (`in_maintenance_window`), zonal resize downtime & cluster access errors
    (`EOF` / `masterAuthorizedNetworksConfig`); node readiness, registration
    (`AUTO_REPAIR_NODES`, Private Google Access) & persistent node-pool labels;
    pod startup timelines, crashing pod logs, `tolerationSeconds: 0` mass
    eviction & Autopilot preemption; or multi-burn-rate SLO alerting
    (`GlobalRules`) & GMP / Grafana / `PodMonitoring` manifests & troubleshooting.

## Golden Path Observability Defaults

Setting                                             | Golden Path Value                                                                                                                                   | Notes
--------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -----
`loggingConfig` components                          | SYSTEM_COMPONENTS, WORKLOADS                                                                                                                        | Full workload logging
`monitoringConfig` components                       | SYSTEM_COMPONENTS, STORAGE, POD, DEPLOYMENT, STATEFULSET, DAEMONSET, HPA, JOBSET, CADVISOR, KUBELET, DCGM, APISERVER, SCHEDULER, CONTROLLER_MANAGER | Full suite including control-plane
`managedPrometheusConfig.enabled`                   | `true`                                                                                                                                              | Google-managed Prometheus
`advancedDatapathObservabilityConfig.enableMetrics` | `true`                                                                                                                                              | Dataplane V2 flow metrics
`loggingService`                                    | `logging.googleapis.com/kubernetes`                                                                                                                 | Cloud Logging
`monitoringService`                                 | `monitoring.googleapis.com/kubernetes`                                                                                                              | Cloud Monitoring

## Enabling Full Monitoring & Logging

Include all four caveats whenever providing a `--monitoring` or `--logging`
command so users avoid accidental metric loss, surprise billing, or silent IAM
failures:

1.  **Control-plane metrics and logs are NOT enabled by default.** State this
    outright: `API_SERVER`, `SCHEDULER`, and `CONTROLLER_MANAGER` are off on
    every new cluster (as are `DCGM`, `CADVISOR`, `KUBELET`, and kube-state
    `POD`, `DEPLOYMENT`, `STATEFULSET`, `DAEMONSET`, `HPA`, `STORAGE`,
    `JOBSET`). Only `SYSTEM` is enabled by default. Link to
    https://docs.cloud.google.com/kubernetes-engine/docs/how-to/control-plane-metrics
    and
    https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs#control_plane_logs.
2.  **The flag replaces, it does not append.** Passing `--monitoring` or
    `--logging` overrides the existing component list; pass the full desired
    list including `SYSTEM`.
3.  **Control-plane and kube-state metrics bill per sample ingested** via
    Managed Service for Prometheus (GMP). Mention the cost impact on large
    clusters; use `--monitoring=SYSTEM` in non-production to reduce cost.
4.  **Verify APIs and IAM permissions (`PermissionDenied`).** Check `gcloud
    container clusters describe {cluster_name} --region {region}
    --format="yaml(loggingConfig,monitoringConfig)"`, ensure
    `logging.googleapis.com` and `monitoring.googleapis.com` are enabled, and
    verify the node service account / GKE service agent has
    `roles/monitoring.metricWriter` and
    `roles/container.defaultNodeServiceAgent`.

> **CLI flag vs. API enum spelling (mixing them fails the command):**
>
> Component      | `gcloud --monitoring=` | `monitoringConfig` API enum
> -------------- | ---------------------- | ---------------------------
> System         | `SYSTEM`               | `SYSTEM_COMPONENTS`
> API server     | `API_SERVER`           | `APISERVER`
> Controller mgr | `CONTROLLER_MANAGER`   | `CONTROLLER_MANAGER`

```bash
# Enable golden path monitoring and control-plane logging suite
gcloud container clusters update {cluster_name} --region {region} \
  --monitoring=SYSTEM,API_SERVER,SCHEDULER,CONTROLLER_MANAGER,STORAGE,POD,DEPLOYMENT,STATEFULSET,DAEMONSET,HPA,JOBSET,CADVISOR,KUBELET,DCGM \
  --logging=SYSTEM,WORKLOAD,API_SERVER,SCHEDULER,CONTROLLER_MANAGER \
  --quiet

# Enable Managed Prometheus and Dataplane V2 flow/policy observability
gcloud container clusters update {cluster_name} --region {region} \
  --enable-managed-prometheus \
  --enable-dataplane-v2-flow-observability \
  --quiet
```

## Core GKE Metrics & Alerting Baseline

Explicitly name **Google Cloud Monitoring** when proposing dashboards and
alerts, and cover cluster/node CPU and memory capacity, pod restarts
(`CrashLoopBackOff`), volume space exhaustion, and API server latency
(`apiserver_request_duration_seconds`). Direct control-plane VM CPU/RAM metrics
are not publicly exposed — read
[Control-Plane Metrics, Storage, Webhooks & Capacity](references/control-plane-metrics-and-storage.md)
whenever asked about control-plane VM CPU/memory or deep control-plane metrics.

Metric                                           | Source             | Use / Alert Threshold
------------------------------------------------ | ------------------ | ---------------------
`apiserver_request_duration_seconds`             | API Server (GMP)   | Control-plane latency (Alert: P99 > 5s)
`scheduler_scheduling_attempt_duration_seconds`  | Scheduler (GMP)    | Current GKE scheduling latency (`scheduler_schedule_attempts_total{result="error"} > 0`)
`container_cpu_usage_seconds_total`              | cAdvisor (Node)    | Worker-node container CPU usage
`container_memory_working_set_bytes`             | cAdvisor (Node)    | Worker-node container memory usage
`kubernetes.io/node/cpu/core_usage_time`         | Cloud Monitoring   | Node CPU usage (`kubernetes.io/node/memory/used_bytes` for memory)
`kube_pod_status_phase`                          | kube-state-metrics | Pod lifecycle phase (requires deploying GMP or self-managed kube-state-metrics)
`kube_pod_container_status_restarts_total`       | kube-state-metrics | Pod crash loops (Alert: > 5 in 10m; requires kube-state-metrics)
`kube_node_status_condition`                     | kube-state-metrics | Node readiness (`condition="Ready", status!="True"`; or `kubernetes.io/node/status_condition`)
`kubelet_volume_stats_used_bytes / capacity`     | Kubelet            | PVC capacity utilization (Alert: > 85%)
`DCGM_FI_DEV_GPU_UTIL`                           | DCGM (GMP)         | GPU utilization (Alert: > 95% sustained)

## Live Resource Usage & Cloud Logging Queries

Use `kubectl top` for live usage (no MCP or `gcloud` equivalent):

```bash
kubectl top pods --all-namespaces --sort-by=cpu
kubectl top nodes
kubectl top pods --containers -n {namespace}
```

Use `gcloud logging read` (or Cloud Logging Log Explorer) with LQL filters:

```bash
# Control-plane component logs (requires API_SERVER / SCHEDULER / CONTROLLER_MANAGER enabled)
gcloud logging read 'resource.type="k8s_control_plane_component" AND resource.labels.cluster_name="{cluster_name}"' --project {project_id} --limit 50 --quiet

# Container errors: resource.type="k8s_container" AND resource.labels.container_name="{container_name}" AND severity>=ERROR
# OOMKilled events: resource.type="k8s_event" AND jsonPayload.reason="OOMKilling"
# FailedScheduling: resource.type="k8s_event" AND jsonPayload.reason="FailedScheduling"
# Cloud Audit Logs: resource.type="k8s_cluster" AND logName:"cloudaudit.googleapis.com"
# Dataplane V2 network policy / packet drop logs: logName:"policy_action" AND jsonPayload.disposition="DENY"
```

## Distributed Tracing, Profiling & Recent Additions

-   **Cloud Trace & OpenTelemetry**: Deploy the OpenTelemetry Collector
    (`googlecloud` exporter with Workload Identity) or enable **Managed
    OpenTelemetry for GKE (Preview)** on GKE 1.34.1-gke.2178000+ (`gcloud beta
    container clusters update {cluster_name} --region {region}
    --managed-otel-scope=COLLECTION_AND_INSTRUMENTATION_COMPONENTS`).
-   **Cloud Profiler**: Continuous low-overhead production CPU/memory profiling.
-   **PSI (Pressure Stall Information) metrics**: cAdvisor
    `container_pressure_{cpu,memory,io}_{waiting,stalled}_seconds_total` via GMP
    `ClusterNodeMonitoring` (GKE 1.35+).

## Supporting Links

-   [GKE System Metrics](https://docs.cloud.google.com/monitoring/api/metrics_kubernetes)
-   [GKE Control-Plane Metrics](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/control-plane-metrics)
-   [GKE Control-Plane Logs](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs#control_plane_logs)
-   [Google Cloud Managed Service for Prometheus](https://cloud.google.com/stackdriver/docs/managed-prometheus)
-   [Troubleshoot Managed Service for Prometheus](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/troubleshooting.md.txt)
-   [Rule Evaluation (Rules / ClusterRules / GlobalRules)](https://docs.cloud.google.com/stackdriver/docs/managed-prometheus/rules-managed.md.txt)
-   [Cloud Logging Query Language (LQL)](https://cloud.google.com/logging/docs/view/logging-query-language)
-   [Google Cloud Monitoring Alerts](https://cloud.google.com/monitoring/alerts)
references/
attribution.md 1.8 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-observability)" \
    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-observability)` 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-observability)
    ```

-   **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.
cluster-node-pod-health-and-gmp.md 12.9 KB
# Cluster/Node/Pod Health, Maintenance & Managed Prometheus (GMP)

## Table of Contents

-   **1. Control-Plane Health (`kcp_healthchecks`) & Maintenance Windows** (Lines 10–65)
-   **2. Node Health, Registration Failures & Persistent Node Labels** (Lines 67–99)
-   **3. Pod Startup Timeline, Mass Evictions & Autopilot Preemption** (Lines 101–128)
-   **4. Multi-Burn-Rate SLO Alerting & GMP Troubleshooting** (Lines 130–204)

## 1. Control-Plane Health (`kcp_healthchecks`) & Maintenance Windows

To check whether Google considers a GKE cluster's control plane healthy, use the
**`kubernetes.io/cluster/kcp_healthchecks`** system metric (on the `k8s_cluster`
monitored resource, included in the default `SYSTEM` metrics package):

1.  **Metric semantics & rate-ratio query**: `kubernetes.io/cluster/kcp_healthchecks`
    is an incremental (`DELTA` / `CUMULATIVE` counter) metric sampled every 60s
    that counts Google-internal control-plane probes, labeled by boolean
    `success` (`"true"` or `"false"`). Chart or alert on control-plane
    availability by dividing the rate of successful checks (`success="true"`) by
    the overall rate of checks across all `success` values:

    ```promql
    sum by (project_id, location, cluster_name) (rate(kubernetes_io:cluster_kcp_healthchecks{monitored_resource="k8s_cluster", success="true"}[5m]))
    / sum by (project_id, location, cluster_name) (rate(kubernetes_io:cluster_kcp_healthchecks{monitored_resource="k8s_cluster"}[5m]))
    ```

2.  **Ruling out a GKE control-plane outage (`kcp_healthchecks` innocence)**:
    Check `kubernetes.io/cluster/kcp_healthchecks` (rate ratio) alongside
    `apiserver_request_duration_seconds` and `apiserver_request_total`
    (`code="429"` / `5xx`) in Cloud Monitoring. When `kcp_healthchecks` and API
    server latency are healthy with no `429` throttling, slow pod deletions or
    client delays originate from client-side request concurrency, pod
    finalizers/graceful termination, or the customer's own pod-creating service
    rather than a GKE control-plane fault.
3.  **Maintenance windows, zonal resize downtime & cluster access errors**:
    -   **Maintenance window metrics & policy limits**: Query
        `kubernetes.io/cluster/in_maintenance_window` (boolean `GAUGE` on
        `monitored_resource="k8s_cluster"`, included in default `SYSTEM`
        metrics; PromQL:
        `kubernetes_io:cluster_in_maintenance_window{monitored_resource="k8s_cluster"}`)
        in Cloud Monitoring and correlate with `gcloud container operations list`
        (or Cloud Audit Logs for `RESIZE_CLUSTER` or `UPGRADE_MASTER`) to verify
        whether brief API unavailability, blocked updates, or lease-loss alerts
        occurred during scheduled maintenance. Move the maintenance window to a
        lower-traffic period or use `kubernetes.io/cluster/in_maintenance_window`
        to suppress transient alerts. Ensure maintenance windows/exclusions do
        not violate GKE limits (see
        https://docs.cloud.google.com/kubernetes-engine/docs/concepts/maintenance-windows-and-exclusions#limitations-maint-exclusions,
        requiring at least 48 hours of total maintenance availability in any
        32-day (and 92-day) rolling window, in contiguous blocks of at least 4
        hours) so routine control-plane upgrades and repairs are not blocked.
    -   **Zonal resize downtime vs. access errors (`EOF` / `CLOUD_KMS_KEY_ERROR`)**:
        Correlate `kubernetes.io/cluster/kcp_healthchecks` and
        `kubernetes.io/cluster/in_maintenance_window` with `gcloud container
        operations list` (`RESIZE_CLUSTER` or `UPGRADE_MASTER`): **zonal
        clusters** have a single control-plane replica that experiences expected
        15–30 minute API downtime during resizes and upgrades (mitigate by
        migrating to a regional cluster). If `kubectl` fails with `EOF` or
        `CLOUD_KMS_KEY_ERROR`, check `gcloud container clusters describe
        {cluster_name}` (`masterAuthorizedNetworksConfig`, `databaseEncryption`,
        and cluster conditions) and project IAM/APIs to resolve client IP
        allowlist blocks (`EOF`), disabled Cloud KMS keys
        (`CLOUD_KMS_KEY_ERROR`), a disabled `container.googleapis.com` API, or
        missing GKE service agent IAM bindings.

## 2. Node Health, Registration Failures & Persistent Node Labels

When proposing node health charts, combine both metrics below and **state both
metrics' limitations explicitly** (neither metric is complete alone):

1.  **`kubernetes.io/node/status_condition`** (on `monitored_resource="k8s_node"`,
    filtered by `condition="Ready"` / `status_condition="Ready"`, grouped by
    `status` = `True` / `False` / `Unknown`; PromQL: `count by (status)
    (kubernetes_io:node_status_condition{monitored_resource="k8s_node",
    condition="Ready"})`): Tracks healthy vs. unhealthy registered nodes, **but
    only reports values for nodes that have successfully bootstrapped** (missing
    VMs stuck failing registration).
2.  **`compute.googleapis.com/instance_group/size`** (on `gce_instance_group`,
    filtered by `instance_group_name="gke-<cluster_name>-.*"`): Tracks the total
    number of GCE nodes in the cluster, **but does not differentiate between
    healthy and unhealthy nodes** (so comparing `instance_group/size` against
    `status_condition="Ready"` is required to spot unbootstrapped VMs).
3.  **Node registration failures (`AUTO_REPAIR_NODES`)**: When new node pools
    fail registration before reporting `kubernetes.io/node/status_condition`,
    query the consumer project's Cloud Audit Logs
    (`cloudaudit.googleapis.com/activity`) for GCE instance creation denials
    (`403` / `constraints/gcp.resourceLocations`), verify Private Google Access
    (`privateIpGoogleAccess`) is enabled on the cluster subnet, and check VPC
    routes/firewall rules so traffic to `*.googleapis.com`, `*.gcr.io`, and
    `*.pkg.dev` is not blackholed into a custom VPN or firewall.
4.  **Node labels overwritten on upgrade (`kubectl label node` vs. Node Pool
    API)**: `gcp-controller-manager` reconciles node labels declared in the GKE
    Node Pool API specification during control-plane upgrades and node repairs
    (visible as `system:gcp-controller-manager` node patches in Cloud Audit
    Logs), reverting manual `kubectl label node {node_name} {key}={val}
    --overwrite` edits on GKE-managed label keys. Update node pool labels
    persistently via `gcloud container node-pools update {pool_name}
    --node-labels=...` (or Terraform `node_config.labels`).

## 3. Pod Startup Timeline, Mass Evictions & Autopilot Preemption

-   **End-to-end pod startup lifecycle & crashing pods**: To pinpoint whether a
    slow-starting pod was delayed during controller creation, scheduling,
    `kubelet` pickup, or container startup, correlate Kubernetes Events
    (`resource.type="k8s_pod"` or `k8s_event`) with Cloud Audit Logs
    (`cloudaudit.googleapis.com/activity`), optional control-plane component
    logs (`kube-scheduler`, `kube-controller-manager`, `kube-apiserver` under
    `resource.type="k8s_control_plane_component"`), and node `kubelet` logs
    (`resource.type="k8s_node"`). For crashing pods, run `kubectl logs
    {pod_name} --previous` (or `-p`), `kubectl describe pod {pod_name}`, and
    query Cloud Logging (`resource.type="k8s_container"`).
-   **`tolerationSeconds: 0` mass pod eviction**: If pods are simultaneously
    evicted during a brief control-plane hiccup when nodes briefly enter
    `NodeStatusUnknown`, inspect workload Pod/Deployment specs (`kubectl get
    deploy -o yaml`) for custom `tolerations` on
    `node.kubernetes.io/unreachable` (`NoExecute`) and
    `node.kubernetes.io/not-ready` (`NoExecute`) with `tolerationSeconds: 0`
    (which overrides Kubernetes's default 300s eviction grace period), and
    remove the `tolerationSeconds: 0` override.
-   **Autopilot single-node bin-packing & system-addon preemption**: If all
    replicas of a Deployment pack onto a single node at its `maxPods` limit
    (`32/32` on Autopilot), surging `system-cluster-critical` addons (priority
    `2000000000`) during a control-plane upgrade trigger scheduler preemption,
    which bypasses `PodDisruptionBudget` when no other capacity is immediately
    available. Configure `topologySpreadConstraints` or `podAntiAffinity` across
    nodes/zones so replicas never co-locate on a single node, and assign an
    appropriate `PriorityClass`.

## 4. Multi-Burn-Rate SLO Alerting & GMP Troubleshooting

### Prometheus / Grafana / PagerDuty Control-Plane SLO Alerting

When generating Grafana dashboards and multi-burn-rate Prometheus alert rules
for GKE control-plane health (routed to PagerDuty or Slack via Alertmanager or
Cloud Monitoring notification channels; output YAML/JSON directly inline without
scratch generator scripts), use `GlobalRules` (`monitoring.googleapis.com/v1`,
required when evaluating against Cloud Monitoring / GMP system metrics) covering
`apiserver_request_duration_seconds` (e.g., fast `5m`/`1h` 14.4x + slow
`30m`/`6h` 6x burn rates), `apiserver_admission_webhook_admission_duration_seconds`,
`apiserver_flowcontrol_rejected_requests_total`, and storage utilization
(`kubernetes_io:cluster_storage_used_bytes / kubernetes_io:cluster_storage_limit_bytes`
or `apiserver_storage_size_bytes`), queried in Grafana via the GMP data source
(`GET` HTTP method and two-argument `label_values(<metric>, <label>)`).
**Always state explicitly that GKE control-plane `apiserver_*` metrics are NOT
enabled by default**, and instruct how to enable them (`gcloud container
clusters update {cluster_name} --region {region}
--monitoring=SYSTEM,API_SERVER,SCHEDULER,CONTROLLER_MANAGER,...
--enable-managed-prometheus`, noting `--monitoring` replaces the existing list).

### Troubleshooting Managed Service for Prometheus (GMP)

Stay read-only (`kubectl get` / `describe` / `logs`) and propose config changes:

1.  **First: split ingestion-side vs. query-side**: Query `up` in the **Metrics
    Explorer PromQL tab** in Cloud Monitoring. If `up` returns data, ingestion
    works and the issue is query-side (Grafana / PromQL / permissions). If `up`
    is empty, the issue is ingestion-side (collectors, scrape config, or write
    IAM).
2.  **Ingestion-side checks**:
    -   **GMP system pods**: Verify GMP is active via `gcloud container clusters
        describe {cluster_name}` and inspect pods in `gmp-system` (Standard) or
        `gke-gmp-system` (Autopilot) (`gmp-operator`, `collector` DaemonSet, and
        `rule-evaluator`):
        ```bash
        kubectl get pods -n gmp-system            # gke-gmp-system on Autopilot
        kubectl logs -n gmp-system -l app.kubernetes.io/name=collector -c prometheus
        ```
        A `collector` in `CrashLoopBackOff` with `OOMKilled` indicates high
        cardinality—drop unneeded series/labels via `metricRelabeling` or apply
        a VPA.
    -   **`PodMonitoring` vs. `ClusterPodMonitoring`**: Always write `PodMonitoring`
        manifests with `apiVersion: monitoring.gke.io/v1` (`kind: PodMonitoring`
        is namespace-scoped; `ClusterPodMonitoring` is cluster-wide), setting
        `spec.selector.matchLabels` to match pod labels and `spec.endpoints`
        with `port` (container port name or number), `path` (e.g., `/metrics`),
        and `interval` (e.g., `30s`).
    -   **Target status debugging**: Temporarily patch `OperatorConfig` in
        `gmp-public` with `features.targetStatus.enabled: true`, run `kubectl
        describe podmonitoring {name}` (`Active Targets`, `Unhealthy Targets`,
        `Last Error`), then disable to prevent operator OOMs on large clusters.
3.  **Permissions (`403` / `PermissionDenied`)**: GMP inherits the **node
    service account**. Ingestion requires `roles/monitoring.metricWriter`
    (`Permission monitoring.timeSeries.create denied` in collector logs);
    `rule-evaluator` and query paths (including Grafana via Workload Identity)
    require `roles/monitoring.viewer`.
4.  **Rule & alert evaluation (`Rules` / `ClusterRules` / `GlobalRules`)**: Use
    `GlobalRules` to evaluate rules against Cloud Monitoring system/control-plane
    metrics (`Rules` and `ClusterRules` silently return no data for them). Check
    `rule-evaluator` logs (`-c evaluator`).
5.  **Query-side (Grafana / PromQL)**:
    -   Point the Grafana data source at the GMP frontend query proxy (not
        `localhost:9090`) and set **HTTP Method to `GET`** (`POST` fails with
        `no match[] parameter provided`).
    -   Use the two-argument `label_values(<metric>, <label>)` in Grafana
        template variables (single-argument `label_values(<label>)` is
        unsupported by GMP).
    -   Include a `monitored_resource` label matcher when querying Cloud
        Monitoring metrics that exist across multiple resource types.
6.  **Cost, cardinality & quota (`429` / `RESOURCE_EXHAUSTED`)**: Inspect Cloud
    Monitoring **Metrics Management** to find top billable/high-cardinality
    metrics. Prune with `metricRelabeling` (`action: drop` or `action:
    labeldrop` for unbounded labels like `user_id`/`request_id`) or raise the
    scrape `interval` before requesting quota increases.
control-plane-metrics-and-storage.md 14.2 KB
# Control-Plane Metrics, Storage, Webhooks & Capacity

## Table of Contents

-   **1. Control-Plane Metrics Prerequisites & KCP VM Boundaries** (Lines 13–34)
-   **2. Etcd-Compatible Storage Backend & Remaining-Capacity Queries** (Lines 36–52)
-   **3. Real-Time Storage Quota Alerts, Per-Resource Footprint & Cleanup** (Lines 54–92)
-   **4. Admission Webhooks, Exclusions, Discovery & Recommendations** (Lines 94–159)
-   **5. Watch Activity & Watch Storms** (Lines 161–167)
-   **6. Pod Churn, Controller-Manager Workqueues & Scheduler Lag** (Lines 169–187)
-   **7. Control-Plane Headroom, Network Egress, Connections & Protobuf** (Lines 189–224)

## 1. Control-Plane Metrics Prerequisites & KCP VM Boundaries

> **Control-plane (KCP) VM CPU and RAM/memory usage are not publicly exposed:**
> GKE manages control-plane VMs internally and exposes **no** KCP VM CPU or
> RAM/memory usage metrics in Cloud Monitoring (`kubernetes.io/cluster/*`,
> `kubernetes.io/master/*`, or worker-node-only `kubernetes.io/node/*` /
> `container_*`) or Managed Service for Prometheus. Instead of KCP VM CPU,
> monitor `kubernetes.io/cluster/kcp_healthchecks`,
> `apiserver_request_duration_seconds`, and APF concurrency saturation
> (`apiserver_flowcontrol_priority_level_seat_utilization` and
> `apiserver_current_inflight_requests`). Instead of KCP VM RAM/memory, monitor
> `apiserver_resource_size_estimate_bytes`, `apiserver_storage_size_bytes`
> (`kubernetes.io/cluster/storage/used_bytes` and
> `kubernetes.io/cluster/storage/limit_bytes`), and
> `kubernetes.io/cluster/kcp_healthchecks`.

Whenever recommending any `apiserver_*`, `scheduler_*`, `workqueue_*`, or
`job_controller_*` metric below, state that it is a Managed Service for
Prometheus (GMP) control-plane metric that is **not enabled by default**
(requires `--monitoring=SYSTEM,API_SERVER,SCHEDULER,CONTROLLER_MANAGER,...` and
`--enable-managed-prometheus`; see `SKILL.md` for CLI vs. API enum spellings)
and link to https://docs.cloud.google.com/kubernetes-engine/docs/how-to/control-plane-metrics.

## 2. Etcd-Compatible Storage Backend & Remaining-Capacity Queries

In self-managed Kubernetes, operators check remaining `etcd` space via `etcdctl
endpoint status` or raw `etcd` metrics (`etcd_mvcc_db_total_size_in_bytes`,
`etcd_server_quota_backend_bytes`). **GKE uses a managed etcd-compatible
storage** backend for cluster state and does not expose `etcdctl` or raw
`etcd_*` server metrics—always state explicitly that **GKE uses an
etcd-compatible storage** backend when answering cluster `etcd` storage
questions. Instead, query the default Cloud Monitoring `SYSTEM` metrics
**`kubernetes.io/cluster/storage/used_bytes`** and
**`kubernetes.io/cluster/storage/limit_bytes`** on `monitored_resource="k8s_cluster"`
(enabled out-of-the-box without `API_SERVER` or GMP opt-in):

```promql
# Remaining control-plane storage bytes (divide used_bytes / limit_bytes for utilization ratio)
kubernetes_io:cluster_storage_limit_bytes{monitored_resource="k8s_cluster"} - kubernetes_io:cluster_storage_used_bytes{monitored_resource="k8s_cluster"}
```

## 3. Real-Time Storage Quota Alerts, Per-Resource Footprint & Cleanup

-   **Real-time storage utilization vs. 6h quota delay**: In Cloud Monitoring,
    `kubernetes.io/cluster/storage/used_bytes` and
    `kubernetes.io/cluster/storage/limit_bytes` sample every 60s (avoiding the
    6-hour delay of GCP quota metrics; opt-in GMP also exposes
    `apiserver_storage_size_bytes`). Configure an alert when `used_bytes /
    limit_bytes` approaches capacity on GKE's etcd-compatible control-plane
    datastore so leaked Pods, Jobs, or Secrets are pruned before `etcdserver:
    mvcc: database space exceeded` write locks occur.
-   **Per-resource byte footprint & GKE scalability limits**: Query
    `apiserver_resource_size_estimate_bytes` (or
    `kubernetes.io/master/apiserver/resource_size_estimate_bytes`) and
    `apiserver_storage_objects` grouped by `group` and `resource` to find which
    resource types or CRDs consume the most storage bytes. Compare against GKE
    scalability limits
    (https://cloud.google.com/kubernetes-engine/docs/concepts/planning-large-clusters:
    keep total Pod or ReplicaSet state below ~800 MiB per resource type, keep
    individual ConfigMaps/Secrets below 1 MiB vs. the 1.5 MiB etcd hard limit,
    and stay below ~30,000 Secrets/ConfigMaps).
-   **Quota exhaustion (`mvcc: database space exceeded`) & CRD bloat cleanup**:
    When creations, updates, or Lease renewals fail with `etcdserver: mvcc:
    database space exceeded`, delete bloated objects in small paced batches:
    -   **Version behavior on failing deletes**: State explicitly that while
        some earlier GKE versions blocked all edits (including deletes) on
        hitting storage quota, this is no longer the case in newer GKE versions
        (`kubectl delete` remains permitted).
    -   Finished `batch/v1` Jobs and CronJob pods (`concurrencyPolicy: Allow`):
        set `.spec.ttlSecondsAfterFinished` on Jobs and
        `successfulJobsHistoryLimit` / `failedJobsHistoryLimit` on CronJobs;
        retained ReplicaSets (lower `.spec.revisionHistoryLimit`), Kyverno
        `admissionreports`, oversized Secrets/ConfigMaps, or stuck finalizers.
-   **Excessive `VolumeSnapshot` objects hanging `LIST` (<50,000 limit)**: When
    new `VolumeSnapshot` objects take 30+ minutes to become ready or deleted
    snapshots stay stuck in `Terminating`, check `apiserver_storage_objects` and
    `apiserver_resource_size_estimate_bytes` (plus `kube-apiserver` slow `LIST`
    `Trace[` logs) for `volumesnapshots` and `volumesnapshotcontents` causing
    `snapshot-controller` `LIST` timeouts; prune old snapshots and enforce a
    retention policy keeping the total count well below 50,000.

## 4. Admission Webhooks, Exclusions, Discovery & Recommendations

-   **Measuring webhook latency & errors**: When API calls or pod creations time
    out (`context deadline exceeded`), query
    `apiserver_admission_webhook_admission_duration_seconds` (grouped by `name`,
    `type`, `operation`, and `rejected`) and
    `apiserver_admission_webhook_rejection_count` alongside `kube-apiserver`
    slow-request `Trace[` logs, GKE Webhook Insights (`Verify webhook with
    unavailable endpoints`), and `kubernetes.io/cluster/kcp_healthchecks` (to
    verify the GKE control plane itself is healthy before requesting an upsize).
    Scale/fix backing webhook pods, tighten `timeoutSeconds` (e.g., 2–5s), scope
    `namespaceSelector`, or set `failurePolicy: Ignore` where appropriate.
-   **System namespace & Lease exclusions (preventing controller leadership loss
    & CNI `NotReady` nodes)**: Inspect `ValidatingWebhookConfiguration` and
    `MutatingWebhookConfiguration` rules. Exclude `kube-system` and
    `kube-node-lease` via `namespaceSelector` on third-party webhooks (Kyverno,
    Datadog, Vault, OpenTelemetry, or OPA Gatekeeper's
    `admission.gatekeeper.sh/ignore` label) and remove `coordination.k8s.io`
    `leases` (`coordination.k8s.io/leases`) from webhook rules so slow/crashed
    webhooks never block controller Lease renewals or `kube-system` CNI pods
    (`netd`, `anetd`, leaving new nodes stuck `NotReady` with `CNI plugin not
    initialized`).
-   **Control-plane upgrade failures & addon deadlocks**: When upgrades fail and
    roll back or Cluster Autoscaler stops initializing after an upgrade with
    `failurePolicy: Fail` webhooks, check Cloud Audit Logs or webhook
    metrics/logs during the upgrade window for denied/timed-out requests from
    `system:apiserver` (on `rbac.authorization.k8s.io/clusterrolebindings`) or
    `system:addon-manager` (on system `customresourcedefinitions` such as
    `capacitybuffers.autoscaling.x-k8s.io`). Exempt `rbac.authorization.k8s.io`
    bootstrap bindings and GKE system CRDs (`*.gke.io`, `autoscaling.x-k8s.io`)
    from webhook rules or set `failurePolicy: Ignore`.
-   **Unavailable webhook endpoints, OOMKilled pods, `APIService` & discovery**:
    -   Inspect `MutatingWebhookConfiguration` / `ValidatingWebhookConfiguration`
        service references, verify `EndpointSlice` addresses match running pod
        IPs, inspect CRD conversion webhooks (`spec.conversion.webhook`), and
        check backing pod health and OOM kills (`jsonPayload.reason="OOMKilling"`,
        `kubectl describe pod {pod_name}`, `kubectl logs {pod_name} --previous`).
        Increase memory limits on OOMKilled webhook pods (e.g., Gatekeeper or
        Kubeflow `cache-server`), fix the deployment, or scope
        rules/`failurePolicy`.
    -   When every `kubectl` command takes 15–30s, run `kubectl get apiservices`
        and `kubectl --v=6` alongside `apiserver_response_sizes` and
        `apiserver_request_duration_seconds` to spot unavailable `APIService`
        backends or multi-megabyte discovery documents from aggregated APIs
        (`custom.metrics.k8s.io`, `external.metrics.k8s.io`). Disable or filter
        unbounded custom metrics exporters (e.g., Airflow or Prometheus adapters
        exporting thousands of series into API discovery).
    -   When custom scripts, cron jobs, or CLI invocations flood
        `/apis/custom.metrics.k8s.io` and `/apis/metrics.k8s.io` with thousands
        of requests per minute (visible in Cloud Audit Logs / `httplog.go`
        `userAgent` and `apiserver_request_total`), clients are polling API
        discovery without a persistent local cache; enable client-side discovery
        caching (`client-go` `disk.NewCachedDiscoveryClientForConfig` /
        `memory.NewMemCacheClient` or a persistent shared `kubectl --cache-dir`
        rather than ephemeral per-run directories).
-   **Proactive GKE Control-Plane & Webhook Insights / Recommendations**: Check
    GKE Insights and Recommendations in the Cloud Console or via `gcloud
    recommender insights list` and `gcloud recommender recommendations list`
    (`--insight-type=google.container.DiagnosisInsight` /
    `--recommender=google.container.DiagnosisRecommender`). Warn users against
    ignoring GKE control-plane recommendations—especially admission webhook
    findings (unavailable endpoints, high latency, missing `kube-system`
    exclusions) or CRDs with an invalid `caBundle`—because they can overload or
    destabilize the control plane. Link to
    https://docs.cloud.google.com/kubernetes-engine/docs/how-to/optimize-webhooks
    and https://docs.cloud.google.com/kubernetes-engine/docs/how-to/crd-with-invalid-caBundle.

## 5. Watch Activity & Watch Storms

When a misconfigured agent or DaemonSet is suspected of causing a watch storm or
repeatedly re-establishing broken watches, query GMP `apiserver_longrunning_requests`
(`verb="WATCH"`, grouped by `group`, `resource`, `scope`) for active watchers,
`apiserver_watch_events_total` (grouped by `group`, `kind`, `version`) for watch
event volume/rate, and `apiserver_watch_events_sizes` for watch payload sizes.

## 6. Pod Churn, Controller-Manager Workqueues & Scheduler Lag

When batch job bursts (tens of thousands of concurrent Jobs) delay pod
creation/scheduling by 10–20 minutes—saturating `kube-controller-manager` and
`kube-scheduler` QPS/workqueues, often exacerbated by crashing DaemonSets—or
when custom controllers fall behind:

-   Enable `SCHEDULER` and `CONTROLLER_MANAGER` control-plane metrics.
-   Query `workqueue_depth`, `workqueue_queue_duration_seconds`,
    `workqueue_adds_total`, `workqueue_retries_total`, and `job_controller_*`
    metrics (such as `job_controller_job_sync_duration_seconds`) on
    `kube-controller-manager`.
-   Query `scheduler_pending_pods`, `scheduler_schedule_attempts_total`, and
    `scheduler_scheduling_attempt_duration_seconds` on `kube-scheduler`, plus
    mutating `apiserver_request_total` (`CREATE`, `DELETE`, `PATCH`, `UPDATE`)
    to measure object churn.
-   Correlate workqueue growth (e.g., `pod-garbage-collector` or `replicaset`
    lag) with API server latency and high churn; prune orphaned objects, tune
    controller concurrency, and pace or batch job submissions.

## 7. Control-Plane Headroom, Network Egress, Connections & Protobuf

-   **Saturation, headroom & control-plane VM autoscaling**: Monitor
    `apiserver_flowcontrol_priority_level_seat_utilization`,
    `apiserver_current_inflight_requests`, and
    `apiserver_request_duration_seconds` (plus
    `apiserver_flowcontrol_request_wait_duration_seconds` and
    `apiserver_flowcontrol_rejected_requests_total`). Always cover three
    operational guidance points when discussing control-plane headroom or
    preventing overload:
    1.  **Correlate spikes with workload changes** (new DaemonSets, unpaginated
        `LIST` calls, bursty controllers) to roll back or tune workloads before
        saturating `kube-apiserver`.
    2.  **Automatic control-plane VM scaling**: Highlight that GKE
        control-plane VMs are autoscaled to match observed load, so
        control-plane capacity adjusts dynamically as cluster activity grows.
    3.  **Proactive resize via node count**: Explain that the GKE control plane
        uses cluster node count as one of its autoscaling signals, so adding
        more nodes upfront (for example, ahead of a planned batch or traffic
        surge) is a relatively simple way to force a proactive control-plane
        resize—while noting that the exact scaling rules change frequently, so
        there is no reliable fixed threshold that GKE can share.
-   **Control-plane network egress, connections (`65k`), & Protobuf**: State
    explicitly out loud that **GKE does not offer a per-replica control-plane
    connection count metric** (so active watch/long-running stream metrics
    serve only as an indirect proxy). Check for heavy response/watch payload
    egress, connection limits (`65k`), or high JSON serialization overhead via
    `apiserver_response_sizes`, `apiserver_watch_events_sizes`,
    `apiserver_longrunning_requests`, and `apiserver_request_total` by
    `contentType` (`application/json` vs.
    `application/vnd.kubernetes.protobuf`). Always advise both mitigations:
    (1) configure custom controllers and high-volume clients to use Protobuf
    serialization (`application/vnd.kubernetes.protobuf`) instead of JSON, and
    (2) scope `WATCH`/`LIST` selectors (`labelSelector`, `fieldSelector`, and
    namespace-scoped informers) to reduce control-plane network egress and
    keep active connections within safe scalability limits.
logging-audit-and-apiserver-traces.md 13.8 KB
# Cloud Logging, Audit Attribution, APF & API Server Traces

## Table of Contents

-   **1. API Server Slow-Request Trace Logs (`trace.go`)** (Lines 11–54)
-   **2. Heavy API Clients (`httplog.go`), Audit Attribution & Slow `LIST`s** (Lines 56–117)
-   **3. API Priority & Fairness (APF) Throttling (`429` / `504` / `404`)** (Lines 119–143)
-   **4. Hot-Object `409 Conflict`s & Leader-Election `RenewDeadline` Timeouts** (Lines 145–169)
-   **5. `pods/exec`, Konnectivity, Cloud KMS & IAM Webhook Authorizer** (Lines 171–211)

## 1. API Server Slow-Request Trace Logs (`trace.go`)

`kube-apiserver` component logs (`API_SERVER`) are an **optional feature that is
not enabled by default** and must be explicitly turned on
(`--logging=SYSTEM,WORKLOAD,API_SERVER`). State this and link to
https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs#control_plane_logs
when recommending `apiserver` log analysis.

1.  **Search for `trace` or `Trace` entries**: Query `apiserver` component logs
    (`resource.type="k8s_control_plane_component" AND
    resource.labels.component_name="apiserver"`) for `trace` or `Trace` (e.g.,
    `textPayload:"Trace["`).
2.  **Structure & interpretation**: `kube-apiserver` uses upstream
    [`k8s.io/utils/trace`](https://github.com/kubernetes/utils/blob/master/trace/README.md)
    (`trace.go`) to log requests exceeding a latency threshold (typically
    500ms). The header records the operation (`"List"`, `"Get"`, `"Create"`,
    `"Patch"`), `url`, `user-agent`, `audit-id`, `client` IP, start timestamp,
    and `total time`. Nested sub-traces appear in brackets `[...]` and steps
    exceeding the step threshold appear as `---"<StepName>" <duration>ms`.
3.  **Distinguishing storage bottlenecks vs. slow-client serialization**:
    -   **Slow backend storage (`etcd`) read or write**: `cacher.GetList`,
        `List(recursive=true) etcd3`, or `GuaranteedUpdate etcd3` (with `initial
        value restored` / `Txn call completed`) dominates `total time`:
        ```text
        I1015 11:36:56.835120      10 trace.go:236] Trace[123456789]: "List" url:/api/v1/pods,user-agent:my-controller/v1.0.0,audit-id:11111111-2222-3333-4444-555555555555,client:10.0.0.1 (15-Oct-2026 11:36:49.460) (total time: 7374ms):
        Trace[123456789]: ["List(recursive=true) etcd3" 6890ms (11:36:49.461)]
        Trace[123456789]: ---"Objects listed" 6891ms (11:36:56.352)
        Trace[123456789]: ---"SerializeObject" 480ms (11:36:56.832)
        ```
    -   **Slow client / response serialization bottleneck**: `"Objects listed"`
        is fast, while `"SerializeObject"` and `---"Write call succeeded"` (or
        `---"Write call failed"`) dominate `total time` because a slow or
        bandwidth-constrained client takes seconds to read a large payload:
        ```text
        I1015 11:40:12.104512      10 trace.go:236] Trace[987654321]: "List" url:/api/v1/pods,user-agent:slow-watcher/v0.1,audit-id:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee,client:10.0.0.2 (15-Oct-2026 11:40:01.002) (total time: 11102ms):
        Trace[987654321]: ---"Objects listed" 45ms (11:40:01.047)
        Trace[987654321]: ["SerializeObject" 11055ms (11:40:01.047)]
        Trace[987654321]: ---"Write call succeeded" 11054ms (11:40:12.101)
        ```
4.  **Upstream docs & future evolution (cite both)**: Link to
    https://github.com/kubernetes/utils/blob/master/trace/README.md for
    `trace.go` and mention
    https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/647-apiserver-tracing
    (KEP-647: APIServer Tracing via OpenTelemetry) as a possible future change.

## 2. Heavy API Clients (`httplog.go`), Audit Attribution & Slow `LIST`s

1.  **`httplog.go` HTTP access logs**: Requires enabling `API_SERVER` component
    logs (`--logging=SYSTEM,WORKLOAD,API_SERVER`; link to
    https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs#control_plane_logs).
    State explicitly that the **`httplog.go` log structure is very stable**
    across Kubernetes releases (making regex extraction and Log Analytics
    queries reliable), and include this example log line:
    ```text
    I1015 11:36:56.835535      10 httplog.go:137] "HTTP" verb="GET" URI="/api/v1/namespaces/default/pods" latency="7.374935s" userAgent="my-controller/v1.0.0 (linux/amd64)" audit-ID="11111111-2222-3333-4444-555555555555" srcIP="10.0.0.1:12345" apf_pl="workload-low" apf_fs="everybody" apf_iseats=1 apf_fseats=0 apf_additionalLatency="0s" apf_execution_time="7.374765s" resp=200
    ```
    -   **Key fields**: `user_agent` (`userAgent` in raw text) identifies the
        client binary/operator; `verb` separates expensive `LIST` or mutating
        `PATCH`/`UPDATE` calls from lightweight `GET`s; `apf_iseats` (with
        `apf_fseats` and `apf_execution_time`) measures API Priority and
        Fairness (APF) concurrency seats occupied (`apf_iseats *
        apf_execution_time` reveals top concurrency consumers).
2.  **Noisy-neighbor attribution & slow/heavy `LIST` queries**: Because
    Prometheus metrics omit caller/user-agent labels to prevent cardinality
    explosion, always pair **`apiserver_request_total`** (grouped by `verb`,
    `resource`, and `code` to quantify QPS/error spikes) with **GKE Cloud Audit
    Logs** (which attribute requests to callers out-of-the-box even when
    optional `API_SERVER` logs are off):
    ```promql
    sum by (verb, resource, code) (rate(apiserver_request_total[5m]))
    ```
    -   Query GKE Cloud Audit Logs (`cloudaudit.googleapis.com/activity` and
        `data_access`) and `kube-apiserver` `Trace[` / `httplog.go` logs,
        aggregating by `protoPayload.authenticationInfo.principalEmail`,
        `protoPayload.requestMetadata.callerSuppliedUserAgent`, and target
        resource/namespace.
    -   Correlate audit log offender attribution with `apiserver_request_total`
        (grouped by `verb`, `resource`, and `code`),
        `apiserver_request_duration_seconds` (`verb="LIST"`),
        `apiserver_response_sizes` (`verb="LIST"`), per-resource storage size
        (`apiserver_resource_size_estimate_bytes` or
        `kubernetes.io/master/apiserver/resource_size_estimate_bytes`, grouped
        by `group` and `resource`), and
        `apiserver_watch_list_duration_seconds`.
    -   **Remediation**: Throttle or fix high-QPS client workloads, refactor or
        paginate expensive cluster-wide `LIST` queries (e.g., `external-dns`,
        `argocd-server`, or custom operators listing all pods), use
        `resourceVersion="0"` (watch cache reads), or switch to cached
        `SharedInformer` watches.
3.  **Unindexed CRD custom `fieldSelector` scans & in-flight tail latency**:
    Custom resources are stored as JSON and have **no** secondary indexes in
    backend storage or the `kube-apiserver` watch cache for custom
    `fieldSelector` paths (even when `spec.versions[].selectableFields` is
    declared; only `metadata.name` and `metadata.namespace` are indexed). Every
    `LIST` with a custom `fieldSelector` (e.g., across 50,000 CRD instances)
    forces `kube-apiserver` to scan and JSON-deserialize every object into
    memory (`unstructured.Unstructured`) to evaluate the filter—acquiring
    multiple API Priority and Fairness (APF) concurrency seats (`apf_iseats` in
    `httplog.go`, `apiserver_flowcontrol_priority_level_seat_utilization`) for
    the full scan duration (`apf_execution_time`) and churning Go heap/garbage
    collection, which queues concurrent requests
    (`apiserver_flowcontrol_request_wait_duration_seconds`) and causes
    in-flight tail-latency regressions (`apiserver_request_duration_seconds`,
    visible in opt-in `API_SERVER` `Trace[` and `httplog.go` logs). Replace
    custom `fieldSelector` `LIST`s with indexed **`labelSelector`s** or watch
    via a **`SharedIndexInformer`** with controller-side **`cache.Indexers`**
    (`IndexField`).

## 3. API Priority & Fairness (APF) Throttling (`429` / `504` / `404`)

When workloads, batch job scripts, or CI runners fail with HTTP `429 Too Many
Requests` or `504 Gateway Timeout` (`context canceled`):

-   **Metrics to query**: Query `apiserver_flowcontrol_rejected_requests_total`,
    `apiserver_flowcontrol_current_inqueue_requests`,
    `apiserver_flowcontrol_request_wait_duration_seconds`, and
    `apiserver_flowcontrol_priority_level_seat_utilization` grouped by
    `priority_level` and `flow_schema`, plus `apiserver_request_total` by status
    code (`404`, `429`, `504`) and verb (`GET`, `LIST`).
-   **Log attribution (`API_SERVER` logs)**: Enable control-plane logging
    (`API_SERVER` via `--logging=SYSTEM,WORKLOAD,API_SERVER`) to pull detailed
    information on `user_agent` (`userAgent`), target resources (`URI` /
    `requestURI`), and source IPs (`src_ip` / `srcIP` / `sourceIPs`) from
    `kube-apiserver` logs (or Cloud Audit Logs) for unpaginated `LIST` calls,
    tight `404` `GET` polling loops, or single-digit millisecond `?timeout=`
    requests.
-   **How APF works & remediation**: APF throttles noisy clients in
    lower-priority lanes (such as `workload-low`) to protect critical system
    traffic (`system`, `leader-election`, `node-high`). Pace client burst QPS,
    replace tight `GET`/`LIST` polling with `SharedInformer` watches, add
    exponential backoff and client-side caching on `404`s, increase overly short
    client request timeouts, or isolate noisy service accounts into a dedicated
    `FlowSchema` and `PriorityLevelConfiguration`.

## 4. Hot-Object `409 Conflict`s & Leader-Election `RenewDeadline` Timeouts

-   **Hot-object write contention (`409 Conflict` & slow `PATCH`/`PUT`)**: When
    runaway controllers fight over or hot-loop updates against a single
    `ConfigMap`, `CustomResourceDefinition`, or `Lease`, query Cloud Audit Logs
    (`cloudaudit.googleapis.com/activity`) grouped by
    `protoPayload.resourceName`, `protoPayload.methodName` (`update` or
    `patch`), and `protoPayload.requestMetadata.callerSuppliedUserAgent` (or
    `protoPayload.authenticationInfo.principalEmail`) and inspect
    `kube-apiserver` `GuaranteedUpdate` `Trace[` logs to pinpoint the hot object
    and responsible agent. Mitigate by reducing the operator's checkpoint/sync
    frequency (e.g., increasing `refreshInterval`) and lowering client QPS; if
    pods or microservices write frequent status heartbeats or distributed locks
    into a single shared `ConfigMap` (causing serialized optimistic-concurrency
    `resourceVersion` contention and `409 Conflict` storms), migrate per-replica
    heartbeats or locks to dedicated `coordination.k8s.io` `Lease` objects.
-   **Leader-election `RenewDeadline / 2` (`?timeout=5s`) timeouts**: When
    third-party operators (e.g., KEDA, VictoriaMetrics) lose Lease leadership
    with `context deadline exceeded` after 5s despite higher general client
    timeouts, explain that `client-go`'s `leaderelection` package sets the
    per-request HTTP timeout on Lease `PUT` renewals to `RenewDeadline / 2` (so
    default `RenewDeadline: 10s` enforces `?timeout=5s` on `requestURI` in Cloud
    Audit Logs and `Trace[` logs). Increase the operator's leader-election flags
    (e.g., `--leader-elect-lease-duration=60s` and
    `--leader-elect-renew-deadline=40s`).

## 5. `pods/exec`, Konnectivity, Cloud KMS & IAM Webhook Authorizer

-   **Excessive `pods/exec` saturating webhooks & Konnectivity**: When
    `warden-validating.common-webhooks.networking.gke.io` admission timeouts
    (`10s`) or `500 error dialing backend: dial timeout, backstop` errors occur
    on `kubectl exec`, query Cloud Audit Logs for `io.k8s.core.v1.pods.exec.get`
    (`connect`) volume and correlate with
    `apiserver_admission_webhook_admission_duration_seconds` for
    `warden-validating` (high `pods/exec` volume evaluates against admission
    webhooks and Konnectivity tunnels). Replace `kubectl exec`-based metrics
    scraping and health checks with Kubelet `/metrics/cadvisor`, Cloud
    Monitoring container metrics (`k8s_container`), and direct pod-to-pod
    HTTP/gRPC endpoints.
-   **Konnectivity (`No agent available`), firewall, & `ip-masq-agent`**: When
    webhook calls or `kubectl exec`/`logs` fail with `No agent available` or
    `context deadline exceeded`, check `kube-apiserver` logs
    (`resource.type="k8s_control_plane_component"`) for `No agent available` or
    dial failures, inspect `konnectivity-agent` pods (`kubectl get pods -n
    kube-system -l k8s-app=konnectivity-agent`), verify VPC firewall rules
    between the control-plane CIDR and node/pod CIDRs (ports `10250`, `8132`,
    and webhook ports), and check the `ip-masq-agent` ConfigMap so
    pod-to-API-server and API-server-to-webhook traffic is not masqueraded or
    blocked.
-   **Disabled Cloud KMS keys breaking encryption (`kms-provider-0` / `failed to
    get dek primitive`)**: Inspect `gcloud container clusters describe`
    (`databaseEncryption` config and error status) and query Cloud Audit Logs
    for `cloudkms.googleapis.com` (`DisableCryptoKeyVersion`,
    `DestroyCryptoKeyVersion`, or `PermissionDenied` on `Encrypt`/`Decrypt`).
    Re-enable the disabled `CryptoKeyVersion`, verify the GKE service agent has
    `roles/cloudkms.cryptoKeyEncrypterDecrypter`, and follow
    https://docs.cloud.google.com/kubernetes-engine/docs/how-to/encrypting-secrets#reencrypt-secrets
    to re-encrypt existing Secrets.
-   **In-cluster GCP IAM OAuth tokens saturating the GKE IAM webhook authorizer
    (`Failed to make webhook authorizer request`)**: When high-QPS in-cluster
    clients (`Helm`, operators) authenticate with GCP IAM OAuth Bearer tokens
    without matching Kubernetes RBAC bindings, `kube-apiserver` invokes the
    external GKE IAM webhook authorizer on every request, which throttles/times
    out under load. Inspect Cloud Audit Logs (`authenticationInfo` and
    `authorizationInfo`) and migrate in-cluster workloads to native Kubernetes
    `ServiceAccount` tokens bound via Kubernetes RBAC (`RoleBinding` /
    `ClusterRoleBinding`) so authorization is evaluated locally in memory.

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