diff --git a/changelog.d/1130.md b/changelog.d/1130.md new file mode 100644 index 0000000000..85bf23f3b0 --- /dev/null +++ b/changelog.d/1130.md @@ -0,0 +1,4 @@ +### Fixed +- The Prometheus server scrapes only itself and the OpenTelemetry Collector. Alloy, run by k8s-monitoring, finds every other target through annotation autodiscovery, `clusterMetrics.kubeDNS` and the Loki and DCGM integrations, so the unread API-server scrape (about 60% of head series) and four jobs that matched nothing are gone (#1130). +- The server's self-scrape carries the `cluster` label, which both remaining server jobs take from one anchor (#1130). +- `k8s/README.md` records which monitoring components run outside k8s-monitoring, and why (#1130). diff --git a/docs/agent/tasks/task-1130-prometheus-scrapes-itself-and-the-collector.md b/docs/agent/tasks/task-1130-prometheus-scrapes-itself-and-the-collector.md new file mode 100644 index 0000000000..8f17c6488f --- /dev/null +++ b/docs/agent/tasks/task-1130-prometheus-scrapes-itself-and-the-collector.md @@ -0,0 +1,115 @@ +# Task: The Prometheus Server Scrapes Only Itself and the OTel Collector, and k8s-monitoring Discovers Every Other Target (#1130) + +**Issue**: [#1130](https://github.com/dan-petty/devops-cli/issues/1130) +**Status**: Done +**Milestone**: v0.2.33 +**Priority**: priority/p1-high +**Scope**: scope/k8s, scope/telemetry +**Feasibility**: Confirmed against the live cluster read-only on 2026-10-09 (kubectl get, Prometheus queries through Grafana): the API-server job held 59,700 of 99,544 head series, 1,375 series lacked a cluster label (all from the self-scrape), and every Argo CD app was Synced; the chart values read at origin/release/v0.2.33 still enabled the four extra scrape jobs this change removes. + +## Description +The cluster had two scrapers. Alloy, run by k8s-monitoring 4.5.2, scraped the kubelet, cAdvisor, kube-state-metrics, node-exporter, DCGM and the llm gateway. The prometheus-community server (chart 29.35.0) ran its own Kubernetes discovery beside it, mostly with chart-default jobs. The API-server job held about 60% of the head series (59,700 of 99,602 on 2026-10-09) and nothing read them; four jobs matched nothing; the cluster name was a literal in five relabel blocks, and the server's self-scrape carried no `cluster` at all. + +The server now runs two jobs: its self-scrape and `kubernetes-pods`, which keeps only namespace `otel`, so the collector's export failures stay visible when Alloy is what fails. Both take their cluster relabel from one YAML anchor. k8s-monitoring takes over every other target with chart features: + +- **Annotation autodiscovery** finds cloudflared, Traefik, Alertmanager and roadmap-service through the `prometheus.io/*` annotations they already carry. It skips `otel`, leaves Service discovery off and sends no ServiceAccount token. +- **`clusterMetrics.kubeDNS`** scrapes CoreDNS, which the server's service-endpoints job scraped before. +- **The Loki integration** selects Loki's single-binary pod by its labels, so Loki's pod annotations are gone. +- **The dcgm-exporter integration** scrapes the exporter every 15s, so the chart's own ServiceMonitor is off. + +Autodiscovery, kube-dns and DCGM each carry a discovery rule that copies the pod's node to `node`, which the node-maintenance silence and the NodeNotReady inhibition match. `k8s/README.md` gains a Scrape Ownership section with a table of the monitoring components that run outside k8s-monitoring, and why. + +Deviations from the issue text: +- **Loki's job is `logging/single-binary`, not `integrations/loki`.** The integration sets `job` to namespace/component for the loki-mixin. It also moves `node` into `instance` and drops `node`, so a Loki `TargetDown` is named by `instance`, which is the node. +- **`annotationAutodiscovery.bearerToken.enabled: false`.** The chart sends the ServiceAccount token to every annotated pod by default, over plain HTTP. No annotated target needs it. +- **Alertmanager carries `k8s.grafana.com/metrics.container: alertmanager`.** Autodiscovery makes one target per container. It would rewrite the config-reloader sidecar's target to the annotated port 9093, so Alertmanager would be scraped twice. +- **roadmap-service is a seventh annotated workload.** The issue lists six; autodiscovery finds it like the others. +- **`clusterMetrics.kubeDNS.extraDiscoveryRules` carries the node rule.** The server's service-endpoints job set `node` on CoreDNS. Without the rule, a CoreDNS `TargetDown` would fall back to the pod address, and the node silence would not cover it. +- **The Loki instance sets `logs.enabled: false`.** The item changes metrics only, and Loki's own pod logs stay as `podLogsViaLoki` ships them. +- **DCGM series lose labels.** They no longer carry the exporter pod's `container`, `endpoint`, `namespace`, `pod` and `service` labels. Nothing reads them: `llm-stack.json` uses `hostname`, `gpu` and `modelName`, dashboard 12239 uses `instance` and `gpu`, and the GPU rules use `node` and `gpu`. +- **Only Loki's integration has an allow list.** The issue expected chart allow lists on Loki, CoreDNS and DCGM. k8s-monitoring 4.5.2 has a default list for Loki only; kube-dns, DCGM and autodiscovery forward every series their targets serve. +- **Traefik is managed by Argo CD.** The issue calls it k3s-managed, but `k8s/argocd/apps/traefik.yaml` installs it in `kube-system`, and the chart sets its `prometheus.io/*` annotations. +- **The dcgm-exporter Application drops `SkipDryRunOnMissingResource`.** The chart no longer renders a ServiceMonitor, so the option has nothing left to skip. `dcgm-exporter-values.yaml` keeps only `serviceMonitor.enabled: false`, because the chart's default is on. +- **The expected drop is about 60k head series.** The issue said 50k; that figure is re-measured live. + +## Acceptance Criteria +- [x] `k8s/monitoring/prometheus-values.yaml` sets `enabled: false` on `kubernetes-api-servers`, `kubernetes-service-endpoints`, `kubernetes-service-endpoints-slow`, `kubernetes-pods-slow`, `kubernetes-services` and `prometheus-pushgateway`, with their relabel blocks deleted. `kubernetes-nodes` and `kubernetes-nodes-cadvisor` stay off. +- [x] `kubernetes-pods` stays enabled, and its `pre_relabel_configs` keep only namespace `otel`. Its comment cites the README's independence reason. +- [x] `prometheus` and `kubernetes-pods` take their cluster relabel from one anchor (`&cluster`). The self-scrape carries `cluster`. +- [x] `annotationAutodiscovery` is set as follows: + - `enabled: true`, `collector: alloy-metrics`; + - the `prometheus.io/scrape`, `prometheus.io/port` and `prometheus.io/path` annotation keys; + - `excludeNamespaces: [otel]`, `services.enabled: false` and `bearerToken.enabled: false`; + - the node rule in `extraDiscoveryRules`. +- [x] `clusterMetrics.kubeDNS.enabled: true`, with the same node rule. +- [x] `integrations.collector: alloy-metrics`, with two instances: + - `loki`: `labelSelectors` `{app.kubernetes.io/name: loki, app.kubernetes.io/component: single-binary}`, the chart's default allow list, and `logs.enabled: false`; + - `dcgm-exporter`: `labelSelectors` `{app.kubernetes.io/name: dcgm-exporter}`, `metrics.scrapeInterval: 15s`, and discovery rules that set `node` and `instance` from `__meta_kubernetes_pod_node_name`. +- [x] `k8s/logging/loki-values.yaml` sets no `podAnnotations`. `k8s/monitoring/dcgm-exporter-values.yaml` sets `serviceMonitor: {enabled: false}` and nothing else under it. +- [x] `test_scrape_ownership_moves_to_k8s_monitoring` asserts all of the above as one tuple, including Alertmanager's three annotations. The enabled server jobs are computed over the 10 default jobs in prometheus 29.35.0's `values.yaml` (`PROMETHEUS_DEFAULT_JOBS`), so a default job that the values leave out counts as on. +- [x] `test_each_annotated_component_has_one_scrape_owner` asserts exactly one owner for each of cloudflared, roadmap-service, Alertmanager, the collector, Loki and DCGM. The owners are the server's `kubernetes-pods` job, autodiscovery, each integration instance, and the DCGM chart's own ServiceMonitor. `test_a_component_with_no_scrape_owner_or_two_fails` runs the four review mutations, and each one fails the check: + - Alertmanager without its scrape annotation; + - the collector without its annotations; + - `otel` removed from `excludeNamespaces`; + - Loki annotated again. +- [x] `test_every_scrape_port_has_one_egress_rule` counts the egress rules in `k8s/monitoring/networkpolicy.yaml` for each scrape port, using one counting helper, `_egress_rules_to`. Each port has exactly one rule: cloudflared 2000, devops 8000, `kube-system` 9100 (Traefik) and 9153 (CoreDNS), logging 3100, monitoring 9093 and 9400, and otel 8888. The policy needed no change. +- [x] `tests/test_stack_dashboards.py` reads the new owners: + - `_dcgm_monitored` reads the k8s-monitoring dcgm-exporter integration; + - `_collector_annotated` also requires the server job to keep namespace `otel`. + + The DCGM and Prometheus server capture fixtures name their new scrapes and target labels. No test compares the DCGM job label. +- [x] `k8s/README.md` has a Scrape Ownership section. Its table has one row for each of the eight components, with the owner and the reason, and the lines after it name the autodiscovered pods and what `devops prometheus targets` lists. The dashboard table, Log and Metric Retention, `LokiRetentionNotRunning`, Planned maintenance (where `node` comes from, and what stops with `alloy-metrics-0`) and the directory listing describe the new owners. +- [x] No test reaches the network or runs `helm`. Each new test's call phase is at most 0.02 s (`uv run pytest tests/test_k8s_monitoring_integration.py --durations=0`). `changelog.d/1130.md` exists; CHANGELOG.md and docs/ROADMAP.md are untouched. +- [x] Review render, outside the gate: `helm template` of the cached k8s-monitoring 4.5.2 and prometheus 29.35.0 charts with the new values. + - The k8s-monitoring render only adds Alloy configuration. The autodiscovery scrape has no `bearer_token_file`. + - The node rule renders in `annotation_autodiscovery_pods`, `kube_dns` and the DCGM instance. DCGM's `scrape_interval` is `"15s"`, and no Loki log rule renders. + - `prometheus.yml` has only the `kubernetes-pods` job, whose first rule keeps `otel`, and the `prometheus` job. Both end with the `cluster` replace rule. +- Pending a person, after the v0.2.33 release PR merges into main and Argo CD syncs the `prometheus`, `k8s-monitoring`, `dcgm-exporter` and `loki` Applications. They track main, so do not apply early with `devops k8s deploy-stack` from the release branch: Argo CD would revert it. + 1. `kubectl get application -n argocd prometheus k8s-monitoring dcgm-exporter loki -o custom-columns=NAME:.metadata.name,SYNC:.status.sync.status,HEALTH:.status.health.status,REV:.status.sync.revisions` shows each one `Synced` and `Healthy` at the merge commit. + - `kubectl get servicemonitor -A` lists only `llm/llm-gateway`. + - `kubectl -n logging get pod loki-0` and `kubectl -n monitoring get pod prometheus-alertmanager-0` show pods restarted since the sync, because their pod template annotations changed. + - In Grafana Explore against Prometheus, `prometheus_config_last_reload_successful` is `1`. + 2. Fifteen minutes later, `count by (job) (up)` returns these jobs and no others besides the unchanged Alloy jobs (kubelet, cAdvisor, resources, kube-state-metrics, node_exporter, llm-gateway): + - `prometheus` 1 and `kubernetes-pods` 1; + - `cloudflared` 2, `traefik` 1, `alertmanager` 1 and `roadmap-service` 1; + - `integrations/kubernetes/kube-dns`, equal to the CoreDNS pods in `kubectl -n kube-system get pods -l k8s-app=kube-dns`; + - `logging/single-binary` 1; + - `integrations/dcgm-exporter`, equal to the GPU nodes in `kubectl get nodes -l nvidia.com/gpu.present=true`. + + No `kubernetes-api-servers`, `kubernetes-service-endpoints` or `dcgm-exporter` job is left. + 3. `count(alertmanager_build_info)` is `1`, so Alertmanager is scraped once. + 4. `count by (job) (up{node=""})` lists only `prometheus`, `llm-gateway`, `integrations/kubernetes/kube-state-metrics`, `integrations/node_exporter` and `logging/single-binary`. + 5. `count by (node, gpu) (DCGM_FI_DEV_GPU_TEMP)` equals the number of GPUs, and the instance variable of dashboard 12239 lists node names. + 6. `loki_compactor_apply_retention_last_successful_run_timestamp_seconds` and `coredns_dns_requests_total` each return series. + 7. `count({__name__=~".+", __name__!~"ALERTS.*", cluster=""})` is empty. + 8. `ALERTS{alertname="TargetDown"}` holds no alert for the new jobs. + 9. Three hours later, `prometheus_tsdb_head_series` is about 60k lower than before the sync (about 99.6k on 2026-10-09). + +## Deliverables +- [x] `k8s/monitoring/prometheus-values.yaml`: + - two scrape jobs, with one cluster anchor; + - the six chart-default jobs off; + - Alertmanager's container annotation; + - the scrape and `LokiRetentionNotRunning` comments rewritten. +- [x] `k8s/monitoring/k8s-monitoring-values.yaml`: `clusterMetrics.kubeDNS`, `annotationAutodiscovery`, and `integrations` with the Loki and DCGM instances. The block stays a plain instance list, so #1131 only appends. +- [x] `k8s/logging/loki-values.yaml`: the pod annotations removed. +- [x] `k8s/monitoring/dcgm-exporter-values.yaml`: the ServiceMonitor off. `k8s/argocd/apps/dcgm-exporter.yaml`: `SkipDryRunOnMissingResource` removed. +- [x] `k8s/monitoring/prometheus-operator-crds-values.yaml` and the `stack_lifecycle.py` release comment: only k8s-monitoring's extraObjects render ServiceMonitors. +- [x] `k8s/monitoring/dashboards/prometheus-server.json`: the "Scrape Duration by Job" description names the jobs that forward `scrape_duration_seconds`. +- [x] `tests/test_k8s_monitoring_integration.py`: + - the ownership, single-owner, mutation and egress-count tests; + - the DCGM test rewritten; + - `_has_egress_port_to_namespace` replaced by `_egress_rules_to`. +- [x] Other test updates: + - `tests/test_stack_dashboards.py` and the DCGM and Prometheus server capture fixtures; + - `tests/test_k8s_monitoring_alerting.py`: the `SERVED_SERIES` comments, and `test_k8s_monitoring_scrapes_loki_and_alertmanager_for_their_health`; + - `tests/test_k8s.py`: the ServiceMonitor release tuple; + - `tests/test_llm_pool_metrics.py`: the DCGM ServiceMonitor flag. +- [x] `k8s/README.md`: the Scrape Ownership section, and the stale lines rewritten. +- [x] Task files #549, #693, #819, #825, #935 and #1485 note what changed since #1130. +- [x] `changelog.d/1130.md`. +- Follow-ups, not in this item: + - #1131 appends the Alloy, Grafana and Pyroscope integrations; + - #822 keeps the CoreDNS dashboard; + - #823 keeps the CRDs and `prometheusOperatorObjects` for the Qdrant monitor; + - #1132 keeps the collector on the server. diff --git a/docs/agent/tasks/task-1485-argocd-image-updater.md b/docs/agent/tasks/task-1485-argocd-image-updater.md index 7a752803c1..e016dabc0f 100644 --- a/docs/agent/tasks/task-1485-argocd-image-updater.md +++ b/docs/agent/tasks/task-1485-argocd-image-updater.md @@ -30,7 +30,7 @@ The owner asked on 2026-10-09 for Argo CD Image Updater to deploy the Service im ## Decisions and Deviations -- **The ImageUpdater ships in the chart's `extraObjects`.** It syncs in the same sync as its CRD (`templates/crd-imageupdaters.yaml` in the chart), and Argo CD skips the dry run of a resource whose CRD is part of the same sync, so the Application needs no `SkipDryRunOnMissingResource`. `k8s-monitoring` and `dcgm-exporter` need that option because their ServiceMonitor CRD comes from another Application. `k8s-monitoring` uses `extraObjects` the same way. +- **The ImageUpdater ships in the chart's `extraObjects`.** It syncs in the same sync as its CRD (`templates/crd-imageupdaters.yaml` in the chart), and Argo CD skips the dry run of a resource whose CRD is part of the same sync, so the Application needs no `SkipDryRunOnMissingResource`. `k8s-monitoring` and `dcgm-exporter` need that option because their ServiceMonitor CRD comes from another Application. Since #1130 dcgm-exporter renders no ServiceMonitor and its Application drops the option. `k8s-monitoring` uses `extraObjects` the same way. - **No native `deploy-stack` release (AGENTS.md's stack-path rule).** Image Updater acts only on Argo CD Applications, and a cluster without Argo CD has none for it to update; its devops stack applies the raw manifests, which name the untagged image, `latest`. Registering the chart in `_HELM_RELEASES_BY_STACK` would also fail on a fresh native cluster: chart 1.3.1 ships its CRD in `templates/`, not `crds/`, and Helm builds every object of a release before it applies any, so the ImageUpdater fails with `ensure CRDs are installed first`. On the Argo CD-managed homelab, `devops k8s deploy-stack` delegates to Argo CD, and the `cluster` app-of-apps syncs the new Application from git with no manual step. Traefik and `gpu-feature-discovery` have no native release either. AGENTS.md's sentence names only `_MANIFESTS_BY_STACK` and `_HELM_RELEASES_BY_STACK`, and this change leaves it as it is: whether it names Argo CD-only add-ons is the owner's decision. - **The CronJob already set `IfNotPresent`.** The issue says the CronJob gets it, but `k8s/devops/cronjob.yaml` has set it since v0.2.26, and the live CronJob runs with it. No manifest changed; the render test pins both workloads. - **Chart defaults stay.** These include the controller's own `imagePullPolicy: Always`, the chart's ClusterRoles (`createClusterRoles: true`) and the `crds.keep` policy. The chart's appVersion (v1.3.0) lags the app's v1.3.1 by one patch; v1.3.0 already has the GHCR pagination fix and is built against Argo CD 3.5. diff --git a/docs/agent/tasks/task-549-alerts-fire-into-nothing-no-alertmanager-and-k3s-false-posit.md b/docs/agent/tasks/task-549-alerts-fire-into-nothing-no-alertmanager-and-k3s-false-posit.md index 73c758f0a0..26fd58b000 100644 --- a/docs/agent/tasks/task-549-alerts-fire-into-nothing-no-alertmanager-and-k3s-false-posit.md +++ b/docs/agent/tasks/task-549-alerts-fire-into-nothing-no-alertmanager-and-k3s-false-posit.md @@ -13,7 +13,7 @@ Owner decisions (2026-10-03): no notification channel is chosen yet, so Alertman ## Key Changes - **`k8s/monitoring/prometheus-values.yaml`**: - - `alertmanager.enabled: true`, on `local-path`, with resources, and pod annotations so the server's kubernetes-pods job scrapes it. + - `alertmanager.enabled: true`, on `local-path`, with resources, and pod annotations so the server's kubernetes-pods job scrapes it. Since #1130 k8s-monitoring's annotation autodiscovery scrapes it through the same annotations. - Receivers: `null` (no integration) is the default; a child route sends `severity=~"critical|warning"` to `webhook`, whose `url_file` is `/etc/alertmanager-webhook/url`. That directory is the Secret `alertmanager-webhook` (key `url`), mounted optional and read-only, with no `subPath`. - Inhibitions: `NodeNotReady` hides `TargetDown` on the same `node`; a critical alert hides the warning of the same `alertname`, `node`, `gpu` and `mountpoint`. - `serverFiles.alerting_rules.yml`: this item's 23 rules in four groups, next to #550's `log-and-metric-retention` group (2 rules), 25 in all: @@ -23,7 +23,7 @@ Owner decisions (2026-10-03): no notification channel is chosen yet, so Alertman - `monitoring-self`: `ClusterMetricsMissing`, `PrometheusConfigReloadFailed`, `PrometheusRuleEvaluationFailures`, `PrometheusNotConnectedToAlertmanager`, `PrometheusDroppingAlerts`, `PrometheusCompactionsFailing`, `PrometheusSizeLimitCutHistory`, `LokiRequestErrors`, `LokiRetentionNotRunning` (its comment says it has no series until #550's Loki migration, whose Loki upgrade turns compactor retention on and adds the scrape annotations, and fires afterwards only if retention stops), `AlertmanagerConfigReloadFailed`, `AlertmanagerNotificationsFailing` (only once the webhook Secret exists). - `log-and-metric-retention` (#550): `LogOrMetricVolumeDiskLow` and `PrometheusNearRetentionSizeCap`, kept as #550 wrote them except that the size-cap rule's TSDB and limit selectors now read this server's self-scrape (`job="prometheus"`), as `PrometheusStorageNearClaim` does. Its matching is one-to-one, so a second Prometheus could not break its evaluation; the pin keeps a second Prometheus from being held to this server's `server.retentionSize` in the alert. The group's comment no longer says it reaches no receiver. The comments say where the rules overlap: `HostFilesystemSpaceLow` and `LogOrMetricVolumeDiskLow` both watch 10% free on the root filesystem of the node holding the claims, the second naming the claim at risk; `PrometheusNearRetentionSizeCap` warns before the size cap deletes blocks, `PrometheusSizeLimitCutHistory` once it has, and `PrometheusStorageNearClaim` only when no cap holds the data under the claim. - Every rule about one node carries `node`. node-exporter names its node in `instance`, so its rules set `node: "{{ $labels.instance }}"`, and `TargetDown` sets `node: "{{ or $labels.node $labels.instance }}"`. -- **`k8s/logging/loki-values.yaml`**: `singleBinary.podAnnotations` `prometheus.io/scrape: "true"` and `prometheus.io/port: "3100"`. The Prometheus server's kubernetes-pods job scrapes Loki through them, only where the logging stack runs. Nothing scraped Loki before. +- **`k8s/logging/loki-values.yaml`**: `singleBinary.podAnnotations` `prometheus.io/scrape: "true"` and `prometheus.io/port: "3100"`. The Prometheus server's kubernetes-pods job scrapes Loki through them, only where the logging stack runs. Nothing scraped Loki before. Since #1130 k8s-monitoring's Loki integration scrapes Loki by its pod labels, and the annotations are gone. - **`k8s/monitoring/grafana-values.yaml`**: the `Alertmanager` datasource (`uid: alertmanager`, `implementation: prometheus`) at `http://prometheus-alertmanager.monitoring.svc.cluster.local:9093`. - **`k8s/README.md`**: an Alerting section with: - the rule table; @@ -37,7 +37,7 @@ Owner decisions (2026-10-03): no notification channel is chosen yet, so Alertman - `test_the_baseline_rule_set` pins the 25 alert names with their severities (this item's 23 and #550's 2); `test_every_rule_waits_routes_and_explains` requires `for`, a routed severity, `summary` and `description`; `test_every_node_scoped_rule_names_its_node` pins the `node` labels. - `test_the_claim_rule_divides_one_series_by_one` pins that each TSDB selector in `PrometheusStorageNearClaim` is matched by `job` and the claim selector is not; `test_the_size_cap_rule_reads_this_server_only` pins `job="prometheus"` on every selector of #550's `PrometheusNearRetentionSizeCap`. - `test_alertmanager_sends_nowhere_until_the_webhook_secret_exists`, `test_alertmanager_inhibits_follow_on_alerts` and `test_grafana_provisions_the_alertmanager_datasource` pin the receiver, the inhibitions and the datasource. - - `test_prometheus_scrapes_loki_and_alertmanager_for_their_health` pins the Loki and Alertmanager pod annotations, the kubernetes-pods job, and the absence of a static scrape (`extraScrapeConfigs`) in the infra stack's Prometheus values. + - `test_prometheus_scrapes_loki_and_alertmanager_for_their_health` pins the Loki and Alertmanager pod annotations, the kubernetes-pods job, and the absence of a static scrape (`extraScrapeConfigs`) in the infra stack's Prometheus values. Since #1130 it is `test_k8s_monitoring_scrapes_loki_and_alertmanager_for_their_health`, which pins the Loki integration's selector and Alertmanager's annotations. - `test_no_scrape_targets_the_components_k3s_runs_in_process` guards that k8s-monitoring scrapes no controller manager, scheduler or proxy. - **`tests/test_k8s.py`**: #550's `_volume_alerts` reads only the `log-and-metric-retention` group, so its test keeps pinning its two rules next to this item's groups. - **`changelog.d/549.md`**: the entries under `### Added`. @@ -84,7 +84,7 @@ Owner decisions (2026-10-03): no notification channel is chosen yet, so Alertman - Logs are kept to 30 days only once #550's Loki migration has run; until then Loki has never applied retention. Nothing alerts on that before the migration, because the Loki scrape `LokiRetentionNotRunning` reads arrives with the same upgrade. #550's README section says so. - `NodeRebooted` fires on uptime under 30 minutes, not on `changes(node_boot_time_seconds[...])`: a node that stayed down longer than the window has no earlier boot time in it, and the shared-breaker outages lasted hours. - `NodeRebooted`, `K3sServiceNotActive` and `GpuPowerLimitServiceNotActive` read `node_boot_time_seconds` and `node_systemd_unit_state`, which #1080 (merged before this item) adds to the host metrics allow list. Until its k8s-monitoring upgrade is applied, those rules have no series and stay silent. -- `TargetDown` names targets without a `node` label by their `instance`. For node-exporter that is the node, so one silence covers it; the kubernetes-pods job (Loki, Alertmanager, the collector) sets `node` itself. For cluster-wide targets the `node` label holds an address that matches no node. +- `TargetDown` names targets without a `node` label by their `instance`. For node-exporter that is the node, so one silence covers it; the kubernetes-pods job (Loki, Alertmanager, the collector) sets `node` itself. Since #1130 Alloy's annotation autodiscovery sets it for Alertmanager, and the Loki integration puts Loki's node in `instance`. For cluster-wide targets the `node` label holds an address that matches no node. - Planned maintenance needs the drain as well as the silence: `ClusterMetricsMissing` has no `node` label, so a node silence does not cover it if the single Alloy metrics pod is left on a powered-off node. While the node holding Prometheus or Alertmanager (local-path, so they cannot move) is down, no alert is evaluated or sent. - `GpuPowerOverSiteBudget` uses one site-wide budget of 1000 W: the GPUs drew 837 to 1061 W together in the 20 minutes before every series stopped at 08:00 UTC on 2026-10-02, the start of an outage of about five hours. Over the 7 days to 2026-10-03, total GPU power stayed over 1000 W for a full 5 minutes in 15 one-minute steps and peaked at 1301 W. It should become one budget per circuit once the new power layout is known. - `GpuTemperatureHigh` at over 85 °C for 10 minutes would not have fired in those 7 days; the hottest GPU peaked at 86 °C, for no 10 minutes in a row. diff --git a/docs/agent/tasks/task-693-llm-gateway-otel-collector-and-prometheus-dashboards.md b/docs/agent/tasks/task-693-llm-gateway-otel-collector-and-prometheus-dashboards.md index 03f095b53d..944432e373 100644 --- a/docs/agent/tasks/task-693-llm-gateway-otel-collector-and-prometheus-dashboards.md +++ b/docs/agent/tasks/task-693-llm-gateway-otel-collector-and-prometheus-dashboards.md @@ -16,7 +16,7 @@ Three dashboards now query only series the cluster collects, checked against cap A timeseries panel scales its y-axis to the data, not to its thresholds, so each panel drawn against a limit (exporter queue fill, collector memory, TSDB size, server memory) sets `axisSoftMax` to that limit and its limit line stays on the axis. -The collector's pods carry `prometheus.io/scrape` and `prometheus.io/port` annotations, so the server's `kubernetes-pods` job scrapes its own telemetry on 8888 directly rather than through Alloy, which it exports to. `prometheus-values.yaml` enables the `prometheus` and `kubernetes-pods` jobs explicitly, since deploy-stack does not pin the chart version that defaults them on. +The collector's pods carry `prometheus.io/scrape` and `prometheus.io/port` annotations, so the server's `kubernetes-pods` job scrapes its own telemetry on 8888 directly rather than through Alloy, which it exports to. `prometheus-values.yaml` enables the `prometheus` and `kubernetes-pods` jobs explicitly, since deploy-stack does not pin the chart version that defaults them on. Since #1130 the `kubernetes-pods` job keeps only namespace `otel`, and the server's other default jobs are off. `selectors`, `grouping_labels` and `falls_back_to_constant` in `src/devops_cli/prometheus/promql.py` read a PromQL expression's series selectors, its grouping labels, and whether an `or` falls back to a constant. They share one tokenizer that reads each string literal and `#` comment as a single token. A name followed by `(`, or by `by`/`without`, is a function or aggregation; the keywords are a closed set in `constants.py`. A quoted name standing alone among a selector's matchers names the metric, as Prometheus 3 allows (`{"utf8.name", job="x"}`), and a quoted label name counts as a label. An `or`, in any case, falls back to a constant when its right operand, after any `on`/`ignoring` list and opening parentheses, opens with `vector(` or a number: `or vector(0)`, `OR vector(0)`, `or on () vector(0)`, `or 0 * up`. `tests/test_stack_dashboards.py` uses them to check each dashboard against the captures in `tests/fixtures/metrics/`. There, a classic histogram serves only `_bucket` (with `le`), `_sum` and `_count`, and a summary serves its own name (with `quantile`), `_sum` and `_count`. @@ -63,5 +63,5 @@ The time to first token metric carries `model_id` but no `api_base`, so its pane - `kubelet_volume_stats_capacity_bytes{persistentvolumeclaim=~".*prometheus.*"}`: no data, so the TSDB size panel reads the server's own size metrics instead. - Every panel expression through the server's query API: all 15 `prometheus-server.json` queries return series. At 14:54 UTC every LiteLLM query in `llm-stack.json` outside `from_source` returned series, time to first token included. The four GPU queries return series at 07:15 UTC, the last DCGM scrape. Since then Alloy has scraped no DCGM target: the dcgm-exporter release was upgraded at 06:40 UTC with values that leave the chart's 25 s `scrapeTimeout`, longer than the 15 s interval, while `dcgm-exporter-values.yaml` here sets 10 s. The release has been upgraded every four hours (revisions 49-51) with values that predate that setting, so the cluster runs values that drifted from this repository. The `otel-collector.json` queries return nothing until the annotations are deployed. - The collector itself counted 1270 metric points failed and 138 sent by `prometheusremotewrite` at capture time, so most of devops-cli's metrics were not reaching Prometheus (#829). "Metric Points Sent and Failed per Exporter" shows this once the collector is scraped. - - `count by (job) (scrape_duration_seconds)` returns `llm-gateway` beside the server's own four jobs, and `dcgm-exporter` carried it until its scrape stopped: Alloy forwards the scrape series for its ServiceMonitor targets, and its cluster-metrics jobs do not. The "Scrape Duration by Job" description says so. + - `count by (job) (scrape_duration_seconds)` returns `llm-gateway` beside the server's own four jobs, and `dcgm-exporter` carried it until its scrape stopped: Alloy forwards the scrape series for its ServiceMonitor targets, and its cluster-metrics jobs do not. The "Scrape Duration by Job" description says so. Since #1130 the DCGM integration, kube-dns and the annotated pods forward it as well, and the description names them. - Re-checked at 15:43 UTC: all 15 `prometheus-server.json` queries still return series. Every `llm-stack.json` query returns nothing: the gateway pod restarted and has served no request since, and DCGM is still unscraped. `up{namespace="otel"}` and every `otel-collector.json` query return nothing, as the annotations are not deployed. diff --git a/docs/agent/tasks/task-819-deploy-stack-installs-prometheus-operator-crds.md b/docs/agent/tasks/task-819-deploy-stack-installs-prometheus-operator-crds.md index 4aea839c91..0f1a2ab001 100644 --- a/docs/agent/tasks/task-819-deploy-stack-installs-prometheus-operator-crds.md +++ b/docs/agent/tasks/task-819-deploy-stack-installs-prometheus-operator-crds.md @@ -28,7 +28,7 @@ Clusters that once ran kube-prometheus-stack still hold its CRDs, because Helm k - [x] **Cluster-scoped adoption**: `CONST_HELM_OWNERSHIP_CONFLICT_RE` matches Helm's ` "" in namespace ""` with an empty namespace, and adoption omits `-n` for it. The `meta.helm.sh/release-namespace` annotation now carries the release's namespace, which Helm checks it against. It used to carry the resource's namespace: empty for a CRD, and `llm` for k8s-monitoring's `llm-gateway` ServiceMonitor, whose release lives in `monitoring`, so neither could be adopted. - [x] **One deploy adopts every leftover CRD**: Helm names one conflicting resource per failed attempt (`existingResourceConflict` in Helm's `pkg/action/validate.go` stops at the first). The old cap of five retries could adopt only five of the ten CRDs. `_run_helm_with_adoption_retries` now allows `DEFAULT_HELM_RECOVERY_MAX_RETRIES` (20) retries and stops as soon as a retry fails exactly like the attempt before it, so a conflict that adoption cannot clear costs one extra Helm run instead of the whole budget. - [x] **Unit tests** (`tests/test_k8s.py`), with `runtime._run_cmd` and `_cluster_reachable` mocked: - - `test_prometheus_operator_crds_install_before_every_service_monitor`: the CRD release is the first infra release, from a registered repo, and the only releases whose values render a ServiceMonitor are k8s-monitoring and dcgm-exporter, both later in infra. + - `test_prometheus_operator_crds_install_before_every_service_monitor`: the CRD release is the first infra release, from a registered repo, and the only releases whose values render a ServiceMonitor are k8s-monitoring and dcgm-exporter, both later in infra. Since #1130 only k8s-monitoring does: k8s-monitoring's dcgm-exporter integration scrapes the exporter, and its chart's monitor is off. - `test_adopt_helm_resource_addresses_cluster_scoped_and_namespaced_conflicts`: the exact kubectl commands for a cluster-scoped CRD (no `-n`) and for the namespaced `llm-gateway` ServiceMonitor (`-n llm`, release namespace `monitoring`). - `test_helm_retries_adopt_each_leftover_crd_until_the_release_installs`: ten successive CRD conflicts are adopted in one run and the eleventh attempt installs; an unchanged repeated conflict stops after one retry. - `test_teardown_stack_keeps_the_prometheus_operator_crds`: `teardown-stack --stack infra` uninstalls every other infra release in reverse order and never the CRD release, whose values carry the keep policy. diff --git a/docs/agent/tasks/task-825-k8s-monitoring-telemetry-fixes.md b/docs/agent/tasks/task-825-k8s-monitoring-telemetry-fixes.md index 61bb9bc4a3..6c68785370 100644 --- a/docs/agent/tasks/task-825-k8s-monitoring-telemetry-fixes.md +++ b/docs/agent/tasks/task-825-k8s-monitoring-telemetry-fixes.md @@ -25,7 +25,7 @@ Resolves missing metrics and empty/zero-value panels across the Kubernetes Grafa - The OpenTelemetry Collector is scraped through its pod annotations by the Prometheus server's `kubernetes-pods` job (#693). A ServiceMonitor would have Alloy scrape it a second time and double every collector series, so none is added. - Qdrant runs with an API key, so its scrape needs credentials, and no dashboard reads Qdrant since #693 removed the unverified row. The authenticated scrape and its dashboard row are #823. 4. **CoreDNS NetworkPolicy Egress**: - - In `monitoring/networkpolicy.yaml`, egress to `kube-system` allowed port 53 (DNS) but omitted port 9153 (CoreDNS metrics endpoint). The `kube-dns` Service carries `prometheus.io/scrape: "true"` and `prometheus.io/port: "9153"`, so the Prometheus server's `kubernetes-service-endpoints` job tries to scrape CoreDNS, and the perimeter dropped it. The CoreDNS dashboard itself is #822. + - In `monitoring/networkpolicy.yaml`, egress to `kube-system` allowed port 53 (DNS) but omitted port 9153 (CoreDNS metrics endpoint). The `kube-dns` Service carries `prometheus.io/scrape: "true"` and `prometheus.io/port: "9153"`, so the Prometheus server's `kubernetes-service-endpoints` job tries to scrape CoreDNS, and the perimeter dropped it. The CoreDNS dashboard itself is #822. Since #1130 k8s-monitoring's `clusterMetrics.kubeDNS` scrapes CoreDNS through the same egress rule. --- @@ -37,5 +37,5 @@ Resolves missing metrics and empty/zero-value panels across the Kubernetes Grafa - Added missing container status and workload label metrics to `clusterMetrics.kube-state-metrics.metricsTuning.includeMetrics`. - Added port 9153 (TCP) to `monitoring-default-perimeter` NetworkPolicy egress to allow CoreDNS metrics scraping. - [x] **Automated Regression Test Suite** (`tests/test_k8s_monitoring_integration.py`, `tests/test_k8s.py`): - - Authored unit test assertions verifying cAdvisor and KSM metrics tuning, KSM metric labels allowlist, collectors extra, monitoring NetworkPolicy egress rules, the DCGM exporter's scrape timeout and capability, and that the OTel collector is scraped once, through its pod annotations, with no ServiceMonitor. + - Authored unit test assertions verifying cAdvisor and KSM metrics tuning, KSM metric labels allowlist, collectors extra, monitoring NetworkPolicy egress rules, the DCGM exporter's scrape timeout and capability (since #1130, the integration's 15s interval with the chart's ServiceMonitor off), and that the OTel collector is scraped once, through its pod annotations, with no ServiceMonitor. - Verified 100% test pass rate with zero flaky tests. diff --git a/docs/agent/tasks/task-935-dcgm-exporter-dashboard-node-names.md b/docs/agent/tasks/task-935-dcgm-exporter-dashboard-node-names.md index 10dc37ea34..06e8348ecd 100644 --- a/docs/agent/tasks/task-935-dcgm-exporter-dashboard-node-names.md +++ b/docs/agent/tasks/task-935-dcgm-exporter-dashboard-node-names.md @@ -17,6 +17,7 @@ Unlike `node-exporter`, which relabels `__meta_kubernetes_pod_node_name` to `ins - Relabel `__meta_kubernetes_pod_node_name` to `node` (action: `replace`, targetLabel: `node`). - Relabel `__meta_kubernetes_pod_node_name` to `instance` (action: `replace`, targetLabel: `instance`). - Ensures all `DCGM_FI_*` metrics published by DCGM Exporter carry both `node` and `instance` labels set to the Kubernetes node name. + - Since #1130 the k8s-monitoring dcgm-exporter integration scrapes the exporter, its discovery rules set `node` and `instance` the same way, and the chart's ServiceMonitor is off. 2. **Metrics Fixtures & Test Assertions**: - Updated `tests/fixtures/metrics/dcgm-exporter.yaml` to include `node` in `target_labels`. - Updated `tests/test_k8s_monitoring_integration.py` (`test_dcgm_exporter_values_timeout_and_capabilities`) to verify `serviceMonitor.relabelings` mapping `__meta_kubernetes_pod_node_name` to both `node` and `instance`. @@ -28,7 +29,7 @@ Unlike `node-exporter`, which relabels `__meta_kubernetes_pod_node_name` to `ins - Verified DCGM Exporter metrics and Grafana dashboard panels resolve Kubernetes node names. ## Acceptance Criteria -- [x] `k8s/monitoring/dcgm-exporter-values.yaml` defines `serviceMonitor.relabelings` replacing `node` and `instance` with `__meta_kubernetes_pod_node_name`. +- [x] `k8s/monitoring/dcgm-exporter-values.yaml` defines `serviceMonitor.relabelings` replacing `node` and `instance` with `__meta_kubernetes_pod_node_name` (since #1130, the dcgm-exporter integration's discovery rules in `k8s/monitoring/k8s-monitoring-values.yaml`). - [x] Metrics fixtures in `tests/fixtures/metrics/dcgm-exporter.yaml` declare `node` target label. - [x] Unit test `test_dcgm_exporter_values_timeout_and_capabilities` passes and validates relabelings. - [x] OpenTelemetry Collector deploys cleanly with `otlp_http/loki` exporter. diff --git a/k8s/README.md b/k8s/README.md index 18ff56cf6a..7923f5a0b1 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -152,6 +152,25 @@ The `monitoring` perimeter (`monitoring/networkpolicy.yaml`) admits Grafana, Pro - `--addressing fqdn` goes through Traefik. - `--addressing proxy` writes `k8s://` addresses that the API server proxies from the control-plane node's host network. kube-router admits host-network traffic only to pods on the same node, so Grafana, Prometheus and Pyroscope answer this way only while they run on the control-plane node. Elsewhere, use port-forward or `fqdn`. The same holds for any namespace behind a perimeter, `llm` included. +## Scrape Ownership + +Alloy, run by the `k8s-monitoring` release (`monitoring/k8s-monitoring-values.yaml`), scrapes every target but two and remote-writes to the Prometheus server: the kubelet, cAdvisor, kube-state-metrics, node-exporter, the `llm-gateway` ServiceMonitor, CoreDNS (`clusterMetrics.kubeDNS`), the pods annotated for scraping (`annotationAutodiscovery`), and Loki and the DCGM exporter (`integrations`). The Prometheus server scrapes only itself and the OpenTelemetry Collector (#1130). These monitoring components run outside k8s-monitoring: + +| Component | Owner | Reason | +| :--- | :--- | :--- | +| Prometheus server and Alertmanager | Their own `prometheus` release (`monitoring/prometheus-values.yaml`) | k8s-monitoring ships collectors, not a metrics store or an alert router. Alloy writes to this server, which evaluates the alert rules and sends alerts to Alertmanager. The server scrapes itself, and Alloy scrapes Alertmanager through its pod annotations | +| Grafana | Its own `grafana` release (`monitoring/grafana-values.yaml`) | k8s-monitoring does not deploy Grafana. Nothing scrapes it yet; #1131 adds its scrape | +| Loki | Its own `loki` release, in the `logging` stack (`logging/loki-values.yaml`) | Loki belongs to the logging stack, so k8s-monitoring's Loki integration scrapes it only where that stack runs | +| Pyroscope server | Its own `pyroscope` release | k8s-monitoring collects telemetry; it does not deploy the server that stores profiles | +| Trace backend (Jaeger) | Its own manifests in `otel/` | k8s-monitoring deploys no trace store | +| dcgm-exporter | Its own `dcgm-exporter` chart (`monitoring/dcgm-exporter-values.yaml`) | k8s-monitoring's dcgm-exporter integration scrapes the exporter but ships none, so the chart deploys it on every GPU node; the chart's own ServiceMonitor stays off | +| otel-collector | Its own `otel-collector` release (`otel/values.yaml`), scraped by the Prometheus server's `kubernetes-pods` job, which keeps only namespace `otel` | devops-cli exports delta temporality, and Alloy's `deltatocumulative` is experimental only, so k8s-monitoring cannot replace the collector (#1132). The server scrapes it, not Alloy, so the collector's export failures stay visible when Alloy is what fails | +| prometheus-operator-crds | Its own release, installed first | The `llm-gateway` ServiceMonitor and #823's Qdrant monitor need the `monitoring.coreos.com` CRDs, which k8s-monitoring 4.x no longer ships | + +cloudflared, Traefik, Alertmanager and roadmap-service are found by annotation autodiscovery, through the `prometheus.io/*` annotations they already carry, each with the pod's `app.kubernetes.io/name` as its job; CoreDNS comes through `clusterMetrics.kubeDNS`. + +`devops prometheus targets` reads the server's `/api/v1/targets`, so it lists only the server's two jobs; Alloy's targets appear in Prometheus as their `up` series. + ## Grafana Dashboards Dashboards live in `monitoring/dashboards/`. Its `kustomization.yaml` generates four ConfigMaps labelled `grafana_dashboard: "1"`, and the Grafana dashboard sidecar (`monitoring/grafana-values.yaml`) loads every ConfigMap with that label: @@ -170,9 +189,9 @@ The stack dashboards chart the cluster workloads and infrastructure services: | Dashboard | Exporter / Sources | How Prometheus / Loki gets its series | | :--- | :--- | :--- | | `sre-service.json`, "SRE Service & Logs" (`devops-sre-service`) | cAdvisor container CPU, memory, network packets/drops, Loki service logs, and Pyroscope flamegraphs | Metrics scraped by Alloy from cAdvisor/Kubelet and Kube State Metrics; logs pushed to Loki via Alloy or OpenTelemetry collector; continuous profiles queried from Pyroscope datasource | -| `ingress-tunnel.json`, "SRE / Ingress & Cloudflare Tunnel" (`devops-ingress-tunnel`) | Traefik ingress metrics (port 9100) and Cloudflare Tunnel metrics (port 2000) | Scraped directly by the Prometheus server's `kubernetes-pods` job via pod annotations; network policy allows monitoring to scrape Cloudflare Tunnel | -| `llm-stack.json`, "LLM Gateway & GPUs" (`devops-llm-stack`) | LiteLLM's Prometheus callback on the gateway (`/metrics/`), and the NVIDIA DCGM exporter on every GPU node | The `llm-gateway` ServiceMonitor in `monitoring/k8s-monitoring-values.yaml` and the DCGM chart's own ServiceMonitor (`serviceMonitor.enabled` in `monitoring/dcgm-exporter-values.yaml`), read by Alloy, which remote-writes to the server | -| `otel-collector.json`, "OpenTelemetry Collector" (`devops-otel-traces`) | The collector's own telemetry on port 8888 | The server's `kubernetes-pods` job, through the `prometheus.io/scrape` and `prometheus.io/port` pod annotations in `otel/values.yaml`; not through Alloy, so the collector's export failures stay visible when Alloy is what fails | +| `ingress-tunnel.json`, "SRE / Ingress & Cloudflare Tunnel" (`devops-ingress-tunnel`) | Traefik ingress metrics (port 9100) and Cloudflare Tunnel metrics (port 2000) | Alloy's annotation autodiscovery (`annotationAutodiscovery` in `monitoring/k8s-monitoring-values.yaml`), through the pods' `prometheus.io/*` annotations; network policy allows monitoring to scrape both ports | +| `llm-stack.json`, "LLM Gateway & GPUs" (`devops-llm-stack`) | LiteLLM's Prometheus callback on the gateway (`/metrics/`), and the NVIDIA DCGM exporter on every GPU node | The `llm-gateway` ServiceMonitor and the `dcgm-exporter` integration (`integrations` in `monitoring/k8s-monitoring-values.yaml`), run by Alloy, which remote-writes to the server | +| `otel-collector.json`, "OpenTelemetry Collector" (`devops-otel-traces`) | The collector's own telemetry on port 8888 | The server's `kubernetes-pods` job, which keeps only namespace `otel`, through the `prometheus.io/scrape` and `prometheus.io/port` pod annotations in `otel/values.yaml`; not through Alloy, whose annotation autodiscovery skips `otel`, so the collector's export failures stay visible when Alloy is what fails | | `prometheus-server.json`, "Prometheus Server" (`devops-prometheus-server`) | The Prometheus server's own `/metrics`, and `up` for every target | The server's `prometheus` job, which scrapes itself (`scrapeConfigs.prometheus` in `monitoring/prometheus-values.yaml`) | | `pyroscope.json`, "Continuous Profiling / Pyroscope Flamegraphs" (`devops-pyroscope`) | Grafana Pyroscope continuous profiling (CPU, memory, goroutines) | Continuous profiles collected by the Alloy profiling agent and scraped by the Pyroscope backend | @@ -204,7 +223,7 @@ Two alerts in `serverFiles.alerting_rules.yml` (`monitoring/prometheus-values.ya They route like every other rule (Alerting, below), and are listed there with the rest. -Loki's compactor retention takes effect once #550's Loki migration has been applied, a step a person runs: the volume rebind above, then the Loki upgrade. Until then Loki deletes no logs by age. The same upgrade adds the pod annotations through which Prometheus scrapes Loki, so `LokiRetentionNotRunning` has no series before it; after it, the alert fires if the compactor stops applying retention. +Loki's compactor retention takes effect once #550's Loki migration has been applied, a step a person runs: the volume rebind above, then the Loki upgrade. Until then Loki deletes no logs by age. k8s-monitoring's Loki integration scrapes Loki wherever the logging stack runs (Scrape Ownership, above), and the migration only turns retention on; `LokiRetentionNotRunning` fires if the compactor stops applying it. ## Host Journals and Health Metrics @@ -240,7 +259,7 @@ Alertmanager runs from the prometheus chart (`alertmanager` in `monitoring/prome | `PrometheusNearRetentionSizeCap` | Prometheus's data uses over 80% of `server.retentionSize`, before the cap deletes blocks younger than 30 days | 1h | warning | | `PrometheusSizeLimitCutHistory` | Prometheus deleted blocks to stay under its size cap | — | warning | | `PrometheusStorageNearClaim` | Prometheus's data uses over 80% of the `prometheus-server` claim, which with the cap at 80% of the claim means the cap is not holding it | 1h | warning | -| `LokiRetentionNotRunning` | Loki's compactor has not applied retention for over an hour; silent until #550's Loki migration, whose upgrade turns retention on and starts the Loki scrape | 30m | warning | +| `LokiRetentionNotRunning` | Loki's compactor has not applied retention for over an hour; retention runs once #550's Loki migration has turned it on | 30m | warning | | `LokiRequestErrors` | Over 5% of a Loki route's requests return 5xx | 15m | warning | | `ClusterMetricsMissing` | `kube_node_status_condition` is absent, so the node rules cannot fire | 10m | critical | | `PrometheusConfigReloadFailed`, `PrometheusRuleEvaluationFailures`, `PrometheusNotConnectedToAlertmanager`, `PrometheusDroppingAlerts`, `PrometheusCompactionsFailing` | Prometheus's own health | 0–15m | warning | @@ -266,7 +285,7 @@ The monitoring perimeter lets Alertmanager reach ports 80 and 443 outside the cl ### Planned maintenance -Silence the node, then drain it. Every alert about one node carries a `node` label: node-exporter's rules copy it from `instance`, the kubernetes-pods job sets it on the pods it scrapes, and `LogOrMetricVolumeDiskLow` takes it from the pod holding the claim. So one silence covers the node, its scrape targets, its units and the `NodeRebooted` that follows. Make it last the work plus 30 minutes: +Silence the node, then drain it. Every alert about one node carries a `node` label: node-exporter's rules copy it from `instance`; the discovery rules of Alloy's annotation autodiscovery, kube-dns job and DCGM integration, and the server's `kubernetes-pods` job for the collector, set it on the pods they scrape; the Loki integration puts Loki's node in `instance`, which `TargetDown` falls back to; and `LogOrMetricVolumeDiskLow` takes it from the pod holding the claim. So one silence covers the node, its scrape targets, its units and the `NodeRebooted` that follows. Make it last the work plus 30 minutes: ```bash kubectl -n monitoring exec statefulset/prometheus-alertmanager -c alertmanager -- \ @@ -275,7 +294,7 @@ kubectl -n monitoring exec statefulset/prometheus-alertmanager -c alertmanager - kubectl drain --ignore-daemonsets --delete-emptydir-data ``` -The drain matters because a few cluster-wide alerts have no `node` label. One pod, `k8s-monitoring-alloy-metrics-0`, forwards every series from kube-state-metrics, node-exporter and the DCGM exporter. Drained, it starts again on another node. Left on a node that powers off, it stays bound there until the node returns. Those series stop, no other node's `NodeNotReady` can fire, and after about 15 minutes `ClusterMetricsMissing` (critical, no `node` label) pages, because the node silence does not match it. Pods on `local-path` volumes (Prometheus, Loki, Grafana, Pyroscope and Alertmanager) cannot move and wait for their node. While the node holding Prometheus or Alertmanager is down, no alert is evaluated or sent at all. +The drain matters because a few cluster-wide alerts have no `node` label. One pod, `k8s-monitoring-alloy-metrics-0`, forwards every series from kube-state-metrics, node-exporter and the DCGM exporter, and scrapes the annotated pods, Loki and CoreDNS. Drained, it starts again on another node. Left on a node that powers off, it stays bound there until the node returns. Those series stop: the `up` series of the targets it scrapes go stale instead of reporting 0, so no `TargetDown` fires for them, and no other node's `NodeNotReady` can fire. After about 15 minutes `ClusterMetricsMissing` (critical, no `node` label) pages, because the node silence does not match it. Pods on `local-path` volumes (Prometheus, Loki, Grafana, Pyroscope and Alertmanager) cannot move and wait for their node. While the node holding Prometheus or Alertmanager is down, no alert is evaluated or sent at all. After the work, let pods back onto the node, and expire the silence if the work ended early: @@ -600,7 +619,7 @@ k8s/ │ ├── service-aliases.yaml # Alias Services for Prometheus and Grafana; the root kustomization lists them │ ├── dcgm-exporter-values.yaml # Helm values for nvidia/dcgm-exporter (GPU metrics) │ ├── grafana-values.yaml # Helm values for grafana/grafana (datasources, dashboard sidecar) -│ ├── k8s-monitoring-values.yaml # Helm values for grafana/k8s-monitoring (Alloy, kube-state-metrics, node-exporter, node journals, and gateway monitors) +│ ├── k8s-monitoring-values.yaml # Helm values for grafana/k8s-monitoring (Alloy, kube-state-metrics, node-exporter, node journals, gateway monitors, annotation autodiscovery, CoreDNS, and the Loki and DCGM integrations) │ ├── prometheus-operator-crds-values.yaml # Helm values for prometheus-community/prometheus-operator-crds (ServiceMonitor and other monitoring.coreos.com CRDs) │ ├── prometheus-values.yaml # Helm values for prometheus-community/prometheus (server, Alertmanager and alert rules) │ └── dashboards/ diff --git a/k8s/argocd/apps/dcgm-exporter.yaml b/k8s/argocd/apps/dcgm-exporter.yaml index 47d3db9fc1..8bf791b53d 100644 --- a/k8s/argocd/apps/dcgm-exporter.yaml +++ b/k8s/argocd/apps/dcgm-exporter.yaml @@ -30,5 +30,3 @@ spec: duration: 5s factor: 2 maxDuration: 3m - syncOptions: - - SkipDryRunOnMissingResource=true diff --git a/k8s/logging/loki-values.yaml b/k8s/logging/loki-values.yaml index 85186e08a2..74710201d1 100644 --- a/k8s/logging/loki-values.yaml +++ b/k8s/logging/loki-values.yaml @@ -44,12 +44,6 @@ loki: singleBinary: replicas: 1 - # The Prometheus server's kubernetes-pods job scrapes Loki's own metrics through these, for the - # Loki alert rules in monitoring/prometheus-values.yaml (#549). The scrape comes and goes with - # this stack, so an infra-only cluster has no Loki target to report down. - podAnnotations: - prometheus.io/scrape: "true" - prometheus.io/port: "3100" resources: requests: cpu: 100m diff --git a/k8s/monitoring/dashboards/prometheus-server.json b/k8s/monitoring/dashboards/prometheus-server.json index 666cdf74d6..8be43e006c 100644 --- a/k8s/monitoring/dashboards/prometheus-server.json +++ b/k8s/monitoring/dashboards/prometheus-server.json @@ -127,7 +127,7 @@ "refId": "A" } ], - "description": "The slowest scrape in each job: the server's own jobs and Alloy's ServiceMonitor targets (the gateway, DCGM). Alloy's cluster-metrics jobs do not forward this series." + "description": "The slowest scrape in each job: the server's own jobs (prometheus, kubernetes-pods), Alloy's ServiceMonitor target (the gateway), the DCGM integration, kube-dns and the pods Alloy finds by annotation. Alloy's other cluster-metrics jobs and the Loki integration keep only up and scrape_samples_scraped." }, { "id": 4, diff --git a/k8s/monitoring/dcgm-exporter-values.yaml b/k8s/monitoring/dcgm-exporter-values.yaml index 134268c26b..40d9de1564 100644 --- a/k8s/monitoring/dcgm-exporter-values.yaml +++ b/k8s/monitoring/dcgm-exporter-values.yaml @@ -39,20 +39,7 @@ arguments: rollingUpdate: maxUnavailable: "50%" +# k8s-monitoring's dcgm-exporter integration (k8s/monitoring/k8s-monitoring-values.yaml) scrapes +# the exporter, so the chart's own ServiceMonitor, on by chart default, stays off. serviceMonitor: - enabled: true - interval: 15s - scrapeTimeout: 10s - relabelings: - - sourceLabels: [__meta_kubernetes_pod_node_name] - separator: ; - regex: ^(.*)$ - targetLabel: node - replacement: $1 - action: replace - - sourceLabels: [__meta_kubernetes_pod_node_name] - separator: ; - regex: ^(.*)$ - targetLabel: instance - replacement: $1 - action: replace + enabled: false diff --git a/k8s/monitoring/k8s-monitoring-values.yaml b/k8s/monitoring/k8s-monitoring-values.yaml index 31402fe51b..2cf985cbf1 100644 --- a/k8s/monitoring/k8s-monitoring-values.yaml +++ b/k8s/monitoring/k8s-monitoring-values.yaml @@ -60,6 +60,17 @@ clusterMetrics: - kube_pod_container_status_terminated - kube_pod_container_status_waiting - kube_deployment_status_replicas_unavailable + # CoreDNS (#1130), which the Prometheus server's service-endpoints job scraped before. The rule + # keeps each CoreDNS pod's node as `node`, as that job set it, so the node-maintenance silence + # and the NodeNotReady inhibition cover its TargetDown (k8s/README.md, Alerting). The other + # Alloy jobs that took over the server's targets reuse it. + kubeDNS: + enabled: true + extraDiscoveryRules: &node_rule | + rule { + source_labels = ["__meta_kubernetes_pod_node_name"] + target_label = "node" + } hostMetrics: enabled: true @@ -140,6 +151,61 @@ prometheusMetricsReceiver: enabled: true collector: alloy-metrics +# Pods annotated for scraping (#1130): cloudflared, Traefik, Alertmanager and roadmap-service, +# found through the `prometheus.io/*` keys they already carry. The job is the pod's +# app.kubernetes.io/name. `otel` is left to the Prometheus server, which scrapes the collector +# so its export failures stay visible when Alloy is what fails. The only annotated Service is +# kube-dns, which clusterMetrics.kubeDNS scrapes, so Service discovery stays off. No annotated +# target needs the ServiceAccount token, which must not go to every annotated pod over plain +# HTTP, so it is not sent. +annotationAutodiscovery: + enabled: true + collector: alloy-metrics + annotations: + scrape: prometheus.io/scrape + metricsPortNumber: prometheus.io/port + metricsPath: prometheus.io/path + excludeNamespaces: + - otel + services: + enabled: false + bearerToken: + enabled: false + extraDiscoveryRules: *node_rule + +# Service integrations (#1130), each a plain list of instances. +integrations: + collector: alloy-metrics + # Loki's own metrics, within the integration's default allow list, wherever the logging stack + # runs; the component selector leaves out the Loki canary pods. Metrics only: Loki's own pod + # logs stay as podLogsViaLoki ships them, without the integration's log processing. + loki: + instances: + - name: loki + labelSelectors: + app.kubernetes.io/name: loki + app.kubernetes.io/component: single-binary + logs: + enabled: false + # The DCGM exporter on every GPU node. Its series carry the GPU's node as `node`, which the GPU + # rules group by, and as `instance`, which dashboard 12239 lists. + dcgm-exporter: + instances: + - name: dcgm-exporter + labelSelectors: + app.kubernetes.io/name: dcgm-exporter + metrics: + scrapeInterval: 15s + extraDiscoveryRules: | + rule { + source_labels = ["__meta_kubernetes_pod_node_name"] + target_label = "node" + } + rule { + source_labels = ["__meta_kubernetes_pod_node_name"] + target_label = "instance" + } + # ── Telemetry Services ─────────────────────────────────────────────────────── telemetryServices: kube-state-metrics: diff --git a/k8s/monitoring/prometheus-operator-crds-values.yaml b/k8s/monitoring/prometheus-operator-crds-values.yaml index 4b1c863b41..2f9c6d86fb 100644 --- a/k8s/monitoring/prometheus-operator-crds-values.yaml +++ b/k8s/monitoring/prometheus-operator-crds-values.yaml @@ -3,9 +3,9 @@ # Repo: https://prometheus-community.github.io/helm-charts # # k8s-monitoring 4.x no longer bundles these CRDs and asks for this chart to be installed first -# (its UPGRADING.md, "Prometheus Operator Object CRDs removed"). Its extraObjects and the -# dcgm-exporter chart render ServiceMonitors, and Alloy's prometheusOperatorObjects feature -# watches ServiceMonitors, PodMonitors and Probes. Deleting a CRD deletes every object of its +# (its UPGRADING.md, "Prometheus Operator Object CRDs removed"). Only its extraObjects render +# ServiceMonitors, and Alloy's prometheusOperatorObjects feature watches ServiceMonitors, +# PodMonitors and Probes. Deleting a CRD deletes every object of its # kind in the cluster, so teardown-stack never uninstalls this release. crds: diff --git a/k8s/monitoring/prometheus-values.yaml b/k8s/monitoring/prometheus-values.yaml index b9f5441f74..d0544e318a 100644 --- a/k8s/monitoring/prometheus-values.yaml +++ b/k8s/monitoring/prometheus-values.yaml @@ -49,10 +49,13 @@ alertmanager: limits: cpu: 100m memory: 128Mi - # The server's kubernetes-pods job scrapes Alertmanager's own metrics for its health rules. + # k8s-monitoring's annotation autodiscovery scrapes Alertmanager's own metrics for its health + # rules. It also finds the config-reloader sidecar and rewrites that target to the annotated + # port, so the container key keeps it from scraping Alertmanager a second time. podAnnotations: prometheus.io/scrape: "true" prometheus.io/port: "9093" + k8s.grafana.com/metrics.container: alertmanager extraSecretMounts: - name: webhook-url mountPath: /etc/alertmanager-webhook @@ -100,43 +103,45 @@ kube-state-metrics: prometheus-pushgateway: enabled: false -# The stack dashboards read the server's self-scrape (prometheus-server.json) and the -# collector, scraped by the kubernetes-pods job through its pod annotations -# (otel-collector.json). Both are on by chart default; they are set here because -# deploy-stack installs the chart without pinning the version that supplies that default. +# The server scrapes only itself (prometheus-server.json) and the otel collector +# (otel-collector.json); k8s-monitoring discovers every other target (k8s/README.md, Scrape +# Ownership). The chart turns each of its default jobs on unless it is set `enabled: false`. scrapeConfigs: + # Both jobs label their series with the cluster, the k8s-monitoring `cluster.name` Alloy + # writes. Prometheus adds `external_labels` only to remote write, federation and alerts, not + # to the series it stores. prometheus: enabled: true - kubernetes-nodes: - enabled: false - kubernetes-nodes-cadvisor: - enabled: false - kubernetes-api-servers: - post_relabel_configs: | + post_relabel_configs: &cluster | - action: replace target_label: cluster replacement: homelab-k3s + # Only the collector, which the server scrapes directly rather than through Alloy, so the + # export failures it counts stay visible when Alloy is what fails (k8s/README.md). Its pods + # carry the `prometheus.io/*` annotations, and k8s-monitoring's autodiscovery skips `otel`. kubernetes-pods: enabled: true - post_relabel_configs: | - - action: replace - target_label: cluster - replacement: homelab-k3s - kubernetes-pods-slow: - post_relabel_configs: | - - action: replace - target_label: cluster - replacement: homelab-k3s + pre_relabel_configs: | + - source_labels: [__meta_kubernetes_namespace] + action: keep + regex: otel + post_relabel_configs: *cluster + kubernetes-api-servers: + enabled: false + kubernetes-nodes: + enabled: false + kubernetes-nodes-cadvisor: + enabled: false kubernetes-service-endpoints: - post_relabel_configs: | - - action: replace - target_label: cluster - replacement: homelab-k3s + enabled: false kubernetes-service-endpoints-slow: - post_relabel_configs: | - - action: replace - target_label: cluster - replacement: homelab-k3s + enabled: false + kubernetes-services: + enabled: false + kubernetes-pods-slow: + enabled: false + prometheus-pushgateway: + enabled: false # Alert rules (#549, #550). Every rule carries `severity` (critical or warning, both routed to # the webhook) and, when it concerns one node, `node`, so one `node=` silence covers a node @@ -414,10 +419,9 @@ serverFiles: description: "Over 5% of Loki's {{ $labels.route }} requests have returned a 5xx status for 15 minutes." # Loki keeps logs 30 days (`retention_period: 720h`), but only its compactor's retention # deletes them, on every compaction (every 10 minutes). #550 turns that retention on - # (`compactor.retention_enabled`). It takes effect with #550's Loki migration, whose Loki - # upgrade also adds the pod annotations this rule's scrape needs, so before it this rule - # has no series; after it, it fires if the compactor stops applying retention. - # Loki and its metrics come with the logging stack; without it this stays silent. + # (`compactor.retention_enabled`), and it takes effect with #550's Loki migration; this + # rule fires if the compactor stops applying it. Loki's series come from k8s-monitoring's + # Loki integration wherever the logging stack runs; without that stack this stays silent. - alert: LokiRetentionNotRunning expr: time() - loki_compactor_apply_retention_last_successful_run_timestamp_seconds > 3600 for: 30m diff --git a/src/devops_cli/commands/k8s/stack_lifecycle.py b/src/devops_cli/commands/k8s/stack_lifecycle.py index 5199ce0d69..ddcf0bbcfd 100644 --- a/src/devops_cli/commands/k8s/stack_lifecycle.py +++ b/src/devops_cli/commands/k8s/stack_lifecycle.py @@ -77,8 +77,8 @@ _HELM_RELEASES_BY_STACK: dict[str, list[dict[str, str]]] = { "infra": [ - # First: k8s-monitoring's extraObjects and dcgm-exporter render ServiceMonitors, and no - # other chart ships their CRD (k8s-monitoring 4.x dropped it). + # First: only k8s-monitoring's extraObjects render ServiceMonitors, and no other chart + # ships their CRD (k8s-monitoring 4.x dropped it). { "name": "prometheus-operator-crds", "chart": "prometheus-community/prometheus-operator-crds", diff --git a/tests/fixtures/metrics/dcgm-exporter.yaml b/tests/fixtures/metrics/dcgm-exporter.yaml index dcaa58d5cb..fcbd663b8b 100644 --- a/tests/fixtures/metrics/dcgm-exporter.yaml +++ b/tests/fixtures/metrics/dcgm-exporter.yaml @@ -14,10 +14,11 @@ taken_from: >- profiling (DCGM_FI_PROF_*) fields, read in the plain text format (version 0.0.4) through the Kubernetes API service proxy. scraped_by: >- - The chart's own ServiceMonitor (serviceMonitor.enabled in - k8s/monitoring/dcgm-exporter-values.yaml), read by Alloy (k8s-monitoring 4.5.2), which - remote-writes to the Prometheus server. -target_labels: [cluster, container, endpoint, instance, job, namespace, node, pod, service] + The k8s-monitoring dcgm-exporter integration (integrations.dcgm-exporter in + k8s/monitoring/k8s-monitoring-values.yaml), run by Alloy (k8s-monitoring 4.5.2), which + remote-writes to the Prometheus server. Its discovery rules set node and instance to the + pod's node. +target_labels: [cluster, instance, job, node] families: DCGM_FI_DEV_DEC_UTIL: {type: gauge, labels: [DCGM_FI_DRIVER_VERSION, UUID, device, gpu, hostname, modelName, pci_bus_id]} DCGM_FI_DEV_ENC_UTIL: {type: gauge, labels: [DCGM_FI_DRIVER_VERSION, UUID, device, gpu, hostname, modelName, pci_bus_id]} diff --git a/tests/fixtures/metrics/prometheus-server.yaml b/tests/fixtures/metrics/prometheus-server.yaml index a5b735438a..4cce02d0eb 100644 --- a/tests/fixtures/metrics/prometheus-server.yaml +++ b/tests/fixtures/metrics/prometheus-server.yaml @@ -14,8 +14,8 @@ taken_from: >- format (version 0.0.4) through the Kubernetes API service proxy. scraped_by: >- The server's own prometheus job, which scrapes localhost:9090 (scrapeConfigs.prometheus in - k8s/monitoring/prometheus-values.yaml). Its relabelling adds no cluster label. -target_labels: [instance, job] + k8s/monitoring/prometheus-values.yaml). Its relabelling adds the cluster label. +target_labels: [cluster, instance, job] families: go_gc_cleanups_executed_cleanups_total: {type: counter, labels: []} go_gc_cleanups_queued_cleanups_total: {type: counter, labels: []} diff --git a/tests/test_k8s.py b/tests/test_k8s.py index 04a9b073c5..fd20dbd1fb 100644 --- a/tests/test_k8s.py +++ b/tests/test_k8s.py @@ -393,7 +393,7 @@ def test_prometheus_operator_crds_install_before_every_service_monitor() -> None ) == ( ("prometheus-operator-crds", "prometheus-community/prometheus-operator-crds", "monitoring"), True, - [("infra", "k8s-monitoring"), ("infra", "dcgm-exporter")], + [("infra", "k8s-monitoring")], ) diff --git a/tests/test_k8s_monitoring_alerting.py b/tests/test_k8s_monitoring_alerting.py index 74520117e3..66a3f37224 100644 --- a/tests/test_k8s_monitoring_alerting.py +++ b/tests/test_k8s_monitoring_alerting.py @@ -25,7 +25,6 @@ PROMETHEUS_VALUES = K8S / "monitoring" / "prometheus-values.yaml" GRAFANA_VALUES = K8S / "monitoring" / "grafana-values.yaml" K8S_MONITORING_VALUES = K8S / "monitoring" / "k8s-monitoring-values.yaml" -LOKI_VALUES = K8S / "logging" / "loki-values.yaml" # Every series an alert rule may select, by what serves it. SERVED_SERIES = frozenset( @@ -50,7 +49,7 @@ "node_filesystem_size_bytes", "node_systemd_unit_state", "node_time_seconds", - # The DCGM exporter on every GPU node, through its own ServiceMonitor. + # The DCGM exporter on every GPU node, through k8s-monitoring's dcgm-exporter integration. "DCGM_FI_DEV_GPU_TEMP", "DCGM_FI_DEV_POWER_USAGE", # The Prometheus server's self-scrape (`scrapeConfigs.prometheus`). @@ -64,11 +63,12 @@ "prometheus_tsdb_size_retentions_total", "prometheus_tsdb_storage_blocks_bytes", "prometheus_tsdb_wal_storage_size_bytes", - # Loki, scraped by the server's kubernetes-pods job through the pod annotations in - # `k8s/logging/loki-values.yaml`, so only where the logging stack runs. + # Loki, scraped by k8s-monitoring's Loki integration within its default allow list, which + # finds Loki's pods only where the logging stack runs. "loki_compactor_apply_retention_last_successful_run_timestamp_seconds", "loki_request_duration_seconds_count", - # Alertmanager, scraped by the server's kubernetes-pods job through its annotations. + # Alertmanager, found through its pod annotations by k8s-monitoring's annotation + # autodiscovery. "alertmanager_config_last_reload_successful", "alertmanager_notifications_failed_total", } @@ -248,23 +248,32 @@ def test_alertmanager_inhibits_follow_on_alerts() -> None: ] -def test_prometheus_scrapes_loki_and_alertmanager_for_their_health() -> None: - """Loki and Alertmanager are scraped through their own pod annotations, with their stacks. +def test_k8s_monitoring_scrapes_loki_and_alertmanager_for_their_health() -> None: + """Loki and Alertmanager are found by k8s-monitoring where they run, with their stacks (#1130). The Prometheus values belong to the infra stack, and Loki only to the logging stack, so a static Loki target in them would be down for good on an infra-only cluster and keep - `TargetDown` firing. The kubernetes-pods job finds an annotated pod only where it runs. + `TargetDown` firing. The Loki integration selects Loki's pods by label, and annotation + autodiscovery finds Alertmanager through its pod annotations; the container annotation keeps + the config-reloader sidecar from being scraped on Alertmanager's port a second time. """ values = _yaml(PROMETHEUS_VALUES) - loki = _yaml(LOKI_VALUES)["singleBinary"]["podAnnotations"] + (loki,) = _yaml(K8S_MONITORING_VALUES)["integrations"]["loki"]["instances"] alertmanager = values["alertmanager"]["podAnnotations"] assert ( - (loki["prometheus.io/scrape"], loki["prometheus.io/port"]), - (alertmanager["prometheus.io/scrape"], alertmanager["prometheus.io/port"]), - values["scrapeConfigs"]["kubernetes-pods"]["enabled"], + loki["labelSelectors"], + alertmanager, "extraScrapeConfigs" in values, - ) == (("true", "3100"), ("true", "9093"), True, False) + ) == ( + {"app.kubernetes.io/name": "loki", "app.kubernetes.io/component": "single-binary"}, + { + "prometheus.io/scrape": "true", + "prometheus.io/port": "9093", + "k8s.grafana.com/metrics.container": "alertmanager", + }, + False, + ) def test_the_claim_rule_divides_one_series_by_one() -> None: diff --git a/tests/test_k8s_monitoring_integration.py b/tests/test_k8s_monitoring_integration.py index 2c8e25727c..766fd8853d 100644 --- a/tests/test_k8s_monitoring_integration.py +++ b/tests/test_k8s_monitoring_integration.py @@ -2,11 +2,15 @@ from __future__ import annotations +import re from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass from pathlib import Path from typing import Any from urllib.parse import urlsplit +import pytest import yaml from devops_cli.commands.k8s.networking import _collect_port_forward_services @@ -23,10 +27,87 @@ # The k8s-monitoring chart's presets that set an Alloy collector's controller (`collectors/presets/`). CONTROLLER_PRESETS = {"singleton", "daemonset", "statefulset", "deployment"} +# The scrape jobs prometheus 29.35.0's values.yaml defines. The chart renders each one unless its +# `scrapeConfigs` entry sets `enabled: false`, so a job the values leave out is on. +PROMETHEUS_DEFAULT_JOBS = ( + "prometheus", + "kubernetes-api-servers", + "kubernetes-nodes", + "kubernetes-nodes-cadvisor", + "kubernetes-service-endpoints", + "kubernetes-service-endpoints-slow", + "prometheus-pushgateway", + "kubernetes-services", + "kubernetes-pods", + "kubernetes-pods-slow", +) + +# The Alloy discovery rules that copy a pod's node name to `node` and to `instance`, with their +# whitespace normalised. +NODE_RULE = 'source_labels = ["__meta_kubernetes_pod_node_name"] target_label = "node"' +INSTANCE_RULE = 'source_labels = ["__meta_kubernetes_pod_node_name"] target_label = "instance"' + +# Pod labels the charts put on the components they install; the repo's values do not hold them. +LOKI_POD_LABELS = {"app.kubernetes.io/name": "loki", "app.kubernetes.io/component": "single-binary"} +DCGM_POD_LABELS = {"app.kubernetes.io/name": "dcgm-exporter"} +ALERTMANAGER_POD_LABELS = {"app.kubernetes.io/name": "alertmanager"} +COLLECTOR_POD_LABELS = {"app.kubernetes.io/name": "opentelemetry-collector"} + +# Metrics ports k3s and the charts set, which the repo's values do not hold. +COREDNS_NAMESPACE = "kube-system" +COREDNS_METRICS_PORT = 9153 +LOKI_METRICS_PORT = 3100 # Loki's http-metrics port, which the Loki integration scrapes +DCGM_METRICS_PORT = 9400 + + +def _k8s_yaml(relative: str) -> Any: + with open(K8S_DIR / relative, encoding="utf-8") as f: + return yaml.load(f, Loader=yaml.CSafeLoader) + def _k8s_monitoring_values() -> Any: - with open(K8S_DIR / "monitoring" / "k8s-monitoring-values.yaml", encoding="utf-8") as f: - return yaml.safe_load(f) + return _k8s_yaml("monitoring/k8s-monitoring-values.yaml") + + +def _squashed(text: str) -> str: + """Alloy configuration with its whitespace normalised, for substring checks.""" + return " ".join(text.split()) + + +def _argo_namespace(app: str) -> str: + """The namespace Argo CD installs an Application into.""" + namespace: str = _k8s_yaml(f"argocd/apps/{app}.yaml")["spec"]["destination"]["namespace"] + return namespace + + +def _integration(values: dict[str, Any], kind: str) -> dict[str, Any]: + """The one instance of a k8s-monitoring service integration.""" + (instance,) = values["integrations"][kind]["instances"] + return dict(instance) + + +def _server_jobs(prometheus: dict[str, Any]) -> tuple[str, ...]: + """The scrape jobs the Prometheus chart renders: its defaults unless turned off, and any added.""" + jobs = prometheus.get("scrapeConfigs", {}) + return tuple( + sorted( + job + for job in {*PROMETHEUS_DEFAULT_JOBS, *jobs} + if jobs.get(job, {}).get("enabled", True) + ) + ) + + +def _server_pod_namespaces(prometheus: dict[str, Any]) -> str: + """The namespace regex the server's kubernetes-pods job keeps before the chart's own rules.""" + rules = yaml.safe_load(prometheus["scrapeConfigs"]["kubernetes-pods"]["pre_relabel_configs"]) + (regex,) = [ + rule["regex"] + for rule in rules + if rule.get("action") == "keep" + and rule.get("source_labels") == ["__meta_kubernetes_namespace"] + ] + return str(regex) def test_k8s_monitoring_cadvisor_and_ksm_metrics_tuning() -> None: @@ -310,26 +391,248 @@ def test_deploy_stack_applies_the_monitoring_services_the_stack_addresses() -> N assert sorted(addressed - kustomized_objects(K8S_DIR, "Service") - helm_services) == [] -def test_dcgm_exporter_values_timeout_and_capabilities() -> None: - """Verify DCGM exporter has bounded scrapeTimeout and SYS_ADMIN capability for datacenter GPUs.""" - dcgm_values_path = K8S_DIR / "monitoring" / "dcgm-exporter-values.yaml" - with open(dcgm_values_path, encoding="utf-8") as f: - data = yaml.safe_load(f) - - sm = data.get("serviceMonitor", {}) - sec = data.get("securityContext", {}) - caps = sec.get("capabilities", {}).get("add", []) - - relabelings = sm.get("relabelings", []) - target_labels = [r.get("targetLabel") for r in relabelings] +def test_dcgm_exporter_is_scraped_by_the_integration_and_holds_sys_admin() -> None: + """The k8s-monitoring dcgm-exporter integration scrapes the exporter every 15s (#1130), so the + chart's own ServiceMonitor, on by chart default, stays off. Datacenter GPUs need SYS_ADMIN for + the DCGM host engine's hardware counters.""" + data = _k8s_yaml("monitoring/dcgm-exporter-values.yaml") + caps = data.get("securityContext", {}).get("capabilities", {}).get("add", []) + integration = _integration(_k8s_monitoring_values(), "dcgm-exporter") assert ( - sm.get("enabled"), - sm.get("interval"), - sm.get("scrapeTimeout"), "SYS_ADMIN" in caps, - target_labels, - ) == (True, "15s", "10s", True, ["node", "instance"]) + data.get("serviceMonitor"), + integration["metrics"]["scrapeInterval"], + ) == (True, {"enabled": False}, "15s") + + +def test_scrape_ownership_moves_to_k8s_monitoring() -> None: + """The Prometheus server scrapes only itself and the otel collector, and k8s-monitoring + discovers every other target (#1130). + + The collector stays on the server so its export failures stay visible when Alloy is what + fails. Both server jobs take the cluster label from one anchor, equal to k8s-monitoring's + `cluster.name`. Alloy finds the other annotated pods through annotation autodiscovery, with + the `prometheus.io/*` keys they already carry and without the ServiceAccount token. CoreDNS, + Loki and DCGM come through the chart's kubeDNS job and integrations. Every Alloy job that + replaces a server job keeps the pod's node as `node`, which the node silence matches. + Alertmanager names its container, so the config-reloader sidecar's target, rewritten to the + annotated port, does not scrape it twice.""" + prometheus = _k8s_yaml("monitoring/prometheus-values.yaml") + values = _k8s_monitoring_values() + jobs = prometheus["scrapeConfigs"] + (cluster_rule,) = yaml.safe_load(jobs["prometheus"]["post_relabel_configs"]) + autodiscovery = values["annotationAutodiscovery"] + kube_dns = values["clusterMetrics"]["kubeDNS"] + loki = _integration(values, "loki") + dcgm = _integration(values, "dcgm-exporter") + dcgm_rules = _squashed(dcgm["extraDiscoveryRules"]) + loki_annotations = _k8s_yaml("logging/loki-values.yaml")["singleBinary"].get("podAnnotations") + + assert ( + _server_jobs(prometheus), + _server_pod_namespaces(prometheus), + jobs["kubernetes-pods"]["post_relabel_configs"] + == jobs["prometheus"]["post_relabel_configs"], + (cluster_rule["action"], cluster_rule["target_label"], cluster_rule["replacement"]), + (autodiscovery["enabled"], autodiscovery["collector"]), + autodiscovery["annotations"], + ( + autodiscovery["excludeNamespaces"], + autodiscovery["services"]["enabled"], + autodiscovery["bearerToken"]["enabled"], + ), + NODE_RULE in _squashed(autodiscovery["extraDiscoveryRules"]), + (kube_dns["enabled"], NODE_RULE in _squashed(kube_dns["extraDiscoveryRules"])), + values["integrations"]["collector"], + (loki["labelSelectors"], loki["logs"]["enabled"], "tuning" in loki.get("metrics", {})), + ( + dcgm["labelSelectors"], + dcgm["metrics"]["scrapeInterval"], + NODE_RULE in dcgm_rules, + INSTANCE_RULE in dcgm_rules, + ), + sorted(key for key in loki_annotations or {} if key.startswith("prometheus.io/")), + _k8s_yaml("monitoring/dcgm-exporter-values.yaml")["serviceMonitor"], + prometheus["alertmanager"]["podAnnotations"], + ) == ( + ("kubernetes-pods", "prometheus"), + "otel", + True, + ("replace", "cluster", values["cluster"]["name"]), + (True, "alloy-metrics"), + { + "scrape": "prometheus.io/scrape", + "metricsPortNumber": "prometheus.io/port", + "metricsPath": "prometheus.io/path", + }, + (["otel"], False, False), + True, + (True, True), + "alloy-metrics", + (LOKI_POD_LABELS, False, False), + (DCGM_POD_LABELS, "15s", True, True), + [], + {"enabled": False}, + { + "prometheus.io/scrape": "true", + "prometheus.io/port": "9093", + "k8s.grafana.com/metrics.container": "alertmanager", + }, + ) + + +@dataclass(frozen=True) +class _Pods: + """A component's pods as a scrape sees them.""" + + namespace: str + labels: dict[str, str] + annotations: dict[str, str] + chart_monitor: bool = False # the component's own chart renders a ServiceMonitor for it + + +def _repo_scrape_sources() -> dict[str, Any]: + """The values and manifests that decide what scrapes each annotated component.""" + return { + "prometheus": _k8s_yaml("monitoring/prometheus-values.yaml"), + "k8s-monitoring": _k8s_monitoring_values(), + "dcgm-exporter": _k8s_yaml("monitoring/dcgm-exporter-values.yaml"), + "otel": _k8s_yaml("otel/values.yaml"), + "loki": _k8s_yaml("logging/loki-values.yaml"), + "cloudflared": _k8s_yaml("cloudflared/deployment.yaml"), + "roadmap-service": _k8s_yaml("devops/roadmap-service/deployment.yaml"), + } + + +def _deployment_pods(deployment: dict[str, Any]) -> _Pods: + template = deployment["spec"]["template"]["metadata"] + return _Pods( + deployment["metadata"]["namespace"], template["labels"], template.get("annotations", {}) + ) + + +def _annotated_components(sources: dict[str, Any]) -> dict[str, _Pods]: + """The components the server's pod discovery scraped before #1130, and DCGM.""" + return { + "cloudflared": _deployment_pods(sources["cloudflared"]), + "roadmap-service": _deployment_pods(sources["roadmap-service"]), + "alertmanager": _Pods( + _argo_namespace("prometheus"), + ALERTMANAGER_POD_LABELS, + sources["prometheus"]["alertmanager"].get("podAnnotations", {}), + ), + "otel-collector": _Pods( + _argo_namespace("otel-collector"), + COLLECTOR_POD_LABELS, + sources["otel"].get("podAnnotations", {}), + ), + "loki": _Pods( + _argo_namespace("loki"), + LOKI_POD_LABELS, + sources["loki"]["singleBinary"].get("podAnnotations") or {}, + ), + "dcgm-exporter": _Pods( + _argo_namespace("dcgm-exporter"), + DCGM_POD_LABELS, + {}, + # The chart renders its ServiceMonitor unless the values turn it off. + chart_monitor=sources["dcgm-exporter"].get("serviceMonitor", {}).get("enabled", True), + ), + } + + +def _scrape_owners(sources: dict[str, Any]) -> dict[str, list[str]]: + """Every scrape that claims each annotated component.""" + server_namespaces = _server_pod_namespaces(sources["prometheus"]) + values = sources["k8s-monitoring"] + autodiscovery = values["annotationAutodiscovery"] + instances = [ + (f"integrations/{kind}", instance["labelSelectors"]) + for kind, integration in values["integrations"].items() + if isinstance(integration, dict) + for instance in integration.get("instances", []) + ] + + def owners(pods: _Pods) -> list[str]: + server = pods.annotations.get("prometheus.io/scrape") == "true" and bool( + re.fullmatch(server_namespaces, pods.namespace) + ) + autodiscovered = ( + autodiscovery["enabled"] is True + and pods.annotations.get(autodiscovery["annotations"]["scrape"]) == "true" + and pods.namespace not in autodiscovery["excludeNamespaces"] + ) + return [ + *(["kubernetes-pods"] if server else []), + *(["annotationAutodiscovery"] if autodiscovered else []), + *(owner for owner, selectors in instances if selectors.items() <= pods.labels.items()), + *(["chart ServiceMonitor"] if pods.chart_monitor else []), + ] + + return {name: owners(pods) for name, pods in _annotated_components(sources).items()} + + +def test_each_annotated_component_has_one_scrape_owner() -> None: + """Each component the server's pod discovery found before #1130 has exactly one scrape: none + leaves a gap in its series, and two would double every series on its dashboards.""" + assert _scrape_owners(_repo_scrape_sources()) == { + "cloudflared": ["annotationAutodiscovery"], + "roadmap-service": ["annotationAutodiscovery"], + "alertmanager": ["annotationAutodiscovery"], + "otel-collector": ["kubernetes-pods"], + "loki": ["integrations/loki"], + "dcgm-exporter": ["integrations/dcgm-exporter"], + } + + +def _drop_alertmanager_scrape_annotation(sources: dict[str, Any]) -> None: + del sources["prometheus"]["alertmanager"]["podAnnotations"]["prometheus.io/scrape"] + + +def _drop_collector_annotations(sources: dict[str, Any]) -> None: + del sources["otel"]["podAnnotations"] + + +def _autodiscover_the_otel_namespace(sources: dict[str, Any]) -> None: + sources["k8s-monitoring"]["annotationAutodiscovery"]["excludeNamespaces"].remove("otel") + + +def _annotate_loki_again(sources: dict[str, Any]) -> None: + sources["loki"]["singleBinary"]["podAnnotations"] = { + "prometheus.io/scrape": "true", + "prometheus.io/port": str(LOKI_METRICS_PORT), + } + + +@pytest.mark.parametrize( + ("mutate", "unowned_or_twice_owned"), + [ + (_drop_alertmanager_scrape_annotation, {"alertmanager": []}), + (_drop_collector_annotations, {"otel-collector": []}), + ( + _autodiscover_the_otel_namespace, + {"otel-collector": ["kubernetes-pods", "annotationAutodiscovery"]}, + ), + (_annotate_loki_again, {"loki": ["annotationAutodiscovery", "integrations/loki"]}), + ], + ids=[ + "alertmanager-unannotated", + "collector-unannotated", + "otel-autodiscovered", + "loki-annotated", + ], +) +def test_a_component_with_no_scrape_owner_or_two_fails( + mutate: Callable[[dict[str, Any]], None], unowned_or_twice_owned: dict[str, list[str]] +) -> None: + """Pin the ownership check on the mutations that break it.""" + sources = _repo_scrape_sources() + mutate(sources) + + assert { + name: owners for name, owners in _scrape_owners(sources).items() if len(owners) != 1 + } == unowned_or_twice_owned def _has_ingress_port_from_namespace( @@ -350,22 +653,63 @@ def _has_ingress_port_from_namespace( return False -def _has_egress_port_to_namespace( - rules: list[dict[str, Any]], target_ns: str, target_port: int -) -> bool: - """Predicate checking whether an egress rule allows target_port to target_ns.""" - for rule in rules: - ns_matches = any( - dst.get("namespaceSelector", {}) - .get("matchLabels", {}) - .get("kubernetes.io/metadata.name") - == target_ns - for dst in rule.get("to", []) - ) - port_matches = any(p.get("port") == target_port for p in rule.get("ports", [])) - if ns_matches and port_matches: - return True - return False +def _peer_in(peer: dict[str, Any], policy_ns: str, target_ns: str) -> bool: + """Whether a NetworkPolicy peer selects pods in `target_ns`. + + A bare `podSelector` selects pods in the policy's own namespace. An ipBlock peer names + addresses rather than a namespace, so it is not counted. + """ + if "namespaceSelector" in peer: + selector = peer["namespaceSelector"].get("matchLabels", {}) + return bool(selector.get("kubernetes.io/metadata.name") == target_ns) + return "podSelector" in peer and policy_ns == target_ns + + +def _egress_rules_to(rules: list[dict[str, Any]], policy_ns: str, target_ns: str, port: int) -> int: + """How many egress rules of a policy in `policy_ns` admit `port` in `target_ns`.""" + return sum( + 1 + for rule in rules + if any(_peer_in(peer, policy_ns, target_ns) for peer in rule.get("to", [])) + and ("ports" not in rule or any(p.get("port") == port for p in rule["ports"])) + ) + + +def test_every_scrape_port_has_one_egress_rule() -> None: + """Alloy's collectors and the Prometheus server both run in `monitoring`, behind its + perimeter, so each port they scrape needs an egress rule there (#1130). Without one the + scrape is dropped; with two, narrowing one rule would leave the port open through the other. + The ports are the annotated pods' own, Traefik's metrics entry point, and the ports the + charts and k3s set for CoreDNS, Loki and DCGM.""" + policy = _k8s_yaml("monitoring/networkpolicy.yaml") + egress = policy["spec"]["egress"] + traefik_port = _k8s_yaml("ingress/traefik-values.yaml")["ports"]["metrics"]["port"] + scrapes = { + *( + (pods.namespace, int(pods.annotations["prometheus.io/port"])) + for pods in _annotated_components(_repo_scrape_sources()).values() + if "prometheus.io/port" in pods.annotations + ), + (_argo_namespace("traefik"), traefik_port), + (COREDNS_NAMESPACE, COREDNS_METRICS_PORT), + (_argo_namespace("loki"), LOKI_METRICS_PORT), + (_argo_namespace("dcgm-exporter"), DCGM_METRICS_PORT), + } + counts = { + scrape: _egress_rules_to(egress, policy["metadata"]["namespace"], *scrape) + for scrape in scrapes + } + + assert sorted(counts.items()) == [ + (("cloudflared", 2000), 1), + (("devops", 8000), 1), + (("kube-system", 9100), 1), + (("kube-system", 9153), 1), + (("logging", 3100), 1), + (("monitoring", 9093), 1), + (("monitoring", 9400), 1), + (("otel", 8888), 1), + ] def test_otel_collector_logs_pipeline_exports_to_loki() -> None: @@ -402,6 +746,6 @@ def test_otel_and_logging_network_policies_allow_telemetry_flow() -> None: assert ( _has_ingress_port_from_namespace(log_ingress, "otel", 3100), - _has_egress_port_to_namespace(otel_egress, "logging", 3100), - _has_egress_port_to_namespace(otel_egress, "monitoring", 9090), + _egress_rules_to(otel_egress, "otel", "logging", 3100) > 0, + _egress_rules_to(otel_egress, "otel", "monitoring", 9090) > 0, ) == (True, True, True) diff --git a/tests/test_llm_pool_metrics.py b/tests/test_llm_pool_metrics.py index b515833761..7d3c8a38a3 100644 --- a/tests/test_llm_pool_metrics.py +++ b/tests/test_llm_pool_metrics.py @@ -115,7 +115,8 @@ def test_the_gateway_serves_its_prometheus_metrics() -> None: def test_the_dcgm_exporter_runs_on_every_gpu_node_without_extra_privileges() -> None: """Verify the exporter is installed with the monitoring stack, scheduled onto GPU nodes with - the NVIDIA runtime, and holds SYS_ADMIN capability required for datacenter GPUs.""" + the NVIDIA runtime, and holds SYS_ADMIN capability required for datacenter GPUs. Its own + ServiceMonitor stays off: k8s-monitoring's dcgm-exporter integration scrapes it (#1130).""" values = yaml.safe_load((K8S / "monitoring/dcgm-exporter-values.yaml").read_text("utf-8")) release = next(r for r in _HELM_RELEASES_BY_STACK["infra"] if r["name"] == "dcgm-exporter") repo = release["chart"].split("/")[0] @@ -132,7 +133,7 @@ def test_the_dcgm_exporter_runs_on_every_gpu_node_without_extra_privileges() -> True, ["SYS_ADMIN"], "50%", - True, + False, ("monitoring", "dcgm-exporter-values.yaml", True), ) diff --git a/tests/test_stack_dashboards.py b/tests/test_stack_dashboards.py index e014e265a3..7d286a7a73 100644 --- a/tests/test_stack_dashboards.py +++ b/tests/test_stack_dashboards.py @@ -31,8 +31,9 @@ CAPTURES = ROOT / "tests" / "fixtures" / "metrics" # Series Prometheus records about every scrape itself, whatever the target serves. Alloy -# forwards all of them for its ServiceMonitor targets (the gateway, DCGM); its cluster-metrics -# jobs keep only `up` and `scrape_samples_scraped`. +# forwards all of them for the gateway's ServiceMonitor, the DCGM integration, the pods its +# annotation autodiscovery finds and kube-dns; its other cluster-metrics jobs keep only `up` +# and `scrape_samples_scraped`. SYNTHETIC_SERIES = frozenset( { "up", @@ -53,7 +54,7 @@ def _yaml(path: Path) -> dict[str, Any]: - loaded: dict[str, Any] = yaml.safe_load(path.read_text(encoding="utf-8")) + loaded: dict[str, Any] = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.CSafeLoader) return loaded @@ -68,15 +69,32 @@ def _gateway_monitored(values: dict[str, Any]) -> bool: def _dcgm_monitored(values: dict[str, Any]) -> bool: - """The DCGM chart creates its own ServiceMonitor.""" - return values.get("serviceMonitor", {}).get("enabled") is True + """k8s-monitoring's dcgm-exporter integration has an instance that selects the exporter.""" + integrations = values.get("integrations", {}) + instances = integrations.get("dcgm-exporter", {}).get("instances", []) + return bool(integrations.get("collector")) and any( + instance.get("labelSelectors") for instance in instances + ) def _collector_annotated(values: dict[str, Any]) -> bool: - """The server's kubernetes-pods job keeps pods annotated for scraping, on their port.""" + """The server's kubernetes-pods job keeps the collector's namespace and its pods annotated + for scraping, on their port.""" wanted = {"prometheus.io/scrape": "true", "prometheus.io/port": "8888"} annotations = values.get("podAnnotations") or {} - return wanted.items() <= annotations.items() and values["ports"]["metrics"]["enabled"] is True + server = _yaml(K8S / "monitoring" / "prometheus-values.yaml") + pods_job = server["scrapeConfigs"]["kubernetes-pods"] + keeps = [ + rule.get("regex") + for rule in yaml.safe_load(pods_job.get("pre_relabel_configs") or "[]") + if rule.get("action") == "keep" + and rule.get("source_labels") == ["__meta_kubernetes_namespace"] + ] + return ( + wanted.items() <= annotations.items() + and values["ports"]["metrics"]["enabled"] is True + and keeps == ["otel"] + ) def _server_jobs_enabled(values: dict[str, Any]) -> bool: @@ -97,7 +115,7 @@ class Exporter: EXPORTERS = { "litellm": Exporter(K8S / "monitoring" / "k8s-monitoring-values.yaml", _gateway_monitored), - "dcgm-exporter": Exporter(K8S / "monitoring" / "dcgm-exporter-values.yaml", _dcgm_monitored), + "dcgm-exporter": Exporter(K8S / "monitoring" / "k8s-monitoring-values.yaml", _dcgm_monitored), "otel-collector": Exporter(K8S / "otel" / "values.yaml", _collector_annotated), "prometheus-server": Exporter( K8S / "monitoring" / "prometheus-values.yaml", _server_jobs_enabled