oomtop-cli 0.2.1

oomtop: see the OOM coming. Terminal resource monitor for local AI work.
Documentation
//! `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::{json_pretty, out, Ctx};
use anyhow::Result;
use oomtop_core::net::{BindScope, FindingKind, Listener, Net, Proto};
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),
    }
}

fn scope_word(l: &Listener) -> &'static str {
    match l.scope {
        BindScope::AllInterfaces => "all",
        BindScope::Loopback => "loopback",
        BindScope::Specific => "specific",
    }
}

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 listeners = shown(net, exposed);
    let n_exposed = net
        .findings
        .iter()
        .filter(|f| f.kind == FindingKind::Exposed)
        .count();
    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;
    // Answer first.
    o.push_str(&format!(
        "{} listening {}{} · {} exposed on all interfaces · {} local {} between groups\n",
        tcp,
        if tcp == 1 { "port" } else { "ports" },
        if udp > 0 {
            format!(" (+{udp} udp)")
        } else {
            String::new()
        },
        if n_exposed == 0 {
            "none".to_string()
        } else {
            n_exposed.to_string()
        },
        n_links,
        if n_links == 1 { "connection" } else { "connections" },
    ));
    let findings: Vec<_> = net
        .findings
        .iter()
        .filter(|f| !exposed || f.kind == FindingKind::Exposed)
        .collect();
    for f in &findings {
        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!("  {tag}: {}", f.sentence));
        if let Some(fix) = &f.fix {
            o.push_str(&format!(" Fix: {fix}."));
        }
        o.push('\n');
    }
    if !listeners.is_empty() {
        o.push('\n');
        o.push_str(&format!(
            "{:<5} {:>5}  {:<22} {:<9} {:>7}  {:>6}  {:<13} {}\n",
            "PROTO", "PORT", "BIND", "SCOPE", "CLIENTS", "AGE", "ROLE", "OWNER"
        ));
        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 bind = l.addrs.join(", ");
            if bind.len() > 22 {
                bind.truncate(21);
                bind.push('…');
            }
            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}"));
                }
            }
            o.push_str(&format!(
                "{:<5} {:>5}  {:<22} {:<9} {:>7}  {:>6}  {:<13} {}\n",
                l.proto.as_str(),
                l.port,
                bind,
                scope_word(l),
                clients,
                age,
                l.role.as_str(),
                owner
            ));
        }
    }
    if !net.tunnels.is_empty() && !exposed {
        o.push_str("\nTunnels and port forwards\n");
        for t in &net.tunnels {
            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!(
            "{} other users' processes not readable without root (their ports are not listed)",
            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 {} listening (see --json)",
            if unix == 1 { "socket" } else { "sockets" }
        ));
    }
    if !notes.is_empty() {
        o.push('\n');
        for n in notes {
            o.push_str(&format!("note: {n}\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() {
        let text = render(&snap(), false, true);
        let first = text.lines().next().unwrap();
        assert_eq!(
            first,
            "1 listening port · 1 exposed on all interfaces · 0 local connections between groups"
        );
        assert!(
            text.contains("EXPOSED: A dev server vite listens on all interfaces"),
            "{text}"
        );
        assert!(text.contains("Fix: bind 127.0.0.1"), "{text}");
        assert!(text.contains("tcp    5173  0.0.0.0"), "{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"
        );
    }
}