oomtop-core 0.2.0

oomtop core: pure data model, units, attribution, headroom, forecast, throttle, query and ranking logic (no I/O)
Documentation
//! Linux namespace sets (SPEC ยง11 "Namespaces"): processes grouped by the namespaces they live in,
//! relative to oomtop's own. Any process that does not share oomtop's pid / net / mount / user / uts / ipc
//! / cgroup namespaces is in some kind of sandbox โ€” a container, `bwrap`/Flatpak, `unshare`, a browser
//! renderer sandbox โ€” so a sandbox that no engine rule knows still shows up, with its member count, memory
//! and owner. Identities are the inode numbers of the `/proc/<pid>/ns/*` links (`net:[4026531840]`),
//! readable for the user's own processes without privileges. macOS has no namespaces.

use crate::measured::sum_bytes;
use crate::model::{Measured, ProcId, Snapshot};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};

/// One namespace type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NsKind {
    Pid,
    Net,
    Mnt,
    User,
    Uts,
    Ipc,
    Cgroup,
}

impl NsKind {
    pub const ALL: [NsKind; 7] = [
        NsKind::Pid,
        NsKind::Net,
        NsKind::Mnt,
        NsKind::User,
        NsKind::Uts,
        NsKind::Ipc,
        NsKind::Cgroup,
    ];

    /// The `/proc/<pid>/ns/<name>` link name.
    pub fn as_str(self) -> &'static str {
        match self {
            NsKind::Pid => "pid",
            NsKind::Net => "net",
            NsKind::Mnt => "mnt",
            NsKind::User => "user",
            NsKind::Uts => "uts",
            NsKind::Ipc => "ipc",
            NsKind::Cgroup => "cgroup",
        }
    }

    pub fn parse(s: &str) -> Option<NsKind> {
        NsKind::ALL.into_iter().find(|k| k.as_str() == s)
    }
}

/// Namespace identities of one process (`None` = link not readable / not present on this kernel).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct NsIds {
    pub pid: Option<u64>,
    pub net: Option<u64>,
    pub mnt: Option<u64>,
    pub user: Option<u64>,
    pub uts: Option<u64>,
    pub ipc: Option<u64>,
    pub cgroup: Option<u64>,
}

impl NsIds {
    pub fn get(&self, k: NsKind) -> Option<u64> {
        match k {
            NsKind::Pid => self.pid,
            NsKind::Net => self.net,
            NsKind::Mnt => self.mnt,
            NsKind::User => self.user,
            NsKind::Uts => self.uts,
            NsKind::Ipc => self.ipc,
            NsKind::Cgroup => self.cgroup,
        }
    }

    pub fn set(&mut self, k: NsKind, v: Option<u64>) {
        match k {
            NsKind::Pid => self.pid = v,
            NsKind::Net => self.net = v,
            NsKind::Mnt => self.mnt = v,
            NsKind::User => self.user = v,
            NsKind::Uts => self.uts = v,
            NsKind::Ipc => self.ipc = v,
            NsKind::Cgroup => self.cgroup = v,
        }
    }

    pub fn is_empty(&self) -> bool {
        NsKind::ALL.iter().all(|k| self.get(*k).is_none())
    }

    /// Kinds known on both sides and different.
    pub fn differs_from(&self, other: &NsIds) -> Vec<NsKind> {
        NsKind::ALL
            .into_iter()
            .filter(|k| matches!((self.get(*k), other.get(*k)), (Some(a), Some(b)) if a != b))
            .collect()
    }

    /// `pid:4026531836 net:โ€ฆ` (known kinds only), the set's stable key.
    pub fn key(&self) -> String {
        NsKind::ALL
            .iter()
            .filter_map(|k| self.get(*k).map(|v| format!("{}:{v}", k.as_str())))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// Parses `readlink /proc/<pid>/ns/*` targets, one per line (`net:[4026531840]`); `pid_for_children` and
/// `time*` links and malformed lines are ignored.
pub fn parse_ns_links(text: &str) -> NsIds {
    let mut ids = NsIds::default();
    for line in text.lines() {
        let Some((name, rest)) = line.trim().split_once(':') else {
            continue;
        };
        let Some(k) = NsKind::parse(name) else {
            continue;
        };
        let v = rest
            .strip_prefix('[')
            .and_then(|r| r.strip_suffix(']'))
            .and_then(|n| n.parse::<u64>().ok());
        if v.is_some() {
            ids.set(k, v);
        }
    }
    ids
}

/// Processes sharing one namespace set that differs from oomtop's.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct NamespaceSet {
    /// [`NsIds::key`] of the set.
    pub id: String,
    pub ids: NsIds,
    /// Which namespaces differ from the reference (oomtop's own).
    pub differs: Vec<NsKind>,
    pub members: Vec<ProcId>,
    pub member_count: usize,
    /// ฮฃ footprint / PSS of the members.
    pub mem_total: Measured<u64>,
    /// The member whose parent is outside the set (the sandbox's entry point), else the oldest member.
    pub root: Option<ProcId>,
    /// Name of the root process.
    pub label: String,
    /// Group of the root process, and that group's owner (who started the sandbox).
    pub group: Option<String>,
    pub owner_group: Option<String>,
    /// Sandbox whose host pids overlap the members (engine/rule detection), if any.
    pub sandbox_id: Option<String>,
}

/// All namespace sets of a snapshot.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct NamespaceReport {
    /// The reference set: oomtop's own namespaces, else the most common set (a replay without oomtop).
    pub reference: Option<NsIds>,
    /// "oomtop" | "most common set".
    pub reference_source: String,
    /// Sets differing from the reference, largest memory first.
    pub sets: Vec<NamespaceSet>,
    /// Processes in the reference set.
    pub in_reference: usize,
    /// Processes whose namespaces could not be read (other users' processes need root).
    pub unreadable: usize,
}

impl NamespaceReport {
    pub fn is_empty(&self) -> bool {
        self.reference.is_none() && self.sets.is_empty() && self.unreadable == 0
    }
}

/// Groups `s.processes` by namespace set relative to oomtop's own (`s.self_pid`).
pub fn namespace_sets(s: &Snapshot) -> NamespaceReport {
    let with: Vec<(&crate::model::Process, NsIds)> = s
        .processes
        .iter()
        .filter_map(|p| p.ns.filter(|n| !n.is_empty()).map(|n| (p, n)))
        .collect();
    let unreadable = s.processes.len() - with.len();
    if with.is_empty() {
        return NamespaceReport {
            unreadable: if s.processes.iter().any(|p| p.ns.is_some()) {
                unreadable
            } else {
                0
            },
            ..Default::default()
        };
    }
    let own = s
        .self_pid
        .and_then(|pid| with.iter().find(|(p, _)| p.id.pid == pid))
        .map(|(_, n)| *n);
    let (reference, reference_source) = match own {
        Some(n) => (n, "oomtop"),
        None => {
            let mut counts: BTreeMap<NsIds, usize> = BTreeMap::new();
            for (_, n) in &with {
                *counts.entry(*n).or_default() += 1;
            }
            let (n, _) = counts
                .into_iter()
                .max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(&a.0)))
                .expect("non-empty");
            (n, "most common set")
        }
    };
    let mut by: BTreeMap<NsIds, Vec<&crate::model::Process>> = BTreeMap::new();
    let mut in_reference = 0;
    for (p, n) in &with {
        if n.differs_from(&reference).is_empty() {
            in_reference += 1;
        } else {
            by.entry(*n).or_default().push(p);
        }
    }
    let mut sets: Vec<NamespaceSet> = by
        .into_iter()
        .map(|(ids, mut ps)| {
            ps.sort_by_key(|p| (p.id.start_time, p.id.pid));
            let pids: HashSet<u32> = ps.iter().map(|p| p.id.pid).collect();
            let root = ps
                .iter()
                .find(|p| p.ppid.is_none_or(|pp| !pids.contains(&pp)))
                .or(ps.first())
                .copied();
            let members: Vec<ProcId> = ps.iter().map(|p| p.id).collect();
            let group = root.and_then(|r| s.group_of(r.id));
            let sandbox_id = s
                .sandboxes
                .iter()
                .find(|sb| sb.host_pids.iter().any(|h| members.contains(h)))
                .map(|sb| sb.id.clone());
            NamespaceSet {
                id: ids.key(),
                differs: ids.differs_from(&reference),
                ids,
                member_count: members.len(),
                mem_total: sum_bytes(
                    ps.iter().map(|p| &p.mem.footprint_or_pss),
                    "ฮฃ member footprint / PSS",
                ),
                root: root.map(|r| r.id),
                label: root.map(|r| r.name.clone()).unwrap_or_default(),
                group: group.map(|g| g.id.clone()),
                owner_group: group.and_then(|g| g.owner_group.clone()),
                sandbox_id,
                members,
            }
        })
        .collect();
    sets.sort_by(|a, b| {
        b.mem_total
            .value
            .unwrap_or(0)
            .cmp(&a.mem_total.value.unwrap_or(0))
            .then(a.id.cmp(&b.id))
    });
    NamespaceReport {
        reference: Some(reference),
        reference_source: reference_source.into(),
        sets,
        in_reference,
        unreadable,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Group, MemBreakdown, Member, Process, Sandbox};

    const HOST: &str = "cgroup:[4026531835]\nipc:[4026531839]\nmnt:[4026531841]\nnet:[4026531840]\npid:[4026531836]\npid_for_children:[4026531836]\ntime:[4026531834]\nuser:[4026531837]\nuts:[4026531838]\n";

    fn ns(text: &str) -> Option<NsIds> {
        Some(parse_ns_links(text))
    }

    fn p(pid: u32, ppid: u32, name: &str, n: Option<NsIds>, mib: u64) -> Process {
        Process {
            id: ProcId::new(pid, pid as u64),
            ppid: Some(ppid),
            name: name.into(),
            ns: n,
            mem: MemBreakdown {
                footprint_or_pss: Measured::exact(mib << 20, "t"),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn parses_links() {
        let n = parse_ns_links(HOST);
        assert_eq!(n.net, Some(4026531840));
        assert_eq!(n.cgroup, Some(4026531835));
        assert_eq!(n.user, Some(4026531837));
        assert_eq!(parse_ns_links("net:[x]\nbogus\nfoo:[1]\n"), NsIds::default());
        assert_eq!(n.key().split(' ').count(), 7);
    }

    #[test]
    fn groups_by_set_relative_to_oomtop() {
        let host = ns(HOST);
        // bwrap sandbox: new pid+net+mnt+user+uts+ipc, same cgroup ns.
        let bwrap_text = HOST
            .replace("pid:[4026531836]", "pid:[4026532300]")
            .replace("net:[4026531840]", "net:[4026532301]")
            .replace("mnt:[4026531841]", "mnt:[4026532302]")
            .replace("user:[4026531837]", "user:[4026532303]");
        let bwrap = ns(&bwrap_text);
        // A container: every namespace new.
        let ctr = ns("cgroup:[1]\nipc:[2]\nmnt:[3]\nnet:[4]\npid:[5]\nuser:[4026531837]\nuts:[7]\n");
        let mut s = Snapshot {
            self_pid: Some(10),
            processes: vec![
                p(1, 0, "systemd", None, 10),
                p(10, 1, "oomtop", host, 30),
                p(20, 1, "bash", host, 5),
                p(30, 20, "bwrap", host, 2),
                p(31, 30, "python3", bwrap, 400),
                p(32, 31, "python3", bwrap, 100),
                p(40, 1, "containerd-shim", host, 10),
                p(41, 40, "nginx", ctr, 50),
            ],
            ..Default::default()
        };
        s.groups.push(Group {
            id: "agent:claude:20".into(),
            members: vec![Member {
                id: ProcId::new(31, 31),
                ..Default::default()
            }],
            owner_group: Some("app:terminal".into()),
            ..Default::default()
        });
        s.sandboxes.push(Sandbox {
            id: "docker:abc".into(),
            host_pids: vec![ProcId::new(41, 41)],
            ..Default::default()
        });
        let r = namespace_sets(&s);
        assert_eq!(r.reference_source, "oomtop");
        assert_eq!(r.in_reference, 4);
        assert_eq!(r.unreadable, 1, "pid 1 (root-owned) is unreadable");
        assert_eq!(r.sets.len(), 2);
        let b = &r.sets[0];
        assert_eq!(b.member_count, 2);
        assert_eq!(b.mem_total.value, Some(500 << 20));
        assert_eq!(b.label, "python3");
        assert_eq!(b.root, Some(ProcId::new(31, 31)));
        assert_eq!(
            b.differs,
            vec![NsKind::Pid, NsKind::Net, NsKind::Mnt, NsKind::User]
        );
        assert_eq!(b.group.as_deref(), Some("agent:claude:20"));
        assert_eq!(b.owner_group.as_deref(), Some("app:terminal"));
        assert_eq!(b.sandbox_id, None, "no engine rule knows it โ€” it still shows up");
        let c = &r.sets[1];
        assert_eq!(c.sandbox_id.as_deref(), Some("docker:abc"));
        assert!(!c.differs.contains(&NsKind::User), "same user ns");
        // Without oomtop in the snapshot (a replay), the most common set is the reference.
        s.self_pid = None;
        let r2 = namespace_sets(&s);
        assert_eq!(r2.reference_source, "most common set");
        assert_eq!(r2.sets.len(), 2);
        // macOS / no data: empty report.
        let r3 = namespace_sets(&Snapshot::default());
        assert!(r3.is_empty());
    }
}