From 93c9288abcfc72d7cfa20e3e48ddbdc505ca6e3e Mon Sep 17 00:00:00 2001 From: Erfan Yousefi Date: Wed, 24 Jun 2026 23:18:39 +0200 Subject: [PATCH] feat(metrics): live cluster usage from metrics.k8s.io in the pulse (Phase 4.2) The pulse showed CPU/mem from pod spec requests/limits, not actual usage. - ResourceProvider::node_metrics reads live per-node usage from metrics.k8s.io (Api on NodeMetrics), parsed via the shared quantity parsers (handles nanocores `n` and `Ki`, the real metrics-server units). - App caches the cluster aggregate per active context (15s TTL, fetched lazily in ensure_active_watch); never blocks the UI. - Pulse gains a [USE] row: actual cpu/mem used vs allocatable + util%, with severity. When no metrics-server is present the cache is None and the row notes that the request/limit rows above apply (graceful degradation). - Hidden `--metrics` probe prints the cluster aggregate for verification. Verified: a real metrics-server-backed cluster (45 nodes -> 15.0 cores / 537 GiB actual usage) and graceful 404 fallback on the kwok lab. Unit test covers the real unit formats. Deferred: per-pod usage column (needs pod-metrics fetch + table column work). Validation: fmt, check, test (85 passed / 4 ignored), release build all green. Co-Authored-By: Claude Opus 4.8 (1M context) --- ROADMAP.md | 9 +++++-- src/cli.rs | 4 +++ src/cluster/extract.rs | 27 +++++++++++++++++++ src/cluster/kube_provider.rs | 26 +++++++++++++++++-- src/cluster/mod.rs | 11 ++++++++ src/lib.rs | 24 +++++++++++++++++ src/ui/app.rs | 50 ++++++++++++++++++++++++++++++++++++ src/ui/app/render_loop.rs | 41 +++++++++++++++++++++++++++++ 8 files changed, 188 insertions(+), 4 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b6a1b41..b881ccd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -162,8 +162,13 @@ Root problem: full object JSON kept for every entity. (Interactive selectable dynamic-list overlay deferred to 4.1c polish.) - [ ] **4.1b dynamic watches + KindId/ResourceKey refactor** (fold 24 typed watches into the dynamic path). - [ ] **4.1c navigation/UX** (discovered kinds in kind-cycle / resource picker, short names from discovery). -- [ ] **4.2 Metrics integration** — `metrics.k8s.io` for real pod/node CPU+mem (top-style). - Current numbers are from spec requests/limits, not usage. +- [~] **4.2 Metrics integration** — DONE (node-level). `ResourceProvider::node_metrics` reads live + usage from `metrics.k8s.io` (via `Api`); App caches it per active context (15s TTL, + lazy) and the pulse shows a `[USE]` row: real cpu/mem used vs allocatable + util%, with severity. + Degrades gracefully to the request/limit rows when no metrics-server (cache → None). Hidden + `--metrics` probe for verification. **Verified: real metrics-server cluster (45 nodes → 15.0 cores + / 537 GiB actual usage) and graceful 404 fallback on the kwok lab.** Unit test on real unit formats + (nanocores/Ki). Deferred: per-pod usage column (needs pod-metrics fetch + table column work). - [ ] **4.3 Resource-correlated events** — selecting a pod shows its events; today Events pane only renders Event objects directly (detail_pane.rs:170 "planned"). - [ ] **4.4 Rendered describe** — kubectl-style human `describe` output alongside YAML/JSON. diff --git a/src/cli.rs b/src/cli.rs index 1aabd7c..131d8c1 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -61,4 +61,8 @@ pub struct Cli { /// With --discover: also list (and describe the first object of) this resource (plural or kind). #[arg(long, hide = true)] pub discover_resource: Option, + + /// Print live cluster usage from metrics.k8s.io for the initial context, then exit (4.2 check). + #[arg(long, hide = true, default_value_t = false)] + pub metrics: bool, } diff --git a/src/cluster/extract.rs b/src/cluster/extract.rs index 26a2a44..1b652c7 100644 --- a/src/cluster/extract.rs +++ b/src/cluster/extract.rs @@ -183,6 +183,23 @@ fn mem(resources: &serde_json::Map, field: &str) -> u64 { .unwrap_or(0) } +/// Parse a `metrics.k8s.io` usage object (`{cpu, memory}`) into (millicores, bytes). Used for both +/// NodeMetrics (`/usage`) and summed PodMetrics container usage. Returns None if neither is present. +pub(crate) fn usage_from_metrics(usage: &Value) -> Option<(u64, u64)> { + let cpu = usage + .get("cpu") + .and_then(Value::as_str) + .map(parse_cpu_millicores); + let mem = usage + .get("memory") + .and_then(Value::as_str) + .map(parse_bytes_quantity); + match (cpu, mem) { + (None, None) => None, + (c, m) => Some((c.unwrap_or(0), m.unwrap_or(0))), + } +} + pub(crate) fn parse_cpu_millicores(value: &str) -> u64 { let value = value.trim(); if value.is_empty() { @@ -269,6 +286,16 @@ mod tests { assert_eq!(r.mem_request_b, (64 + 32) * 1024 * 1024); } + #[test] + fn parses_real_metrics_usage_units() { + // formats seen on a real cluster: nanocores + Ki memory + let usage = json!({ "cpu": "429753714n", "memory": "10872076Ki" }); + let (cpu_m, mem_b) = usage_from_metrics(&usage).expect("usage parses"); + assert_eq!(cpu_m, 430); // ~0.43 cores + assert_eq!(mem_b, 10872076u64 * 1024); // ~10.4 GiB + assert!(usage_from_metrics(&json!({})).is_none()); + } + #[test] fn extracts_node_capacity() { let raw = json!({ diff --git a/src/cluster/kube_provider.rs b/src/cluster/kube_provider.rs index 41ad6e6..7b299e3 100644 --- a/src/cluster/kube_provider.rs +++ b/src/cluster/kube_provider.rs @@ -39,8 +39,9 @@ use tracing::{error, warn}; use crate::model::{ResourceEntity, ResourceKey, ResourceKind, StateDelta}; use super::{ - ActionError, ActionExecutor, ActionResult, DiscoveredResource, DynamicRow, PodLogEvent, - PodLogRequest, PodLogStream, ResourceProvider, WatchTarget, extract::extracted_for, + ActionError, ActionExecutor, ActionResult, DiscoveredResource, DynamicRow, NodeUsage, + PodLogEvent, PodLogRequest, PodLogStream, ResourceProvider, WatchTarget, + extract::{extracted_for, usage_from_metrics}, }; /// Bounded one-shot dynamic list size (Phase 4.1 read-only browse). @@ -420,6 +421,27 @@ impl ResourceProvider for KubeResourceProvider { }; Ok(serde_json::to_value(api.get(name).await?)?) } + + async fn node_metrics(&self, context: &str) -> anyhow::Result> { + let client = self.client_for_context(context).await?; + let gvk = GroupVersionKind::gvk("metrics.k8s.io", "v1beta1", "NodeMetrics"); + let mut ar = ApiResource::from_gvk(&gvk); + ar.plural = "nodes".to_string(); + let api: Api = Api::all_with(client, &ar); + let list = api.list(&ListParams::default()).await?; + let rows = list + .into_iter() + .filter_map(|obj| { + let usage = obj.data.get("usage")?; + let (cpu_used_m, mem_used_b) = usage_from_metrics(usage)?; + Some(NodeUsage { + cpu_used_m, + mem_used_b, + }) + }) + .collect(); + Ok(rows) + } } /// Best-effort status string for a dynamic object (no curated extractor for unknown kinds). diff --git a/src/cluster/mod.rs b/src/cluster/mod.rs index b00194e..06259d9 100644 --- a/src/cluster/mod.rs +++ b/src/cluster/mod.rs @@ -41,6 +41,13 @@ impl DiscoveredResource { } } +/// Actual resource usage for one node, from `metrics.k8s.io` (Phase 4.2). +#[derive(Debug, Clone, Copy)] +pub struct NodeUsage { + pub cpu_used_m: u64, + pub mem_used_b: u64, +} + /// A generic row from a one-shot dynamic list (no curated columns). #[derive(Debug, Clone)] pub struct DynamicRow { @@ -137,6 +144,10 @@ pub trait ResourceProvider: Send + Sync { namespace: Option<&str>, name: &str, ) -> anyhow::Result; + + /// Per-node actual usage from `metrics.k8s.io` (Phase 4.2). Errors if the metrics API is not + /// served (no metrics-server); callers degrade gracefully. + async fn node_metrics(&self, context: &str) -> anyhow::Result>; } #[async_trait] diff --git a/src/lib.rs b/src/lib.rs index b7b8341..1e93223 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,6 +75,10 @@ pub async fn run() -> anyhow::Result<()> { .await; } + if cli.metrics { + return run_metrics_probe(resource_provider.as_ref(), &initial_context).await; + } + if cli.bench || cli.soak_secs > 0 { return ui::run_bench( contexts, @@ -178,6 +182,26 @@ async fn run_discover( Ok(()) } +/// Headless Phase 4.2 check: fetch live node usage from metrics.k8s.io and print the cluster +/// aggregate (no node names), verifying the metrics path against a real cluster. +async fn run_metrics_probe(provider: &dyn ResourceProvider, context: &str) -> anyhow::Result<()> { + match provider.node_metrics(context).await { + Ok(nodes) if !nodes.is_empty() => { + let cpu_m: u64 = nodes.iter().map(|n| n.cpu_used_m).sum(); + let mem_b: u64 = nodes.iter().map(|n| n.mem_used_b).sum(); + println!( + "metrics.k8s.io OK: {} nodes reporting; cluster usage cpu={:.2} cores, mem={:.1} GiB", + nodes.len(), + cpu_m as f64 / 1000.0, + mem_b as f64 / (1024.0 * 1024.0 * 1024.0), + ); + } + Ok(_) => println!("metrics.k8s.io served but reported 0 nodes (no usage data yet)"), + Err(err) => println!("metrics.k8s.io unavailable (graceful fallback to requests): {err}"), + } + Ok(()) +} + fn init_tracing() { if std::env::var_os("RUST_LOG").is_none() { return; diff --git a/src/ui/app.rs b/src/ui/app.rs index 87e8aff..d42f77c 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -377,6 +377,18 @@ struct App { detail_cache: Option, /// Per-context API discovery catalog (Phase 4.1), cached after first `:api`/dynamic browse. discovery_cache: HashMap>, + /// Live cluster usage from metrics.k8s.io (Phase 4.2), refreshed lazily for the active context. + /// `None` means metrics-server isn't available — the pulse falls back to request-based numbers. + metrics: Option, + metrics_fetched: Option<(String, Instant)>, +} + +/// Cluster-wide actual usage summed from node metrics (Phase 4.2). +#[derive(Debug, Clone, Copy)] +struct ClusterMetrics { + cpu_used_m: u64, + mem_used_b: u64, + nodes_reporting: usize, } /// On-demand full object for the active detail/describe/decode/edit view. Single-slot: holds the @@ -925,6 +937,8 @@ impl App { needs_terminal_reset: false, detail_cache: None, discovery_cache: HashMap::new(), + metrics: None, + metrics_fetched: None, } } @@ -1689,6 +1703,35 @@ impl App { self.status_line = format!("watch setup error: {err}"); } self.maybe_load_detail().await; + self.maybe_refresh_metrics().await; + } + + /// Refresh live cluster usage (metrics.k8s.io) for the active context, at most every 15s. + /// On any error/absence (no metrics-server) the cache clears and the pulse degrades to + /// request-based numbers — never blocks or errors the UI. + async fn maybe_refresh_metrics(&mut self) { + let context = self.current_tab().context.clone(); + let stale = match &self.metrics_fetched { + Some((ctx, at)) => ctx != &context || at.elapsed() > Duration::from_secs(15), + None => true, + }; + if !stale { + return; + } + let provider = self.resource_provider.clone(); + self.metrics = match provider.node_metrics(&context).await { + Ok(nodes) if !nodes.is_empty() => { + let cpu_used_m = nodes.iter().map(|n| n.cpu_used_m).sum(); + let mem_used_b = nodes.iter().map(|n| n.mem_used_b).sum(); + Some(ClusterMetrics { + cpu_used_m, + mem_used_b, + nodes_reporting: nodes.len(), + }) + } + _ => None, + }; + self.metrics_fetched = Some((context, Instant::now())); } /// Fetch the full object for the selected row on demand when a detail pane is active and the @@ -2336,6 +2379,13 @@ mod tests { "metadata": { "name": name, "namespace": "ns-00" } })) } + + async fn node_metrics( + &self, + _context: &str, + ) -> anyhow::Result> { + Ok(Vec::new()) + } } struct NoopExecutor; diff --git a/src/ui/app/render_loop.rs b/src/ui/app/render_loop.rs index 177264b..9429c6e 100644 --- a/src/ui/app/render_loop.rs +++ b/src/ui/app/render_loop.rs @@ -320,6 +320,47 @@ impl App { Severity::Ok, ), ]; + // Phase 4.2: live actual usage from metrics.k8s.io when a metrics-server is present; + // otherwise note its absence (the rows above are request/limit-based). + match &self.metrics { + Some(m) => { + let cpu_sev = match ratio_percent_value(m.cpu_used_m, node_caps.cpu_alloc_m) { + Some(pct) if pct >= 90.0 => Severity::Err, + Some(pct) if pct >= 75.0 => Severity::Warn, + _ => Severity::Ok, + }; + pulse_rows.push(( + "[USE]".to_string(), + vec![ + format!( + "cpu {} / {} ({})", + format_millicpu(m.cpu_used_m), + format_millicpu(node_caps.cpu_alloc_m), + percent(m.cpu_used_m, node_caps.cpu_alloc_m) + ), + format!( + "mem {} / {} ({})", + format_bytes(m.mem_used_b), + format_bytes(node_caps.mem_alloc_b), + percent(m.mem_used_b, node_caps.mem_alloc_b) + ), + format!("live · {} nodes reporting", m.nodes_reporting), + ], + cpu_sev, + )); + } + None => { + pulse_rows.push(( + "[USE]".to_string(), + vec![ + "live usage: metrics-server not available".to_string(), + "(rows above are request/limit-based)".to_string(), + String::new(), + ], + Severity::Ok, + )); + } + } if let Some(err) = watch_error { pulse_rows.push(( "[ALERT]".to_string(),