Skip to main content

oomtop_core/
cluster.rs

1//! Containers, local Kubernetes and VM slack (SPEC §8.3, §11). Pure: inputs come from the snapshot
2//! (processes and their cgroup paths, `Snapshot::cgroups`, sandboxes) and from the adapters
3//! ([`Isolation::containers`] from the container engines, [`Isolation::kube`] / [`Isolation::kube_contexts`]
4//! from the optional Kubernetes adapter); [`IsolationTracker::update`] derives everything else:
5//!
6//! - **cluster tree** node → namespace → pod → container ([`Cluster`]), merged from three sources, each
7//!   optional: kubelet cgroup paths (Linux, [`crate::attribution::parse_kube_cgroup`]: QoS, pod UID, full
8//!   container id, per-pod/container memory from cgroup files), engine labels (`io.kubernetes.*` from
9//!   cri-dockerd, kind / k3d / minikube node containers) and the API server (names, limits, restarts, last
10//!   termination reason, kubelet working sets);
11//! - **per-limit forecast** ([`crate::limits`]) for every container, pod, cgroup and engine VM with a limit;
12//! - **VM slack** ([`VmSlack`]): host footprint of an engine VM minus what its containers use — memory held
13//!   by the VM, not by any container. An estimate, never counted as safe reclaim;
14//! - **namespace sets** ([`crate::namespaces`]);
15//! - **stale containers** ([`StaleContainer`]): running with ~0 CPU over the observed window, or stopped
16//!   and still holding a writable layer. Data only; scoring is `crate::staleness`'s job.
17
18use crate::attribution::{parse_cgroup, parse_kube_cgroup, CgroupScope, KubeCgroup, QosClass};
19use crate::limits::{evaluate, CgroupMem, LimitInput, LimitKind, LimitStatus, LimitTarget, LimitTracker};
20use crate::measured::sum_bytes;
21use crate::model::{Measured, ProcId, SandboxKind, Snapshot, SourceStatus};
22use crate::namespaces::{namespace_sets, NamespaceReport};
23use crate::units::{format_bytes, UnitSystem};
24use serde::{Deserialize, Serialize};
25use std::collections::BTreeMap;
26
27/// Engine label keys kept in [`ContainerInfo::labels`] (everything else is dropped: labels are free-form
28/// and may carry anything).
29pub const LABEL_PREFIXES: &[&str] = &[
30    "io.kubernetes.",
31    "io.x-k8s.kind.",
32    "k3d.cluster",
33    "k3d.role",
34    "name.minikube.sigs.k8s.io",
35    "role.minikube.sigs.k8s.io",
36    "mode.minikube.sigs.k8s.io",
37    "com.docker.compose.project",
38    "com.docker.compose.service",
39];
40
41/// Whether an engine label is kept (see [`LABEL_PREFIXES`]).
42pub fn keep_label(key: &str) -> bool {
43    LABEL_PREFIXES.iter().any(|p| key.starts_with(p))
44}
45
46/// The sentence of every [`VmSlack`] finding.
47pub const VM_SLACK_SENTENCE: &str =
48    "held by the VM, not used by containers; restarting the engine returns it";
49/// Slack below `max(this, 10 % of the VM footprint)` is not reported (guest kernel and engine overhead).
50pub const VM_SLACK_MIN_BYTES: u64 = 256 << 20;
51/// A running container is "idle" below this average CPU (percent of one core) …
52pub const STALE_CPU_PCT: f64 = 0.5;
53/// … observed over at least this long.
54pub const STALE_MIN_OBSERVED_S: u64 = 120;
55
56// ---------------------------------------------------------------------------------------------------------
57// Inputs (filled by the adapters)
58// ---------------------------------------------------------------------------------------------------------
59
60/// What a container engine (Docker API: Docker, Docker Desktop, OrbStack, Colima, Rancher Desktop, Podman)
61/// reports about one container, running or not. Running containers are also [`crate::model::Sandbox`]es
62/// with the same `sandbox_id`.
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
64#[serde(default)]
65pub struct ContainerInfo {
66    /// `<runtime>:<12 hex>`, as [`crate::model::Sandbox::id`].
67    pub sandbox_id: String,
68    /// Full container id.
69    pub id: String,
70    /// Engine runtime ("docker", "docker-desktop", "orbstack", "colima", "rancher-desktop", "podman").
71    pub engine: String,
72    /// The engine runs containers inside a VM (its host cost is the VM's).
73    pub vm_hosted: bool,
74    pub name: String,
75    pub image: String,
76    /// "running" | "exited" | "created" | "paused" | "restarting" | "dead".
77    pub state: String,
78    /// Engine status text ("Up 3 hours", "Exited (137) 2 days ago").
79    pub status_text: String,
80    pub created_ms: Option<u64>,
81    pub started_ms: Option<u64>,
82    pub finished_ms: Option<u64>,
83    pub exit_code: Option<i64>,
84    /// `State.OOMKilled`: the container's last run ended in a kernel OOM kill.
85    pub oom_killed: Option<bool>,
86    pub restart_count: Option<u32>,
87    /// Cumulative CPU time (`cpu_stats.cpu_usage.total_usage`, ns) and when it was read.
88    pub cpu_total_ns: Option<u64>,
89    pub stats_at_ms: Option<u64>,
90    /// Writable layer / whole filesystem size, only when the engine reported them (`size=1` listings).
91    pub size_rw: Option<u64>,
92    pub size_root_fs: Option<u64>,
93    /// Allowlisted labels only ([`LABEL_PREFIXES`]).
94    pub labels: BTreeMap<String, String>,
95}
96
97/// A local Kubernetes distribution.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
99#[serde(rename_all = "snake_case")]
100pub enum KubeDistro {
101    Kind,
102    Minikube,
103    K3d,
104    K3s,
105    DockerDesktop,
106    #[serde(rename = "orbstack")]
107    OrbStack,
108    RancherDesktop,
109    Colima,
110    Microk8s,
111    #[default]
112    Unknown,
113}
114
115impl KubeDistro {
116    pub fn title(self) -> &'static str {
117        match self {
118            KubeDistro::Kind => "kind",
119            KubeDistro::Minikube => "minikube",
120            KubeDistro::K3d => "k3d",
121            KubeDistro::K3s => "k3s",
122            KubeDistro::DockerDesktop => "Docker Desktop",
123            KubeDistro::OrbStack => "OrbStack",
124            KubeDistro::RancherDesktop => "Rancher Desktop",
125            KubeDistro::Colima => "Colima",
126            KubeDistro::Microk8s => "MicroK8s",
127            KubeDistro::Unknown => "Kubernetes",
128        }
129    }
130
131    /// The distribution a kubeconfig context name implies, by the names the tools write
132    /// (`kind-<name>`, `k3d-<name>`, `minikube`, `docker-desktop`, `orbstack`, `rancher-desktop`, `colima`,
133    /// `microk8s`).
134    pub fn from_context(name: &str) -> Option<KubeDistro> {
135        Some(match name {
136            n if n.starts_with("kind-") => KubeDistro::Kind,
137            n if n.starts_with("k3d-") => KubeDistro::K3d,
138            "minikube" => KubeDistro::Minikube,
139            "docker-desktop" | "docker-for-desktop" => KubeDistro::DockerDesktop,
140            "orbstack" => KubeDistro::OrbStack,
141            "rancher-desktop" => KubeDistro::RancherDesktop,
142            n if n == "colima" || n.starts_with("colima-") => KubeDistro::Colima,
143            "microk8s" => KubeDistro::Microk8s,
144            _ => return None,
145        })
146    }
147
148    /// Cluster name inside its distribution for a context name (`kind-dev` → `dev`).
149    pub fn cluster_name_from_context(self, ctx: &str) -> String {
150        match self {
151            KubeDistro::Kind => ctx.strip_prefix("kind-").unwrap_or(ctx).to_string(),
152            KubeDistro::K3d => ctx.strip_prefix("k3d-").unwrap_or(ctx).to_string(),
153            KubeDistro::Colima => ctx.strip_prefix("colima-").unwrap_or("default").to_string(),
154            _ => ctx.to_string(),
155        }
156    }
157}
158
159/// One kubeconfig context as the Kubernetes adapter judged it (SPEC §13 kube safety rules). Refused
160/// contexts never carry their server URL.
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
162#[serde(default)]
163pub struct KubeContextSummary {
164    pub name: String,
165    pub current: bool,
166    pub distro: Option<KubeDistro>,
167    /// The server is loopback (literal 127.0.0.0/8, ::1, `localhost`, `*.localhost`).
168    pub local: bool,
169    /// oomtop can and may call its API (loopback + plain HTTP + no credential plugin).
170    pub live: bool,
171    /// Why (not): "loopback http, token" / "refused: exec credential plugin (never run)" / …
172    pub verdict: String,
173}
174
175/// Kubelet `stats/summary` of one node (through the API server's node proxy).
176#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
177#[serde(default)]
178pub struct KubeNodeStats {
179    pub name: String,
180    pub working_set: Option<u64>,
181    pub available: Option<u64>,
182    pub pods: Vec<KubePodStats>,
183}
184
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
186#[serde(default)]
187pub struct KubePodStats {
188    pub namespace: String,
189    pub name: String,
190    pub uid: String,
191    pub working_set: Option<u64>,
192    pub containers: Vec<KubeContainerStats>,
193}
194
195#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
196#[serde(default)]
197pub struct KubeContainerStats {
198    pub name: String,
199    pub working_set: Option<u64>,
200    pub usage: Option<u64>,
201    /// `availableBytes`: present only when the container has a memory limit (limit = working set + this).
202    pub available: Option<u64>,
203    pub start_ms: Option<u64>,
204}
205
206/// One pod from `GET /api/v1/pods`.
207#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
208#[serde(default)]
209pub struct KubePodInfo {
210    pub namespace: String,
211    pub name: String,
212    pub uid: String,
213    pub node: Option<String>,
214    pub phase: Option<String>,
215    pub qos: Option<QosClass>,
216    pub created_ms: Option<u64>,
217    pub containers: Vec<KubeContainerSpec>,
218}
219
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
221#[serde(default)]
222pub struct KubeContainerSpec {
223    pub name: String,
224    /// Container id without the `containerd://` prefix.
225    pub id: Option<String>,
226    /// `containerd` | `cri-o` | `docker` (the prefix).
227    pub runtime: Option<String>,
228    pub mem_limit: Option<u64>,
229    pub mem_request: Option<u64>,
230    pub restarts: Option<u32>,
231    /// "running" | "waiting" | "terminated".
232    pub state: Option<String>,
233    /// `lastState.terminated.reason` ("OOMKilled", "Error", "Completed").
234    pub last_termination_reason: Option<String>,
235    pub last_termination_ms: Option<u64>,
236    pub last_exit_code: Option<i64>,
237}
238
239/// What the Kubernetes adapter read from one context's API server.
240#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
241#[serde(default)]
242pub struct KubeApiData {
243    pub context: String,
244    pub distro: Option<KubeDistro>,
245    pub status: SourceStatus,
246    pub at_ms: u64,
247    pub nodes: Vec<KubeNodeStats>,
248    pub pods: Vec<KubePodInfo>,
249}
250
251// ---------------------------------------------------------------------------------------------------------
252// Outputs
253// ---------------------------------------------------------------------------------------------------------
254
255/// A local cluster: node → namespace → pod → container.
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
257#[serde(default)]
258pub struct Cluster {
259    /// `host`, `kind:<name>`, `k3d:<name>`, `minikube:<profile>`, `docker-desktop`, `context:<name>`…
260    pub id: String,
261    pub name: String,
262    pub distro: KubeDistro,
263    pub context: Option<String>,
264    /// How it was recognised ("process k3s", "label io.x-k8s.kind.cluster", "kubeconfig context", "kubelet
265    /// cgroups").
266    pub evidence: Vec<String>,
267    /// API data status, when an API was read for it.
268    pub api: Option<SourceStatus>,
269    pub nodes: Vec<KubeNode>,
270    /// Why the tree is empty or partial ("pods run inside the VM; …").
271    pub notes: Vec<String>,
272}
273
274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
275#[serde(default)]
276pub struct KubeNode {
277    pub name: String,
278    /// The node's container (kind, k3d, minikube) or VM sandbox.
279    pub sandbox_id: Option<String>,
280    /// Node memory: its container's/VM's, else the kubelet's node working set, else Σ pods.
281    pub mem: Measured<u64>,
282    pub namespaces: Vec<KubeNamespace>,
283}
284
285#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
286#[serde(default)]
287pub struct KubeNamespace {
288    /// Empty when only cgroup paths are known (no names without the API or engine labels).
289    pub name: String,
290    pub mem: Measured<u64>,
291    pub pods: Vec<KubePod>,
292}
293
294#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
295#[serde(default)]
296pub struct KubePod {
297    pub uid: Option<String>,
298    pub name: Option<String>,
299    pub qos: Option<QosClass>,
300    pub phase: Option<String>,
301    pub mem: Measured<u64>,
302    /// Pod-level cgroup `memory.max`.
303    pub limit: Option<u64>,
304    pub cgroup: Option<String>,
305    /// [`LimitStatus::id`] of the pod's limit, when it has one.
306    pub limit_id: Option<String>,
307    pub containers: Vec<KubeContainer>,
308}
309
310#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
311#[serde(default)]
312pub struct KubeContainer {
313    pub name: Option<String>,
314    /// Full container id.
315    pub id: Option<String>,
316    pub runtime: Option<String>,
317    pub mem: Measured<u64>,
318    pub limit: Measured<u64>,
319    pub restarts: Option<u32>,
320    /// Last termination reason ("OOMKilled").
321    pub last_termination: Option<String>,
322    pub host_pids: Vec<ProcId>,
323    pub sandbox_id: Option<String>,
324    pub cgroup: Option<String>,
325    /// [`LimitStatus::id`] of this container's limit, when it has one.
326    pub limit_id: Option<String>,
327}
328
329/// Memory an engine VM holds that none of its containers uses (SPEC §11 "VM slack").
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
331#[serde(default)]
332pub struct VmSlack {
333    pub sandbox_id: String,
334    pub label: String,
335    pub runtime: String,
336    /// Host footprint of the VM process(es).
337    pub vm_footprint: Measured<u64>,
338    /// Σ container memory inside it (engine stats).
339    pub containers: Measured<u64>,
340    /// The VM's configured memory, when known.
341    pub configured: Option<u64>,
342    /// `vm_footprint − containers`; always an estimate.
343    pub slack: Measured<u64>,
344    /// "<label>: 3.1 GiB held by the VM, not used by containers; restarting the engine returns it".
345    pub summary: String,
346    /// Caveats (footprint is a lower bound, container sum incomplete).
347    pub notes: Vec<String>,
348    /// Always false: restarting an engine stops every container, so this is never offered as safe reclaim.
349    pub counts_as_reclaim: bool,
350}
351
352/// A container that is running but idle, or stopped and still on disk.
353#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
354#[serde(default)]
355pub struct StaleContainer {
356    pub sandbox_id: String,
357    pub name: String,
358    pub engine: String,
359    pub image: String,
360    pub state: String,
361    pub created_ms: Option<u64>,
362    pub started_ms: Option<u64>,
363    pub finished_ms: Option<u64>,
364    /// Seconds since it started (running) or stopped (not running).
365    pub age_s: Option<u64>,
366    /// Average CPU over the observed window, percent of one core (running containers).
367    pub cpu_pct: Measured<f64>,
368    pub observed_s: u64,
369    pub mem: Measured<u64>,
370    /// Writable layer size (stopped containers), when the engine reported it.
371    pub disk: Measured<u64>,
372    pub exit_code: Option<i64>,
373    pub oom_killed: Option<bool>,
374    /// "running, ~0 CPU for 12 min" / "exited (137) 2 days ago".
375    pub reason: String,
376}
377
378/// Everything container/cluster-shaped in one snapshot (`Snapshot::isolation`).
379#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
380#[serde(default)]
381pub struct Isolation {
382    /// Engine data per container (input from the adapters).
383    #[serde(skip_serializing_if = "Vec::is_empty")]
384    pub containers: Vec<ContainerInfo>,
385    /// kubeconfig contexts and the safety verdict on each (input from the Kubernetes adapter).
386    #[serde(skip_serializing_if = "Vec::is_empty")]
387    pub kube_contexts: Vec<KubeContextSummary>,
388    /// API data per live context (input from the Kubernetes adapter).
389    #[serde(skip_serializing_if = "Vec::is_empty")]
390    pub kube: Vec<KubeApiData>,
391    /// Every limit, most urgent first.
392    #[serde(skip_serializing_if = "Vec::is_empty")]
393    pub limits: Vec<LimitStatus>,
394    #[serde(skip_serializing_if = "Vec::is_empty")]
395    pub clusters: Vec<Cluster>,
396    #[serde(skip_serializing_if = "Vec::is_empty")]
397    pub vm_slack: Vec<VmSlack>,
398    #[serde(skip_serializing_if = "NamespaceReport::is_empty")]
399    pub namespaces: NamespaceReport,
400    #[serde(skip_serializing_if = "Vec::is_empty")]
401    pub stale_containers: Vec<StaleContainer>,
402}
403
404impl Isolation {
405    pub fn is_empty(&self) -> bool {
406        self.containers.is_empty()
407            && self.kube_contexts.is_empty()
408            && self.kube.is_empty()
409            && self.limits.is_empty()
410            && self.clusters.is_empty()
411            && self.vm_slack.is_empty()
412            && self.namespaces.is_empty()
413            && self.stale_containers.is_empty()
414    }
415
416    pub fn limit(&self, id: &str) -> Option<&LimitStatus> {
417        self.limits.iter().find(|l| l.id == id)
418    }
419
420    pub fn container(&self, sandbox_id: &str) -> Option<&ContainerInfo> {
421        self.containers.iter().find(|c| c.sandbox_id == sandbox_id)
422    }
423}
424
425/// Export redaction (called by [`crate::redact::redact_snapshot`]): free text that comes from engines or
426/// processes goes through [`crate::redact::redact_text`]; group ids are renamed like everywhere else.
427pub fn redact(iso: &mut Isolation, rename: &dyn Fn(&mut Option<String>)) {
428    use crate::redact::redact_text;
429    for c in &mut iso.containers {
430        c.name = redact_text(&c.name);
431        c.image = redact_text(&c.image);
432        c.status_text = redact_text(&c.status_text);
433        for v in c.labels.values_mut() {
434            *v = redact_text(v);
435        }
436    }
437    for l in &mut iso.limits {
438        l.label = redact_text(&l.label);
439        l.summary = redact_text(&l.summary);
440    }
441    for v in &mut iso.vm_slack {
442        v.label = redact_text(&v.label);
443        v.summary = redact_text(&v.summary);
444    }
445    for s in &mut iso.stale_containers {
446        s.name = redact_text(&s.name);
447        s.image = redact_text(&s.image);
448        s.reason = redact_text(&s.reason);
449    }
450    for n in &mut iso.namespaces.sets {
451        n.label = redact_text(&n.label);
452        rename(&mut n.group);
453        rename(&mut n.owner_group);
454    }
455}
456
457// ---------------------------------------------------------------------------------------------------------
458// Small parsers shared with the adapters
459// ---------------------------------------------------------------------------------------------------------
460
461fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
462    let y = if m <= 2 { y - 1 } else { y };
463    let era = if y >= 0 { y } else { y - 399 } / 400;
464    let yoe = y - era * 400;
465    let mp = (m as i64 + 9) % 12;
466    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
467    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
468    era * 146_097 + doe - 719_468
469}
470
471/// RFC 3339 timestamp (`2026-12-05T10:11:12.123456789Z`, `…+01:00`) → ms since the epoch. Docker's zero
472/// time (`0001-01-01T00:00:00Z`) and anything before 1970 → `None`.
473pub fn parse_rfc3339_ms(s: &str) -> Option<u64> {
474    let s = s.trim();
475    if s.len() < 20 {
476        return None;
477    }
478    let num = |a: usize, b: usize| s.get(a..b)?.parse::<i64>().ok();
479    let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?);
480    let (h, mi, se) = (num(11, 13)?, num(14, 16)?, num(17, 19)?);
481    if s.as_bytes()[4] != b'-' || !matches!(s.as_bytes()[10], b'T' | b't' | b' ') {
482        return None;
483    }
484    let mut rest = &s[19..];
485    let mut ms = 0i64;
486    if let Some(frac) = rest.strip_prefix('.') {
487        let digits: String = frac.chars().take_while(|c| c.is_ascii_digit()).collect();
488        let first3: String = digits.chars().chain("000".chars()).take(3).collect();
489        ms = first3.parse().ok()?;
490        rest = &frac[digits.len()..];
491    }
492    let offset_s = match rest {
493        "Z" | "z" => 0,
494        o if o.len() == 6 && (o.starts_with('+') || o.starts_with('-')) => {
495            let sign = if o.starts_with('-') { -1 } else { 1 };
496            sign * (o.get(1..3)?.parse::<i64>().ok()? * 3600 + o.get(4..6)?.parse::<i64>().ok()? * 60)
497        }
498        _ => return None,
499    };
500    if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || se > 60 {
501        return None;
502    }
503    let days = days_from_civil(y, mo as u32, d as u32);
504    let secs = days * 86_400 + h * 3600 + mi * 60 + se - offset_s;
505    (secs > 0).then(|| secs as u64 * 1000 + ms as u64)
506}
507
508/// Kubernetes resource quantity → bytes (`128Mi`, `1Gi`, `1G`, `500M`, `1e9`, `1.5Gi`, `100k`, `129e6`,
509/// `1000m` = 1 byte). `None` for anything else.
510pub fn parse_k8s_quantity(s: &str) -> Option<u64> {
511    let s = s.trim();
512    if s.is_empty() {
513        return None;
514    }
515    let bin = |e: i32| 1024f64.powi(e);
516    let dec = |e: i32| 1000f64.powi(e);
517    let suffixes: [(&str, f64); 13] = [
518        ("Ki", bin(1)),
519        ("Mi", bin(2)),
520        ("Gi", bin(3)),
521        ("Ti", bin(4)),
522        ("Pi", bin(5)),
523        ("Ei", bin(6)),
524        ("k", dec(1)),
525        ("M", dec(2)),
526        ("G", dec(3)),
527        ("T", dec(4)),
528        ("P", dec(5)),
529        ("E", dec(6)),
530        ("m", 0.001),
531    ];
532    let (num, mult) = suffixes
533        .iter()
534        .find_map(|(suf, m)| s.strip_suffix(suf).map(|n| (n, *m)))
535        .unwrap_or((s, 1.0));
536    // Plain numbers may carry a decimal exponent (`1e9`, `129e6`).
537    if !num
538        .bytes()
539        .all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-'))
540    {
541        return None;
542    }
543    let v: f64 = num.parse().ok()?;
544    let bytes = v * mult;
545    (bytes.is_finite() && bytes >= 0.0).then(|| bytes.round() as u64)
546}
547
548// ---------------------------------------------------------------------------------------------------------
549// The tracker
550// ---------------------------------------------------------------------------------------------------------
551
552#[derive(Debug, Clone, Copy, Default)]
553struct CpuObs {
554    first: (u64, u64),
555    last: (u64, u64),
556}
557
558/// The only state behind [`Isolation`]: limit histories and per-container CPU counters. The engine owns
559/// one and calls [`IsolationTracker::update`] after attribution and adapters.
560#[derive(Debug, Clone, Default)]
561pub struct IsolationTracker {
562    pub limits: LimitTracker,
563    cpu: BTreeMap<String, CpuObs>,
564}
565
566impl IsolationTracker {
567    pub fn new() -> Self {
568        Self::default()
569    }
570
571    /// Fills `s.isolation`'s derived parts (namespaces, clusters, limits, VM slack, stale containers) from
572    /// the snapshot and the adapters' inputs already in `s.isolation`.
573    pub fn update(&mut self, s: &mut Snapshot) {
574        let now = s.taken_at_ms;
575        let namespaces = namespace_sets(s);
576        let mut clusters = build_clusters(s);
577        let inputs = limit_inputs(s, &clusters);
578        let limits = evaluate(&mut self.limits, inputs, now);
579        link_limits(&mut clusters, &limits);
580        let vm_slack = vm_slack(s);
581        let stale = self.stale(s, now);
582        let iso = &mut s.isolation;
583        iso.namespaces = namespaces;
584        iso.clusters = clusters;
585        iso.limits = limits;
586        iso.vm_slack = vm_slack;
587        iso.stale_containers = stale;
588    }
589
590    fn stale(&mut self, s: &Snapshot, now: u64) -> Vec<StaleContainer> {
591        let mut out = Vec::new();
592        let mut seen = Vec::new();
593        for c in &s.isolation.containers {
594            let age_from = |t: Option<u64>| t.map(|t| now.saturating_sub(t) / 1000);
595            if c.state == "running" {
596                seen.push(c.sandbox_id.clone());
597                let (Some(ns), Some(at)) = (c.cpu_total_ns, c.stats_at_ms) else {
598                    continue;
599                };
600                let e = self.cpu.entry(c.sandbox_id.clone()).or_insert(CpuObs {
601                    first: (at, ns),
602                    last: (at, ns),
603                });
604                if ns < e.last.1 {
605                    // Counter went back: the container restarted under the same id.
606                    *e = CpuObs {
607                        first: (at, ns),
608                        last: (at, ns),
609                    };
610                } else if at > e.last.0 {
611                    e.last = (at, ns);
612                }
613                let dt_ms = e.last.0.saturating_sub(e.first.0);
614                let observed_s = dt_ms / 1000;
615                if observed_s < STALE_MIN_OBSERVED_S {
616                    continue;
617                }
618                let pct = (e.last.1 - e.first.1) as f64 / (dt_ms as f64 * 1e6) * 100.0;
619                if pct >= STALE_CPU_PCT {
620                    continue;
621                }
622                let mem = s
623                    .sandboxes
624                    .iter()
625                    .find(|sb| sb.id == c.sandbox_id)
626                    .map(|sb| sb.guest_mem.clone())
627                    .unwrap_or_else(|| Measured::unavailable(c.engine.clone(), "no stats"));
628                out.push(StaleContainer {
629                    sandbox_id: c.sandbox_id.clone(),
630                    name: c.name.clone(),
631                    engine: c.engine.clone(),
632                    image: c.image.clone(),
633                    state: c.state.clone(),
634                    created_ms: c.created_ms,
635                    started_ms: c.started_ms,
636                    finished_ms: c.finished_ms,
637                    age_s: age_from(c.started_ms.or(c.created_ms)),
638                    cpu_pct: Measured::estimate(
639                        pct,
640                        format!("{} Δ cpu_stats.total_usage over {observed_s} s", c.engine),
641                    ),
642                    observed_s,
643                    mem,
644                    disk: size_measured(c),
645                    exit_code: None,
646                    oom_killed: c.oom_killed,
647                    reason: format!(
648                        "running, {pct:.1}% CPU over {}",
649                        crate::units::format_duration(observed_s)
650                    ),
651                });
652            } else if matches!(c.state.as_str(), "exited" | "created" | "dead") {
653                let since = c.finished_ms.filter(|_| c.state != "created").or(c.created_ms);
654                out.push(StaleContainer {
655                    sandbox_id: c.sandbox_id.clone(),
656                    name: c.name.clone(),
657                    engine: c.engine.clone(),
658                    image: c.image.clone(),
659                    state: c.state.clone(),
660                    created_ms: c.created_ms,
661                    started_ms: c.started_ms,
662                    finished_ms: c.finished_ms,
663                    age_s: age_from(since),
664                    cpu_pct: Measured::unavailable(c.engine.clone(), "not running"),
665                    observed_s: 0,
666                    mem: Measured::exact(0, format!("{} (not running)", c.engine)),
667                    disk: size_measured(c),
668                    exit_code: c.exit_code,
669                    oom_killed: c.oom_killed,
670                    reason: if c.status_text.is_empty() {
671                        c.state.clone()
672                    } else {
673                        c.status_text.to_ascii_lowercase()
674                    },
675                });
676            }
677        }
678        self.cpu.retain(|k, _| seen.contains(k));
679        out.sort_by(|a, b| {
680            (a.state != "running")
681                .cmp(&(b.state != "running"))
682                .then(b.age_s.cmp(&a.age_s))
683                .then(a.sandbox_id.cmp(&b.sandbox_id))
684        });
685        out
686    }
687}
688
689fn size_measured(c: &ContainerInfo) -> Measured<u64> {
690    match c.size_rw {
691        Some(v) => Measured::exact(v, format!("{} SizeRw", c.engine)),
692        None => Measured::unavailable(
693            c.engine.clone(),
694            "engine lists sizes only on request (size=1 walks every layer; not requested)",
695        ),
696    }
697}
698
699// ---------------------------------------------------------------------------------------------------------
700// Cluster tree
701// ---------------------------------------------------------------------------------------------------------
702
703#[derive(Default)]
704struct PodAcc {
705    pod: KubePod,
706    namespace: String,
707    /// container key (id, else name) → container
708    containers: BTreeMap<String, KubeContainer>,
709}
710
711#[derive(Default)]
712struct NodeAcc {
713    sandbox_id: Option<String>,
714    mem: Measured<u64>,
715    /// pod key (uid, else ns/name) → pod
716    pods: BTreeMap<String, PodAcc>,
717}
718
719#[derive(Default)]
720struct ClusterAcc {
721    c: Cluster,
722    nodes: BTreeMap<String, NodeAcc>,
723}
724
725fn cgroup_mem<'a>(s: &'a Snapshot, path: &str) -> Option<&'a CgroupMem> {
726    s.cgroups.iter().find(|c| c.path == path)
727}
728
729/// Container id inside a node prefix (`/system.slice/docker-<id>.scope/kubelet.slice` → id).
730fn node_container_id(prefix: &str) -> Option<String> {
731    prefix.split('/').find_map(|seg| {
732        let s = seg.strip_suffix(".scope")?;
733        ["docker-", "libpod-", "cri-containerd-"]
734            .iter()
735            .find_map(|p| s.strip_prefix(p))
736            .filter(|id| id.len() >= 12 && id.bytes().all(|b| b.is_ascii_hexdigit()))
737            .map(str::to_string)
738    })
739}
740
741/// Cluster identity of a node container from its labels.
742fn node_cluster_of(c: &ContainerInfo) -> Option<(String, String, KubeDistro, String)> {
743    let l = &c.labels;
744    if let Some(name) = l.get("io.x-k8s.kind.cluster") {
745        let distro = if c.engine == "docker-desktop" && name == "desktop" {
746            KubeDistro::DockerDesktop
747        } else {
748            KubeDistro::Kind
749        };
750        let id = if distro == KubeDistro::DockerDesktop {
751            "docker-desktop".to_string()
752        } else {
753            format!("kind:{name}")
754        };
755        return Some((id, name.clone(), distro, "label io.x-k8s.kind.cluster".into()));
756    }
757    if let Some(name) = l.get("k3d.cluster") {
758        if matches!(
759            l.get("k3d.role").map(String::as_str),
760            Some("loadbalancer" | "registry" | "noRole")
761        ) {
762            return None;
763        }
764        return Some((
765            format!("k3d:{name}"),
766            name.clone(),
767            KubeDistro::K3d,
768            "label k3d.cluster".into(),
769        ));
770    }
771    if let Some(name) = l.get("name.minikube.sigs.k8s.io") {
772        return Some((
773            format!("minikube:{name}"),
774            name.clone(),
775            KubeDistro::Minikube,
776            "label name.minikube.sigs.k8s.io".into(),
777        ));
778    }
779    None
780}
781
782fn proc_matches(s: &Snapshot, f: impl Fn(&crate::model::Process) -> bool) -> bool {
783    s.processes.iter().any(f)
784}
785
786fn base(exe: &str) -> &str {
787    exe.rsplit('/').next().unwrap_or(exe)
788}
789
790/// The distribution running directly on this host, from its processes.
791fn host_distro(s: &Snapshot) -> (KubeDistro, Option<String>) {
792    if proc_matches(s, |p| p.name == "kubelite" || p.exe.contains("/snap/microk8s/")) {
793        return (KubeDistro::Microk8s, Some("process kubelite (microk8s)".into()));
794    }
795    if proc_matches(s, |p| {
796        (p.name == "k3s" || base(&p.exe) == "k3s" || p.name.starts_with("k3s-"))
797            && !p
798                .cmdline
799                .iter()
800                .any(|a| a == "kubectl" || a == "crictl" || a == "ctr")
801    }) {
802        return (KubeDistro::K3s, Some("process k3s".into()));
803    }
804    if proc_matches(s, |p| p.name == "kubelet" || base(&p.exe) == "kubelet") {
805        return (KubeDistro::Unknown, Some("process kubelet".into()));
806    }
807    (KubeDistro::Unknown, None)
808}
809
810/// Clusters that run inside an app's VM (no pods visible from the host), from processes and contexts.
811fn vm_clusters(s: &Snapshot) -> Vec<(String, String, KubeDistro, String, Option<String>)> {
812    let ctx = |name: &str| s.isolation.kube_contexts.iter().any(|c| c.name == name);
813    let app = |needle: &str| proc_matches(s, |p| p.exe.contains(needle));
814    let vm_of = |runtime_pred: &dyn Fn(&crate::model::Sandbox) -> bool| {
815        s.sandboxes
816            .iter()
817            .find(|sb| sb.kind == SandboxKind::Vm && runtime_pred(sb))
818            .map(|sb| sb.id.clone())
819    };
820    let mut out = Vec::new();
821    if ctx("docker-desktop") && app("/Docker.app/") {
822        out.push((
823            "docker-desktop".into(),
824            "docker-desktop".into(),
825            KubeDistro::DockerDesktop,
826            "kubeconfig context docker-desktop + Docker Desktop running".into(),
827            vm_of(&|sb| sb.label.starts_with("Docker") || sb.runtime == "docker-desktop"),
828        ));
829    }
830    if ctx("orbstack") && app("/OrbStack.app/") {
831        out.push((
832            "orbstack".into(),
833            "orbstack".into(),
834            KubeDistro::OrbStack,
835            "kubeconfig context orbstack + OrbStack running".into(),
836            vm_of(&|sb| sb.runtime == "orbstack" || sb.label.starts_with("OrbStack")),
837        ));
838    }
839    if ctx("rancher-desktop") && app("/Rancher Desktop.app/") {
840        out.push((
841            "rancher-desktop".into(),
842            "rancher-desktop".into(),
843            KubeDistro::RancherDesktop,
844            "kubeconfig context rancher-desktop + Rancher Desktop running".into(),
845            vm_of(&|sb| sb.label.starts_with("Rancher Desktop")),
846        ));
847    }
848    let colima_k8s = proc_matches(s, |p| {
849        (p.name == "colima" || base(&p.exe) == "colima")
850            && p.cmdline.iter().any(|a| a == "--kubernetes" || a == "-k")
851    });
852    if colima_k8s || (ctx("colima") && proc_matches(s, |p| p.name == "colima" || base(&p.exe) == "colima")) {
853        out.push((
854            "colima".into(),
855            "colima".into(),
856            KubeDistro::Colima,
857            if colima_k8s {
858                "process colima --kubernetes".into()
859            } else {
860                "kubeconfig context colima + colima running".into()
861            },
862            vm_of(&|sb| sb.runtime == "colima" || sb.label.contains("olima")),
863        ));
864    }
865    // minikube with a VM driver (qemu, vfkit, hyperkit, virtualbox): its VM process names the profile.
866    if proc_matches(s, |p| {
867        !p.name.starts_with("minikube") && p.cmdline.iter().any(|a| a.contains("/.minikube/machines/"))
868    }) {
869        out.push((
870            "minikube:minikube".into(),
871            "minikube".into(),
872            KubeDistro::Minikube,
873            "minikube VM process".into(),
874            None,
875        ));
876    }
877    out
878}
879
880impl ClusterAcc {
881    fn new(id: &str, name: &str, distro: KubeDistro, evidence: String) -> Self {
882        ClusterAcc {
883            c: Cluster {
884                id: id.into(),
885                name: name.into(),
886                distro,
887                evidence: vec![evidence],
888                ..Default::default()
889            },
890            nodes: BTreeMap::new(),
891        }
892    }
893
894    fn evidence(&mut self, e: String) {
895        if !self.c.evidence.contains(&e) {
896            self.c.evidence.push(e);
897        }
898    }
899}
900
901fn pod_entry<'a>(node: &'a mut NodeAcc, uid: Option<&str>, ns: &str, name: Option<&str>) -> &'a mut PodAcc {
902    // Find by uid, then by ns/name.
903    let key = match uid {
904        Some(u) => u.to_string(),
905        None => format!("{ns}/{}", name.unwrap_or("?")),
906    };
907    if !node.pods.contains_key(&key) {
908        if let Some(n) = name {
909            if let Some(k) = node
910                .pods
911                .iter()
912                .find(|(_, p)| p.pod.name.as_deref() == Some(n) && p.namespace == ns)
913                .map(|(k, _)| k.clone())
914            {
915                return node.pods.get_mut(&k).expect("present");
916            }
917        }
918    }
919    node.pods.entry(key).or_insert_with(|| PodAcc {
920        pod: KubePod {
921            uid: uid.map(str::to_string),
922            ..Default::default()
923        },
924        ..Default::default()
925    })
926}
927
928fn container_entry<'a>(pod: &'a mut PodAcc, id: Option<&str>, name: Option<&str>) -> &'a mut KubeContainer {
929    let found = pod
930        .containers
931        .iter()
932        .find(|(_, c)| {
933            (id.is_some() && c.id.as_deref() == id)
934                || (name.is_some() && c.name.as_deref() == name && (id.is_none() || c.id.is_none()))
935        })
936        .map(|(k, _)| k.clone());
937    let key = found.unwrap_or_else(|| id.or(name).unwrap_or("?").to_string());
938    pod.containers.entry(key).or_default()
939}
940
941/// Builds the cluster tree from cgroup paths, engine labels and API data (module docs).
942pub fn build_clusters(s: &Snapshot) -> Vec<Cluster> {
943    let mut acc: BTreeMap<String, ClusterAcc> = BTreeMap::new();
944    let host_name = if s.host.hostname.is_empty() {
945        "this host".to_string()
946    } else {
947        s.host.hostname.clone()
948    };
949    let sandbox_mem = |id: &str| {
950        s.sandboxes
951            .iter()
952            .find(|sb| sb.id == id)
953            .map(|sb| sb.guest_mem.clone())
954    };
955
956    // 1. Node containers (kind / k3d / minikube) from engine labels.
957    for c in &s.isolation.containers {
958        if c.state != "running" {
959            continue;
960        }
961        let Some((id, name, distro, ev)) = node_cluster_of(c) else {
962            continue;
963        };
964        let a = acc
965            .entry(id.clone())
966            .or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev.clone()));
967        a.evidence(ev);
968        let n = a.nodes.entry(c.name.clone()).or_default();
969        n.sandbox_id = Some(c.sandbox_id.clone());
970        n.mem =
971            sandbox_mem(&c.sandbox_id).unwrap_or_else(|| Measured::unavailable(c.engine.clone(), "no stats"));
972    }
973
974    // 2. Pod containers from cri-dockerd labels (Docker Desktop / native docker runtime).
975    for c in &s.isolation.containers {
976        let l = &c.labels;
977        let Some(uid) = l.get("io.kubernetes.pod.uid") else {
978            continue;
979        };
980        if c.state != "running"
981            || l.get("io.kubernetes.docker.type").map(String::as_str) == Some("podsandbox")
982        {
983            continue;
984        }
985        let (cid, node) = if c.vm_hosted {
986            let id = if c.engine == "docker-desktop" {
987                "docker-desktop".to_string()
988            } else {
989                c.engine.clone()
990            };
991            (id.clone(), id)
992        } else {
993            ("host".to_string(), host_name.clone())
994        };
995        let distro = if c.engine == "docker-desktop" {
996            KubeDistro::DockerDesktop
997        } else {
998            KubeDistro::Unknown
999        };
1000        let a = acc.entry(cid.clone()).or_insert_with(|| {
1001            ClusterAcc::new(&cid, &cid, distro, "labels io.kubernetes.* (cri-dockerd)".into())
1002        });
1003        a.evidence("labels io.kubernetes.* (cri-dockerd)".into());
1004        let n = a.nodes.entry(node).or_default();
1005        let ns = l.get("io.kubernetes.pod.namespace").cloned().unwrap_or_default();
1006        let pname = l.get("io.kubernetes.pod.name").cloned();
1007        let p = pod_entry(n, Some(uid), &ns, pname.as_deref());
1008        p.namespace = ns;
1009        p.pod.name = p.pod.name.take().or(pname);
1010        let cname = l.get("io.kubernetes.container.name").cloned();
1011        let k = container_entry(p, Some(&c.id), cname.as_deref());
1012        k.id = Some(c.id.clone());
1013        k.name = cname;
1014        k.runtime = Some("docker".into());
1015        k.sandbox_id = Some(c.sandbox_id.clone());
1016        k.restarts = c.restart_count;
1017        if let Some(m) = sandbox_mem(&c.sandbox_id) {
1018            k.mem = m;
1019        }
1020        if let Some(sb) = s.sandboxes.iter().find(|sb| sb.id == c.sandbox_id) {
1021            k.host_pids = sb.host_pids.clone();
1022            k.limit = sb.configured_mem.clone();
1023        }
1024    }
1025
1026    // 3. Kubelet cgroup paths of host processes (Linux).
1027    let mut kube_procs: Vec<(&crate::model::Process, KubeCgroup)> = s
1028        .processes
1029        .iter()
1030        .filter_map(|p| Some((p, parse_kube_cgroup(p.cgroup.as_deref()?)?)))
1031        .collect();
1032    kube_procs.sort_by_key(|(p, _)| (p.id.start_time, p.id.pid));
1033    if !kube_procs.is_empty() {
1034        let (hd, hev) = host_distro(s);
1035        for (p, k) in &kube_procs {
1036            let (cid, node) = if k.node_prefix.is_empty() {
1037                let a = acc.entry("host".into()).or_insert_with(|| {
1038                    ClusterAcc::new("host", &host_name, hd, "kubelet cgroups on this host".into())
1039                });
1040                if let Some(e) = &hev {
1041                    a.evidence(e.clone());
1042                }
1043                if a.c.distro == KubeDistro::Unknown {
1044                    a.c.distro = hd;
1045                }
1046                ("host".to_string(), host_name.clone())
1047            } else {
1048                let nid = node_container_id(&k.node_prefix);
1049                let node_ci = nid.as_ref().and_then(|id| {
1050                    s.isolation
1051                        .containers
1052                        .iter()
1053                        .find(|c| c.id.starts_with(id.as_str()) || id.starts_with(c.id.as_str()))
1054                });
1055                match node_ci.and_then(|c| node_cluster_of(c).map(|x| (x, c))) {
1056                    Some(((id, name, distro, ev), c)) => {
1057                        let a = acc
1058                            .entry(id.clone())
1059                            .or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev));
1060                        a.evidence("kubelet cgroups inside the node container".into());
1061                        (id, c.name.clone())
1062                    }
1063                    None => {
1064                        let short: String = nid.clone().unwrap_or_default().chars().take(12).collect();
1065                        let id = format!("nested:{short}");
1066                        acc.entry(id.clone()).or_insert_with(|| {
1067                            ClusterAcc::new(
1068                                &id,
1069                                &format!("cluster in container {short}"),
1070                                KubeDistro::Unknown,
1071                                "kubelet cgroups inside a container".into(),
1072                            )
1073                        });
1074                        (id, format!("container {short}"))
1075                    }
1076                }
1077            };
1078            let a = acc.get_mut(&cid).expect("inserted");
1079            let n = a.nodes.entry(node).or_default();
1080            let pa = pod_entry(n, Some(&k.pod_uid), "", None);
1081            pa.pod.qos = Some(k.qos);
1082            if pa.pod.cgroup.is_none() {
1083                pa.pod.cgroup = Some(k.pod_cgroup.clone());
1084                if let Some(cg) = cgroup_mem(s, &k.pod_cgroup) {
1085                    pa.pod.mem = cg.working_set_measured();
1086                    pa.pod.limit = cg.max;
1087                }
1088            }
1089            let Some(id) = k.container_id.as_deref().filter(|_| !k.conmon) else {
1090                continue;
1091            };
1092            let c = container_entry(pa, Some(id), None);
1093            c.id = Some(id.to_string());
1094            c.runtime = c.runtime.take().or(k.runtime.clone());
1095            if !c.host_pids.contains(&p.id) {
1096                c.host_pids.push(p.id);
1097            }
1098            if c.name.is_none() && p.name == "pause" {
1099                c.name = Some("pause".into());
1100            }
1101            if let Some(cg) = k.container_cgroup.as_deref() {
1102                c.cgroup = Some(cg.to_string());
1103                if let Some(m) = cgroup_mem(s, cg) {
1104                    c.mem = m.working_set_measured();
1105                    c.limit = match m.max {
1106                        Some(v) => Measured::exact(v, "cgroup memory.max"),
1107                        None if m.limits_read => Measured::unavailable("cgroup memory.max", "no limit"),
1108                        None => Measured::unavailable("cgroup memory.max", "not read"),
1109                    };
1110                }
1111            }
1112        }
1113        // Containers without cgroup numbers: Σ their processes (an estimate).
1114        for a in acc.values_mut() {
1115            for n in a.nodes.values_mut() {
1116                for pa in n.pods.values_mut() {
1117                    for c in pa.containers.values_mut() {
1118                        if !c.mem.is_available() && !c.host_pids.is_empty() {
1119                            let mems: Vec<&Measured<u64>> = c
1120                                .host_pids
1121                                .iter()
1122                                .filter_map(|id| s.process(*id).map(|p| &p.mem.footprint_or_pss))
1123                                .collect();
1124                            c.mem = sum_bytes(mems, "Σ process PSS (cgroup not read)").into_estimate();
1125                        }
1126                    }
1127                }
1128            }
1129        }
1130    }
1131
1132    // 4. API data: names, limits, restarts, termination reasons, kubelet working sets.
1133    for d in &s.isolation.kube {
1134        let node_names: Vec<String> = d
1135            .pods
1136            .iter()
1137            .filter_map(|p| p.node.clone())
1138            .chain(d.nodes.iter().map(|n| n.name.clone()))
1139            .collect();
1140        // The cluster that already has one of these nodes, else one keyed by the context.
1141        let existing = acc
1142            .iter()
1143            .find(|(_, a)| node_names.iter().any(|n| a.nodes.contains_key(n)))
1144            .map(|(k, _)| k.clone());
1145        let distro = d.distro.or_else(|| KubeDistro::from_context(&d.context));
1146        let cid = existing.unwrap_or_else(|| match distro {
1147            Some(KubeDistro::Kind) => {
1148                format!("kind:{}", KubeDistro::Kind.cluster_name_from_context(&d.context))
1149            }
1150            Some(KubeDistro::K3d) => format!("k3d:{}", KubeDistro::K3d.cluster_name_from_context(&d.context)),
1151            Some(KubeDistro::Minikube) => "minikube:minikube".into(),
1152            Some(KubeDistro::DockerDesktop) => "docker-desktop".into(),
1153            Some(KubeDistro::OrbStack) => "orbstack".into(),
1154            Some(KubeDistro::RancherDesktop) => "rancher-desktop".into(),
1155            Some(KubeDistro::Colima) => "colima".into(),
1156            _ => format!("context:{}", d.context),
1157        });
1158        let a = acc.entry(cid.clone()).or_insert_with(|| {
1159            ClusterAcc::new(
1160                &cid,
1161                &distro.map_or(d.context.clone(), |x| x.cluster_name_from_context(&d.context)),
1162                distro.unwrap_or_default(),
1163                "kubeconfig context".into(),
1164            )
1165        });
1166        a.evidence(format!("API via context {}", d.context));
1167        a.c.context = Some(d.context.clone());
1168        a.c.api = Some(d.status.clone());
1169        for p in &d.pods {
1170            let node = p.node.clone().unwrap_or_else(|| "(unscheduled)".into());
1171            let n = a.nodes.entry(node).or_default();
1172            let pa = pod_entry(n, Some(&p.uid), &p.namespace, Some(&p.name));
1173            pa.namespace = p.namespace.clone();
1174            pa.pod.name = Some(p.name.clone());
1175            pa.pod.phase = p.phase.clone();
1176            pa.pod.qos = p.qos.or(pa.pod.qos);
1177            for cs in &p.containers {
1178                let c = container_entry(pa, cs.id.as_deref(), Some(&cs.name));
1179                c.name = Some(cs.name.clone());
1180                c.id = c.id.take().or(cs.id.clone());
1181                c.runtime = c.runtime.take().or(cs.runtime.clone());
1182                c.restarts = cs.restarts;
1183                c.last_termination = cs.last_termination_reason.clone();
1184                if !c.limit.is_available() {
1185                    c.limit = match cs.mem_limit {
1186                        Some(l) => Measured::exact(l, "pod spec resources.limits.memory"),
1187                        None => Measured::unavailable("pod spec", "no memory limit"),
1188                    };
1189                }
1190            }
1191        }
1192        for ns in &d.nodes {
1193            let n = a.nodes.entry(ns.name.clone()).or_default();
1194            if !n.mem.is_available() {
1195                if let Some(ws) = ns.working_set {
1196                    n.mem = Measured::exact(ws, "kubelet stats/summary node workingSetBytes");
1197                }
1198            }
1199            for ps in &ns.pods {
1200                let pa = pod_entry(n, Some(&ps.uid), &ps.namespace, Some(&ps.name));
1201                pa.namespace = ps.namespace.clone();
1202                pa.pod.name = pa.pod.name.take().or(Some(ps.name.clone()));
1203                if !pa.pod.mem.is_available() {
1204                    if let Some(ws) = ps.working_set {
1205                        pa.pod.mem = Measured::exact(ws, "kubelet stats/summary workingSetBytes");
1206                    }
1207                }
1208                for cs in &ps.containers {
1209                    let c = container_entry(pa, None, Some(&cs.name));
1210                    c.name = Some(cs.name.clone());
1211                    if !c.mem.is_available() {
1212                        if let Some(ws) = cs.working_set {
1213                            c.mem = Measured::exact(ws, "kubelet stats/summary workingSetBytes");
1214                        }
1215                    }
1216                }
1217            }
1218        }
1219    }
1220
1221    // 5. Clusters inside app VMs (no pods visible from the host without the API).
1222    for (id, name, distro, ev, vm) in vm_clusters(s) {
1223        let a = acc
1224            .entry(id.clone())
1225            .or_insert_with(|| ClusterAcc::new(&id, &name, distro, ev.clone()));
1226        a.evidence(ev);
1227        if a.nodes.is_empty() {
1228            let n = a.nodes.entry(name.clone()).or_default();
1229            if let Some(v) = &vm {
1230                n.sandbox_id = Some(v.clone());
1231                n.mem = s
1232                    .sandboxes
1233                    .iter()
1234                    .find(|sb| &sb.id == v)
1235                    .and_then(|sb| {
1236                        let fp: Vec<&Measured<u64>> = sb
1237                            .host_pids
1238                            .iter()
1239                            .filter_map(|h| s.process(*h).map(|p| &p.mem.footprint_or_pss))
1240                            .collect();
1241                        (!fp.is_empty()).then(|| sum_bytes(fp, "VM host footprint"))
1242                    })
1243                    .unwrap_or_else(|| Measured::unavailable("vm", "VM process not found"));
1244            }
1245        }
1246    }
1247
1248    // Contexts: attach names; note what is missing.
1249    for a in acc.values_mut() {
1250        if a.c.context.is_none() {
1251            a.c.context = s
1252                .isolation
1253                .kube_contexts
1254                .iter()
1255                .find(|c| match a.c.distro {
1256                    KubeDistro::Kind => c.name == format!("kind-{}", a.c.name),
1257                    KubeDistro::K3d => c.name == format!("k3d-{}", a.c.name),
1258                    KubeDistro::Unknown => false,
1259                    d => c.distro == Some(d),
1260                })
1261                .map(|c| c.name.clone());
1262        }
1263        let has_pods = a.nodes.values().any(|n| !n.pods.is_empty());
1264        let named = a
1265            .nodes
1266            .values()
1267            .flat_map(|n| n.pods.values())
1268            .any(|p| p.pod.name.is_some());
1269        if !has_pods {
1270            a.c.notes.push(
1271                "pods run inside the node container or VM: names and per-pod memory need the API server \
1272                 (oomtop calls it only for loopback plain-HTTP contexts; see `oomtop doctor`)"
1273                    .into(),
1274            );
1275        } else if !named {
1276            a.c.notes.push(
1277                "pod and container names need the API server or engine labels; cgroup paths give QoS, pod \
1278                 UID and container id only"
1279                    .into(),
1280            );
1281        }
1282    }
1283
1284    acc.into_values().map(finish_cluster).collect()
1285}
1286
1287fn finish_cluster(a: ClusterAcc) -> Cluster {
1288    let mut c = a.c;
1289    for (name, n) in a.nodes {
1290        let mut by_ns: BTreeMap<String, Vec<KubePod>> = BTreeMap::new();
1291        for (_, pa) in n.pods {
1292            let mut pod = pa.pod;
1293            pod.containers = pa.containers.into_values().collect();
1294            pod.containers
1295                .sort_by(|x, y| x.name.cmp(&y.name).then(x.id.cmp(&y.id)));
1296            if !pod.mem.is_available() && !pod.containers.is_empty() {
1297                pod.mem = sum_bytes(pod.containers.iter().map(|c| &c.mem), "Σ container working sets");
1298            }
1299            by_ns.entry(pa.namespace).or_default().push(pod);
1300        }
1301        let mut namespaces: Vec<KubeNamespace> = by_ns
1302            .into_iter()
1303            .map(|(name, mut pods)| {
1304                pods.sort_by(|x, y| x.name.cmp(&y.name).then(x.uid.cmp(&y.uid)));
1305                KubeNamespace {
1306                    mem: sum_bytes(pods.iter().map(|p| &p.mem), "Σ pod memory"),
1307                    name,
1308                    pods,
1309                }
1310            })
1311            .collect();
1312        namespaces.sort_by(|a, b| a.name.cmp(&b.name));
1313        let mem = if n.mem.is_available() || namespaces.is_empty() {
1314            n.mem
1315        } else {
1316            sum_bytes(namespaces.iter().map(|x| &x.mem), "Σ pod memory")
1317        };
1318        c.nodes.push(KubeNode {
1319            name,
1320            sandbox_id: n.sandbox_id,
1321            mem,
1322            namespaces,
1323        });
1324    }
1325    c
1326}
1327
1328/// Sets `limit_id` on pods and containers that have a [`LimitStatus`].
1329fn link_limits(clusters: &mut [Cluster], limits: &[LimitStatus]) {
1330    for c in clusters {
1331        for n in &mut c.nodes {
1332            for ns in &mut n.namespaces {
1333                for p in &mut ns.pods {
1334                    if let Some(cg) = &p.cgroup {
1335                        let id = format!("cgroup:{cg}");
1336                        if limits.iter().any(|l| l.id == id) {
1337                            p.limit_id = Some(id);
1338                        }
1339                    }
1340                    for k in &mut p.containers {
1341                        k.limit_id = limits
1342                            .iter()
1343                            .find(|l| {
1344                                k.cgroup.as_ref().is_some_and(|cg| l.cgroup.as_ref() == Some(cg))
1345                                    || k.sandbox_id
1346                                        .as_ref()
1347                                        .is_some_and(|sb| l.sandbox_id.as_ref() == Some(sb))
1348                                    || (l.pod.as_deref()
1349                                        == Some(&format!("{}/{}", ns.name, p.name.as_deref().unwrap_or("")))
1350                                        && l.label == k.name.clone().unwrap_or_default()
1351                                        && l.id.starts_with("k8s:"))
1352                            })
1353                            .map(|l| l.id.clone());
1354                    }
1355                }
1356            }
1357        }
1358    }
1359}
1360
1361// ---------------------------------------------------------------------------------------------------------
1362// Limit inputs
1363// ---------------------------------------------------------------------------------------------------------
1364
1365fn unit_label(path: &str) -> String {
1366    path.rsplit('/')
1367        .find(|s| !s.is_empty())
1368        .unwrap_or(path)
1369        .to_string()
1370}
1371
1372/// Every limit in the snapshot, de-duplicated: cgroup files (Linux, freshest) first, then engine limits
1373/// of containers without a cgroup entry, engine VMs, then API-only Kubernetes containers.
1374pub fn limit_inputs(s: &Snapshot, clusters: &[Cluster]) -> Vec<LimitInput> {
1375    let mut out: Vec<LimitInput> = Vec::new();
1376    // Names of Kubernetes containers / pods by container id / pod cgroup.
1377    let mut kube_names: BTreeMap<String, (String, String)> = BTreeMap::new();
1378    let mut pod_names: BTreeMap<String, String> = BTreeMap::new();
1379    for c in clusters {
1380        for n in &c.nodes {
1381            for ns in &n.namespaces {
1382                for p in &ns.pods {
1383                    let pod = format!("{}/{}", ns.name, p.name.as_deref().unwrap_or("?"));
1384                    if let Some(cg) = &p.cgroup {
1385                        pod_names.insert(cg.clone(), pod.clone());
1386                    }
1387                    for k in &p.containers {
1388                        if let Some(id) = &k.id {
1389                            kube_names.insert(id.clone(), (pod.clone(), k.name.clone().unwrap_or_default()));
1390                        }
1391                    }
1392                }
1393            }
1394        }
1395    }
1396    let ci_by_id = |id: &str| {
1397        s.isolation
1398            .containers
1399            .iter()
1400            .find(|c| c.id.starts_with(id) || (!c.id.is_empty() && id.starts_with(c.id.as_str())))
1401    };
1402    let mut covered_sandboxes: Vec<String> = Vec::new();
1403    let mut covered_kube_ids: Vec<String> = Vec::new();
1404    for cg in s.cgroups.iter().filter(|c| c.has_limit()) {
1405        let (limit, target) = match (cg.max, cg.high) {
1406            (Some(m), _) => (Measured::exact(m, "cgroup memory.max"), LimitTarget::Max),
1407            (None, Some(h)) => (Measured::exact(h, "cgroup memory.high"), LimitTarget::High),
1408            _ => continue,
1409        };
1410        let mut i = LimitInput {
1411            id: format!("cgroup:{}", cg.path),
1412            kind: LimitKind::Cgroup,
1413            label: unit_label(&cg.path),
1414            runtime: None,
1415            cgroup: Some(cg.path.clone()),
1416            usage: cg.working_set_measured(),
1417            read_at_ms: (cg.current.is_some() && cg.at_ms > 0).then_some(cg.at_ms),
1418            limit,
1419            target,
1420            high: cg.high.filter(|h| cg.max.is_none_or(|m| *h < m)),
1421            peak: match cg.peak {
1422                Some(p) => Measured::exact(p, "cgroup memory.peak"),
1423                None => Measured::unavailable("cgroup memory.peak", "not available (kernel < 5.19)"),
1424            },
1425            events: cg.events,
1426            ..Default::default()
1427        };
1428        if let Some(k) = parse_kube_cgroup(&cg.path) {
1429            i.runtime = Some("kubernetes".into());
1430            match &k.container_id {
1431                Some(id) => {
1432                    i.kind = LimitKind::Container;
1433                    covered_kube_ids.push(id.clone());
1434                    if let Some((pod, name)) = kube_names.get(id) {
1435                        i.pod = Some(pod.clone());
1436                        if !name.is_empty() {
1437                            i.label = name.clone();
1438                        }
1439                    } else {
1440                        i.label = id.chars().take(12).collect();
1441                    }
1442                }
1443                None => {
1444                    i.kind = LimitKind::Pod;
1445                    i.label = pod_names
1446                        .get(&k.pod_cgroup)
1447                        .cloned()
1448                        .unwrap_or_else(|| format!("pod {}", k.pod_uid));
1449                    i.pod = pod_names.get(&k.pod_cgroup).cloned();
1450                }
1451            }
1452        } else if let Some(CgroupScope::Container { runtime, id }) = parse_cgroup(&cg.path) {
1453            i.kind = LimitKind::Container;
1454            i.runtime = Some(runtime.clone());
1455            if let Some(ci) = ci_by_id(&id) {
1456                i.label = ci.name.clone();
1457                i.sandbox_id = Some(ci.sandbox_id.clone());
1458                i.oom_killed_last_exit = ci.oom_killed;
1459                i.restarts = ci.restart_count;
1460                covered_sandboxes.push(ci.sandbox_id.clone());
1461            } else if let Some(sb) = s.sandboxes.iter().find(|sb| sb.id.ends_with(&format!(":{id}"))) {
1462                i.label = sb.label.clone();
1463                i.sandbox_id = Some(sb.id.clone());
1464                covered_sandboxes.push(sb.id.clone());
1465            } else {
1466                i.label = format!("{runtime} {id}");
1467            }
1468        } else if cg.path.ends_with(".service") || cg.path.ends_with(".scope") || cg.path.ends_with(".slice")
1469        {
1470            i.runtime = Some("systemd".into());
1471        }
1472        out.push(i);
1473    }
1474    // Engine containers with a limit and no cgroup entry (VM-hosted engines, or cgroups not readable).
1475    for sb in &s.sandboxes {
1476        if sb.kind != SandboxKind::Container || covered_sandboxes.contains(&sb.id) {
1477            continue;
1478        }
1479        let Some(limit) = sb.limits.mem_max else {
1480            continue;
1481        };
1482        let ci = s.isolation.container(&sb.id);
1483        if let Some(c) = ci {
1484            if c.labels.contains_key("io.kubernetes.pod.uid") {
1485                covered_kube_ids.push(c.id.clone());
1486            }
1487        }
1488        out.push(LimitInput {
1489            id: sb.id.clone(),
1490            kind: LimitKind::Container,
1491            label: sb.label.clone(),
1492            runtime: Some(sb.runtime.clone()),
1493            sandbox_id: Some(sb.id.clone()),
1494            usage: sb.guest_mem.clone(),
1495            // Only a fresh engine reading is a new trend point (carried-over values are estimates).
1496            read_at_ms: ci
1497                .and_then(|c| c.stats_at_ms)
1498                .filter(|_| sb.guest_mem.quality == crate::model::Quality::Exact),
1499            limit: if sb.configured_mem.is_available() {
1500                sb.configured_mem.clone()
1501            } else {
1502                Measured::exact(limit, format!("{} HostConfig.Memory", sb.runtime))
1503            },
1504            peak: Measured::unavailable(sb.runtime.clone(), "engines do not report a peak"),
1505            oom_killed_last_exit: ci.and_then(|c| c.oom_killed),
1506            restarts: ci.and_then(|c| c.restart_count),
1507            ..Default::default()
1508        });
1509    }
1510    // Engine VMs: Σ containers against the VM's memory.
1511    for sb in &s.sandboxes {
1512        if sb.kind != SandboxKind::Vm || !sb.guest_mem.source.starts_with("Σ container memory") {
1513            continue;
1514        }
1515        let Some(size) = sb.configured_mem.value else {
1516            continue;
1517        };
1518        let complete = sb.guest_mem.source == "Σ container memory (engine stats)";
1519        let read_at = s
1520            .isolation
1521            .containers
1522            .iter()
1523            .filter(|c| c.engine == sb.runtime || sb.started_by_group.is_some())
1524            .filter_map(|c| c.stats_at_ms)
1525            .max();
1526        out.push(LimitInput {
1527            id: sb.id.clone(),
1528            kind: LimitKind::Vm,
1529            label: sb.label.clone(),
1530            runtime: Some(sb.runtime.clone()),
1531            sandbox_id: Some(sb.id.clone()),
1532            usage: sb.guest_mem.clone(),
1533            read_at_ms: read_at.filter(|_| complete),
1534            limit: Measured::exact(size, sb.configured_mem.source.clone()),
1535            peak: Measured::unavailable(sb.runtime.clone(), "not reported"),
1536            ..Default::default()
1537        });
1538    }
1539    // Kubernetes containers known only from the API (pods inside a VM or node container).
1540    for d in &s.isolation.kube {
1541        let stats: BTreeMap<(String, String, String), &KubeContainerStats> = d
1542            .nodes
1543            .iter()
1544            .flat_map(|n| n.pods.iter())
1545            .flat_map(|p| {
1546                p.containers
1547                    .iter()
1548                    .map(move |c| ((p.namespace.clone(), p.name.clone(), c.name.clone()), c))
1549            })
1550            .collect();
1551        for p in &d.pods {
1552            for c in &p.containers {
1553                let Some(limit) = c.mem_limit else { continue };
1554                if c.id
1555                    .as_ref()
1556                    .is_some_and(|id| covered_kube_ids.iter().any(|x| x == id))
1557                {
1558                    continue;
1559                }
1560                let st = stats.get(&(p.namespace.clone(), p.name.clone(), c.name.clone()));
1561                out.push(LimitInput {
1562                    id: format!("k8s:{}/{}/{}/{}", d.context, p.namespace, p.name, c.name),
1563                    kind: LimitKind::Container,
1564                    label: c.name.clone(),
1565                    runtime: Some("kubernetes".into()),
1566                    pod: Some(format!("{}/{}", p.namespace, p.name)),
1567                    usage: match st.and_then(|s| s.working_set) {
1568                        Some(ws) => Measured::exact(ws, "kubelet stats/summary workingSetBytes"),
1569                        None => Measured::unavailable("kubelet stats/summary", "no stats for this container"),
1570                    },
1571                    read_at_ms: st.and_then(|s| s.working_set).map(|_| d.at_ms),
1572                    limit: Measured::exact(limit, "pod spec resources.limits.memory"),
1573                    peak: Measured::unavailable("kubelet", "not reported"),
1574                    oom_killed_last_exit: c.last_termination_reason.as_ref().map(|r| r == "OOMKilled"),
1575                    restarts: c.restarts,
1576                    ..Default::default()
1577                });
1578            }
1579        }
1580    }
1581    out
1582}
1583
1584// ---------------------------------------------------------------------------------------------------------
1585// VM slack
1586// ---------------------------------------------------------------------------------------------------------
1587
1588/// VM slack of every engine VM whose containers were measured (module docs).
1589pub fn vm_slack(s: &Snapshot) -> Vec<VmSlack> {
1590    let mut out = Vec::new();
1591    for sb in &s.sandboxes {
1592        if sb.kind != SandboxKind::Vm || !sb.guest_mem.source.starts_with("Σ container memory") {
1593            continue;
1594        }
1595        let Some(sum) = sb.guest_mem.value else { continue };
1596        let fps: Vec<&Measured<u64>> = sb
1597            .host_pids
1598            .iter()
1599            .filter_map(|h| s.process(*h).map(|p| &p.mem.footprint_or_pss))
1600            .collect();
1601        if fps.is_empty() {
1602            continue;
1603        }
1604        let vm_fp = sum_bytes(fps, "VM host footprint");
1605        let Some(fp) = vm_fp.value else { continue };
1606        let slack = fp.saturating_sub(sum);
1607        if slack < VM_SLACK_MIN_BYTES.max(fp / 10) {
1608            continue;
1609        }
1610        let mut notes = Vec::new();
1611        if sb.footprint_lower_bound {
1612            notes.push(
1613                "the VM's host footprint is a lower bound (compressed guest memory is not in it), so the \
1614                 slack may be larger"
1615                    .to_string(),
1616            );
1617        }
1618        if sb.guest_mem.source.contains("lower bound") {
1619            notes.push("not every container was measured, so the slack may be smaller".to_string());
1620        }
1621        if sb.guest_mem.source.contains("earlier refresh") {
1622            notes.push("some container values are from an earlier refresh".to_string());
1623        }
1624        notes.push("includes the guest kernel, page cache and the engine's own services".to_string());
1625        out.push(VmSlack {
1626            sandbox_id: sb.id.clone(),
1627            label: sb.label.clone(),
1628            runtime: sb.runtime.clone(),
1629            vm_footprint: vm_fp,
1630            containers: sb.guest_mem.clone(),
1631            configured: sb.configured_mem.value,
1632            slack: Measured::estimate(slack, "VM host footprint − Σ container memory"),
1633            summary: format!(
1634                "{}: {} {VM_SLACK_SENTENCE}",
1635                sb.label,
1636                format_bytes(slack, UnitSystem::Iec, 1)
1637            ),
1638            notes,
1639            counts_as_reclaim: false,
1640        });
1641    }
1642    out
1643}
1644
1645#[cfg(test)]
1646mod tests {
1647    use super::*;
1648    use crate::forecast::MemoryEvents;
1649    use crate::model::{MemBreakdown, Process, Sandbox, SandboxLimits};
1650
1651    const GIB: u64 = 1 << 30;
1652    const MIB: u64 = 1 << 20;
1653    const CID: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
1654    const UID: &str = "8f6c1c3e-3b5a-4b8e-9d55-0a1b2c3d4e5f";
1655
1656    fn proc(pid: u32, name: &str, cgroup: &str, mib: u64) -> Process {
1657        Process {
1658            id: ProcId::new(pid, pid as u64),
1659            ppid: Some(1),
1660            name: name.into(),
1661            cgroup: Some(cgroup.into()),
1662            mem: MemBreakdown {
1663                footprint_or_pss: Measured::exact(mib * MIB, "t"),
1664                ..Default::default()
1665            },
1666            ..Default::default()
1667        }
1668    }
1669
1670    #[test]
1671    fn parsers() {
1672        assert_eq!(parse_rfc3339_ms("1970-01-01T00:00:01Z"), Some(1000));
1673        assert_eq!(
1674            parse_rfc3339_ms("2026-12-05T10:11:12.123456789Z"),
1675            Some(1_796_465_472_123)
1676        );
1677        assert_eq!(
1678            parse_rfc3339_ms("2026-12-05T11:11:12+01:00"),
1679            parse_rfc3339_ms("2026-12-05T10:11:12Z")
1680        );
1681        assert_eq!(parse_rfc3339_ms("0001-01-01T00:00:00Z"), None, "docker zero time");
1682        assert_eq!(parse_rfc3339_ms("yesterday"), None);
1683        for (q, v) in [
1684            ("128Mi", 128 * MIB),
1685            ("1Gi", GIB),
1686            ("1G", 1_000_000_000),
1687            ("500M", 500_000_000),
1688            ("1e9", 1_000_000_000),
1689            ("129e6", 129_000_000),
1690            ("1.5Gi", 3 * GIB / 2),
1691            ("100k", 100_000),
1692            ("64Ki", 65536),
1693            ("12345", 12345),
1694            ("1000m", 1),
1695        ] {
1696            assert_eq!(parse_k8s_quantity(q), Some(v), "{q}");
1697        }
1698        assert_eq!(parse_k8s_quantity("lots"), None);
1699        assert_eq!(parse_k8s_quantity(""), None);
1700        assert!(keep_label("io.kubernetes.pod.name"));
1701        assert!(!keep_label("org.opencontainers.image.source"));
1702        assert_eq!(KubeDistro::from_context("kind-dev"), Some(KubeDistro::Kind));
1703        assert_eq!(KubeDistro::Kind.cluster_name_from_context("kind-dev"), "dev");
1704        assert_eq!(KubeDistro::from_context("prod-eu"), None);
1705    }
1706
1707    /// A k3s host: cgroup paths give the tree and per-container limits; the API (when present) names them.
1708    #[test]
1709    fn host_cluster_from_cgroups_with_limits_and_api_names() {
1710        let pod_cg = format!("/kubepods/burstable/pod{UID}");
1711        let ctr_cg = format!("{pod_cg}/{CID}");
1712        let mut s = Snapshot {
1713            taken_at_ms: 1_000_000,
1714            processes: vec![
1715                Process {
1716                    name: "k3s".into(),
1717                    exe: "/usr/local/bin/k3s".into(),
1718                    cmdline: vec!["/usr/local/bin/k3s".into(), "server".into()],
1719                    ..proc(100, "k3s", "/system.slice/k3s.service", 500)
1720                },
1721                proc(200, "nginx", &ctr_cg, 40),
1722                proc(201, "nginx", &ctr_cg, 10),
1723            ],
1724            ..Default::default()
1725        };
1726        s.host.hostname = "box".into();
1727        s.cgroups = vec![
1728            CgroupMem {
1729                path: ctr_cg.clone(),
1730                current: Some(300 * MIB),
1731                inactive_file: Some(100 * MIB),
1732                max: Some(256 * MIB),
1733                limits_read: true,
1734                events: Some(MemoryEvents {
1735                    oom_kill: 2,
1736                    ..Default::default()
1737                }),
1738                at_ms: 1_000_000,
1739                ..Default::default()
1740            },
1741            CgroupMem {
1742                path: pod_cg.clone(),
1743                current: Some(310 * MIB),
1744                inactive_file: Some(100 * MIB),
1745                limits_read: true,
1746                at_ms: 1_000_000,
1747                ..Default::default()
1748            },
1749        ];
1750        let mut tr = IsolationTracker::new();
1751        tr.update(&mut s);
1752        let iso = &s.isolation;
1753        assert_eq!(iso.clusters.len(), 1);
1754        let c = &iso.clusters[0];
1755        assert_eq!((c.id.as_str(), c.distro), ("host", KubeDistro::K3s));
1756        assert!(c.evidence.iter().any(|e| e == "process k3s"), "{:?}", c.evidence);
1757        let pod = &c.nodes[0].namespaces[0].pods[0];
1758        assert_eq!(c.nodes[0].name, "box");
1759        assert_eq!(pod.uid.as_deref(), Some(UID));
1760        assert_eq!(pod.qos, Some(QosClass::Burstable));
1761        assert_eq!(pod.mem.value, Some(210 * MIB));
1762        let k = &pod.containers[0];
1763        assert_eq!(k.id.as_deref(), Some(CID));
1764        assert_eq!(k.mem.value, Some(200 * MIB));
1765        assert_eq!(k.host_pids.len(), 2);
1766        assert_eq!(k.limit.value, Some(256 * MIB));
1767        assert_eq!(k.limit_id.as_deref(), Some(format!("cgroup:{ctr_cg}").as_str()));
1768        assert!(c.notes[0].contains("names need the API"));
1769        let l = &iso.limits[0];
1770        assert_eq!(l.kind, LimitKind::Container);
1771        assert_eq!(l.oom_kills.value, Some(2));
1772        assert_eq!(l.pct.map(|p| p.round()), Some(78.0));
1773
1774        // Now the API names the pod (same uid, container id with runtime prefix stripped by the adapter).
1775        s.isolation.kube = vec![KubeApiData {
1776            context: "default".into(),
1777            status: SourceStatus::Available,
1778            at_ms: 1_000_000,
1779            pods: vec![KubePodInfo {
1780                namespace: "shop".into(),
1781                name: "web-7d9f".into(),
1782                uid: UID.into(),
1783                node: Some("box".into()),
1784                phase: Some("Running".into()),
1785                qos: Some(QosClass::Burstable),
1786                containers: vec![KubeContainerSpec {
1787                    name: "nginx".into(),
1788                    id: Some(CID.into()),
1789                    runtime: Some("containerd".into()),
1790                    mem_limit: Some(256 * MIB),
1791                    restarts: Some(3),
1792                    last_termination_reason: Some("OOMKilled".into()),
1793                    ..Default::default()
1794                }],
1795                ..Default::default()
1796            }],
1797            ..Default::default()
1798        }];
1799        tr.update(&mut s);
1800        let c = &s.isolation.clusters[0];
1801        assert_eq!(
1802            s.isolation.clusters.len(),
1803            1,
1804            "merged into the host cluster by node name"
1805        );
1806        let ns = &c.nodes[0].namespaces[0];
1807        assert_eq!(ns.name, "shop");
1808        let pod = &ns.pods[0];
1809        assert_eq!(pod.name.as_deref(), Some("web-7d9f"));
1810        assert_eq!(pod.containers.len(), 1, "matched by id, not duplicated by name");
1811        assert_eq!(pod.containers[0].name.as_deref(), Some("nginx"));
1812        assert_eq!(pod.containers[0].last_termination.as_deref(), Some("OOMKilled"));
1813        let l = &s.isolation.limits[0];
1814        assert_eq!(l.label, "nginx");
1815        assert_eq!(l.pod.as_deref(), Some("shop/web-7d9f"));
1816        assert_eq!(
1817            s.isolation.limits.len(),
1818            1,
1819            "the API container is covered by its cgroup"
1820        );
1821    }
1822
1823    /// macOS: a kind cluster in Docker Desktop: node containers by label, pods only via the API.
1824    #[test]
1825    fn kind_nodes_from_labels_and_api_only_limits() {
1826        let mut s = Snapshot {
1827            taken_at_ms: 5_000_000,
1828            ..Default::default()
1829        };
1830        let mut labels = BTreeMap::new();
1831        labels.insert("io.x-k8s.kind.cluster".to_string(), "dev".to_string());
1832        labels.insert("io.x-k8s.kind.role".to_string(), "control-plane".to_string());
1833        s.isolation.containers.push(ContainerInfo {
1834            sandbox_id: "docker-desktop:aaaa1111bbbb".into(),
1835            id: "aaaa1111bbbb2222".into(),
1836            engine: "docker-desktop".into(),
1837            vm_hosted: true,
1838            name: "dev-control-plane".into(),
1839            state: "running".into(),
1840            labels,
1841            ..Default::default()
1842        });
1843        s.sandboxes.push(Sandbox {
1844            id: "docker-desktop:aaaa1111bbbb".into(),
1845            kind: SandboxKind::Container,
1846            runtime: "docker-desktop".into(),
1847            label: "dev-control-plane".into(),
1848            guest_mem: Measured::exact(900 * MIB, "docker-desktop stats"),
1849            ..Default::default()
1850        });
1851        s.isolation.kube = vec![KubeApiData {
1852            context: "kind-dev".into(),
1853            distro: None,
1854            status: SourceStatus::Available,
1855            at_ms: 5_000_000,
1856            nodes: vec![KubeNodeStats {
1857                name: "dev-control-plane".into(),
1858                working_set: Some(800 * MIB),
1859                pods: vec![KubePodStats {
1860                    namespace: "default".into(),
1861                    name: "api".into(),
1862                    uid: "u1".into(),
1863                    containers: vec![KubeContainerStats {
1864                        name: "app".into(),
1865                        working_set: Some(120 * MIB),
1866                        ..Default::default()
1867                    }],
1868                    ..Default::default()
1869                }],
1870                ..Default::default()
1871            }],
1872            pods: vec![KubePodInfo {
1873                namespace: "default".into(),
1874                name: "api".into(),
1875                uid: "u1".into(),
1876                node: Some("dev-control-plane".into()),
1877                containers: vec![KubeContainerSpec {
1878                    name: "app".into(),
1879                    mem_limit: Some(128 * MIB),
1880                    ..Default::default()
1881                }],
1882                ..Default::default()
1883            }],
1884        }];
1885        let mut tr = IsolationTracker::new();
1886        tr.update(&mut s);
1887        let c = &s.isolation.clusters[0];
1888        assert_eq!((c.id.as_str(), c.distro), ("kind:dev", KubeDistro::Kind));
1889        assert_eq!(c.context.as_deref(), Some("kind-dev"));
1890        let n = &c.nodes[0];
1891        assert_eq!(n.sandbox_id.as_deref(), Some("docker-desktop:aaaa1111bbbb"));
1892        assert_eq!(n.mem.value, Some(900 * MIB), "the node container's memory");
1893        let k = &n.namespaces[0].pods[0].containers[0];
1894        assert_eq!(k.mem.value, Some(120 * MIB));
1895        assert_eq!(k.limit.value, Some(128 * MIB));
1896        let l = &s.isolation.limits[0];
1897        assert_eq!(l.id, "k8s:kind-dev/default/api/app");
1898        assert_eq!(l.state, crate::limits::LimitState::Near);
1899        assert_eq!(k.limit_id.as_deref(), Some("k8s:kind-dev/default/api/app"));
1900    }
1901
1902    /// Docker Desktop VM: slack is reported as an estimate and never as reclaim; small slack is not.
1903    #[test]
1904    fn vm_slack_finding() {
1905        let vm = ProcId::new(900, 1);
1906        let mut s = Snapshot::default();
1907        s.processes.push(Process {
1908            id: vm,
1909            mem: MemBreakdown {
1910                footprint_or_pss: Measured::exact(6 * GIB, "t"),
1911                ..Default::default()
1912            },
1913            ..Default::default()
1914        });
1915        s.sandboxes.push(Sandbox {
1916            id: "vz:docker".into(),
1917            kind: SandboxKind::Vm,
1918            runtime: "virtualization.framework".into(),
1919            label: "Docker VM".into(),
1920            host_pids: vec![vm],
1921            configured_mem: Measured::exact(8 * GIB, "docker-desktop /info MemTotal"),
1922            guest_mem: Measured::estimate(2 * GIB, "Σ container memory (engine stats)"),
1923            limits: SandboxLimits {
1924                mem_max: Some(8 * GIB),
1925                cpus: None,
1926            },
1927            footprint_lower_bound: true,
1928            ..Default::default()
1929        });
1930        let v = vm_slack(&s);
1931        assert_eq!(v.len(), 1);
1932        assert_eq!(v[0].slack.value, Some(4 * GIB));
1933        assert_eq!(v[0].slack.quality, crate::model::Quality::Estimate);
1934        assert!(!v[0].counts_as_reclaim);
1935        assert_eq!(
1936            v[0].summary,
1937            "Docker VM: 4.0 GiB held by the VM, not used by containers; restarting the engine returns it"
1938        );
1939        assert!(v[0].notes[0].contains("lower bound"));
1940        // The VM is also a limit: Σ containers against its 8 GiB.
1941        let mut tr = IsolationTracker::new();
1942        tr.update(&mut s);
1943        let l = s.isolation.limit("vz:docker").unwrap();
1944        assert_eq!((l.kind, l.limit.value), (LimitKind::Vm, Some(8 * GIB)));
1945        // Containers use nearly everything: no finding.
1946        s.sandboxes[0].guest_mem = Measured::estimate(5900 * MIB, "Σ container memory (engine stats)");
1947        assert!(vm_slack(&s).is_empty());
1948    }
1949
1950    #[test]
1951    fn stale_containers() {
1952        let mut s = Snapshot {
1953            taken_at_ms: 10_000_000,
1954            ..Default::default()
1955        };
1956        let run = |ns: u64, at: u64| ContainerInfo {
1957            sandbox_id: "docker:idle".into(),
1958            name: "idle".into(),
1959            engine: "docker".into(),
1960            state: "running".into(),
1961            started_ms: Some(1_000_000),
1962            cpu_total_ns: Some(ns),
1963            stats_at_ms: Some(at),
1964            ..Default::default()
1965        };
1966        s.isolation.containers = vec![
1967            run(1_000_000_000, 9_000_000),
1968            ContainerInfo {
1969                sandbox_id: "docker:old".into(),
1970                name: "old".into(),
1971                engine: "docker".into(),
1972                state: "exited".into(),
1973                status_text: "Exited (137) 2 days ago".into(),
1974                finished_ms: Some(10_000_000 - 2 * 3_600_000),
1975                exit_code: Some(137),
1976                ..Default::default()
1977            },
1978        ];
1979        let mut tr = IsolationTracker::new();
1980        tr.update(&mut s);
1981        assert_eq!(
1982            s.isolation.stale_containers.len(),
1983            1,
1984            "running: not observed long enough yet"
1985        );
1986        let old = &s.isolation.stale_containers[0];
1987        assert_eq!(old.reason, "exited (137) 2 days ago");
1988        assert!(old.disk.unavailable_reason().unwrap().contains("size=1"));
1989        // 3 min later, 20 ms of CPU used: 0.01 % → idle.
1990        s.isolation.containers[0] = run(1_020_000_000, 9_180_000);
1991        s.taken_at_ms = 10_180_000;
1992        tr.update(&mut s);
1993        let st = &s.isolation.stale_containers;
1994        assert_eq!(st[0].sandbox_id, "docker:idle", "running ones first");
1995        assert!(st[0].cpu_pct.value.unwrap() < 0.02);
1996        assert_eq!(st[0].observed_s, 180);
1997        assert_eq!(st[0].age_s, Some(9180));
1998        // Busy container: 30 s of CPU in 3 min → not stale.
1999        s.isolation.containers[0] = run(31_000_000_000, 9_360_000);
2000        tr.update(&mut s);
2001        assert!(s
2002            .isolation
2003            .stale_containers
2004            .iter()
2005            .all(|c| c.sandbox_id != "docker:idle"));
2006    }
2007
2008    #[test]
2009    fn empty_snapshot_is_empty() {
2010        let mut s = Snapshot::default();
2011        IsolationTracker::new().update(&mut s);
2012        assert!(s.isolation.is_empty());
2013        let json = serde_json::to_value(&s).unwrap();
2014        assert!(json.get("isolation").is_none(), "left out of JSON when empty");
2015        assert!(json.get("cgroups").is_none());
2016    }
2017}