oomtop-cli 0.2.1

oomtop: see the OOM coming. Terminal resource monitor for local AI work.
Documentation
//! `oomtop sandboxes` and `oomtop ns` (SPEC §8.3, §11): containers, VMs and local Kubernetes — every limit
//! with how close it is and an ETA when the trend is real, the cluster tree, memory an engine VM holds that no
//! container uses, stale containers — and Linux namespace sets. Answer first, one line per fact, no tables.

use super::{json_pretty, out, Ctx};
use anyhow::Result;
use oomtop_core::cluster::Isolation;
use oomtop_core::limits::LimitState;
use oomtop_core::namespaces::NamespaceReport;
use oomtop_core::provider::SnapshotProvider;
use oomtop_core::redact::redact_snapshot;
use oomtop_core::units::format_duration;
use oomtop_core::{Measured, OsKind, Quality, Sandbox, SandboxKind, Snapshot, SourceStatus};
use serde::Serialize;
use std::collections::BTreeMap;

/// Frames a replay is advanced through at most (limit trends need the observed window).
const MAX_REPLAY_FRAMES: usize = 10_000;

/// One on-demand sample live; with `--replay`, the last frame after playing every frame (trends build up
/// over the replayed window, as in the TUI).
fn snapshot(ctx: &Ctx) -> Result<Snapshot> {
    let mut e = ctx.engine(true)?;
    let mut s = e.snapshot();
    if ctx.replaying() {
        for _ in 0..MAX_REPLAY_FRAMES {
            if e.replay_done() {
                break;
            }
            s = e.snapshot();
        }
    }
    Ok(if ctx.config().privacy.redact_exports {
        redact_snapshot(&s)
    } else {
        s
    })
}

/// Source statuses relevant here (engines, Kubernetes, cgroups, namespaces).
fn statuses(s: &Snapshot) -> BTreeMap<String, SourceStatus> {
    s.source_status
        .iter()
        .filter(|(k, _)| {
            k.starts_with("adapter.docker")
                || matches!(
                    k.as_str(),
                    "adapter.docker-desktop"
                        | "adapter.orbstack"
                        | "adapter.colima"
                        | "adapter.rancher-desktop"
                        | "adapter.podman"
                        | "adapter.k8s"
                        | "linux.cgroups"
                        | "linux.ns"
                )
        })
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect()
}

#[derive(Serialize)]
struct SandboxesReport<'a> {
    schema_version: u32,
    taken_at_ms: u64,
    sandboxes: &'a [Sandbox],
    #[serde(flatten)]
    isolation: &'a Isolation,
    status: BTreeMap<String, SourceStatus>,
}

fn status_word(st: &SourceStatus) -> String {
    match st {
        SourceStatus::Available => "available".into(),
        SourceStatus::Partial(r) => format!("partial ({r})"),
        SourceStatus::Unavailable(r) => format!("unavailable ({r})"),
    }
}

fn mem(ctx: &Ctx, m: &Measured<u64>) -> String {
    match (&m.value, &m.quality) {
        (Some(v), Quality::Exact) => ctx.fmt(*v),
        (Some(v), _) => format!("{} (est.)", ctx.fmt(*v)),
        (None, Quality::Unavailable(r)) => format!("n/a ({r})"),
        (None, _) => "n/a".into(),
    }
}

fn kind_word(k: SandboxKind) -> &'static str {
    match k {
        SandboxKind::Container => "container",
        SandboxKind::Vm => "VM",
        SandboxKind::MicroVm => "microVM",
        SandboxKind::ProcessSandbox => "process sandbox",
    }
}

pub fn sandboxes(ctx: &Ctx, json: bool) -> Result<i32> {
    let s = snapshot(ctx)?;
    let iso = &s.isolation;
    if json {
        out(&json_pretty(&SandboxesReport {
            schema_version: oomtop_core::SCHEMA_VERSION,
            taken_at_ms: s.taken_at_ms,
            sandboxes: &s.sandboxes,
            isolation: iso,
            status: statuses(&s),
        })?);
        return Ok(0);
    }
    let units = ctx.units();
    let dec = ctx.config().format.decimals as usize;
    let mut o = String::new();
    let nothing = s.sandboxes.is_empty() && iso.is_empty();
    if nothing {
        o.push_str("No containers, VMs or local clusters found.\n");
    }
    if !iso.limits.is_empty() {
        o.push_str("Limits (most urgent first)\n");
        for l in &iso.limits {
            let mark = match l.state {
                LimitState::AtLimit => "AT LIMIT · ",
                LimitState::Near => "near · ",
                _ if l.forecast.is_some() => "trend · ",
                _ => "",
            };
            o.push_str(&format!("  {mark}{}\n", l.sentence(units, dec)));
        }
        if iso.limits.iter().all(|l| l.forecast.is_none()) && !ctx.replaying() {
            o.push_str(
                "  (an ETA needs ≥ 2 min of readings with a steady trend; a one-shot command takes one — the TUI \
                 and `oomtop serve` keep watching)\n",
            );
        }
    }
    if !iso.vm_slack.is_empty() {
        o.push_str("VM slack\n");
        for v in &iso.vm_slack {
            let slack = v.slack.value.unwrap_or(0);
            o.push_str(&format!(
                "  {}: {} {} (estimate; not counted as reclaim)\n",
                v.label,
                ctx.fmt(slack),
                oomtop_core::cluster::VM_SLACK_SENTENCE
            ));
            o.push_str(&format!(
                "    VM footprint {} · containers {}\n",
                mem(ctx, &v.vm_footprint),
                mem(ctx, &v.containers)
            ));
            for n in &v.notes {
                o.push_str(&format!("    · {n}\n"));
            }
        }
    }
    if !iso.clusters.is_empty() {
        o.push_str("Clusters\n");
        for c in &iso.clusters {
            let ctx_note = c
                .context
                .as_ref()
                .map(|x| format!(", context {x}"))
                .unwrap_or_default();
            o.push_str(&format!(
                "  {} ({}{ctx_note}) — {}\n",
                c.name,
                c.distro.title(),
                c.evidence.join("; ")
            ));
            if let Some(api) = &c.api {
                o.push_str(&format!("    API: {}\n", status_word(api)));
            }
            for n in &c.nodes {
                o.push_str(&format!("    node {} · {}\n", n.name, mem(ctx, &n.mem)));
                for ns in &n.namespaces {
                    let name = if ns.name.is_empty() {
                        "(namespace unknown)"
                    } else {
                        &ns.name
                    };
                    o.push_str(&format!("      {name} · {}\n", mem(ctx, &ns.mem)));
                    for p in &ns.pods {
                        let pname = p
                            .name
                            .clone()
                            .or_else(|| p.uid.as_ref().map(|u| format!("pod {u}")))
                            .unwrap_or_else(|| "pod ?".into());
                        let mut line = format!("        {pname}");
                        if let Some(q) = p.qos {
                            line.push_str(&format!(" · {}", q.as_str()));
                        }
                        line.push_str(&format!(" · {}", mem(ctx, &p.mem)));
                        if let Some(l) = p.limit {
                            line.push_str(&format!(" of {}", ctx.fmt(l)));
                        }
                        o.push_str(&line);
                        o.push('\n');
                        for k in &p.containers {
                            let name = k
                                .name
                                .clone()
                                .or_else(|| k.id.as_ref().map(|i| i.chars().take(12).collect()))
                                .unwrap_or_else(|| "?".into());
                            let mut line = format!("          {name} · {}", mem(ctx, &k.mem));
                            if let Some(l) = k.limit.value {
                                line.push_str(&format!(" of {}", ctx.fmt(l)));
                            }
                            if let Some(r) = k.restarts.filter(|r| *r > 0) {
                                line.push_str(&format!(" · restarts {r}"));
                            }
                            if let Some(t) = &k.last_termination {
                                line.push_str(&format!(" · last exit {t}"));
                            }
                            o.push_str(&line);
                            o.push('\n');
                        }
                    }
                }
            }
            for n in &c.notes {
                o.push_str(&format!("    · {n}\n"));
            }
        }
    }
    if !s.sandboxes.is_empty() {
        o.push_str("Sandboxes\n");
        for sb in &s.sandboxes {
            let mut line = format!(
                "  {} · {} · {} · {}",
                sb.label,
                kind_word(sb.kind),
                sb.runtime,
                mem(ctx, &sb.guest_mem)
            );
            if let Some(m) = sb.configured_mem.value {
                line.push_str(&format!(
                    " · {} {}",
                    if sb.kind == SandboxKind::Container {
                        "limit"
                    } else {
                        "configured"
                    },
                    ctx.fmt(m)
                ));
            }
            if let Some(c) = iso.container(&sb.id) {
                if let Some(t) = c.started_ms {
                    line.push_str(&format!(
                        " · up {}",
                        format_duration(s.taken_at_ms.saturating_sub(t) / 1000)
                    ));
                }
                if c.oom_killed == Some(true) {
                    line.push_str(" · last run OOM-killed");
                }
            }
            o.push_str(&line);
            o.push('\n');
        }
    }
    if !iso.stale_containers.is_empty() {
        o.push_str("Stale containers\n");
        for c in &iso.stale_containers {
            let disk = match c.disk.value {
                Some(d) => format!(" · writable layer {}", ctx.fmt(d)),
                None => String::new(),
            };
            o.push_str(&format!(
                "  {} ({}, {}) · {}{disk}\n",
                c.name, c.image, c.engine, c.reason
            ));
        }
    }
    let ns = &iso.namespaces;
    if !ns.sets.is_empty() {
        o.push_str(&format!("Namespace sets: {} (see `oomtop ns`)\n", ns.sets.len()));
    }
    if !iso.kube_contexts.is_empty() {
        o.push_str("Kubernetes contexts\n");
        for k in &iso.kube_contexts {
            o.push_str(&format!(
                "  {}{} · {}\n",
                k.name,
                if k.current { " (current)" } else { "" },
                k.verdict
            ));
        }
    }
    let st = statuses(&s);
    if !st.is_empty() {
        o.push_str("Sources\n");
        for (k, v) in &st {
            o.push_str(&format!("  {k}: {}\n", status_word(v)));
        }
    }
    out(&o);
    Ok(0)
}

#[derive(Serialize)]
struct NsReport<'a> {
    schema_version: u32,
    taken_at_ms: u64,
    supported: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<&'static str>,
    #[serde(flatten)]
    namespaces: &'a NamespaceReport,
    #[serde(skip_serializing_if = "Option::is_none")]
    status: Option<&'a SourceStatus>,
}

const NO_NS: &str = "Namespaces are a Linux kernel feature; macOS has none. Containers, VMs and Seatbelt \
                     sandboxes on this Mac are listed by `oomtop sandboxes`.";

pub fn ns(ctx: &Ctx, json: bool) -> Result<i32> {
    let s = snapshot(ctx)?;
    let linux = s.host.os == OsKind::Linux || s.processes.iter().any(|p| p.ns.is_some());
    let r = &s.isolation.namespaces;
    if json {
        out(&json_pretty(&NsReport {
            schema_version: oomtop_core::SCHEMA_VERSION,
            taken_at_ms: s.taken_at_ms,
            supported: linux,
            reason: (!linux).then_some(NO_NS),
            namespaces: r,
            status: s.source_status.get("linux.ns"),
        })?);
        return Ok(0);
    }
    if !linux {
        out(&format!("{NO_NS}\n"));
        return Ok(0);
    }
    let mut o = String::new();
    match &r.reference {
        None => {
            let why = match s.source_status.get("linux.ns") {
                Some(st) => status_word(st),
                None => "not recorded (the live Linux process source collects it; older recordings lack it)"
                    .into(),
            };
            o.push_str(&format!("No namespace data: {why}.\n"));
        }
        Some(_) => {
            if r.sets.is_empty() {
                o.push_str(&format!(
                    "Every readable process shares oomtop's namespaces ({} processes).\n",
                    r.in_reference
                ));
            } else {
                o.push_str(&format!(
                    "{} namespace set(s) differ from {} ({} processes share it):\n",
                    r.sets.len(),
                    if r.reference_source == "oomtop" {
                        "oomtop's own".to_string()
                    } else {
                        format!("the {}", r.reference_source)
                    },
                    r.in_reference
                ));
            }
            for set in &r.sets {
                let differs: Vec<&str> = set.differs.iter().map(|k| k.as_str()).collect();
                let mut line = format!(
                    "  {} · {} process(es) · {} · new {}",
                    if set.label.is_empty() { "?" } else { &set.label },
                    set.member_count,
                    mem(ctx, &set.mem_total),
                    differs.join("+")
                );
                if let Some(sb) = &set.sandbox_id {
                    line.push_str(&format!(" · sandbox {sb}"));
                }
                if let Some(g) = &set.group {
                    line.push_str(&format!(" · group {g}"));
                }
                if let Some(g) = &set.owner_group {
                    line.push_str(&format!(" · started by {g}"));
                }
                o.push_str(&line);
                o.push('\n');
            }
        }
    }
    if r.unreadable > 0 {
        o.push_str(&format!(
            "{} processes of other users were not inspected (their /proc/<pid>/ns links need root).\n",
            r.unreadable
        ));
    }
    out(&o);
    Ok(0)
}