Skip to main content

oomtop_core/
namespaces.rs

1//! Linux namespace sets (SPEC §11 "Namespaces"): processes grouped by the namespaces they live in,
2//! relative to oomtop's own. Any process that does not share oomtop's pid / net / mount / user / uts / ipc
3//! / cgroup namespaces is in some kind of sandbox — a container, `bwrap`/Flatpak, `unshare`, a browser
4//! renderer sandbox — so a sandbox that no engine rule knows still shows up, with its member count, memory
5//! and owner. Identities are the inode numbers of the `/proc/<pid>/ns/*` links (`net:[4026531840]`),
6//! readable for the user's own processes without privileges. macOS has no namespaces.
7
8use crate::measured::sum_bytes;
9use crate::model::{Measured, ProcId, Snapshot};
10use serde::{Deserialize, Serialize};
11use std::collections::{BTreeMap, HashSet};
12
13/// One namespace type.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum NsKind {
17    Pid,
18    Net,
19    Mnt,
20    User,
21    Uts,
22    Ipc,
23    Cgroup,
24}
25
26impl NsKind {
27    pub const ALL: [NsKind; 7] = [
28        NsKind::Pid,
29        NsKind::Net,
30        NsKind::Mnt,
31        NsKind::User,
32        NsKind::Uts,
33        NsKind::Ipc,
34        NsKind::Cgroup,
35    ];
36
37    /// The `/proc/<pid>/ns/<name>` link name.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            NsKind::Pid => "pid",
41            NsKind::Net => "net",
42            NsKind::Mnt => "mnt",
43            NsKind::User => "user",
44            NsKind::Uts => "uts",
45            NsKind::Ipc => "ipc",
46            NsKind::Cgroup => "cgroup",
47        }
48    }
49
50    pub fn parse(s: &str) -> Option<NsKind> {
51        NsKind::ALL.into_iter().find(|k| k.as_str() == s)
52    }
53}
54
55/// Namespace identities of one process (`None` = link not readable / not present on this kernel).
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
57#[serde(default)]
58pub struct NsIds {
59    pub pid: Option<u64>,
60    pub net: Option<u64>,
61    pub mnt: Option<u64>,
62    pub user: Option<u64>,
63    pub uts: Option<u64>,
64    pub ipc: Option<u64>,
65    pub cgroup: Option<u64>,
66}
67
68impl NsIds {
69    pub fn get(&self, k: NsKind) -> Option<u64> {
70        match k {
71            NsKind::Pid => self.pid,
72            NsKind::Net => self.net,
73            NsKind::Mnt => self.mnt,
74            NsKind::User => self.user,
75            NsKind::Uts => self.uts,
76            NsKind::Ipc => self.ipc,
77            NsKind::Cgroup => self.cgroup,
78        }
79    }
80
81    pub fn set(&mut self, k: NsKind, v: Option<u64>) {
82        match k {
83            NsKind::Pid => self.pid = v,
84            NsKind::Net => self.net = v,
85            NsKind::Mnt => self.mnt = v,
86            NsKind::User => self.user = v,
87            NsKind::Uts => self.uts = v,
88            NsKind::Ipc => self.ipc = v,
89            NsKind::Cgroup => self.cgroup = v,
90        }
91    }
92
93    pub fn is_empty(&self) -> bool {
94        NsKind::ALL.iter().all(|k| self.get(*k).is_none())
95    }
96
97    /// Kinds known on both sides and different.
98    pub fn differs_from(&self, other: &NsIds) -> Vec<NsKind> {
99        NsKind::ALL
100            .into_iter()
101            .filter(|k| matches!((self.get(*k), other.get(*k)), (Some(a), Some(b)) if a != b))
102            .collect()
103    }
104
105    /// `pid:4026531836 net:…` (known kinds only), the set's stable key.
106    pub fn key(&self) -> String {
107        NsKind::ALL
108            .iter()
109            .filter_map(|k| self.get(*k).map(|v| format!("{}:{v}", k.as_str())))
110            .collect::<Vec<_>>()
111            .join(" ")
112    }
113}
114
115/// Parses `readlink /proc/<pid>/ns/*` targets, one per line (`net:[4026531840]`); `pid_for_children` and
116/// `time*` links and malformed lines are ignored.
117pub fn parse_ns_links(text: &str) -> NsIds {
118    let mut ids = NsIds::default();
119    for line in text.lines() {
120        let Some((name, rest)) = line.trim().split_once(':') else {
121            continue;
122        };
123        let Some(k) = NsKind::parse(name) else {
124            continue;
125        };
126        let v = rest
127            .strip_prefix('[')
128            .and_then(|r| r.strip_suffix(']'))
129            .and_then(|n| n.parse::<u64>().ok());
130        if v.is_some() {
131            ids.set(k, v);
132        }
133    }
134    ids
135}
136
137/// Processes sharing one namespace set that differs from oomtop's.
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
139#[serde(default)]
140pub struct NamespaceSet {
141    /// [`NsIds::key`] of the set.
142    pub id: String,
143    pub ids: NsIds,
144    /// Which namespaces differ from the reference (oomtop's own).
145    pub differs: Vec<NsKind>,
146    pub members: Vec<ProcId>,
147    pub member_count: usize,
148    /// Σ footprint / PSS of the members.
149    pub mem_total: Measured<u64>,
150    /// The member whose parent is outside the set (the sandbox's entry point), else the oldest member.
151    pub root: Option<ProcId>,
152    /// Name of the root process.
153    pub label: String,
154    /// Group of the root process, and that group's owner (who started the sandbox).
155    pub group: Option<String>,
156    pub owner_group: Option<String>,
157    /// Sandbox whose host pids overlap the members (engine/rule detection), if any.
158    pub sandbox_id: Option<String>,
159}
160
161/// All namespace sets of a snapshot.
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
163#[serde(default)]
164pub struct NamespaceReport {
165    /// The reference set: oomtop's own namespaces, else the most common set (a replay without oomtop).
166    pub reference: Option<NsIds>,
167    /// "oomtop" | "most common set".
168    pub reference_source: String,
169    /// Sets differing from the reference, largest memory first.
170    pub sets: Vec<NamespaceSet>,
171    /// Processes in the reference set.
172    pub in_reference: usize,
173    /// Processes whose namespaces could not be read (other users' processes need root).
174    pub unreadable: usize,
175}
176
177impl NamespaceReport {
178    pub fn is_empty(&self) -> bool {
179        self.reference.is_none() && self.sets.is_empty() && self.unreadable == 0
180    }
181}
182
183/// Groups `s.processes` by namespace set relative to oomtop's own (`s.self_pid`).
184pub fn namespace_sets(s: &Snapshot) -> NamespaceReport {
185    let with: Vec<(&crate::model::Process, NsIds)> = s
186        .processes
187        .iter()
188        .filter_map(|p| p.ns.filter(|n| !n.is_empty()).map(|n| (p, n)))
189        .collect();
190    let unreadable = s.processes.len() - with.len();
191    if with.is_empty() {
192        return NamespaceReport {
193            unreadable: if s.processes.iter().any(|p| p.ns.is_some()) {
194                unreadable
195            } else {
196                0
197            },
198            ..Default::default()
199        };
200    }
201    let own = s
202        .self_pid
203        .and_then(|pid| with.iter().find(|(p, _)| p.id.pid == pid))
204        .map(|(_, n)| *n);
205    let (reference, reference_source) = match own {
206        Some(n) => (n, "oomtop"),
207        None => {
208            let mut counts: BTreeMap<NsIds, usize> = BTreeMap::new();
209            for (_, n) in &with {
210                *counts.entry(*n).or_default() += 1;
211            }
212            let (n, _) = counts
213                .into_iter()
214                .max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(&a.0)))
215                .expect("non-empty");
216            (n, "most common set")
217        }
218    };
219    let mut by: BTreeMap<NsIds, Vec<&crate::model::Process>> = BTreeMap::new();
220    let mut in_reference = 0;
221    for (p, n) in &with {
222        if n.differs_from(&reference).is_empty() {
223            in_reference += 1;
224        } else {
225            by.entry(*n).or_default().push(p);
226        }
227    }
228    let mut sets: Vec<NamespaceSet> = by
229        .into_iter()
230        .map(|(ids, mut ps)| {
231            ps.sort_by_key(|p| (p.id.start_time, p.id.pid));
232            let pids: HashSet<u32> = ps.iter().map(|p| p.id.pid).collect();
233            let root = ps
234                .iter()
235                .find(|p| p.ppid.is_none_or(|pp| !pids.contains(&pp)))
236                .or(ps.first())
237                .copied();
238            let members: Vec<ProcId> = ps.iter().map(|p| p.id).collect();
239            let group = root.and_then(|r| s.group_of(r.id));
240            let sandbox_id = s
241                .sandboxes
242                .iter()
243                .find(|sb| sb.host_pids.iter().any(|h| members.contains(h)))
244                .map(|sb| sb.id.clone());
245            NamespaceSet {
246                id: ids.key(),
247                differs: ids.differs_from(&reference),
248                ids,
249                member_count: members.len(),
250                mem_total: sum_bytes(
251                    ps.iter().map(|p| &p.mem.footprint_or_pss),
252                    "Σ member footprint / PSS",
253                ),
254                root: root.map(|r| r.id),
255                label: root.map(|r| r.name.clone()).unwrap_or_default(),
256                group: group.map(|g| g.id.clone()),
257                owner_group: group.and_then(|g| g.owner_group.clone()),
258                sandbox_id,
259                members,
260            }
261        })
262        .collect();
263    sets.sort_by(|a, b| {
264        b.mem_total
265            .value
266            .unwrap_or(0)
267            .cmp(&a.mem_total.value.unwrap_or(0))
268            .then(a.id.cmp(&b.id))
269    });
270    NamespaceReport {
271        reference: Some(reference),
272        reference_source: reference_source.into(),
273        sets,
274        in_reference,
275        unreadable,
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use crate::model::{Group, MemBreakdown, Member, Process, Sandbox};
283
284    const HOST: &str = "cgroup:[4026531835]\nipc:[4026531839]\nmnt:[4026531841]\nnet:[4026531840]\npid:[4026531836]\npid_for_children:[4026531836]\ntime:[4026531834]\nuser:[4026531837]\nuts:[4026531838]\n";
285
286    fn ns(text: &str) -> Option<NsIds> {
287        Some(parse_ns_links(text))
288    }
289
290    fn p(pid: u32, ppid: u32, name: &str, n: Option<NsIds>, mib: u64) -> Process {
291        Process {
292            id: ProcId::new(pid, pid as u64),
293            ppid: Some(ppid),
294            name: name.into(),
295            ns: n,
296            mem: MemBreakdown {
297                footprint_or_pss: Measured::exact(mib << 20, "t"),
298                ..Default::default()
299            },
300            ..Default::default()
301        }
302    }
303
304    #[test]
305    fn parses_links() {
306        let n = parse_ns_links(HOST);
307        assert_eq!(n.net, Some(4026531840));
308        assert_eq!(n.cgroup, Some(4026531835));
309        assert_eq!(n.user, Some(4026531837));
310        assert_eq!(parse_ns_links("net:[x]\nbogus\nfoo:[1]\n"), NsIds::default());
311        assert_eq!(n.key().split(' ').count(), 7);
312    }
313
314    #[test]
315    fn groups_by_set_relative_to_oomtop() {
316        let host = ns(HOST);
317        // bwrap sandbox: new pid+net+mnt+user+uts+ipc, same cgroup ns.
318        let bwrap_text = HOST
319            .replace("pid:[4026531836]", "pid:[4026532300]")
320            .replace("net:[4026531840]", "net:[4026532301]")
321            .replace("mnt:[4026531841]", "mnt:[4026532302]")
322            .replace("user:[4026531837]", "user:[4026532303]");
323        let bwrap = ns(&bwrap_text);
324        // A container: every namespace new.
325        let ctr = ns("cgroup:[1]\nipc:[2]\nmnt:[3]\nnet:[4]\npid:[5]\nuser:[4026531837]\nuts:[7]\n");
326        let mut s = Snapshot {
327            self_pid: Some(10),
328            processes: vec![
329                p(1, 0, "systemd", None, 10),
330                p(10, 1, "oomtop", host, 30),
331                p(20, 1, "bash", host, 5),
332                p(30, 20, "bwrap", host, 2),
333                p(31, 30, "python3", bwrap, 400),
334                p(32, 31, "python3", bwrap, 100),
335                p(40, 1, "containerd-shim", host, 10),
336                p(41, 40, "nginx", ctr, 50),
337            ],
338            ..Default::default()
339        };
340        s.groups.push(Group {
341            id: "agent:claude:20".into(),
342            members: vec![Member {
343                id: ProcId::new(31, 31),
344                ..Default::default()
345            }],
346            owner_group: Some("app:terminal".into()),
347            ..Default::default()
348        });
349        s.sandboxes.push(Sandbox {
350            id: "docker:abc".into(),
351            host_pids: vec![ProcId::new(41, 41)],
352            ..Default::default()
353        });
354        let r = namespace_sets(&s);
355        assert_eq!(r.reference_source, "oomtop");
356        assert_eq!(r.in_reference, 4);
357        assert_eq!(r.unreadable, 1, "pid 1 (root-owned) is unreadable");
358        assert_eq!(r.sets.len(), 2);
359        let b = &r.sets[0];
360        assert_eq!(b.member_count, 2);
361        assert_eq!(b.mem_total.value, Some(500 << 20));
362        assert_eq!(b.label, "python3");
363        assert_eq!(b.root, Some(ProcId::new(31, 31)));
364        assert_eq!(
365            b.differs,
366            vec![NsKind::Pid, NsKind::Net, NsKind::Mnt, NsKind::User]
367        );
368        assert_eq!(b.group.as_deref(), Some("agent:claude:20"));
369        assert_eq!(b.owner_group.as_deref(), Some("app:terminal"));
370        assert_eq!(b.sandbox_id, None, "no engine rule knows it — it still shows up");
371        let c = &r.sets[1];
372        assert_eq!(c.sandbox_id.as_deref(), Some("docker:abc"));
373        assert!(!c.differs.contains(&NsKind::User), "same user ns");
374        // Without oomtop in the snapshot (a replay), the most common set is the reference.
375        s.self_pid = None;
376        let r2 = namespace_sets(&s);
377        assert_eq!(r2.reference_source, "most common set");
378        assert_eq!(r2.sets.len(), 2);
379        // macOS / no data: empty report.
380        let r3 = namespace_sets(&Snapshot::default());
381        assert!(r3.is_empty());
382    }
383}