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