1use std::collections::HashMap;
23use std::hash::Hash;
24use std::time::Instant;
25
26#[cfg(target_os = "linux")]
27mod linux;
28#[cfg(target_os = "linux")]
29use linux as os;
30
31#[cfg(target_os = "macos")]
32mod macos;
33#[cfg(target_os = "macos")]
34use macos as os;
35
36#[cfg(windows)]
37mod windows;
38#[cfg(windows)]
39use windows as os;
40#[cfg(windows)]
41pub use windows::{recent_parents, ParentTable};
42
43#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
44mod os {
45 pub fn snapshot() -> std::io::Result<Vec<super::ProcInfo>> {
46 Err(std::io::Error::new(
47 std::io::ErrorKind::Unsupported,
48 "no process reader for this OS",
49 ))
50 }
51 pub fn command_line(_pid: u32) -> Option<String> {
52 None
53 }
54 pub fn start_key(_pid: u32) -> Option<u64> {
55 None
56 }
57 pub fn write_bytes(_pid: u32) -> Option<u64> {
58 None
59 }
60 pub fn storage_write_bytes(_pid: u32) -> Option<i64> {
61 None
62 }
63 pub fn cpu_count() -> usize {
64 std::thread::available_parallelism()
65 .map(|n| n.get())
66 .unwrap_or(1)
67 }
68}
69
70#[cfg(windows)]
73pub const MEMORY_METRIC: &str = "private working set";
74#[cfg(target_os = "macos")]
75pub const MEMORY_METRIC: &str = "memory footprint";
76#[cfg(not(any(windows, target_os = "macos")))]
77pub const MEMORY_METRIC: &str = "anonymous resident + swap";
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct ProcInfo {
82 pub pid: u32,
83 pub ppid: Option<u32>,
87 pub start_key: u64,
92 pub started_at_ms: Option<u64>,
94 pub name: String,
96 pub cpu_ns: Option<u64>,
98 pub mem_private: Option<u64>,
100 pub mem_resident: Option<u64>,
102 pub mem_commit: Option<u64>,
104}
105
106impl ProcInfo {
107 pub fn key(&self) -> ProcKey {
109 ProcKey {
110 pid: self.pid,
111 start_key: self.start_key,
112 }
113 }
114
115 pub fn measured(&self) -> bool {
118 self.cpu_ns.is_some() || self.mem_private.is_some()
119 }
120
121 pub fn is_child_of(&self, parent: &ProcInfo) -> bool {
125 if self.ppid != Some(parent.pid) || parent.pid == self.pid {
126 return false;
127 }
128 match (parent.started_at_ms, self.started_at_ms) {
129 (Some(p), Some(c)) => p <= c,
130 _ => true,
131 }
132 }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
137pub struct ProcKey {
138 pub pid: u32,
139 pub start_key: u64,
140}
141
142pub fn snapshot() -> std::io::Result<Vec<ProcInfo>> {
144 os::snapshot()
145}
146
147pub fn command_line(pid: u32) -> Option<String> {
151 os::command_line(pid)
152}
153
154pub fn is_running(key: ProcKey) -> bool {
158 os::start_key(key.pid) == Some(key.start_key)
159}
160
161pub fn command_line_of(key: ProcKey) -> Option<String> {
165 if os::start_key(key.pid)? != key.start_key {
166 return None;
167 }
168 let line = os::command_line(key.pid)?;
169 (os::start_key(key.pid)? == key.start_key).then_some(line)
170}
171
172pub fn write_bytes(pid: u32) -> Option<u64> {
178 os::write_bytes(pid)
179}
180
181pub fn storage_write_bytes(pid: u32) -> Option<i64> {
190 os::storage_write_bytes(pid)
191}
192
193pub fn cpu_count() -> usize {
196 os::cpu_count().max(1)
197}
198
199#[derive(Debug)]
206pub struct RateMeter<K> {
207 prev: HashMap<K, (u64, Instant)>,
208 next: HashMap<K, (u64, Instant)>,
209}
210
211impl<K> Default for RateMeter<K> {
212 fn default() -> Self {
213 Self {
214 prev: HashMap::new(),
215 next: HashMap::new(),
216 }
217 }
218}
219
220impl<K: Eq + Hash + Clone> RateMeter<K> {
221 pub fn new() -> Self {
222 Self::default()
223 }
224
225 pub fn sample(&mut self, key: K, total_ns: u64, now: Instant) -> Option<f64> {
229 let rate = self.prev.get(&key).and_then(|&(was, at)| {
230 let wall = now.checked_duration_since(at)?.as_nanos();
231 (wall > 0 && total_ns >= was).then(|| (total_ns - was) as f64 / wall as f64)
232 });
233 self.next.insert(key, (total_ns, now));
234 rate
235 }
236
237 pub fn finish(&mut self) {
239 self.prev = std::mem::take(&mut self.next);
240 }
241
242 pub fn len(&self) -> usize {
244 self.prev.len()
245 }
246
247 pub fn is_empty(&self) -> bool {
248 self.prev.is_empty()
249 }
250}
251
252pub fn base_name(path: &str) -> &str {
254 path.rsplit(['/', '\\']).next().unwrap_or(path)
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260 use std::time::Duration;
261
262 fn proc(pid: u32, ppid: Option<u32>, started: Option<u64>) -> ProcInfo {
263 ProcInfo {
264 pid,
265 ppid,
266 start_key: started.unwrap_or(0),
267 started_at_ms: started,
268 name: String::new(),
269 cpu_ns: None,
270 mem_private: None,
271 mem_resident: None,
272 mem_commit: None,
273 }
274 }
275
276 #[test]
277 fn this_process_reports_the_bytes_it_has_written() {
278 let me = std::process::id();
279 let before = write_bytes(me);
280 #[cfg(any(windows, target_os = "linux"))]
282 {
283 use std::io::Write;
284 let path = std::env::temp_dir().join(format!("procstats-write-{me}.bin"));
285 let mut f = std::fs::File::create(&path).unwrap();
286 f.write_all(&vec![7u8; 4 * 1024 * 1024]).unwrap();
287 f.sync_all().unwrap();
288 drop(f);
289 let _ = std::fs::remove_file(&path);
290 let after = write_bytes(me).expect("write counters");
291 assert!(after >= before.expect("write counters") + 4 * 1024 * 1024, "{before:?} -> {after}");
292 }
293 #[cfg(not(any(windows, target_os = "linux")))]
294 let _ = before;
295 }
296
297 #[test]
298 fn rate_needs_two_rounds_and_is_a_fraction_of_one_core() {
299 let mut m = RateMeter::new();
300 let t0 = Instant::now();
301 assert_eq!(
302 m.sample("a", 1_000_000_000, t0),
303 None,
304 "first round has no rate"
305 );
306 m.finish();
307 let r = m
309 .sample("a", 2_500_000_000, t0 + Duration::from_secs(1))
310 .unwrap();
311 assert!((r - 1.5).abs() < 1e-9, "{r}");
312 }
313
314 #[test]
315 fn a_key_missing_from_a_round_starts_over() {
316 let mut m = RateMeter::new();
317 let t0 = Instant::now();
318 m.sample(1, 100, t0);
319 m.finish();
320 m.finish(); assert_eq!(m.sample(1, 200, t0 + Duration::from_secs(2)), None);
322 assert!(m.is_empty(), "nothing finished yet this round");
323 }
324
325 #[test]
326 fn a_counter_that_goes_backwards_has_no_rate() {
327 let mut m = RateMeter::new();
328 let t0 = Instant::now();
329 m.sample(1, 500, t0);
330 m.finish();
331 assert_eq!(m.sample(1, 100, t0 + Duration::from_secs(1)), None);
332 }
333
334 #[test]
335 fn a_parent_that_started_after_its_child_is_a_reused_pid() {
336 let parent = proc(10, None, Some(2_000));
337 let child = proc(11, Some(10), Some(1_000));
338 assert!(!child.is_child_of(&parent));
339 let real_parent = proc(10, None, Some(500));
340 assert!(child.is_child_of(&real_parent));
341 assert!(!child.is_child_of(&proc(12, None, Some(0))), "wrong pid");
342 assert!(
343 proc(11, Some(10), None).is_child_of(&parent),
344 "unknown start times trust the pid"
345 );
346 }
347
348 #[test]
349 fn base_name_strips_either_separator() {
350 assert_eq!(base_name(r"C:\Program Files\nodejs\node.exe"), "node.exe");
351 assert_eq!(base_name("/usr/bin/node"), "node");
352 assert_eq!(base_name("node"), "node");
353 }
354
355 #[test]
358 fn snapshot_sees_this_process_with_cpu_and_memory() {
359 let me = std::process::id();
360 let all = snapshot().expect("snapshot");
361 assert!(all.len() > 1, "only {} processes", all.len());
362 let p = all
363 .iter()
364 .find(|p| p.pid == me)
365 .expect("this process is listed");
366 assert!(p.cpu_ns.is_some(), "{p:?}");
367 assert!(p.mem_private.unwrap_or(0) > 0, "{p:?}");
368 assert!(
369 p.mem_resident.unwrap_or(0) >= p.mem_private.unwrap_or(0) / 4,
370 "{p:?}"
371 );
372 assert!(p.ppid.is_some(), "{p:?}");
373 assert!(!p.name.is_empty(), "{p:?}");
374 let now_ms = std::time::SystemTime::now()
375 .duration_since(std::time::UNIX_EPOCH)
376 .unwrap()
377 .as_millis() as u64;
378 let started = p.started_at_ms.expect("start time");
379 assert!(
380 started <= now_ms + 5_000 && started > now_ms - 24 * 3600 * 1000,
381 "started {started}, now {now_ms}"
382 );
383 let again = snapshot().unwrap();
385 assert_eq!(again.iter().find(|q| q.pid == me).unwrap().key(), p.key());
386 }
387
388 #[test]
389 fn cpu_time_grows_while_this_process_spins() {
390 let me = std::process::id();
391 let cpu = || {
392 snapshot()
393 .unwrap()
394 .into_iter()
395 .find(|p| p.pid == me)
396 .and_then(|p| p.cpu_ns)
397 .unwrap()
398 };
399 let before = cpu();
400 let spin_until = Instant::now() + Duration::from_millis(300);
401 let mut x = 0u64;
402 while Instant::now() < spin_until {
403 x = x.wrapping_mul(6364136223846793005).wrapping_add(1);
404 }
405 std::hint::black_box(x);
406 let after = cpu();
407 assert!(
409 after >= before + 100_000_000,
410 "before {before} after {after}"
411 );
412 assert!(
414 after < before + 30_000_000_000,
415 "before {before} after {after}"
416 );
417 }
418
419 #[test]
420 fn command_line_of_this_process_names_its_executable() {
421 let line = command_line(std::process::id()).expect("own command line");
422 let exe = std::env::current_exe().unwrap();
423 let stem = exe.file_stem().unwrap().to_string_lossy().to_string();
424 assert!(line.contains(&stem), "{line:?} lacks {stem:?}");
425 assert_eq!(command_line(u32::MAX - 7), None);
426 }
427
428 #[test]
429 fn a_command_line_only_for_the_exact_process() {
430 let me = snapshot()
431 .unwrap()
432 .into_iter()
433 .find(|p| p.pid == std::process::id())
434 .unwrap();
435 assert!(command_line_of(me.key()).is_some(), "{me:?}");
436 let newer = ProcKey {
437 pid: me.pid,
438 start_key: me.start_key.wrapping_add(1),
439 };
440 assert_eq!(command_line_of(newer), None, "same PID, another process");
441 }
442
443 #[test]
444 fn cpu_count_is_at_least_what_this_process_may_use() {
445 let usable = std::thread::available_parallelism()
446 .map(|n| n.get())
447 .unwrap_or(1);
448 assert!(cpu_count() >= usable, "{} < {usable}", cpu_count());
449 }
450}
451
452#[cfg(test)]
455agentmux_common::checkout_guard!();
456
457#[doc(hidden)]
460pub const CHECKOUT_DIR: &str = env!("CARGO_MANIFEST_DIR");