proc-cli 2.0.2

Semantic CLI tool for process management. Target by port, PID, name or path.
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
//! `proc why` - Explain why a port is busy or trace process ancestry
//!
//! Examples:
//!   proc why :3000              # Why is port 3000 busy? (ancestry + port context)
//!   proc why node               # Show ancestry for the processes named node
//!   proc why node --cmd         # ... or with node anywhere in their command line
//!   proc why 1234               # Show ancestry for PID 1234
//!   proc why :3000 :8080        # Several targets: separate arguments
//!   proc why :3000 --json       # JSON output with port context
//!
//! Commas still work (`proc why :3000,:8080`) but are deprecated.

use crate::core::{
    flatten_targets, parse_target, resolve_target, NameMatch, PortInfo, Process, ProcessStatus,
    Protocol, TargetType,
};
use crate::error::{ExitCode, ProcError, Result};
use crate::out_println;
use crate::ui::{uptime_label, Printer};
use clap::Args;
use colored::*;
use serde::Serialize;
use std::collections::HashMap;

/// Trace why a port is busy or show process ancestry
#[derive(Args, Debug)]
pub struct WhyCommand {
    /// Target(s): :port, PID, or process name (separate arguments for several)
    #[arg(required = true, num_args = 1.., value_parser = crate::core::validate_target_arg)]
    pub target: Vec<String>,

    /// Match name targets as a substring of the process name or full command line (like pkill -f)
    #[arg(long)]
    pub cmd: bool,

    /// Output as JSON
    #[arg(long, short = 'j')]
    pub json: bool,

    /// Show verbose output
    #[arg(long, short = 'v')]
    pub verbose: bool,
}

impl WhyCommand {
    /// Executes the why command, showing ancestry and port context.
    pub fn execute(&self) -> Result<()> {
        let printer = Printer::from_flags(self.json, self.verbose);

        let all_processes = Process::find_all()?;
        let pid_map: HashMap<u32, &Process> = all_processes.iter().map(|p| (p.pid, p)).collect();

        let targets = flatten_targets(&self.target);
        let mode = NameMatch::from_flag(self.cmd);

        // JSON results are collected across targets and printed as one document
        let mut json_results: Vec<WhyOutput> = Vec::new();
        let mut found_any = false;
        let mut first_error: Option<ProcError> = None;
        let mut not_found: Vec<String> = Vec::new();
        // Read once for every process shown (see `with_ports`)
        let listening = std::cell::OnceCell::new();

        for (i, target_str) in targets.iter().enumerate() {
            if i > 0 && !self.json {
                out_println!();
            }

            let parsed = parse_target(target_str);

            // Collect port context for port targets; every holder of the port is
            // traced below, the context is the port they share
            let port_context: Option<PortInfo> = if let TargetType::Port(port) = &parsed {
                PortInfo::holders_of(*port)
                    .ok()
                    .and_then(|holders| holders.into_iter().next())
            } else {
                None
            };

            // Resolve to processes
            let target_processes = match found_processes(target_str, |t| resolve_target(t, mode)) {
                Ok(procs) => procs,
                Err((error, warning)) => {
                    printer.warning(&warning);
                    first_error.get_or_insert(error);
                    not_found.push(target_str.clone());
                    continue;
                }
            };
            found_any = true;

            if self.json {
                json_results.extend(target_processes.iter().map(|proc| {
                    let chain = self.build_ancestry_chain(proc, &pid_map);
                    let ports = listening
                        .get_or_init(|| PortInfo::get_all_listening().unwrap_or_default())
                        .iter()
                        .filter(|p| p.pid == proc.pid)
                        .cloned()
                        .collect();
                    WhyOutput {
                        target: target_str.clone(),
                        port: port_context.as_ref().map(|p| p.port),
                        protocol: port_context.as_ref().map(|p| p.protocol),
                        process: WhyProcessInfo {
                            pid: proc.pid,
                            name: proc.name.clone(),
                            command: proc.command.clone(),
                            cwd: proc.cwd.clone(),
                            status: proc.status,
                            uptime_secs: proc.uptime_secs,
                        },
                        ports,
                        ancestry: chain,
                    }
                }));
            } else {
                // Print port header if applicable
                if let Some(ref port_info) = port_context {
                    out_println!(
                        "{} Port {} ({}):",
                        "✓".green().bold(),
                        port_info.port.to_string().cyan().bold(),
                        format!("{:?}", port_info.protocol).to_uppercase()
                    );
                } else {
                    out_println!(
                        "{} Ancestry for '{}':",
                        "✓".green().bold(),
                        target_str.cyan()
                    );
                }
                out_println!();

                for proc in &target_processes {
                    self.print_ancestry_with_context(proc, &pid_map);
                    out_println!();
                }
            }
        }

        if !found_any {
            let error =
                first_error.unwrap_or_else(|| ProcError::ProcessNotFound(self.target.join(" ")));
            if self.json {
                return Err(error);
            }
            // Humans already saw a warning per target
            return Err(ProcError::reported(
                ExitCode::from(&error),
                error.to_string(),
            ));
        }

        if self.json {
            printer.print_json(&WhyEnvelope {
                action: "why",
                success: true,
                count: json_results.len(),
                not_found,
                results: json_results,
            });
        }

        Ok(())
    }

    /// Build the ancestor chain from root down to target
    fn build_ancestry_chain(
        &self,
        target: &Process,
        pid_map: &HashMap<u32, &Process>,
    ) -> Vec<AncestryEntry> {
        ancestor_chain(target, pid_map)
            .into_iter()
            .map(|proc| AncestryEntry {
                pid: proc.pid,
                name: proc.name.clone(),
                command: proc.command.clone(),
                cwd: proc.cwd.clone(),
                status: proc.status,
                uptime_secs: proc.uptime_secs,
                is_target: proc.pid == target.pid,
            })
            .collect()
    }

    /// Print ancestry tree with working directory and command context
    fn print_ancestry_with_context(&self, target: &Process, pid_map: &HashMap<u32, &Process>) {
        let chain = ancestor_chain(target, pid_map);

        for (i, proc) in chain.iter().enumerate() {
            let is_target = proc.pid == target.pid;
            let indent = "    ".repeat(i);
            let connector = if i == 0 { "" } else { "└── " };

            let symbol = status_indicator(proc.status);

            // Build the command summary (skip exe name, show args)
            let cmd_summary = proc
                .command
                .as_ref()
                .and_then(|c| {
                    let parts: Vec<&str> = c.split_whitespace().collect();
                    if parts.len() > 1 {
                        Some(parts[1..].join(" "))
                    } else {
                        None
                    }
                })
                .unwrap_or_default();

            if is_target {
                let cmd_part = if cmd_summary.is_empty() {
                    String::new()
                } else {
                    format!(" {}", cmd_summary)
                };
                out_println!(
                    "{}{}{} {} [{}]{}{}  {}",
                    indent.bright_black(),
                    connector.bright_black(),
                    symbol,
                    proc.name.cyan().bold(),
                    proc.pid.to_string().cyan().bold(),
                    cmd_part,
                    uptime_label(proc.uptime_secs).bright_black(),
                    "← target".yellow()
                );
                // Show working directory for the target
                if let Some(ref cwd) = proc.cwd {
                    let dir_indent = "    ".repeat(i + 1);
                    out_println!(
                        "{}{}",
                        dir_indent.bright_black(),
                        format!("dir: {}", cwd).bright_black()
                    );
                }
            } else {
                let cmd_part = if cmd_summary.is_empty() {
                    String::new()
                } else {
                    format!(" {}", cmd_summary)
                };
                out_println!(
                    "{}{}{} {} [{}]{}{}",
                    indent.bright_black(),
                    connector.bright_black(),
                    symbol,
                    proc.name.white(),
                    proc.pid.to_string().cyan(),
                    cmd_part.bright_black(),
                    uptime_label(proc.uptime_secs).bright_black()
                );
            }
        }
    }
}

/// Resolve one target to the processes it names. An error carries the warning
/// to show a person: the resolve error's own text, or a plain "no process found"
/// if the target resolved to nothing.
fn found_processes(
    target: &str,
    resolve: impl Fn(&str) -> Result<Vec<Process>>,
) -> std::result::Result<Vec<Process>, (ProcError, String)> {
    match resolve(target) {
        Ok(processes) if processes.is_empty() => Err((
            ProcError::ProcessNotFound(target.to_string()),
            format!("No process found for '{}'", target),
        )),
        Ok(processes) => Ok(processes),
        Err(e) => {
            let warning = e.to_string();
            Err((e, warning))
        }
    }
}

/// The target and its ancestors, from the root down to the target. Stops at a
/// parent that isn't running any more (or isn't listed) and after 100 levels,
/// so a loop in the parent links can't run forever.
fn ancestor_chain<'a>(target: &Process, pid_map: &HashMap<u32, &'a Process>) -> Vec<&'a Process> {
    let mut chain: Vec<&Process> = Vec::new();
    let mut current_pid = Some(target.pid);

    while let Some(pid) = current_pid {
        let Some(proc) = pid_map.get(&pid) else {
            break;
        };
        chain.push(proc);
        current_pid = proc.parent_pid;
        if chain.len() > 100 {
            break;
        }
    }

    chain.reverse();
    chain
}

/// The symbol in front of a process in the ancestry tree
fn status_indicator(status: ProcessStatus) -> ColoredString {
    match status {
        ProcessStatus::Running => "●".green(),
        ProcessStatus::Sleeping => "○".blue(),
        ProcessStatus::Stopped => "◐".yellow(),
        ProcessStatus::Zombie => "✗".red(),
        _ => "?".white(),
    }
}

#[derive(Serialize)]
struct WhyEnvelope {
    action: &'static str,
    success: bool,
    count: usize,
    /// The targets that matched nothing
    not_found: Vec<String>,
    results: Vec<WhyOutput>,
}

#[derive(Serialize)]
struct WhyOutput {
    target: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    port: Option<u16>,
    #[serde(skip_serializing_if = "Option::is_none")]
    protocol: Option<Protocol>,
    process: WhyProcessInfo,
    ports: Vec<PortInfo>,
    ancestry: Vec<AncestryEntry>,
}

#[derive(Serialize)]
struct WhyProcessInfo {
    pid: u32,
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    command: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cwd: Option<String>,
    status: ProcessStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    uptime_secs: Option<u64>,
}

#[derive(Serialize)]
struct AncestryEntry {
    pid: u32,
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    command: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cwd: Option<String>,
    status: ProcessStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    uptime_secs: Option<u64>,
    is_target: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn process(pid: u32, parent_pid: Option<u32>) -> Process {
        Process {
            pid,
            name: format!("p{pid}"),
            exe_path: None,
            cwd: None,
            command: None,
            argv0: None,
            raw: None,
            cpu_percent: 0.0,
            memory_mb: 0.0,
            status: ProcessStatus::Sleeping,
            user: None,
            parent_pid,
            start_time: None,
            uptime_secs: None,
        }
    }

    fn pids(chain: &[&Process]) -> Vec<u32> {
        chain.iter().map(|p| p.pid).collect()
    }

    #[test]
    fn a_chain_runs_from_the_root_down_to_the_target() {
        let (root, mid, leaf) = (process(1, None), process(2, Some(1)), process(3, Some(2)));
        let map: HashMap<u32, &Process> =
            [&root, &mid, &leaf].iter().map(|p| (p.pid, *p)).collect();
        assert_eq!(pids(&ancestor_chain(&leaf, &map)), vec![1, 2, 3]);
    }

    #[test]
    fn a_chain_stops_at_a_parent_that_is_not_listed() {
        // The parent exited, or belongs to another user and can't be read
        let (mid, leaf) = (process(2, Some(1)), process(3, Some(2)));
        let map: HashMap<u32, &Process> = [&mid, &leaf].iter().map(|p| (p.pid, *p)).collect();
        assert_eq!(pids(&ancestor_chain(&leaf, &map)), vec![2, 3]);
    }

    #[test]
    fn a_target_that_is_not_listed_has_no_chain() {
        let map: HashMap<u32, &Process> = HashMap::new();
        assert!(ancestor_chain(&process(3, Some(2)), &map).is_empty());
    }

    #[test]
    fn a_loop_in_the_parent_links_ends_after_101_entries() {
        let (a, b) = (process(1, Some(2)), process(2, Some(1)));
        let map: HashMap<u32, &Process> = [&a, &b].iter().map(|p| (p.pid, *p)).collect();
        let chain = ancestor_chain(&a, &map);
        assert_eq!(chain.len(), 101);
        // Walked up from the target, so the chain ends on the target
        assert_eq!(chain.last().map(|p| p.pid), Some(1));
    }

    #[test]
    fn each_status_has_its_own_symbol() {
        let symbol = |status| (*status_indicator(status)).to_string();
        assert_eq!(symbol(ProcessStatus::Running), "●");
        assert_eq!(symbol(ProcessStatus::Sleeping), "○");
        assert_eq!(symbol(ProcessStatus::Stopped), "◐");
        assert_eq!(symbol(ProcessStatus::Zombie), "✗");
        assert_eq!(symbol(ProcessStatus::Dead), "?");
        assert_eq!(symbol(ProcessStatus::Unknown), "?");
    }

    #[test]
    fn a_target_that_resolves_to_nothing_is_not_found() {
        let (error, warning) = found_processes("ghost", |_| Ok(Vec::new())).unwrap_err();
        assert!(
            matches!(&error, ProcError::ProcessNotFound(t) if t == "ghost"),
            "{error:?}"
        );
        assert_eq!(warning, "No process found for 'ghost'");
    }

    #[test]
    fn a_target_that_fails_to_resolve_warns_with_the_error() {
        let (error, warning) =
            found_processes("ghost", |_| Err(ProcError::PortNotFound(1))).unwrap_err();
        assert!(matches!(error, ProcError::PortNotFound(1)), "{error:?}");
        assert_eq!(warning, ProcError::PortNotFound(1).to_string());
    }

    #[test]
    fn a_target_that_resolves_gives_its_processes() {
        let found = found_processes("p", |_| Ok(vec![process(5, None)])).unwrap();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].pid, 5);
    }
}