feat(metrics): per-pod CPU/MEM usage columns in the Pods table (Phase 4.2)
Builds on the cluster [USE] pulse row with the per-pod view operators actually want: live usage per pod, not just the aggregate. - ResourceProvider::pod_metrics reads metrics.k8s.io PodMetrics (scoped to the active namespace or cluster-wide), summing usage across each pod's containers. - App caches it as (namespace,name) -> (cpu_m, mem_b) per context+namespace, refreshed lazily alongside node metrics (15s TTL). - The Pods table swaps its Summary column for CPU and MEM (live usage), looked up per visible row (O(viewport)); other kinds are unchanged. When no metrics-server: cells show "-" and the title flags "metrics-server n/a". - `--metrics` probe now also reports pod-metrics counts. Verified on a real metrics-server cluster: 45 nodes / 821 pods reporting live usage; graceful fallback on kwok. Tests: columns render with seeded usage, and the unavailable note. Validation: fmt, check, test (87 passed / 4 ignored), release build all green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
6cc10a0afa
commit
1389b060ca
7 files changed
+229
-44
No files matched your search
+5
-3
@@ -166,9 +166,11 @@ Root problem: full object JSON kept for every entity.
|
||||
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).
|
||||
`--metrics` probe for verification. Pulse `[USE]` row (cluster) **+ per-pod CPU/MEM columns in the
|
||||
Pods table** (`pod_metrics` fetch, cached per ctx+ns, looked up per visible row; title flags
|
||||
"metrics-server n/a" when absent). **Verified on a real cluster: 45 nodes / 821 pods reporting
|
||||
real usage; graceful 404 fallback on kwok.** Unit tests: real unit formats, pod columns render +
|
||||
unavailable note.
|
||||
- [ ] **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.
|
||||
|
||||
@@ -62,6 +62,14 @@ krust --all-contexts
|
||||
|
||||
All of the above are remappable via `keymap.toml`; the on-screen help line reflects your active bindings.
|
||||
|
||||
## Metrics
|
||||
|
||||
If the cluster has a metrics-server (`metrics.k8s.io`), krust shows live usage:
|
||||
- the **Pods table** gains **CPU** and **MEM** columns (actual usage per pod, summed across containers)
|
||||
- the **Cluster Pulse** panel shows a `[USE]` row: cluster cpu/mem used vs allocatable + util%
|
||||
|
||||
Without a metrics-server these degrade gracefully (columns show `-`, the table title notes `metrics-server n/a`, and the pulse falls back to request/limit-based numbers).
|
||||
|
||||
## Logs and Runtime Inspect
|
||||
|
||||
- `l`: open logs pane
|
||||
|
||||
@@ -40,7 +40,7 @@ use crate::model::{ResourceEntity, ResourceKey, ResourceKind, StateDelta};
|
||||
|
||||
use super::{
|
||||
ActionError, ActionExecutor, ActionResult, DiscoveredResource, DynamicRow, NodeUsage,
|
||||
PodLogEvent, PodLogRequest, PodLogStream, ResourceProvider, WatchTarget,
|
||||
PodLogEvent, PodLogRequest, PodLogStream, PodUsage, ResourceProvider, WatchTarget,
|
||||
extract::{extracted_for, usage_from_metrics},
|
||||
};
|
||||
|
||||
@@ -442,6 +442,45 @@ impl ResourceProvider for KubeResourceProvider {
|
||||
.collect();
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
async fn pod_metrics(
|
||||
&self,
|
||||
context: &str,
|
||||
namespace: Option<&str>,
|
||||
) -> anyhow::Result<Vec<PodUsage>> {
|
||||
let client = self.client_for_context(context).await?;
|
||||
let gvk = GroupVersionKind::gvk("metrics.k8s.io", "v1beta1", "PodMetrics");
|
||||
let mut ar = ApiResource::from_gvk(&gvk);
|
||||
ar.plural = "pods".to_string();
|
||||
let api: Api<DynamicObject> = match namespace {
|
||||
Some(ns) => Api::namespaced_with(client, ns, &ar),
|
||||
None => Api::all_with(client, &ar),
|
||||
};
|
||||
let list = api.list(&ListParams::default()).await?;
|
||||
let rows = list
|
||||
.into_iter()
|
||||
.filter_map(|obj| {
|
||||
let namespace = obj.namespace()?;
|
||||
let name = obj.name_any();
|
||||
// Sum usage across the pod's containers.
|
||||
let containers = obj.data.get("containers").and_then(|v| v.as_array())?;
|
||||
let (mut cpu_used_m, mut mem_used_b) = (0u64, 0u64);
|
||||
for container in containers {
|
||||
if let Some(usage) = container.get("usage").and_then(usage_from_metrics) {
|
||||
cpu_used_m = cpu_used_m.saturating_add(usage.0);
|
||||
mem_used_b = mem_used_b.saturating_add(usage.1);
|
||||
}
|
||||
}
|
||||
Some(PodUsage {
|
||||
namespace,
|
||||
name,
|
||||
cpu_used_m,
|
||||
mem_used_b,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(rows)
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort status string for a dynamic object (no curated extractor for unknown kinds).
|
||||
|
||||
@@ -48,6 +48,15 @@ pub struct NodeUsage {
|
||||
pub mem_used_b: u64,
|
||||
}
|
||||
|
||||
/// Actual resource usage for one pod (summed across its containers), from `metrics.k8s.io`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PodUsage {
|
||||
pub namespace: String,
|
||||
pub name: String,
|
||||
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 {
|
||||
@@ -148,6 +157,14 @@ pub trait ResourceProvider: Send + Sync {
|
||||
/// 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>>;
|
||||
|
||||
/// Per-pod actual usage (summed across containers) from `metrics.k8s.io`, scoped to a namespace
|
||||
/// or cluster-wide. Errors if the metrics API is not served; callers degrade gracefully.
|
||||
async fn pod_metrics(
|
||||
&self,
|
||||
context: &str,
|
||||
namespace: Option<&str>,
|
||||
) -> anyhow::Result<Vec<PodUsage>>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
|
||||
+12
@@ -199,6 +199,18 @@ async fn run_metrics_probe(provider: &dyn ResourceProvider, context: &str) -> an
|
||||
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}"),
|
||||
}
|
||||
match provider.pod_metrics(context, None).await {
|
||||
Ok(pods) if !pods.is_empty() => {
|
||||
let cpu_m: u64 = pods.iter().map(|p| p.cpu_used_m).sum();
|
||||
println!(
|
||||
"pod metrics OK: {} pods reporting; summed cpu={:.2} cores",
|
||||
pods.len(),
|
||||
cpu_m as f64 / 1000.0,
|
||||
);
|
||||
}
|
||||
Ok(_) => println!("pod metrics: 0 pods reporting"),
|
||||
Err(err) => println!("pod metrics unavailable: {err}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+88
-15
@@ -380,7 +380,11 @@ struct App {
|
||||
/// 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)>,
|
||||
/// Per-pod live usage `(namespace, name) -> (cpu_millicores, mem_bytes)` for the active scope,
|
||||
/// shown as CPU/MEM columns in the Pods table. Empty when no metrics-server.
|
||||
pod_metrics: HashMap<(String, String), (u64, u64)>,
|
||||
/// (context, namespace-scope, fetched-at) guarding the 15s metrics refresh.
|
||||
metrics_fetched: Option<(String, Option<String>, Instant)>,
|
||||
}
|
||||
|
||||
/// Cluster-wide actual usage summed from node metrics (Phase 4.2).
|
||||
@@ -938,6 +942,7 @@ impl App {
|
||||
detail_cache: None,
|
||||
discovery_cache: HashMap::new(),
|
||||
metrics: None,
|
||||
pod_metrics: HashMap::new(),
|
||||
metrics_fetched: None,
|
||||
}
|
||||
}
|
||||
@@ -1706,32 +1711,48 @@ impl App {
|
||||
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.
|
||||
/// Refresh live usage (metrics.k8s.io) for the active context+namespace, at most every 15s:
|
||||
/// cluster totals (node metrics) for the pulse and per-pod usage for the table columns. On any
|
||||
/// error/absence (no metrics-server) the caches clear and the UI degrades — never blocks.
|
||||
async fn maybe_refresh_metrics(&mut self) {
|
||||
let context = self.current_tab().context.clone();
|
||||
let namespace = self.current_tab().namespace.clone();
|
||||
let stale = match &self.metrics_fetched {
|
||||
Some((ctx, at)) => ctx != &context || at.elapsed() > Duration::from_secs(15),
|
||||
Some((ctx, ns, at)) => {
|
||||
ctx != &context || ns != &namespace || 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(),
|
||||
})
|
||||
}
|
||||
Ok(nodes) if !nodes.is_empty() => Some(ClusterMetrics {
|
||||
cpu_used_m: nodes.iter().map(|n| n.cpu_used_m).sum(),
|
||||
mem_used_b: nodes.iter().map(|n| n.mem_used_b).sum(),
|
||||
nodes_reporting: nodes.len(),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
self.metrics_fetched = Some((context, Instant::now()));
|
||||
|
||||
self.pod_metrics = match provider.pod_metrics(&context, namespace.as_deref()).await {
|
||||
Ok(pods) => pods
|
||||
.into_iter()
|
||||
.map(|p| ((p.namespace, p.name), (p.cpu_used_m, p.mem_used_b)))
|
||||
.collect(),
|
||||
Err(_) => HashMap::new(),
|
||||
};
|
||||
|
||||
self.metrics_fetched = Some((context, namespace, Instant::now()));
|
||||
}
|
||||
|
||||
/// Live usage `(cpu_millicores, mem_bytes)` for a pod, if metrics are available.
|
||||
fn pod_usage(&self, namespace: Option<&str>, name: &str) -> Option<(u64, u64)> {
|
||||
self.pod_metrics
|
||||
.get(&(namespace.unwrap_or_default().to_string(), name.to_string()))
|
||||
.copied()
|
||||
}
|
||||
|
||||
/// Fetch the full object for the selected row on demand when a detail pane is active and the
|
||||
@@ -2260,6 +2281,12 @@ impl App {
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// Inject per-pod usage directly (tests don't run the async metrics refresh).
|
||||
fn seed_pod_metrics_for_test(&mut self, namespace: &str, name: &str, cpu_m: u64, mem_b: u64) {
|
||||
self.pod_metrics
|
||||
.insert((namespace.to_string(), name.to_string()), (cpu_m, mem_b));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2386,6 +2413,19 @@ mod tests {
|
||||
) -> anyhow::Result<Vec<crate::cluster::NodeUsage>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn pod_metrics(
|
||||
&self,
|
||||
_context: &str,
|
||||
_namespace: Option<&str>,
|
||||
) -> anyhow::Result<Vec<crate::cluster::PodUsage>> {
|
||||
Ok(vec![crate::cluster::PodUsage {
|
||||
namespace: "default".to_string(),
|
||||
name: "pod-ok".to_string(),
|
||||
cpu_used_m: 250,
|
||||
mem_used_b: 64 * 1024 * 1024,
|
||||
}])
|
||||
}
|
||||
}
|
||||
|
||||
struct NoopExecutor;
|
||||
@@ -2862,6 +2902,39 @@ mod tests {
|
||||
assert_eq!(recomputed.pods, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pods_table_renders_live_cpu_mem_columns() {
|
||||
let mut app = test_app();
|
||||
app.store.apply(StateDelta::Upsert(mk_entity(
|
||||
"ctx-dev",
|
||||
ResourceKind::Pods,
|
||||
Some("default"),
|
||||
"pod-a",
|
||||
"Running",
|
||||
)));
|
||||
app.seed_pod_metrics_for_test("default", "pod-a", 1500, 256 * 1024 * 1024);
|
||||
|
||||
let snap = render_snapshot(&mut app, 140, 20);
|
||||
assert!(snap.contains("CPU") && snap.contains("MEM"), "{snap}");
|
||||
assert!(snap.contains("1.50c"), "expected cpu usage column: {snap}");
|
||||
assert!(snap.contains("256Mi"), "expected mem usage column: {snap}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pods_table_notes_when_metrics_unavailable() {
|
||||
let mut app = test_app();
|
||||
app.store.apply(StateDelta::Upsert(mk_entity(
|
||||
"ctx-dev",
|
||||
ResourceKind::Pods,
|
||||
Some("default"),
|
||||
"pod-a",
|
||||
"Running",
|
||||
)));
|
||||
// no seeded pod_metrics → CPU/MEM are "-" and the title flags it
|
||||
let snap = render_snapshot(&mut app, 140, 20);
|
||||
assert!(snap.contains("metrics-server n/a"), "{snap}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_table_pane_has_light_icons_and_status_tags() {
|
||||
let mut app = test_app();
|
||||
|
||||
+59
-25
@@ -642,6 +642,8 @@ impl App {
|
||||
match active.pane {
|
||||
Pane::Table => {
|
||||
// Materialize only the visible window — O(viewport), not O(total rows).
|
||||
// Pods get live CPU/MEM usage columns (metrics.k8s.io) instead of Summary.
|
||||
let pods_view = active.kind() == ResourceKind::Pods;
|
||||
let viewport_rows = table_viewport_rows(chunks[2].height);
|
||||
let start = table_offset;
|
||||
let end = start.saturating_add(viewport_rows).min(vm.len());
|
||||
@@ -651,39 +653,71 @@ impl App {
|
||||
let row = materialize_row(&self.store, key)?;
|
||||
let sev = classify_status_severity(&row.status);
|
||||
let status = format!("{} {}", severity_tag(sev), row.status);
|
||||
Some(
|
||||
Row::new(vec![
|
||||
let cells = if pods_view {
|
||||
let (cpu, mem) =
|
||||
match self.pod_usage(key.namespace.as_deref(), &key.name) {
|
||||
Some((c, m)) => (format_millicpu(c), format_bytes(m)),
|
||||
None => ("-".to_string(), "-".to_string()),
|
||||
};
|
||||
vec![
|
||||
Cell::from(row.namespace),
|
||||
Cell::from(row.name),
|
||||
Cell::from(status),
|
||||
Cell::from(cpu),
|
||||
Cell::from(mem),
|
||||
Cell::from(row.age),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
Cell::from(row.namespace),
|
||||
Cell::from(row.name),
|
||||
Cell::from(status),
|
||||
Cell::from(row.age),
|
||||
Cell::from(row.summary),
|
||||
])
|
||||
.style(severity_style(&theme, sev)),
|
||||
)
|
||||
]
|
||||
};
|
||||
Some(Row::new(cells).style(severity_style(&theme, sev)))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let table = Table::new(
|
||||
rows,
|
||||
[
|
||||
Constraint::Length(18),
|
||||
Constraint::Length(38),
|
||||
Constraint::Length(20),
|
||||
Constraint::Length(10),
|
||||
Constraint::Min(10),
|
||||
],
|
||||
)
|
||||
.header(
|
||||
Row::new(vec!["Namespace", "Name", "Status", "Age", "Summary"])
|
||||
.style(theme.table_header),
|
||||
)
|
||||
.block(Block::default().borders(Borders::ALL).title(format!(
|
||||
"[KIND] {} ({})",
|
||||
active.kind(),
|
||||
vm.len()
|
||||
)))
|
||||
.row_highlight_style(theme.row_highlight);
|
||||
let (header, widths): (Vec<&str>, Vec<Constraint>) = if pods_view {
|
||||
(
|
||||
vec!["Namespace", "Name", "Status", "CPU", "MEM", "Age"],
|
||||
vec![
|
||||
Constraint::Length(18),
|
||||
Constraint::Min(20),
|
||||
Constraint::Length(20),
|
||||
Constraint::Length(9),
|
||||
Constraint::Length(10),
|
||||
Constraint::Length(8),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
(
|
||||
vec!["Namespace", "Name", "Status", "Age", "Summary"],
|
||||
vec![
|
||||
Constraint::Length(18),
|
||||
Constraint::Length(38),
|
||||
Constraint::Length(20),
|
||||
Constraint::Length(10),
|
||||
Constraint::Min(10),
|
||||
],
|
||||
)
|
||||
};
|
||||
let metrics_note = if pods_view && self.pod_metrics.is_empty() {
|
||||
" (CPU/MEM: metrics-server n/a)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let table = Table::new(rows, widths)
|
||||
.header(Row::new(header).style(theme.table_header))
|
||||
.block(Block::default().borders(Borders::ALL).title(format!(
|
||||
"[KIND] {} ({}){}",
|
||||
active.kind(),
|
||||
vm.len(),
|
||||
metrics_note
|
||||
)))
|
||||
.row_highlight_style(theme.row_highlight);
|
||||
|
||||
// Rows are pre-sliced to the window, so the widget offset is 0 and the
|
||||
// selection is window-relative.
|
||||
|
||||
Reference in new issue
Block a user