monitr 0.3.41

A lightweight macOS activity monitor TUI built with Rust and Ratatui
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
use std::{
    fmt::Write as _,
    process::{Command, Output},
    time::Duration,
};

use serde::Serialize;

use crate::{
    error::{self, Result},
    format,
    process_record::ProcessRecord,
    sampler::Sampler,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InspectOptions {
    pub pid: u32,
    pub json: bool,
    pub limit: usize,
    pub full: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct Inspection {
    pub process: InspectProcess,
    pub files: Vec<FileEntry>,
    pub sockets: Vec<SocketEntry>,
}

/// The open files and sockets held by a process, independent of the heavier
/// `Inspection` (which also re-samples process metadata). The TUI uses this to
/// surface handles for the already-selected process without a fresh sample.
#[derive(Debug, Clone, Default)]
pub struct ProcessHandles {
    pub files: Vec<FileEntry>,
    pub sockets: Vec<SocketEntry>,
}

pub type InspectProcess = ProcessRecord;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FileEntry {
    pub fd: String,
    pub file_type: String,
    pub device: Option<String>,
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SocketEntry {
    pub fd: String,
    pub protocol: String,
    pub local: String,
    pub remote: Option<String>,
    pub state: Option<String>,
}

pub fn inspect(options: InspectOptions, interval: Duration) -> Result<Inspection> {
    let mut sampler = Sampler::new()?;
    let baseline = sampler.sample(Some(options.pid));
    let previous = crate::sampler::collect_process_samples(&baseline.processes);
    
    std::thread::sleep(interval);
    
    let mut snapshot = sampler.sample(Some(options.pid));
    crate::sampler::apply_process_trends(&mut snapshot.processes, &previous);
    
    let process = snapshot
        .processes
        .iter()
        .find(|process| process.pid == options.pid)
        .ok_or_else(|| error::message(format!("process {} is not visible", options.pid)))?;

    let handles = collect_handles(options.pid)?;
    Ok(Inspection {
        process: InspectProcess::from(process),
        files: handles.files,
        sockets: handles.sockets,
    })
}

pub fn render(inspection: &Inspection, options: InspectOptions) -> Result<String> {
    if options.json {
        return Ok(serde_json::to_string_pretty(inspection)?);
    }

    let mut out = String::new();
    let process = &inspection.process;
    let _ = writeln!(
        out,
        "{} pid {} | ppid {} | user {} | status {} | priority {}",
        process.name,
        process.pid,
        process
            .parent_pid
            .map(|pid| pid.to_string())
            .unwrap_or_else(|| "-".to_string()),
        process.user,
        process.status,
        process
            .priority
            .map(|priority| priority.to_string())
            .unwrap_or_else(|| "-".to_string())
    );
    let _ = writeln!(
        out,
        "CPU {} | Memory {} | Virtual {} | Mem% {} | runtime {} | impact {}",
        format::percent(process.cpu_usage_percent as f64),
        format::bytes(process.memory_bytes),
        format::bytes(process.virtual_memory_bytes),
        format::percent(process.memory_percent),
        format::duration(process.runtime_seconds),
        format::number(process.energy_impact),
    );
    let _ = writeln!(
        out,
        "Disk R {} | W {} | Total R {} | W {}",
        format::bytes_rate(process.disk_read_bytes_per_sec),
        format::bytes_rate(process.disk_write_bytes_per_sec),
        format::bytes(process.total_disk_read_bytes),
        format::bytes(process.total_disk_written_bytes),
    );
    let _ = writeln!(
        out,
        "Network In {} | Out {}",
        process
            .network_in_bytes_per_sec
            .map(|value| format::bytes_rate(value))
            .unwrap_or_else(|| "-".to_string()),
        process
            .network_out_bytes_per_sec
            .map(|value| format::bytes_rate(value))
            .unwrap_or_else(|| "-".to_string()),
    );
    if process.total_network_read_bytes.is_none() && process.total_network_written_bytes.is_none() {
        let _ = writeln!(
            out,
            "Total network traffic unavailable at process level in this sample"
        );
    } else {
        let _ = writeln!(
            out,
            "Total Network In {} | Out {}",
            process
                .total_network_read_bytes
                .map(|value| format::bytes(value))
                .unwrap_or_else(|| "-".to_string()),
            process
                .total_network_written_bytes
                .map(|value| format::bytes(value))
                .unwrap_or_else(|| "-".to_string()),
        );
    }
    let _ = writeln!(
        out,
        "started {} | session {} | threads {} | open files {}",
        format::epoch_time(process.start_time_unix),
        process
            .session_id
            .map(|id| id.to_string())
            .unwrap_or_else(|| "-".to_string()),
        process
            .thread_count
            .map(|count| count.to_string())
            .unwrap_or_else(|| "-".to_string()),
        process
            .open_files
            .map(|files| {
                process
                    .open_files_limit
                    .map(|limit| format!("{files}/{limit}"))
                    .unwrap_or_else(|| files.to_string())
            })
            .unwrap_or_else(|| "-".to_string()),
    );
    let _ = writeln!(out, "cwd: {}", process.cwd);
    let _ = writeln!(out, "exe: {}", process.executable);
    let _ = writeln!(out, "cmd: {}", process.command);

    let _ = writeln!(out);
    let _ = writeln!(out, "Sockets");
    if inspection.sockets.is_empty() {
        let _ = writeln!(out, "  none visible");
    } else {
        for socket in inspection.sockets.iter().take(options.limit) {
            let remote_or_state = socket
                .remote
                .as_deref()
                .or(socket.state.as_deref())
                .unwrap_or("-");
            let _ = writeln!(
                out,
                "  {:<5} {:<5} {:<32} {}",
                socket.fd,
                socket.protocol,
                format::truncate_middle(&socket.local, 32),
                remote_or_state,
            );
        }
    }

    let _ = writeln!(out);
    let _ = writeln!(out, "Open files");
    if inspection.files.is_empty() {
        let _ = writeln!(out, "  none visible");
    } else {
        for file in inspection.files.iter().take(options.limit) {
            let _ = writeln!(
                out,
                "  {:<5} {:<5} {}",
                file.fd,
                file.file_type,
                format::truncate_middle(&file.name, 88),
            );
        }
    }
    Ok(out)
}


pub fn collect_handles(pid: u32) -> Result<ProcessHandles> {
    ensure_lsof_available()?;
    let output = Command::new("lsof")
        .args(["-nP", "-p", &pid.to_string(), "-F", "ftDnPnT"])
        .output()?;
    if !output.status.success() && output.stdout.is_empty() {
        if is_empty_lsof_result(&output) {
            return Ok(ProcessHandles::default());
        }
        return Err(error::message(lsof_failure_message("handles", &output)));
    }
    let (files, sockets) = parse_lsof_combined(&String::from_utf8_lossy(&output.stdout));
    Ok(ProcessHandles { files, sockets })
}

fn ensure_lsof_available() -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        if Command::new("which").arg("lsof").output().is_err() {
            return Err(error::message(
                "lsof is not found in PATH. Please install it or ensure it is available.",
            ));
        }
    }
    Ok(())
}

fn is_empty_lsof_result(output: &Output) -> bool {
    // lsof returns 1 when no files are found for the PID
    output.status.code() == Some(1)
}

fn lsof_failure_message(kind: &str, output: &Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stderr = stderr.trim();
    if stderr.contains("Permission denied") {
        return format!(
            "lsof {kind} failed: Permission denied. Try running with sudo or granting 'Full Disk Access' to your terminal."
        );
    }
    if stderr.is_empty() {
        format!(
            "lsof {kind} failed with status {}",
            output
                .status
                .code()
                .map(|code| code.to_string())
                .unwrap_or_else(|| "signal".to_string())
        )
    } else {
        format!("lsof {kind} failed: {stderr}")
    }
}

#[derive(Default)]
struct DescriptorFields {
    fd: String,
    file_type: String,
    device: Option<String>,
    name: String,
    protocol: String,
    local: String,
    remote: Option<String>,
    state: Option<String>,
}

fn parse_lsof_combined(output: &str) -> (Vec<FileEntry>, Vec<SocketEntry>) {
    let mut files = Vec::new();
    let mut sockets = Vec::new();
    let mut current = DescriptorFields::default();

    for line in output.lines().filter(|line| !line.is_empty()) {
        let mut chars = line.chars();
        let Some(field) = chars.next() else {
            continue;
        };
        let value = chars.as_str();

        match field {
            'f' => {
                flush_descriptor(&mut current, &mut files, &mut sockets);
                current.fd = value.to_string();
            }
            't' => current.file_type = value.to_string(),
            'D' => current.device = Some(value.to_string()),
            'n' => {
                current.name = value.to_string();
                let (local, remote) = value
                    .split_once("->")
                    .map(|(local, remote)| (local.to_string(), Some(remote.to_string())))
                    .unwrap_or_else(|| (value.to_string(), None));
                current.local = local;
                current.remote = remote;
            }
            'P' => current.protocol = value.to_string(),
            'T' => {
                if let Some(state) = value.strip_prefix("ST=") {
                    current.state = Some(state.to_string());
                }
            }
            _ => {}
        }
    }
    flush_descriptor(&mut current, &mut files, &mut sockets);
    (files, sockets)
}

fn flush_descriptor(
    current: &mut DescriptorFields,
    files: &mut Vec<FileEntry>,
    sockets: &mut Vec<SocketEntry>,
) {
    if current.fd.is_empty() {
        *current = DescriptorFields::default();
        return;
    }

    let is_socket = !current.protocol.is_empty() || current.file_type.starts_with("IPv");

    if is_socket {
        if !current.local.is_empty() {
            sockets.push(SocketEntry {
                fd: current.fd.clone(),
                protocol: value_or_dash(&current.protocol),
                local: current.local.clone(),
                remote: current.remote.clone(),
                state: current.state.clone(),
            });
        }
    } else if !current.name.is_empty() {
        files.push(FileEntry {
            fd: current.fd.clone(),
            file_type: value_or_dash(&current.file_type),
            device: current.device.clone(),
            name: current.name.clone(),
        });
    }
    *current = DescriptorFields::default();
}

fn value_or_dash(value: &str) -> String {
    if value.is_empty() {
        "-".to_string()
    } else {
        value.to_string()
    }
}

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

    #[test]
    fn parses_lsof_combined_entries() {
        let (files, sockets) = parse_lsof_combined(
            "\
p34138
fcwd
tDIR
D0x1000011
n/Users/miloevans/monitr
f1
tPIPE
n->0x42f88a3c7b8a6378
f18
tIPv4
PTCP
n127.0.0.1:18789
TST=LISTEN
f24
tIPv6
PUDP
n[::1]:5353->[ff02::fb]:5353
",
        );

        assert_eq!(files.len(), 2);
        assert_eq!(files[0].fd, "cwd");
        assert_eq!(files[0].file_type, "DIR");
        assert_eq!(files[0].name, "/Users/miloevans/monitr");
        assert_eq!(files[1].fd, "1");
        assert_eq!(files[1].file_type, "PIPE");

        assert_eq!(sockets.len(), 2);
        assert_eq!(sockets[0].protocol, "TCP");
        assert_eq!(sockets[0].state.as_deref(), Some("LISTEN"));
        assert_eq!(sockets[1].remote.as_deref(), Some("[ff02::fb]:5353"));
    }
}