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<DynamicObject> 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) <noreply@anthropic.com>
This commit is contained in:
Erfan YousefiandClaude Opus 4.8 authored and Erfan committed 2026-06-24 23:28:17 +02:00
1 parent f9976e22cf
commit 93c9288abc
8 files changed
+188 -4

No files matched your search

+7 -2
View File
@@ -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<DynamicObject>`); 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.
+4
View File
@@ -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<String>,
/// 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,
}
+27
View File
@@ -183,6 +183,23 @@ fn mem(resources: &serde_json::Map<String, Value>, 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!({
+24 -2
View File
@@ -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<Vec<NodeUsage>> {
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<DynamicObject> = 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).
+11
View File
@@ -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<serde_json::Value>;
/// 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<Vec<NodeUsage>>;
}
#[async_trait]
+24
View File
@@ -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;
+50
View File
@@ -377,6 +377,18 @@ struct App {
detail_cache: Option<DetailObject>,
/// Per-context API discovery catalog (Phase 4.1), cached after first `:api`/dynamic browse.
discovery_cache: HashMap<String, Vec<DiscoveredResource>>,
/// 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<ClusterMetrics>,
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<Vec<crate::cluster::NodeUsage>> {
Ok(Vec::new())
}
}
struct NoopExecutor;
+41
View File
@@ -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(),