use crate::attribution::{parse_cgroup, parse_kube_cgroup, CgroupScope, KubeCgroup, QosClass};
use crate::limits::{evaluate, CgroupMem, LimitInput, LimitKind, LimitStatus, LimitTarget, LimitTracker};
use crate::measured::sum_bytes;
use crate::model::{Measured, ProcId, SandboxKind, Snapshot, SourceStatus};
use crate::namespaces::{namespace_sets, NamespaceReport};
use crate::units::{format_bytes, UnitSystem};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
pub const LABEL_PREFIXES: &[&str] = &[
"io.kubernetes.",
"io.x-k8s.kind.",
"k3d.cluster",
"k3d.role",
"name.minikube.sigs.k8s.io",
"role.minikube.sigs.k8s.io",
"mode.minikube.sigs.k8s.io",
"com.docker.compose.project",
"com.docker.compose.service",
];
pub fn keep_label(key: &str) -> bool {
LABEL_PREFIXES.iter().any(|p| key.starts_with(p))
}
pub const VM_SLACK_SENTENCE: &str =
"held by the VM, not used by containers; restarting the engine returns it";
pub const VM_SLACK_MIN_BYTES: u64 = 256 << 20;
pub const STALE_CPU_PCT: f64 = 0.5;
pub const STALE_MIN_OBSERVED_S: u64 = 120;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ContainerInfo {
pub sandbox_id: String,
pub id: String,
pub engine: String,
pub vm_hosted: bool,
pub name: String,
pub image: String,
pub state: String,
pub status_text: String,
pub created_ms: Option<u64>,
pub started_ms: Option<u64>,
pub finished_ms: Option<u64>,
pub exit_code: Option<i64>,
pub oom_killed: Option<bool>,
pub restart_count: Option<u32>,
pub cpu_total_ns: Option<u64>,
pub stats_at_ms: Option<u64>,
pub size_rw: Option<u64>,
pub size_root_fs: Option<u64>,
pub labels: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum KubeDistro {
Kind,
Minikube,
K3d,
K3s,
DockerDesktop,
#[serde(rename = "orbstack")]
OrbStack,
RancherDesktop,
Colima,
Microk8s,
#[default]
Unknown,
}
impl KubeDistro {
pub fn title(self) -> &'static str {
match self {
KubeDistro::Kind => "kind",
KubeDistro::Minikube => "minikube",
KubeDistro::K3d => "k3d",
KubeDistro::K3s => "k3s",
KubeDistro::DockerDesktop => "Docker Desktop",
KubeDistro::OrbStack => "OrbStack",
KubeDistro::RancherDesktop => "Rancher Desktop",
KubeDistro::Colima => "Colima",
KubeDistro::Microk8s => "MicroK8s",
KubeDistro::Unknown => "Kubernetes",
}
}
pub fn from_context(name: &str) -> Option<KubeDistro> {
Some(match name {
n if n.starts_with("kind-") => KubeDistro::Kind,
n if n.starts_with("k3d-") => KubeDistro::K3d,
"minikube" => KubeDistro::Minikube,
"docker-desktop" | "docker-for-desktop" => KubeDistro::DockerDesktop,
"orbstack" => KubeDistro::OrbStack,
"rancher-desktop" => KubeDistro::RancherDesktop,
n if n == "colima" || n.starts_with("colima-") => KubeDistro::Colima,
"microk8s" => KubeDistro::Microk8s,
_ => return None,
})
}
pub fn cluster_name_from_context(self, ctx: &str) -> String {
match self {
KubeDistro::Kind => ctx.strip_prefix("kind-").unwrap_or(ctx).to_string(),
KubeDistro::K3d => ctx.strip_prefix("k3d-").unwrap_or(ctx).to_string(),
KubeDistro::Colima => ctx.strip_prefix("colima-").unwrap_or("default").to_string(),
_ => ctx.to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeContextSummary {
pub name: String,
pub current: bool,
pub distro: Option<KubeDistro>,
pub local: bool,
pub live: bool,
pub verdict: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeNodeStats {
pub name: String,
pub working_set: Option<u64>,
pub available: Option<u64>,
pub pods: Vec<KubePodStats>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubePodStats {
pub namespace: String,
pub name: String,
pub uid: String,
pub working_set: Option<u64>,
pub containers: Vec<KubeContainerStats>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeContainerStats {
pub name: String,
pub working_set: Option<u64>,
pub usage: Option<u64>,
pub available: Option<u64>,
pub start_ms: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubePodInfo {
pub namespace: String,
pub name: String,
pub uid: String,
pub node: Option<String>,
pub phase: Option<String>,
pub qos: Option<QosClass>,
pub created_ms: Option<u64>,
pub containers: Vec<KubeContainerSpec>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeContainerSpec {
pub name: String,
pub id: Option<String>,
pub runtime: Option<String>,
pub mem_limit: Option<u64>,
pub mem_request: Option<u64>,
pub restarts: Option<u32>,
pub state: Option<String>,
pub last_termination_reason: Option<String>,
pub last_termination_ms: Option<u64>,
pub last_exit_code: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeApiData {
pub context: String,
pub distro: Option<KubeDistro>,
pub status: SourceStatus,
pub at_ms: u64,
pub nodes: Vec<KubeNodeStats>,
pub pods: Vec<KubePodInfo>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Cluster {
pub id: String,
pub name: String,
pub distro: KubeDistro,
pub context: Option<String>,
pub evidence: Vec<String>,
pub api: Option<SourceStatus>,
pub nodes: Vec<KubeNode>,
pub notes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeNode {
pub name: String,
pub sandbox_id: Option<String>,
pub mem: Measured<u64>,
pub namespaces: Vec<KubeNamespace>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeNamespace {
pub name: String,
pub mem: Measured<u64>,
pub pods: Vec<KubePod>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubePod {
pub uid: Option<String>,
pub name: Option<String>,
pub qos: Option<QosClass>,
pub phase: Option<String>,
pub mem: Measured<u64>,
pub limit: Option<u64>,
pub cgroup: Option<String>,
pub limit_id: Option<String>,
pub containers: Vec<KubeContainer>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KubeContainer {
pub name: Option<String>,
pub id: Option<String>,
pub runtime: Option<String>,
pub mem: Measured<u64>,
pub limit: Measured<u64>,
pub restarts: Option<u32>,
pub last_termination: Option<String>,
pub host_pids: Vec<ProcId>,
pub sandbox_id: Option<String>,
pub cgroup: Option<String>,
pub limit_id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct VmSlack {
pub sandbox_id: String,
pub label: String,
pub runtime: String,
pub vm_footprint: Measured<u64>,
pub containers: Measured<u64>,
pub configured: Option<u64>,
pub slack: Measured<u64>,
pub summary: String,
pub notes: Vec<String>,
pub counts_as_reclaim: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct StaleContainer {
pub sandbox_id: String,
pub name: String,
pub engine: String,
pub image: String,
pub state: String,
pub created_ms: Option<u64>,
pub started_ms: Option<u64>,
pub finished_ms: Option<u64>,
pub age_s: Option<u64>,
pub cpu_pct: Measured<f64>,
pub observed_s: u64,
pub mem: Measured<u64>,
pub disk: Measured<u64>,
pub exit_code: Option<i64>,
pub oom_killed: Option<bool>,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Isolation {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub containers: Vec<ContainerInfo>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub kube_contexts: Vec<KubeContextSummary>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub kube: Vec<KubeApiData>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub limits: Vec<LimitStatus>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub clusters: Vec<Cluster>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub vm_slack: Vec<VmSlack>,
#[serde(skip_serializing_if = "NamespaceReport::is_empty")]
pub namespaces: NamespaceReport,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub stale_containers: Vec<StaleContainer>,
}
impl Isolation {
pub fn is_empty(&self) -> bool {
self.containers.is_empty()
&& self.kube_contexts.is_empty()
&& self.kube.is_empty()
&& self.limits.is_empty()
&& self.clusters.is_empty()
&& self.vm_slack.is_empty()
&& self.namespaces.is_empty()
&& self.stale_containers.is_empty()
}
pub fn limit(&self, id: &str) -> Option<&LimitStatus> {
self.limits.iter().find(|l| l.id == id)
}
pub fn container(&self, sandbox_id: &str) -> Option<&ContainerInfo> {
self.containers.iter().find(|c| c.sandbox_id == sandbox_id)
}
}
pub fn redact(iso: &mut Isolation, rename: &dyn Fn(&mut Option<String>)) {
use crate::redact::redact_text;
for c in &mut iso.containers {
c.name = redact_text(&c.name);
c.image = redact_text(&c.image);
c.status_text = redact_text(&c.status_text);
for v in c.labels.values_mut() {
*v = redact_text(v);
}
}
for l in &mut iso.limits {
l.label = redact_text(&l.label);
l.summary = redact_text(&l.summary);
}
for v in &mut iso.vm_slack {
v.label = redact_text(&v.label);
v.summary = redact_text(&v.summary);
}
for s in &mut iso.stale_containers {
s.name = redact_text(&s.name);
s.image = redact_text(&s.image);
s.reason = redact_text(&s.reason);
}
for n in &mut iso.namespaces.sets {
n.label = redact_text(&n.label);
rename(&mut n.group);
rename(&mut n.owner_group);
}
}
fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = (m as i64 + 9) % 12;
let doy = (153 * mp + 2) / 5 + d as i64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
pub fn parse_rfc3339_ms(s: &str) -> Option<u64> {
let s = s.trim();
if s.len() < 20 {
return None;
}
let num = |a: usize, b: usize| s.get(a..b)?.parse::<i64>().ok();
let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?);
let (h, mi, se) = (num(11, 13)?, num(14, 16)?, num(17, 19)?);
if s.as_bytes()[4] != b'-' || !matches!(s.as_bytes()[10], b'T' | b't' | b' ') {
return None;
}
let mut rest = &s[19..];
let mut ms = 0i64;
if let Some(frac) = rest.strip_prefix('.') {
let digits: String = frac.chars().take_while(|c| c.is_ascii_digit()).collect();
let first3: String = digits.chars().chain("000".chars()).take(3).collect();
ms = first3.parse().ok()?;
rest = &frac[digits.len()..];
}
let offset_s = match rest {
"Z" | "z" => 0,
o if o.len() == 6 && (o.starts_with('+') || o.starts_with('-')) => {
let sign = if o.starts_with('-') { -1 } else { 1 };
sign * (o.get(1..3)?.parse::<i64>().ok()? * 3600 + o.get(4..6)?.parse::<i64>().ok()? * 60)
}
_ => return None,
};
if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || se > 60 {
return None;
}
let days = days_from_civil(y, mo as u32, d as u32);
let secs = days * 86_400 + h * 3600 + mi * 60 + se - offset_s;
(secs > 0).then(|| secs as u64 * 1000 + ms as u64)
}
pub fn parse_k8s_quantity(s: &str) -> Option<u64> {
let s = s.trim();
if s.is_empty() {
return None;
}
let bin = |e: i32| 1024f64.powi(e);
let dec = |e: i32| 1000f64.powi(e);
let suffixes: [(&str, f64); 13] = [
("Ki", bin(1)),
("Mi", bin(2)),
("Gi", bin(3)),
("Ti", bin(4)),
("Pi", bin(5)),
("Ei", bin(6)),
("k", dec(1)),
("M", dec(2)),
("G", dec(3)),
("T", dec(4)),
("P", dec(5)),
("E", dec(6)),
("m", 0.001),
];
let (num, mult) = suffixes
.iter()
.find_map(|(suf, m)| s.strip_suffix(suf).map(|n| (n, *m)))
.unwrap_or((s, 1.0));
if !num
.bytes()
.all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-'))
{
return None;
}
let v: f64 = num.parse().ok()?;
let bytes = v * mult;
(bytes.is_finite() && bytes >= 0.0).then(|| bytes.round() as u64)
}
#[derive(Debug, Clone, Copy, Default)]
struct CpuObs {
first: (u64, u64),
last: (u64, u64),
}
#[derive(Debug, Clone, Default)]
pub struct IsolationTracker {
pub limits: LimitTracker,
cpu: BTreeMap<String, CpuObs>,
}
impl IsolationTracker {
pub fn new() -> Self {
Self::default()
}
pub fn update(&mut self, s: &mut Snapshot) {
let now = s.taken_at_ms;
let namespaces = namespace_sets(s);
let mut clusters = build_clusters(s);
let inputs = limit_inputs(s, &clusters);
let limits = evaluate(&mut self.limits, inputs, now);
link_limits(&mut clusters, &limits);
let vm_slack = vm_slack(s);
let stale = self.stale(s, now);
let iso = &mut s.isolation;
iso.namespaces = namespaces;
iso.clusters = clusters;
iso.limits = limits;
iso.vm_slack = vm_slack;
iso.stale_containers = stale;
}
fn stale(&mut self, s: &Snapshot, now: u64) -> Vec<StaleContainer> {
let mut out = Vec::new();
let mut seen = Vec::new();
for c in &s.isolation.containers {
let age_from = |t: Option<u64>| t.map(|t| now.saturating_sub(t) / 1000);
if c.state == "running" {
seen.push(c.sandbox_id.clone());
let (Some(ns), Some(at)) = (c.cpu_total_ns, c.stats_at_ms) else {
continue;
};
let e = self.cpu.entry(c.sandbox_id.clone()).or_insert(CpuObs {
first: (at, ns),
last: (at, ns),
});
if ns < e.last.1 {
*e = CpuObs {
first: (at, ns),
last: (at, ns),
};
} else if at > e.last.0 {
e.last = (at, ns);
}
let dt_ms = e.last.0.saturating_sub(e.first.0);
let observed_s = dt_ms / 1000;
if observed_s < STALE_MIN_OBSERVED_S {
continue;
}
let pct = (e.last.1 - e.first.1) as f64 / (dt_ms as f64 * 1e6) * 100.0;
if pct >= STALE_CPU_PCT {
continue;
}
let mem = s
.sandboxes
.iter()
.find(|sb| sb.id == c.sandbox_id)
.map(|sb| sb.guest_mem.clone())
.unwrap_or_else(|| Measured::unavailable(c.engine.clone(), "no stats"));
out.push(StaleContainer {
sandbox_id: c.sandbox_id.clone(),
name: c.name.clone(),
engine: c.engine.clone(),
image: c.image.clone(),
state: c.state.clone(),
created_ms: c.created_ms,
started_ms: c.started_ms,
finished_ms: c.finished_ms,
age_s: age_from(c.started_ms.or(c.created_ms)),
cpu_pct: Measured::estimate(
pct,
format!("{} Δ cpu_stats.total_usage over {observed_s} s", c.engine),
),
observed_s,
mem,
disk: size_measured(c),
exit_code: None,
oom_killed: c.oom_killed,
reason: format!(
"running, {pct:.1}% CPU over {}",
crate::units::format_duration(observed_s)
),
});
} else if matches!(c.state.as_str(), "exited" | "created" | "dead") {
let since = c.finished_ms.filter(|_| c.state != "created").or(c.created_ms);
out.push(StaleContainer {
sandbox_id: c.sandbox_id.clone(),
name: c.name.clone(),
engine: c.engine.clone(),
image: c.image.clone(),
state: c.state.clone(),
created_ms: c.created_ms,
started_ms: c.started_ms,
finished_ms: c.finished_ms,
age_s: age_from(since),
cpu_pct: Measured::unavailable(c.engine.clone(), "not running"),
observed_s: 0,
mem: Measured::exact(0, format!("{} (not running)", c.engine)),
disk: size_measured(c),
exit_code: c.exit_code,
oom_killed: c.oom_killed,
reason: if c.status_text.is_empty() {
c.state.clone()
} else {
c.status_text.to_ascii_lowercase()
},
});
}
}
self.cpu.retain(|k, _| seen.contains(k));
out.sort_by(|a, b| {
(a.state != "running")
.cmp(&(b.state != "running"))
.then(b.age_s.cmp(&a.age_s))
.then(a.sandbox_id.cmp(&b.sandbox_id))
});
out
}
}
fn size_measured(c: &ContainerInfo) -> Measured<u64> {
match c.size_rw {
Some(v) => Measured::exact(v, format!("{} SizeRw", c.engine)),
None => Measured::unavailable(
c.engine.clone(),
"engine lists sizes only on request (size=1 walks every layer; not requested)",
),
}
}
#[derive(Default)]
struct PodAcc {
pod: KubePod,
namespace: String,
containers: BTreeMap<String, KubeContainer>,
}
#[derive(Default)]
struct NodeAcc {
sandbox_id: Option<String>,
mem: Measured<u64>,
pods: BTreeMap<String, PodAcc>,
}
#[derive(Default)]
struct ClusterAcc {
c: Cluster,
nodes: BTreeMap<String, NodeAcc>,
}
fn cgroup_mem<'a>(s: &'a Snapshot, path: &str) -> Option<&'a CgroupMem> {
s.cgroups.iter().find(|c| c.path == path)
}
fn node_container_id(prefix: &str) -> Option<String> {
prefix.split('/').find_map(|seg| {
let s = seg.strip_suffix(".scope")?;
["docker-", "libpod-", "cri-containerd-"]
.iter()
.find_map(|p| s.strip_prefix(p))
.filter(|id| id.len() >= 12 && id.bytes().all(|b| b.is_ascii_hexdigit()))
.map(str::to_string)
})
}
fn node_cluster_of(c: &ContainerInfo) -> Option<(String, String, KubeDistro, String)> {
let l = &c.labels;
if let Some(name) = l.get("io.x-k8s.kind.cluster") {
let distro = if c.engine == "docker-desktop" && name == "desktop" {
KubeDistro::DockerDesktop
} else {
KubeDistro::Kind
};
let id = if distro == KubeDistro::DockerDesktop {
"docker-desktop".to_string()
} else {
format!("kind:{name}")
};
return Some((id, name.clone(), distro, "label io.x-k8s.kind.cluster".into()));
}
if let Some(name) = l.get("k3d.cluster") {
if matches!(
l.get("k3d.role").map(String::as_str),
Some("loadbalancer" | "registry" | "noRole")
) {
return None;
}
return Some((
format!("k3d:{name}"),
name.clone(),
KubeDistro::K3d,
"label k3d.cluster".into(),
));
}
if let Some(name) = l.get("name.minikube.sigs.k8s.io") {
return Some((
format!("minikube:{name}"),
name.clone(),
KubeDistro::Minikube,
"label name.minikube.sigs.k8s.io".into(),
));
}
None
}
fn proc_matches(s: &Snapshot, f: impl Fn(&crate::model::Process) -> bool) -> bool {
s.processes.iter().any(f)
}
fn base(exe: &str) -> &str {
exe.rsplit('/').next().unwrap_or(exe)
}
fn host_distro(s: &Snapshot) -> (KubeDistro, Option<String>) {
if proc_matches(s, |p| p.name == "kubelite" || p.exe.contains("/snap/microk8s/")) {
return (KubeDistro::Microk8s, Some("process kubelite (microk8s)".into()));
}
if proc_matches(s, |p| {
(p.name == "k3s" || base(&p.exe) == "k3s" || p.name.starts_with("k3s-"))
&& !p
.cmdline
.iter()
.any(|a| a == "kubectl" || a == "crictl" || a == "ctr")
}) {
return (KubeDistro::K3s, Some("process k3s".into()));
}
if proc_matches(s, |p| p.name == "kubelet" || base(&p.exe) == "kubelet") {
return (KubeDistro::Unknown, Some("process kubelet".into()));
}
(KubeDistro::Unknown, None)
}
fn vm_clusters(s: &Snapshot) -> Vec<(String, String, KubeDistro, String, Option<String>)> {
let ctx = |name: &str| s.isolation.kube_contexts.iter().any(|c| c.name == name);
let app = |needle: &str| proc_matches(s, |p| p.exe.contains(needle));
let vm_of = |runtime_pred: &dyn Fn(&crate::model::Sandbox) -> bool| {
s.sandboxes
.iter()
.find(|sb| sb.kind == SandboxKind::Vm && runtime_pred(sb))
.map(|sb| sb.id.clone())
};
let mut out = Vec::new();
if ctx("docker-desktop") && app("/Docker.app/") {
out.push((
"docker-desktop".into(),
"docker-desktop".into(),
KubeDistro::DockerDesktop,
"kubeconfig context docker-desktop + Docker Desktop running".into(),
vm_of(&|sb| sb.label.starts_with("Docker") || sb.runtime == "docker-desktop"),
));
}
if ctx("orbstack") && app("/OrbStack.app/") {
out.push((
"orbstack".into(),
"orbstack".into(),
KubeDistro::OrbStack,
"kubeconfig context orbstack + OrbStack running".into(),
vm_of(&|sb| sb.runtime == "orbstack" || sb.label.starts_with("OrbStack")),
));
}
if ctx("rancher-desktop") && app("/Rancher Desktop.app/") {
out.push((
"rancher-desktop".into(),
"rancher-desktop".into(),
KubeDistro::RancherDesktop,
"kubeconfig context rancher-desktop + Rancher Desktop running".into(),
vm_of(&|sb| sb.label.starts_with("Rancher Desktop")),
));
}
let colima_k8s = proc_matches(s, |p| {
(p.name == "colima" || base(&p.exe) == "colima")
&& p.cmdline.iter().any(|a| a == "--kubernetes" || a == "-k")
});
if colima_k8s || (ctx("colima") && proc_matches(s, |p| p.name == "colima" || base(&p.exe) == "colima")) {
out.push((
"colima".into(),
"colima".into(),
KubeDistro::Colima,
if colima_k8s {
"process colima --kubernetes".into()
} else {
"kubeconfig context colima + colima running".into()
},
vm_of(&|sb| sb.runtime == "colima" || sb.label.contains("olima")),
));
}
if proc_matches(s, |p| {
!p.name.starts_with("minikube") && p.cmdline.iter().any(|a| a.contains("/.minikube/machines/"))
}) {
out.push((
"minikube:minikube".into(),
"minikube".into(),
KubeDistro::Minikube,
"minikube VM process".into(),
None,
));
}
out
}
impl ClusterAcc {
fn new(id: &str, name: &str, distro: KubeDistro, evidence: String) -> Self {
ClusterAcc {
c: Cluster {
id: id.into(),
name: name.into(),
distro,
evidence: vec![evidence],
..Default::default()
},
nodes: BTreeMap::new(),
}
}
fn evidence(&mut self, e: String) {
if !self.c.evidence.contains(&e) {
self.c.evidence.push(e);
}
}
}
fn pod_entry<'a>(node: &'a mut NodeAcc, uid: Option<&str>, ns: &str, name: Option<&str>) -> &'a mut PodAcc {
let key = match uid {
Some(u) => u.to_string(),
None => format!("{ns}/{}", name.unwrap_or("?")),
};
if !node.pods.contains_key(&key) {
if let Some(n) = name {
if let Some(k) = node
.pods
.iter()
.find(|(_, p)| p.pod.name.as_deref() == Some(n) && p.namespace == ns)
.map(|(k, _)| k.clone())
{
return node.pods.get_mut(&k).expect("present");
}
}
}
node.pods.entry(key).or_insert_with(|| PodAcc {
pod: KubePod {
uid: uid.map(str::to_string),
..Default::default()
},
..Default::default()
})
}
fn container_entry<'a>(pod: &'a mut PodAcc, id: Option<&str>, name: Option<&str>) -> &'a mut KubeContainer {
let found = pod
.containers
.iter()
.find(|(_, c)| {
(id.is_some() && c.id.as_deref() == id)
|| (name.is_some() && c.name.as_deref() == name && (id.is_none() || c.id.is_none()))
})
.map(|(k, _)| k.clone());
let key = found.unwrap_or_else(|| id.or(name).unwrap_or("?").to_string());
pod.containers.entry(key).or_default()
}
pub fn build_clusters(s: &Snapshot) -> Vec<Cluster> {
let mut acc: BTreeMap<String, ClusterAcc> = BTreeMap::new();
let host_name = if s.host.hostname.is_empty() {
"this host".to_string()
} else {
s.host.hostname.clone()
};
let sandbox_mem = |id: &str| {
s.sandboxes
.iter()
.find(|sb| sb.id == id)
.map(|sb| sb.guest_mem.clone())
};
for c in &s.isolation.containers {
if c.state != "running" {
continue;
}
let Some((id, name, distro, ev)) = node_cluster_of(c) else {
continue;
};
let a = acc
.entry(id.clone())
.or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev.clone()));
a.evidence(ev);
let n = a.nodes.entry(c.name.clone()).or_default();
n.sandbox_id = Some(c.sandbox_id.clone());
n.mem =
sandbox_mem(&c.sandbox_id).unwrap_or_else(|| Measured::unavailable(c.engine.clone(), "no stats"));
}
for c in &s.isolation.containers {
let l = &c.labels;
let Some(uid) = l.get("io.kubernetes.pod.uid") else {
continue;
};
if c.state != "running"
|| l.get("io.kubernetes.docker.type").map(String::as_str) == Some("podsandbox")
{
continue;
}
let (cid, node) = if c.vm_hosted {
let id = if c.engine == "docker-desktop" {
"docker-desktop".to_string()
} else {
c.engine.clone()
};
(id.clone(), id)
} else {
("host".to_string(), host_name.clone())
};
let distro = if c.engine == "docker-desktop" {
KubeDistro::DockerDesktop
} else {
KubeDistro::Unknown
};
let a = acc.entry(cid.clone()).or_insert_with(|| {
ClusterAcc::new(&cid, &cid, distro, "labels io.kubernetes.* (cri-dockerd)".into())
});
a.evidence("labels io.kubernetes.* (cri-dockerd)".into());
let n = a.nodes.entry(node).or_default();
let ns = l.get("io.kubernetes.pod.namespace").cloned().unwrap_or_default();
let pname = l.get("io.kubernetes.pod.name").cloned();
let p = pod_entry(n, Some(uid), &ns, pname.as_deref());
p.namespace = ns;
p.pod.name = p.pod.name.take().or(pname);
let cname = l.get("io.kubernetes.container.name").cloned();
let k = container_entry(p, Some(&c.id), cname.as_deref());
k.id = Some(c.id.clone());
k.name = cname;
k.runtime = Some("docker".into());
k.sandbox_id = Some(c.sandbox_id.clone());
k.restarts = c.restart_count;
if let Some(m) = sandbox_mem(&c.sandbox_id) {
k.mem = m;
}
if let Some(sb) = s.sandboxes.iter().find(|sb| sb.id == c.sandbox_id) {
k.host_pids = sb.host_pids.clone();
k.limit = sb.configured_mem.clone();
}
}
let mut kube_procs: Vec<(&crate::model::Process, KubeCgroup)> = s
.processes
.iter()
.filter_map(|p| Some((p, parse_kube_cgroup(p.cgroup.as_deref()?)?)))
.collect();
kube_procs.sort_by_key(|(p, _)| (p.id.start_time, p.id.pid));
if !kube_procs.is_empty() {
let (hd, hev) = host_distro(s);
for (p, k) in &kube_procs {
let (cid, node) = if k.node_prefix.is_empty() {
let a = acc.entry("host".into()).or_insert_with(|| {
ClusterAcc::new("host", &host_name, hd, "kubelet cgroups on this host".into())
});
if let Some(e) = &hev {
a.evidence(e.clone());
}
if a.c.distro == KubeDistro::Unknown {
a.c.distro = hd;
}
("host".to_string(), host_name.clone())
} else {
let nid = node_container_id(&k.node_prefix);
let node_ci = nid.as_ref().and_then(|id| {
s.isolation
.containers
.iter()
.find(|c| c.id.starts_with(id.as_str()) || id.starts_with(c.id.as_str()))
});
match node_ci.and_then(|c| node_cluster_of(c).map(|x| (x, c))) {
Some(((id, name, distro, ev), c)) => {
let a = acc
.entry(id.clone())
.or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev));
a.evidence("kubelet cgroups inside the node container".into());
(id, c.name.clone())
}
None => {
let short: String = nid.clone().unwrap_or_default().chars().take(12).collect();
let id = format!("nested:{short}");
acc.entry(id.clone()).or_insert_with(|| {
ClusterAcc::new(
&id,
&format!("cluster in container {short}"),
KubeDistro::Unknown,
"kubelet cgroups inside a container".into(),
)
});
(id, format!("container {short}"))
}
}
};
let a = acc.get_mut(&cid).expect("inserted");
let n = a.nodes.entry(node).or_default();
let pa = pod_entry(n, Some(&k.pod_uid), "", None);
pa.pod.qos = Some(k.qos);
if pa.pod.cgroup.is_none() {
pa.pod.cgroup = Some(k.pod_cgroup.clone());
if let Some(cg) = cgroup_mem(s, &k.pod_cgroup) {
pa.pod.mem = cg.working_set_measured();
pa.pod.limit = cg.max;
}
}
let Some(id) = k.container_id.as_deref().filter(|_| !k.conmon) else {
continue;
};
let c = container_entry(pa, Some(id), None);
c.id = Some(id.to_string());
c.runtime = c.runtime.take().or(k.runtime.clone());
if !c.host_pids.contains(&p.id) {
c.host_pids.push(p.id);
}
if c.name.is_none() && p.name == "pause" {
c.name = Some("pause".into());
}
if let Some(cg) = k.container_cgroup.as_deref() {
c.cgroup = Some(cg.to_string());
if let Some(m) = cgroup_mem(s, cg) {
c.mem = m.working_set_measured();
c.limit = match m.max {
Some(v) => Measured::exact(v, "cgroup memory.max"),
None if m.limits_read => Measured::unavailable("cgroup memory.max", "no limit"),
None => Measured::unavailable("cgroup memory.max", "not read"),
};
}
}
}
for a in acc.values_mut() {
for n in a.nodes.values_mut() {
for pa in n.pods.values_mut() {
for c in pa.containers.values_mut() {
if !c.mem.is_available() && !c.host_pids.is_empty() {
let mems: Vec<&Measured<u64>> = c
.host_pids
.iter()
.filter_map(|id| s.process(*id).map(|p| &p.mem.footprint_or_pss))
.collect();
c.mem = sum_bytes(mems, "Σ process PSS (cgroup not read)").into_estimate();
}
}
}
}
}
}
for d in &s.isolation.kube {
let node_names: Vec<String> = d
.pods
.iter()
.filter_map(|p| p.node.clone())
.chain(d.nodes.iter().map(|n| n.name.clone()))
.collect();
let existing = acc
.iter()
.find(|(_, a)| node_names.iter().any(|n| a.nodes.contains_key(n)))
.map(|(k, _)| k.clone());
let distro = d.distro.or_else(|| KubeDistro::from_context(&d.context));
let cid = existing.unwrap_or_else(|| match distro {
Some(KubeDistro::Kind) => {
format!("kind:{}", KubeDistro::Kind.cluster_name_from_context(&d.context))
}
Some(KubeDistro::K3d) => format!("k3d:{}", KubeDistro::K3d.cluster_name_from_context(&d.context)),
Some(KubeDistro::Minikube) => "minikube:minikube".into(),
Some(KubeDistro::DockerDesktop) => "docker-desktop".into(),
Some(KubeDistro::OrbStack) => "orbstack".into(),
Some(KubeDistro::RancherDesktop) => "rancher-desktop".into(),
Some(KubeDistro::Colima) => "colima".into(),
_ => format!("context:{}", d.context),
});
let a = acc.entry(cid.clone()).or_insert_with(|| {
ClusterAcc::new(
&cid,
&distro.map_or(d.context.clone(), |x| x.cluster_name_from_context(&d.context)),
distro.unwrap_or_default(),
"kubeconfig context".into(),
)
});
a.evidence(format!("API via context {}", d.context));
a.c.context = Some(d.context.clone());
a.c.api = Some(d.status.clone());
for p in &d.pods {
let node = p.node.clone().unwrap_or_else(|| "(unscheduled)".into());
let n = a.nodes.entry(node).or_default();
let pa = pod_entry(n, Some(&p.uid), &p.namespace, Some(&p.name));
pa.namespace = p.namespace.clone();
pa.pod.name = Some(p.name.clone());
pa.pod.phase = p.phase.clone();
pa.pod.qos = p.qos.or(pa.pod.qos);
for cs in &p.containers {
let c = container_entry(pa, cs.id.as_deref(), Some(&cs.name));
c.name = Some(cs.name.clone());
c.id = c.id.take().or(cs.id.clone());
c.runtime = c.runtime.take().or(cs.runtime.clone());
c.restarts = cs.restarts;
c.last_termination = cs.last_termination_reason.clone();
if !c.limit.is_available() {
c.limit = match cs.mem_limit {
Some(l) => Measured::exact(l, "pod spec resources.limits.memory"),
None => Measured::unavailable("pod spec", "no memory limit"),
};
}
}
}
for ns in &d.nodes {
let n = a.nodes.entry(ns.name.clone()).or_default();
if !n.mem.is_available() {
if let Some(ws) = ns.working_set {
n.mem = Measured::exact(ws, "kubelet stats/summary node workingSetBytes");
}
}
for ps in &ns.pods {
let pa = pod_entry(n, Some(&ps.uid), &ps.namespace, Some(&ps.name));
pa.namespace = ps.namespace.clone();
pa.pod.name = pa.pod.name.take().or(Some(ps.name.clone()));
if !pa.pod.mem.is_available() {
if let Some(ws) = ps.working_set {
pa.pod.mem = Measured::exact(ws, "kubelet stats/summary workingSetBytes");
}
}
for cs in &ps.containers {
let c = container_entry(pa, None, Some(&cs.name));
c.name = Some(cs.name.clone());
if !c.mem.is_available() {
if let Some(ws) = cs.working_set {
c.mem = Measured::exact(ws, "kubelet stats/summary workingSetBytes");
}
}
}
}
}
}
for (id, name, distro, ev, vm) in vm_clusters(s) {
let a = acc
.entry(id.clone())
.or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev.clone()));
a.evidence(ev);
if a.nodes.is_empty() {
let n = a.nodes.entry(name.clone()).or_default();
if let Some(v) = &vm {
n.sandbox_id = Some(v.clone());
n.mem = s
.sandboxes
.iter()
.find(|sb| &sb.id == v)
.and_then(|sb| {
let fp: Vec<&Measured<u64>> = sb
.host_pids
.iter()
.filter_map(|h| s.process(*h).map(|p| &p.mem.footprint_or_pss))
.collect();
(!fp.is_empty()).then(|| sum_bytes(fp, "VM host footprint"))
})
.unwrap_or_else(|| Measured::unavailable("vm", "VM process not found"));
}
}
}
for a in acc.values_mut() {
if a.c.context.is_none() {
a.c.context = s
.isolation
.kube_contexts
.iter()
.find(|c| match a.c.distro {
KubeDistro::Kind => c.name == format!("kind-{}", a.c.name),
KubeDistro::K3d => c.name == format!("k3d-{}", a.c.name),
KubeDistro::Unknown => false,
d => c.distro == Some(d),
})
.map(|c| c.name.clone());
}
let has_pods = a.nodes.values().any(|n| !n.pods.is_empty());
let named = a
.nodes
.values()
.flat_map(|n| n.pods.values())
.any(|p| p.pod.name.is_some());
if !has_pods {
a.c.notes.push(
"pods run inside the node container or VM: names and per-pod memory need the API server \
(oomtop calls it only for loopback plain-HTTP contexts; see `oomtop doctor`)"
.into(),
);
} else if !named {
a.c.notes.push(
"pod and container names need the API server or engine labels; cgroup paths give QoS, pod \
UID and container id only"
.into(),
);
}
}
acc.into_values().map(finish_cluster).collect()
}
fn finish_cluster(a: ClusterAcc) -> Cluster {
let mut c = a.c;
for (name, n) in a.nodes {
let mut by_ns: BTreeMap<String, Vec<KubePod>> = BTreeMap::new();
for (_, pa) in n.pods {
let mut pod = pa.pod;
pod.containers = pa.containers.into_values().collect();
pod.containers
.sort_by(|x, y| x.name.cmp(&y.name).then(x.id.cmp(&y.id)));
if !pod.mem.is_available() && !pod.containers.is_empty() {
pod.mem = sum_bytes(pod.containers.iter().map(|c| &c.mem), "Σ container working sets");
}
by_ns.entry(pa.namespace).or_default().push(pod);
}
let mut namespaces: Vec<KubeNamespace> = by_ns
.into_iter()
.map(|(name, mut pods)| {
pods.sort_by(|x, y| x.name.cmp(&y.name).then(x.uid.cmp(&y.uid)));
KubeNamespace {
mem: sum_bytes(pods.iter().map(|p| &p.mem), "Σ pod memory"),
name,
pods,
}
})
.collect();
namespaces.sort_by(|a, b| a.name.cmp(&b.name));
let mem = if n.mem.is_available() || namespaces.is_empty() {
n.mem
} else {
sum_bytes(namespaces.iter().map(|x| &x.mem), "Σ pod memory")
};
c.nodes.push(KubeNode {
name,
sandbox_id: n.sandbox_id,
mem,
namespaces,
});
}
c
}
fn link_limits(clusters: &mut [Cluster], limits: &[LimitStatus]) {
for c in clusters {
for n in &mut c.nodes {
for ns in &mut n.namespaces {
for p in &mut ns.pods {
if let Some(cg) = &p.cgroup {
let id = format!("cgroup:{cg}");
if limits.iter().any(|l| l.id == id) {
p.limit_id = Some(id);
}
}
for k in &mut p.containers {
k.limit_id = limits
.iter()
.find(|l| {
k.cgroup.as_ref().is_some_and(|cg| l.cgroup.as_ref() == Some(cg))
|| k.sandbox_id
.as_ref()
.is_some_and(|sb| l.sandbox_id.as_ref() == Some(sb))
|| (l.pod.as_deref()
== Some(&format!("{}/{}", ns.name, p.name.as_deref().unwrap_or("")))
&& l.label == k.name.clone().unwrap_or_default()
&& l.id.starts_with("k8s:"))
})
.map(|l| l.id.clone());
}
}
}
}
}
}
fn unit_label(path: &str) -> String {
path.rsplit('/')
.find(|s| !s.is_empty())
.unwrap_or(path)
.to_string()
}
pub fn limit_inputs(s: &Snapshot, clusters: &[Cluster]) -> Vec<LimitInput> {
let mut out: Vec<LimitInput> = Vec::new();
let mut kube_names: BTreeMap<String, (String, String)> = BTreeMap::new();
let mut pod_names: BTreeMap<String, String> = BTreeMap::new();
for c in clusters {
for n in &c.nodes {
for ns in &n.namespaces {
for p in &ns.pods {
let pod = format!("{}/{}", ns.name, p.name.as_deref().unwrap_or("?"));
if let Some(cg) = &p.cgroup {
pod_names.insert(cg.clone(), pod.clone());
}
for k in &p.containers {
if let Some(id) = &k.id {
kube_names.insert(id.clone(), (pod.clone(), k.name.clone().unwrap_or_default()));
}
}
}
}
}
}
let ci_by_id = |id: &str| {
s.isolation
.containers
.iter()
.find(|c| c.id.starts_with(id) || (!c.id.is_empty() && id.starts_with(c.id.as_str())))
};
let mut covered_sandboxes: Vec<String> = Vec::new();
let mut covered_kube_ids: Vec<String> = Vec::new();
for cg in s.cgroups.iter().filter(|c| c.has_limit()) {
let (limit, target) = match (cg.max, cg.high) {
(Some(m), _) => (Measured::exact(m, "cgroup memory.max"), LimitTarget::Max),
(None, Some(h)) => (Measured::exact(h, "cgroup memory.high"), LimitTarget::High),
_ => continue,
};
let mut i = LimitInput {
id: format!("cgroup:{}", cg.path),
kind: LimitKind::Cgroup,
label: unit_label(&cg.path),
runtime: None,
cgroup: Some(cg.path.clone()),
usage: cg.working_set_measured(),
read_at_ms: (cg.current.is_some() && cg.at_ms > 0).then_some(cg.at_ms),
limit,
target,
high: cg.high.filter(|h| cg.max.is_none_or(|m| *h < m)),
peak: match cg.peak {
Some(p) => Measured::exact(p, "cgroup memory.peak"),
None => Measured::unavailable("cgroup memory.peak", "not available (kernel < 5.19)"),
},
events: cg.events,
..Default::default()
};
if let Some(k) = parse_kube_cgroup(&cg.path) {
i.runtime = Some("kubernetes".into());
match &k.container_id {
Some(id) => {
i.kind = LimitKind::Container;
covered_kube_ids.push(id.clone());
if let Some((pod, name)) = kube_names.get(id) {
i.pod = Some(pod.clone());
if !name.is_empty() {
i.label = name.clone();
}
} else {
i.label = id.chars().take(12).collect();
}
}
None => {
i.kind = LimitKind::Pod;
i.label = pod_names
.get(&k.pod_cgroup)
.cloned()
.unwrap_or_else(|| format!("pod {}", k.pod_uid));
i.pod = pod_names.get(&k.pod_cgroup).cloned();
}
}
} else if let Some(CgroupScope::Container { runtime, id }) = parse_cgroup(&cg.path) {
i.kind = LimitKind::Container;
i.runtime = Some(runtime.clone());
if let Some(ci) = ci_by_id(&id) {
i.label = ci.name.clone();
i.sandbox_id = Some(ci.sandbox_id.clone());
i.oom_killed_last_exit = ci.oom_killed;
i.restarts = ci.restart_count;
covered_sandboxes.push(ci.sandbox_id.clone());
} else if let Some(sb) = s.sandboxes.iter().find(|sb| sb.id.ends_with(&format!(":{id}"))) {
i.label = sb.label.clone();
i.sandbox_id = Some(sb.id.clone());
covered_sandboxes.push(sb.id.clone());
} else {
i.label = format!("{runtime} {id}");
}
} else if cg.path.ends_with(".service") || cg.path.ends_with(".scope") || cg.path.ends_with(".slice")
{
i.runtime = Some("systemd".into());
}
out.push(i);
}
for sb in &s.sandboxes {
if sb.kind != SandboxKind::Container || covered_sandboxes.contains(&sb.id) {
continue;
}
let Some(limit) = sb.limits.mem_max else {
continue;
};
let ci = s.isolation.container(&sb.id);
if let Some(c) = ci {
if c.labels.contains_key("io.kubernetes.pod.uid") {
covered_kube_ids.push(c.id.clone());
}
}
out.push(LimitInput {
id: sb.id.clone(),
kind: LimitKind::Container,
label: sb.label.clone(),
runtime: Some(sb.runtime.clone()),
sandbox_id: Some(sb.id.clone()),
usage: sb.guest_mem.clone(),
read_at_ms: ci
.and_then(|c| c.stats_at_ms)
.filter(|_| sb.guest_mem.quality == crate::model::Quality::Exact),
limit: if sb.configured_mem.is_available() {
sb.configured_mem.clone()
} else {
Measured::exact(limit, format!("{} HostConfig.Memory", sb.runtime))
},
peak: Measured::unavailable(sb.runtime.clone(), "engines do not report a peak"),
oom_killed_last_exit: ci.and_then(|c| c.oom_killed),
restarts: ci.and_then(|c| c.restart_count),
..Default::default()
});
}
for sb in &s.sandboxes {
if sb.kind != SandboxKind::Vm || !sb.guest_mem.source.starts_with("Σ container memory") {
continue;
}
let Some(size) = sb.configured_mem.value else {
continue;
};
let complete = sb.guest_mem.source == "Σ container memory (engine stats)";
let read_at = s
.isolation
.containers
.iter()
.filter(|c| c.engine == sb.runtime || sb.started_by_group.is_some())
.filter_map(|c| c.stats_at_ms)
.max();
out.push(LimitInput {
id: sb.id.clone(),
kind: LimitKind::Vm,
label: sb.label.clone(),
runtime: Some(sb.runtime.clone()),
sandbox_id: Some(sb.id.clone()),
usage: sb.guest_mem.clone(),
read_at_ms: read_at.filter(|_| complete),
limit: Measured::exact(size, sb.configured_mem.source.clone()),
peak: Measured::unavailable(sb.runtime.clone(), "not reported"),
..Default::default()
});
}
for d in &s.isolation.kube {
let stats: BTreeMap<(String, String, String), &KubeContainerStats> = d
.nodes
.iter()
.flat_map(|n| n.pods.iter())
.flat_map(|p| {
p.containers
.iter()
.map(move |c| ((p.namespace.clone(), p.name.clone(), c.name.clone()), c))
})
.collect();
for p in &d.pods {
for c in &p.containers {
let Some(limit) = c.mem_limit else { continue };
if c.id
.as_ref()
.is_some_and(|id| covered_kube_ids.iter().any(|x| x == id))
{
continue;
}
let st = stats.get(&(p.namespace.clone(), p.name.clone(), c.name.clone()));
out.push(LimitInput {
id: format!("k8s:{}/{}/{}/{}", d.context, p.namespace, p.name, c.name),
kind: LimitKind::Container,
label: c.name.clone(),
runtime: Some("kubernetes".into()),
pod: Some(format!("{}/{}", p.namespace, p.name)),
usage: match st.and_then(|s| s.working_set) {
Some(ws) => Measured::exact(ws, "kubelet stats/summary workingSetBytes"),
None => Measured::unavailable("kubelet stats/summary", "no stats for this container"),
},
read_at_ms: st.and_then(|s| s.working_set).map(|_| d.at_ms),
limit: Measured::exact(limit, "pod spec resources.limits.memory"),
peak: Measured::unavailable("kubelet", "not reported"),
oom_killed_last_exit: c.last_termination_reason.as_ref().map(|r| r == "OOMKilled"),
restarts: c.restarts,
..Default::default()
});
}
}
}
out
}
pub fn vm_slack(s: &Snapshot) -> Vec<VmSlack> {
let mut out = Vec::new();
for sb in &s.sandboxes {
if sb.kind != SandboxKind::Vm || !sb.guest_mem.source.starts_with("Σ container memory") {
continue;
}
let Some(sum) = sb.guest_mem.value else { continue };
let fps: Vec<&Measured<u64>> = sb
.host_pids
.iter()
.filter_map(|h| s.process(*h).map(|p| &p.mem.footprint_or_pss))
.collect();
if fps.is_empty() {
continue;
}
let vm_fp = sum_bytes(fps, "VM host footprint");
let Some(fp) = vm_fp.value else { continue };
let slack = fp.saturating_sub(sum);
if slack < VM_SLACK_MIN_BYTES.max(fp / 10) {
continue;
}
let mut notes = Vec::new();
if sb.footprint_lower_bound {
notes.push(
"the VM's host footprint is a lower bound (compressed guest memory is not in it), so the \
slack may be larger"
.to_string(),
);
}
if sb.guest_mem.source.contains("lower bound") {
notes.push("not every container was measured, so the slack may be smaller".to_string());
}
if sb.guest_mem.source.contains("earlier refresh") {
notes.push("some container values are from an earlier refresh".to_string());
}
notes.push("includes the guest kernel, page cache and the engine's own services".to_string());
out.push(VmSlack {
sandbox_id: sb.id.clone(),
label: sb.label.clone(),
runtime: sb.runtime.clone(),
vm_footprint: vm_fp,
containers: sb.guest_mem.clone(),
configured: sb.configured_mem.value,
slack: Measured::estimate(slack, "VM host footprint − Σ container memory"),
summary: format!(
"{}: {} {VM_SLACK_SENTENCE}",
sb.label,
format_bytes(slack, UnitSystem::Iec, 1)
),
notes,
counts_as_reclaim: false,
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::forecast::MemoryEvents;
use crate::model::{MemBreakdown, Process, Sandbox, SandboxLimits};
const GIB: u64 = 1 << 30;
const MIB: u64 = 1 << 20;
const CID: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const UID: &str = "8f6c1c3e-3b5a-4b8e-9d55-0a1b2c3d4e5f";
fn proc(pid: u32, name: &str, cgroup: &str, mib: u64) -> Process {
Process {
id: ProcId::new(pid, pid as u64),
ppid: Some(1),
name: name.into(),
cgroup: Some(cgroup.into()),
mem: MemBreakdown {
footprint_or_pss: Measured::exact(mib * MIB, "t"),
..Default::default()
},
..Default::default()
}
}
#[test]
fn parsers() {
assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:01Z"), Some(1000));
assert_eq!(
parse_rfc3339_ms("2026-12-05T10:11:12.123456789Z"),
Some(1_796_465_472_123)
);
assert_eq!(
parse_rfc3339_ms("2026-12-05T11:11:12+01:00"),
parse_rfc3339_ms("2026-12-05T10:11:12Z")
);
assert_eq!(parse_rfc3339_ms("0001-01-01T00:00:00Z"), None, "docker zero time");
assert_eq!(parse_rfc3339_ms("yesterday"), None);
for (q, v) in [
("128Mi", 128 * MIB),
("1Gi", GIB),
("1G", 1_000_000_000),
("500M", 500_000_000),
("1e9", 1_000_000_000),
("129e6", 129_000_000),
("1.5Gi", 3 * GIB / 2),
("100k", 100_000),
("64Ki", 65536),
("12345", 12345),
("1000m", 1),
] {
assert_eq!(parse_k8s_quantity(q), Some(v), "{q}");
}
assert_eq!(parse_k8s_quantity("lots"), None);
assert_eq!(parse_k8s_quantity(""), None);
assert!(keep_label("io.kubernetes.pod.name"));
assert!(!keep_label("org.opencontainers.image.source"));
assert_eq!(KubeDistro::from_context("kind-dev"), Some(KubeDistro::Kind));
assert_eq!(KubeDistro::Kind.cluster_name_from_context("kind-dev"), "dev");
assert_eq!(KubeDistro::from_context("prod-eu"), None);
}
#[test]
fn host_cluster_from_cgroups_with_limits_and_api_names() {
let pod_cg = format!("/kubepods/burstable/pod{UID}");
let ctr_cg = format!("{pod_cg}/{CID}");
let mut s = Snapshot {
taken_at_ms: 1_000_000,
processes: vec![
Process {
name: "k3s".into(),
exe: "/usr/local/bin/k3s".into(),
cmdline: vec!["/usr/local/bin/k3s".into(), "server".into()],
..proc(100, "k3s", "/system.slice/k3s.service", 500)
},
proc(200, "nginx", &ctr_cg, 40),
proc(201, "nginx", &ctr_cg, 10),
],
..Default::default()
};
s.host.hostname = "box".into();
s.cgroups = vec![
CgroupMem {
path: ctr_cg.clone(),
current: Some(300 * MIB),
inactive_file: Some(100 * MIB),
max: Some(256 * MIB),
limits_read: true,
events: Some(MemoryEvents {
oom_kill: 2,
..Default::default()
}),
at_ms: 1_000_000,
..Default::default()
},
CgroupMem {
path: pod_cg.clone(),
current: Some(310 * MIB),
inactive_file: Some(100 * MIB),
limits_read: true,
at_ms: 1_000_000,
..Default::default()
},
];
let mut tr = IsolationTracker::new();
tr.update(&mut s);
let iso = &s.isolation;
assert_eq!(iso.clusters.len(), 1);
let c = &iso.clusters[0];
assert_eq!((c.id.as_str(), c.distro), ("host", KubeDistro::K3s));
assert!(c.evidence.iter().any(|e| e == "process k3s"), "{:?}", c.evidence);
let pod = &c.nodes[0].namespaces[0].pods[0];
assert_eq!(c.nodes[0].name, "box");
assert_eq!(pod.uid.as_deref(), Some(UID));
assert_eq!(pod.qos, Some(QosClass::Burstable));
assert_eq!(pod.mem.value, Some(210 * MIB));
let k = &pod.containers[0];
assert_eq!(k.id.as_deref(), Some(CID));
assert_eq!(k.mem.value, Some(200 * MIB));
assert_eq!(k.host_pids.len(), 2);
assert_eq!(k.limit.value, Some(256 * MIB));
assert_eq!(k.limit_id.as_deref(), Some(format!("cgroup:{ctr_cg}").as_str()));
assert!(c.notes[0].contains("names need the API"));
let l = &iso.limits[0];
assert_eq!(l.kind, LimitKind::Container);
assert_eq!(l.oom_kills.value, Some(2));
assert_eq!(l.pct.map(|p| p.round()), Some(78.0));
s.isolation.kube = vec![KubeApiData {
context: "default".into(),
status: SourceStatus::Available,
at_ms: 1_000_000,
pods: vec![KubePodInfo {
namespace: "shop".into(),
name: "web-7d9f".into(),
uid: UID.into(),
node: Some("box".into()),
phase: Some("Running".into()),
qos: Some(QosClass::Burstable),
containers: vec![KubeContainerSpec {
name: "nginx".into(),
id: Some(CID.into()),
runtime: Some("containerd".into()),
mem_limit: Some(256 * MIB),
restarts: Some(3),
last_termination_reason: Some("OOMKilled".into()),
..Default::default()
}],
..Default::default()
}],
..Default::default()
}];
tr.update(&mut s);
let c = &s.isolation.clusters[0];
assert_eq!(
s.isolation.clusters.len(),
1,
"merged into the host cluster by node name"
);
let ns = &c.nodes[0].namespaces[0];
assert_eq!(ns.name, "shop");
let pod = &ns.pods[0];
assert_eq!(pod.name.as_deref(), Some("web-7d9f"));
assert_eq!(pod.containers.len(), 1, "matched by id, not duplicated by name");
assert_eq!(pod.containers[0].name.as_deref(), Some("nginx"));
assert_eq!(pod.containers[0].last_termination.as_deref(), Some("OOMKilled"));
let l = &s.isolation.limits[0];
assert_eq!(l.label, "nginx");
assert_eq!(l.pod.as_deref(), Some("shop/web-7d9f"));
assert_eq!(
s.isolation.limits.len(),
1,
"the API container is covered by its cgroup"
);
}
#[test]
fn kind_nodes_from_labels_and_api_only_limits() {
let mut s = Snapshot {
taken_at_ms: 5_000_000,
..Default::default()
};
let mut labels = BTreeMap::new();
labels.insert("io.x-k8s.kind.cluster".to_string(), "dev".to_string());
labels.insert("io.x-k8s.kind.role".to_string(), "control-plane".to_string());
s.isolation.containers.push(ContainerInfo {
sandbox_id: "docker-desktop:aaaa1111bbbb".into(),
id: "aaaa1111bbbb2222".into(),
engine: "docker-desktop".into(),
vm_hosted: true,
name: "dev-control-plane".into(),
state: "running".into(),
labels,
..Default::default()
});
s.sandboxes.push(Sandbox {
id: "docker-desktop:aaaa1111bbbb".into(),
kind: SandboxKind::Container,
runtime: "docker-desktop".into(),
label: "dev-control-plane".into(),
guest_mem: Measured::exact(900 * MIB, "docker-desktop stats"),
..Default::default()
});
s.isolation.kube = vec![KubeApiData {
context: "kind-dev".into(),
distro: None,
status: SourceStatus::Available,
at_ms: 5_000_000,
nodes: vec![KubeNodeStats {
name: "dev-control-plane".into(),
working_set: Some(800 * MIB),
pods: vec![KubePodStats {
namespace: "default".into(),
name: "api".into(),
uid: "u1".into(),
containers: vec![KubeContainerStats {
name: "app".into(),
working_set: Some(120 * MIB),
..Default::default()
}],
..Default::default()
}],
..Default::default()
}],
pods: vec![KubePodInfo {
namespace: "default".into(),
name: "api".into(),
uid: "u1".into(),
node: Some("dev-control-plane".into()),
containers: vec![KubeContainerSpec {
name: "app".into(),
mem_limit: Some(128 * MIB),
..Default::default()
}],
..Default::default()
}],
}];
let mut tr = IsolationTracker::new();
tr.update(&mut s);
let c = &s.isolation.clusters[0];
assert_eq!((c.id.as_str(), c.distro), ("kind:dev", KubeDistro::Kind));
assert_eq!(c.context.as_deref(), Some("kind-dev"));
let n = &c.nodes[0];
assert_eq!(n.sandbox_id.as_deref(), Some("docker-desktop:aaaa1111bbbb"));
assert_eq!(n.mem.value, Some(900 * MIB), "the node container's memory");
let k = &n.namespaces[0].pods[0].containers[0];
assert_eq!(k.mem.value, Some(120 * MIB));
assert_eq!(k.limit.value, Some(128 * MIB));
let l = &s.isolation.limits[0];
assert_eq!(l.id, "k8s:kind-dev/default/api/app");
assert_eq!(l.state, crate::limits::LimitState::Near);
assert_eq!(k.limit_id.as_deref(), Some("k8s:kind-dev/default/api/app"));
}
#[test]
fn vm_slack_finding() {
let vm = ProcId::new(900, 1);
let mut s = Snapshot::default();
s.processes.push(Process {
id: vm,
mem: MemBreakdown {
footprint_or_pss: Measured::exact(6 * GIB, "t"),
..Default::default()
},
..Default::default()
});
s.sandboxes.push(Sandbox {
id: "vz:docker".into(),
kind: SandboxKind::Vm,
runtime: "virtualization.framework".into(),
label: "Docker VM".into(),
host_pids: vec![vm],
configured_mem: Measured::exact(8 * GIB, "docker-desktop /info MemTotal"),
guest_mem: Measured::estimate(2 * GIB, "Σ container memory (engine stats)"),
limits: SandboxLimits {
mem_max: Some(8 * GIB),
cpus: None,
},
footprint_lower_bound: true,
..Default::default()
});
let v = vm_slack(&s);
assert_eq!(v.len(), 1);
assert_eq!(v[0].slack.value, Some(4 * GIB));
assert_eq!(v[0].slack.quality, crate::model::Quality::Estimate);
assert!(!v[0].counts_as_reclaim);
assert_eq!(
v[0].summary,
"Docker VM: 4.0 GiB held by the VM, not used by containers; restarting the engine returns it"
);
assert!(v[0].notes[0].contains("lower bound"));
let mut tr = IsolationTracker::new();
tr.update(&mut s);
let l = s.isolation.limit("vz:docker").unwrap();
assert_eq!((l.kind, l.limit.value), (LimitKind::Vm, Some(8 * GIB)));
s.sandboxes[0].guest_mem = Measured::estimate(5900 * MIB, "Σ container memory (engine stats)");
assert!(vm_slack(&s).is_empty());
}
#[test]
fn stale_containers() {
let mut s = Snapshot {
taken_at_ms: 10_000_000,
..Default::default()
};
let run = |ns: u64, at: u64| ContainerInfo {
sandbox_id: "docker:idle".into(),
name: "idle".into(),
engine: "docker".into(),
state: "running".into(),
started_ms: Some(1_000_000),
cpu_total_ns: Some(ns),
stats_at_ms: Some(at),
..Default::default()
};
s.isolation.containers = vec![
run(1_000_000_000, 9_000_000),
ContainerInfo {
sandbox_id: "docker:old".into(),
name: "old".into(),
engine: "docker".into(),
state: "exited".into(),
status_text: "Exited (137) 2 days ago".into(),
finished_ms: Some(10_000_000 - 2 * 3_600_000),
exit_code: Some(137),
..Default::default()
},
];
let mut tr = IsolationTracker::new();
tr.update(&mut s);
assert_eq!(
s.isolation.stale_containers.len(),
1,
"running: not observed long enough yet"
);
let old = &s.isolation.stale_containers[0];
assert_eq!(old.reason, "exited (137) 2 days ago");
assert!(old.disk.unavailable_reason().unwrap().contains("size=1"));
s.isolation.containers[0] = run(1_020_000_000, 9_180_000);
s.taken_at_ms = 10_180_000;
tr.update(&mut s);
let st = &s.isolation.stale_containers;
assert_eq!(st[0].sandbox_id, "docker:idle", "running ones first");
assert!(st[0].cpu_pct.value.unwrap() < 0.02);
assert_eq!(st[0].observed_s, 180);
assert_eq!(st[0].age_s, Some(9180));
s.isolation.containers[0] = run(31_000_000_000, 9_360_000);
tr.update(&mut s);
assert!(s
.isolation
.stale_containers
.iter()
.all(|c| c.sandbox_id != "docker:idle"));
}
#[test]
fn empty_snapshot_is_empty() {
let mut s = Snapshot::default();
IsolationTracker::new().update(&mut s);
assert!(s.isolation.is_empty());
let json = serde_json::to_value(&s).unwrap();
assert!(json.get("isolation").is_none(), "left out of JSON when empty");
assert!(json.get("cgroups").is_none());
}
}