oomtop-cli 0.2.2

oomtop: see the OOM coming. Terminal resource monitor for local AI work.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! `oomtop ports` (SPEC §12.2, §5 "Network"): listening ports → process → group, exposure and stale-helper
//! findings, tunnels, port conflicts and (`--links`) which group talks to which over loopback / unix
//! sockets. Answer first; meaning is in words ("EXPOSED", "idle"), never color alone. Works with
//! `--replay`. Observation only: nothing is connected to, resolved or probed.

use super::table::{pad, rpad, term_width, Ink};
use super::{json_pretty, out, Ctx};
use anyhow::Result;
use oomtop_core::net::{BindScope, FindingKind, Listener, Net, Proto, ServerRole};
use oomtop_core::provider::SnapshotProvider;
use oomtop_core::redact::redact_snapshot;
use oomtop_core::units::format_duration;
use oomtop_core::{Snapshot, SourceStatus};
use serde::Serialize;

#[derive(Serialize)]
struct PortsReport<'a> {
    schema_version: u32,
    taken_at_ms: u64,
    /// Socket source status (`macos.net` / `linux.net`).
    status: Option<(&'a String, &'a SourceStatus)>,
    collected: bool,
    quality: &'a oomtop_core::Quality,
    listeners: Vec<&'a Listener>,
    tunnels: &'a [oomtop_core::net::Tunnel],
    findings: Vec<&'a oomtop_core::net::NetFinding>,
    conflicts: &'a [oomtop_core::net::PortConflict],
    #[serde(skip_serializing_if = "Option::is_none")]
    links: Option<&'a oomtop_core::net::LinkMatrix>,
    clients_connected: &'a std::collections::BTreeMap<String, u32>,
    gaps: &'a [oomtop_core::net::NetGap],
    other_users: u32,
}

fn net_status(s: &Snapshot) -> Option<(&String, &SourceStatus)> {
    s.source_status
        .iter()
        .find(|(k, _)| k.as_str() == "macos.net" || k.as_str() == "linux.net")
}

fn owner_text(l: &Listener) -> String {
    match &l.group_label {
        Some(g) if g != &l.process => format!("{g} · {} {}", l.process, l.owner.pid),
        _ => format!("{} {}", l.process, l.owner.pid),
    }
}

/// Who can reach it, in words: this machine only, the network, or the specific address it is bound to.
fn reach(l: &Listener) -> String {
    match l.scope {
        BindScope::AllInterfaces => "network".into(),
        BindScope::Loopback => "this machine".into(),
        BindScope::Specific => l.addrs.join(", "),
    }
}

fn shown(net: &Net, exposed_only: bool) -> Vec<&Listener> {
    net.listeners
        .iter()
        .filter(|l| l.proto != Proto::Unix)
        .filter(|l| !exposed_only || l.scope == BindScope::AllInterfaces)
        .collect()
}

pub fn run(ctx: &Ctx, json: bool, exposed: bool, links: bool) -> Result<i32> {
    let mut e = ctx.engine(true)?;
    let snap = e.snapshot();
    let s = if json && ctx.config().privacy.redact_exports {
        redact_snapshot(&snap)
    } else {
        snap
    };
    let net = &s.net;
    if json {
        // JSON keeps unix listeners too (the plain table shows TCP/UDP only).
        let listeners: Vec<&Listener> = net
            .listeners
            .iter()
            .filter(|l| !exposed || l.scope == BindScope::AllInterfaces)
            .collect();
        let report = PortsReport {
            schema_version: oomtop_core::SCHEMA_VERSION,
            taken_at_ms: s.taken_at_ms,
            status: net_status(&s),
            collected: net.collected,
            quality: &net.quality,
            listeners,
            tunnels: &net.tunnels,
            findings: net
                .findings
                .iter()
                .filter(|f| !exposed || f.kind == FindingKind::Exposed)
                .collect(),
            conflicts: &net.conflicts,
            links: links.then_some(&net.links),
            clients_connected: &net.clients_connected,
            gaps: &net.gaps,
            other_users: net.other_users,
        };
        out(&json_pretty(&report)?);
        return Ok(0);
    }
    out(&render(&s, exposed, links));
    Ok(0)
}

/// Plain text, answer first (pure, for tests).
fn render(s: &Snapshot, exposed: bool, links: bool) -> String {
    let net = &s.net;
    let mut o = String::new();
    if !net.collected {
        let why = match net_status(s) {
            Some((_, SourceStatus::Unavailable(r))) | Some((_, SourceStatus::Partial(r))) => r.clone(),
            _ => "no socket source in this sample (a fixture recorded before sockets were collected?)".into(),
        };
        o.push_str(&format!("Ports: not available: {why}\n"));
        return o;
    }
    let ink = Ink::detect();
    let mut listeners = shown(net, exposed);
    listeners.sort_by_key(|l| l.display_rank());
    let n_links: u32 = net.links.links.iter().map(|l| l.connections).sum();
    let tcp = listeners.iter().filter(|l| l.proto == Proto::Tcp).count();
    let udp = listeners.len() - tcp;
    let ports_word = |n: usize| if n == 1 { "port" } else { "ports" };

    // Answer first: is anything of yours reachable from the network?
    let exposed_findings: Vec<_> = net
        .findings
        .iter()
        .filter(|f| f.kind == FindingKind::Exposed)
        .collect();
    if exposed_findings.is_empty() {
        let mut line = format!("{tcp} {} listening", ports_word(tcp));
        if udp > 0 {
            line.push_str(&format!(" (+{udp} udp)"));
        }
        line.push_str(". No dev server, model server or container is reachable from your network.");
        o.push_str(&format!("{}\n", ink.bold(&line)));
        // Others open to the network (AirPlay receivers, OS services): named, not alarming.
        let mut others: Vec<String> = Vec::new();
        for l in listeners.iter().filter(|l| l.scope == BindScope::AllInterfaces) {
            let who = l.group_label.clone().unwrap_or_else(|| l.process.clone());
            if !others.contains(&who) {
                others.push(who);
            }
        }
        let n_open = listeners
            .iter()
            .filter(|l| l.scope == BindScope::AllInterfaces)
            .count();
        if n_open > 0 {
            o.push_str(&format!(
                "{} {} open to the network, held by {}.\n",
                n_open,
                if n_open == 1 { "port is" } else { "ports are" },
                match others.len() {
                    1 => others[0].clone(),
                    n => format!("{} and {}", others[..n - 1].join(", "), others[n - 1]),
                }
            ));
        }
    } else {
        let n = exposed_findings.len();
        o.push_str(&format!(
            "{}\n",
            ink.bold(&format!(
                "{n} of your {} reachable from your network.",
                if n == 1 { "servers is" } else { "servers are" }
            ))
        ));
    }
    // Findings: what to do about it, one line each.
    for f in net
        .findings
        .iter()
        .filter(|f| !exposed || f.kind == FindingKind::Exposed)
    {
        let tag = match f.kind {
            FindingKind::Exposed => "EXPOSED",
            FindingKind::IdleListener => "idle",
            FindingKind::StaleTunnel => "stale tunnel",
            FindingKind::PublicTunnel => "public tunnel",
            FindingKind::PortConflict => "conflict",
        };
        o.push_str(&format!("  {}: {}", ink.bold(tag), f.sentence));
        if let Some(fix) = &f.fix {
            o.push_str(&format!(" Fix: {fix}."));
        }
        o.push('\n');
    }

    if !listeners.is_empty() {
        let show_role = listeners.iter().any(|l| l.role != ServerRole::Other);
        let port_txt = |l: &Listener| {
            if l.proto == Proto::Udp {
                format!("{}/udp", l.port)
            } else {
                l.port.to_string()
            }
        };
        let port_w = listeners
            .iter()
            .map(|l| port_txt(l).len())
            .max()
            .unwrap_or(4)
            .max(4);
        let reach_w = listeners
            .iter()
            .map(|l| reach(l).chars().count())
            .max()
            .unwrap_or(5)
            .max(5);
        let role_w = if show_role {
            listeners
                .iter()
                .map(|l| l.role.as_str().len())
                .max()
                .unwrap_or(4)
                .max(4)
                + 2
        } else {
            0
        };
        // OWNER takes what the other columns leave.
        let fixed = 2 + port_w + 2 + reach_w + 2 + 7 + 2 + 6 + 2 + role_w;
        let longest = listeners
            .iter()
            .map(|l| owner_text(l).chars().count() + if l.published.is_some() { 18 } else { 0 })
            .max()
            .unwrap_or(5);
        let owner_w = longest.max(5).min(term_width().saturating_sub(fixed).max(16));
        o.push('\n');
        let mut head = format!(
            "  {}  {}  {}  {}  {}",
            pad("PORT", port_w),
            pad("OWNER", owner_w),
            pad("REACH", reach_w),
            rpad("CLIENTS", 7),
            rpad("UP", 6)
        );
        if show_role {
            head.push_str(&format!("  {}", "ROLE"));
        }
        o.push_str(&format!("{}\n", ink.dim(head.trim_end())));
        for l in &listeners {
            let clients = match (l.clients.value, &l.clients.quality) {
                (Some(n), oomtop_core::Quality::Estimate) => format!("~{n}"),
                (Some(n), _) => n.to_string(),
                (None, _) => "n/a".into(),
            };
            let age = l.age_s.value.map(format_duration).unwrap_or_else(|| "n/a".into());
            let mut owner = owner_text(l);
            if let Some(p) = &l.published {
                if let Some(cp) = p.container_port {
                    owner.push_str(&format!(" → container :{cp}"));
                }
            }
            let mut row = format!(
                "  {}  {}  {}  {}  {}",
                pad(&port_txt(l), port_w),
                pad(&owner, owner_w),
                pad(&reach(l), reach_w),
                rpad(&clients, 7),
                rpad(&age, 6)
            );
            if show_role && l.role != ServerRole::Other {
                row.push_str(&format!("  {}", l.role.as_str()));
            }
            let row = row.trim_end().to_string();
            o.push_str(&format!(
                "{}\n",
                if l.is_exposed_server() {
                    ink.bold(&row)
                } else {
                    row
                }
            ));
        }
    }
    if !links && n_links > 0 {
        o.push_str(&format!(
            "\n{}\n",
            ink.dim(&format!(
                "  {n_links} local {} between groups: oomtop ports --links",
                if n_links == 1 { "connection" } else { "connections" }
            ))
        ));
    }
    // Tunnels not already a row above (no local listening port of their own, e.g. ssh -R or a cloud tunnel).
    let in_table = |t: &&oomtop_core::net::Tunnel| {
        t.listen_ports
            .iter()
            .any(|p| listeners.iter().any(|l| l.port == *p))
    };
    let extra: Vec<_> = net.tunnels.iter().filter(|t| !in_table(t)).collect();
    if !extra.is_empty() && !exposed {
        o.push_str("\nTunnels and port forwards\n");
        for t in extra {
            let ports = if t.listen_ports.is_empty() {
                String::new()
            } else {
                format!(
                    " on {}",
                    t.listen_ports
                        .iter()
                        .map(|p| format!(":{p}"))
                        .collect::<Vec<_>>()
                        .join(" ")
                )
            };
            let clients = match t.clients.value {
                Some(n) => format!("{n} clients"),
                None => "clients not visible".into(),
            };
            o.push_str(&format!(
                "  {}{} ({} {}), open {}, {}{}\n",
                t.kind.as_str(),
                ports,
                t.process,
                t.owner.pid,
                t.age_s.value.map(format_duration).unwrap_or_else(|| "n/a".into()),
                clients,
                if t.stale { ", stale" } else { "" }
            ));
        }
    }
    if links {
        let m = &net.links;
        o.push('\n');
        if m.links.is_empty() {
            o.push_str("No local connections between groups.\n");
        } else {
            o.push_str("Who talks to whom (client group → server group)\n");
            for l in &m.links {
                let via = match (l.via, l.port, &l.path) {
                    (Proto::Unix, _, Some(p)) => format!("unix {p}"),
                    (_, Some(p), _) => format!("tcp :{p}"),
                    _ => l.via.as_str().to_string(),
                };
                o.push_str(&format!(
                    "  {} → {}  via {via}  ({} {})\n",
                    m.clients[l.client].label,
                    m.servers[l.server].label,
                    l.connections,
                    if l.connections == 1 {
                        "connection"
                    } else {
                        "connections"
                    }
                ));
            }
        }
        if !net.unix_peers {
            o.push_str("  (unix-socket peers are not visible on this OS: TCP loopback links only)\n");
        }
    }
    // What was not seen, and why.
    let mut notes: Vec<String> = Vec::new();
    if let Some((name, SourceStatus::Partial(r))) = net_status(s) {
        notes.push(format!("{name}: {r}"));
    }
    if net.other_users > 0 {
        notes.push(format!(
            "ports of {} other users' processes (needs root)",
            net.other_users
        ));
    }
    if !net.gaps.is_empty() {
        let netns = net.gaps.iter().filter(|g| g.reason.contains("namespace")).count();
        if netns > 0 {
            notes.push(format!(
                "{netns} processes in another network namespace (not listed)"
            ));
        }
        let other = net.gaps.len() - netns;
        if other > 0 {
            notes.push(format!("{other} processes could not be read"));
        }
    }
    let unix = net.listeners.iter().filter(|l| l.proto == Proto::Unix).count();
    if unix > 0 && !exposed {
        notes.push(format!(
            "{unix} unix {} (oomtop ports --json)",
            if unix == 1 { "socket" } else { "sockets" }
        ));
    }
    if !notes.is_empty() {
        o.push('\n');
        for n in notes {
            o.push_str(&format!("{}\n", ink.dim(&format!("  not shown: {n}"))));
        }
    }
    o
}

#[cfg(test)]
mod tests {
    use super::*;
    use oomtop_core::net::{AddrClass, Endpoint, SockState, Socket};
    use oomtop_core::{Group, GroupKind, Member, ProcId, Process, Quality};

    fn snap() -> Snapshot {
        let now = 1_700_010_000_000u64;
        let p = Process {
            id: ProcId::new(100, now - 7_200_000),
            name: "node".into(),
            cmdline: vec!["node".into(), "vite".into()],
            ..Default::default()
        };
        let mut s = Snapshot {
            taken_at_ms: now,
            ..Default::default()
        };
        s.groups = vec![Group {
            id: "other:vite:100".into(),
            kind: GroupKind::Other,
            label: "vite".into(),
            members: vec![Member {
                id: p.id,
                ..Default::default()
            }],
            ..Default::default()
        }];
        s.net.collected = true;
        s.net.quality = Quality::Exact;
        s.net.sockets = vec![Socket {
            owner: p.id,
            proto: Proto::Tcp,
            state: SockState::Listen,
            local: Some(Endpoint {
                addr: "0.0.0.0".into(),
                port: 5173,
                class: AddrClass::Any,
            }),
            ..Default::default()
        }];
        s.processes = vec![p];
        oomtop_core::net::analyze(&mut s);
        s
    }

    #[test]
    fn plain_output_is_answer_first_and_says_exposed_in_words() {
        // (render() only adds bold on a terminal; tests run without one)
        let text = render(&snap(), false, true);
        let first = text.lines().next().unwrap();
        assert_eq!(first, "1 of your servers is reachable from your network.");
        assert!(
            text.contains("EXPOSED: A dev server vite listens on all interfaces"),
            "{text}"
        );
        assert!(text.contains("Fix: bind 127.0.0.1"), "{text}");
        let row = text
            .lines()
            .find(|l| l.trim_start().starts_with("5173"))
            .unwrap_or_default();
        assert!(row.contains("network") && row.contains("dev server"), "{text}");
        assert!(text.contains("No local connections between groups."), "{text}");
    }

    #[test]
    fn not_collected_says_why() {
        let mut s = Snapshot::default();
        s.source_status.insert(
            "linux.net".into(),
            SourceStatus::Unavailable("/proc/net not readable".into()),
        );
        assert_eq!(
            render(&s, false, false),
            "Ports: not available: /proc/net not readable\n"
        );
    }
}