Debian Codegraph @

src/collection/processes/linux/mod.rs

raw symbols SCIP
1 //! Process data collection for Linux.
2
3 mod process;
4
5 use std::{
6 fs::{self, File},
7 io::{BufRead, BufReader},
8 time::Duration,
9 };
10
11 use concat_string::concat_string;
12 use process::*;
13 use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
14 use sysinfo::ProcessStatus;
15
16 use super::{Pid, ProcessHarvest, UserTable, process_status_str};
17 use crate::collection::{DataCollector, error::CollectionResult, processes::ProcessType};
18
19 /// Maximum character length of a `/proc/<PID>/stat` process name (the length is
20 /// 16, but this includes a null terminator).
21 ///
22 /// If it's equal or greater, then we instead refer to the command for the name.
23 const MAX_STAT_NAME_LEN: usize = 15;
24
25 #[derive(Debug, Clone, Default)]
26 pub struct PrevProcDetails {
27 total_read_bytes: u64,
28 total_write_bytes: u64,
29 cpu_time: u64,
30 }
31
32 /// Given `/proc/stat` file contents, determine the idle and non-idle values of
33 /// the CPU used to calculate CPU usage.
34 fn fetch_cpu_usage(line: &str) -> (f64, f64) {
35 /// Converts a `Option<&str>` value to an f64. If it fails to parse or is
36 /// `None`, it will return `0_f64`.
37 fn str_to_f64(val: Option<&str>) -> f64 {
38 val.and_then(|v| v.parse::<f64>().ok()).unwrap_or(0_f64)
39 }
40
41 let mut val = line.split_whitespace();
42 let user = str_to_f64(val.next());
43 let nice: f64 = str_to_f64(val.next());
44 let system: f64 = str_to_f64(val.next());
45 let idle: f64 = str_to_f64(val.next());
46 let iowait: f64 = str_to_f64(val.next());
47 let irq: f64 = str_to_f64(val.next());
48 let softirq: f64 = str_to_f64(val.next());
49 let steal: f64 = str_to_f64(val.next());
50
51 // Note we do not get guest/guest_nice, as they are calculated as part of
52 // user/nice respectively See https://github.com/htop-dev/htop/blob/main/linux/LinuxProcessList.c
53 let idle = idle + iowait;
54 let non_idle = user + nice + system + irq + softirq + steal;
55
56 (idle, non_idle)
57 }
58
59 struct CpuUsage {
60 /// Difference between the total delta and the idle delta.
61 cpu_usage: f64,
62
63 /// Overall CPU usage as a fraction.
64 cpu_fraction: f64,
65 }
66
67 fn cpu_usage_calculation(
68 prev_idle: &mut f64, prev_non_idle: &mut f64,
69 ) -> CollectionResult<CpuUsage> {
70 let (idle, non_idle) = {
71 // From SO answer: https://stackoverflow.com/a/23376195
72 let first_line = {
73 // We just need a single line from this file. Read it and return it.
74 let mut reader = BufReader::new(File::open("/proc/stat")?);
75 let mut buffer = String::new();
76 reader.read_line(&mut buffer)?;
77
78 buffer
79 };
80
81 fetch_cpu_usage(&first_line)
82 };
83
84 let total = idle + non_idle;
85 let prev_total = *prev_idle + *prev_non_idle;
86
87 let total_delta = total - prev_total;
88 let idle_delta = idle - *prev_idle;
89
90 *prev_idle = idle;
91 *prev_non_idle = non_idle;
92
93 // TODO: Should these return errors instead?
94 let cpu_usage = if total_delta - idle_delta != 0.0 {
95 total_delta - idle_delta
96 } else {
97 1.0
98 };
99
100 let cpu_fraction = if total_delta != 0.0 {
101 cpu_usage / total_delta
102 } else {
103 0.0
104 };
105
106 Ok(CpuUsage {
107 cpu_usage,
108 cpu_fraction,
109 })
110 }
111
112 /// Returns the usage and a new set of process times.
113 ///
114 /// NB: cpu_fraction should be represented WITHOUT the x100 factor!
115 fn get_linux_cpu_usage(
116 stat: &Stat, cpu_usage: f64, cpu_fraction: f64, prev_proc_times: u64,
117 use_current_cpu_total: bool,
118 ) -> (f32, u64) {
119 // Based heavily on https://stackoverflow.com/a/23376195 and https://stackoverflow.com/a/1424556
120 let new_proc_times = stat.utime + stat.stime;
121 let diff = new_proc_times.saturating_sub(prev_proc_times) as f64; // No try_from for u64 -> f64... oh well.
122
123 if cpu_usage == 0.0 {
124 (0.0, new_proc_times)
125 } else if use_current_cpu_total {
126 (((diff / cpu_usage) * 100.0) as f32, new_proc_times)
127 } else {
128 (
129 ((diff / cpu_usage) * 100.0 * cpu_fraction) as f32,
130 new_proc_times,
131 )
132 }
133 }
134
135 fn read_proc(
136 prev_proc: &PrevProcDetails, process: Process, args: ReadProcArgs, user_table: &mut UserTable,
137 thread_parent: Option<Pid>,
138 ) -> CollectionResult<(ProcessHarvest, u64)> {
139 let Process {
140 pid: _pid,
141 uid,
142 stat,
143 io,
144 cmdline,
145 } = process;
146
147 let ReadProcArgs {
148 use_current_cpu_total,
149 cpu_usage,
150 cpu_fraction,
151 total_memory,
152 time_difference_in_secs,
153 system_uptime,
154 get_process_threads: _,
155 } = args;
156
157 let process_state_char = stat.state;
158 let process_state = (
159 process_status_str(ProcessStatus::from(process_state_char)),
160 process_state_char,
161 );
162 let (cpu_usage_percent, new_process_times) = get_linux_cpu_usage(
163 &stat,
164 cpu_usage,
165 cpu_fraction,
166 prev_proc.cpu_time,
167 use_current_cpu_total,
168 );
169
170 let (parent_pid, process_type) = if let Some(thread_parent) = thread_parent {
171 (Some(thread_parent), ProcessType::ProcessThread)
172 } else if stat.is_kernel_thread {
173 (Some(stat.ppid), ProcessType::Kernel)
174 } else {
175 (Some(stat.ppid), ProcessType::Regular)
176 };
177
178 let mem_usage = stat.rss_bytes();
179 let mem_usage_percent = (mem_usage as f64 / total_memory as f64 * 100.0) as f32;
180 let virtual_mem = stat.vsize;
181
182 // XXX: This can fail if permission is denied.
183 let (total_read, total_write, read_per_sec, write_per_sec) = if let Some(io) = io {
184 let total_read = io.read_bytes;
185 let total_write = io.write_bytes;
186 let prev_total_read = prev_proc.total_read_bytes;
187 let prev_total_write = prev_proc.total_write_bytes;
188
189 let read_per_sec = total_read
190 .saturating_sub(prev_total_read)
191 .checked_div(time_difference_in_secs)
192 .unwrap_or(0);
193
194 let write_per_sec = total_write
195 .saturating_sub(prev_total_write)
196 .checked_div(time_difference_in_secs)
197 .unwrap_or(0);
198
199 (total_read, total_write, read_per_sec, write_per_sec)
200 } else {
201 (0, 0, 0, 0)
202 };
203
204 let user = uid.and_then(|uid| user_table.uid_to_username(uid).ok());
205
206 let time = if let Ok(ticks_per_sec) = u32::try_from(rustix::param::clock_ticks_per_second()) {
207 if ticks_per_sec == 0 {
208 Duration::ZERO
209 } else {
210 Duration::from_secs(
211 system_uptime.saturating_sub(stat.start_time / ticks_per_sec as u64),
212 )
213 }
214 } else {
215 Duration::ZERO
216 };
217
218 let (command, name) = {
219 let comm = stat.comm;
220 if let Some(cmdline) = cmdline {
221 if cmdline.is_empty() {
222 (concat_string!("[", comm, "]"), comm)
223 } else {
224 // If the comm fits then we'll default to whatever is set.
225 // If it doesn't, we need to do some magic to determine what it's
226 // supposed to be.
227
228 // TODO: We might want to re-evaluate if we want to do it like this,
229 // as it turns out I was dumb and sometimes comm != process name...
230 //
231 // What we should do is store:
232 // - basename (what we're kinda doing now, except we're gating on comm length)
233 // - command (full thing)
234 // - comm (as a separate thing)
235 //
236 // Stuff like htop also offers the option to "highlight" basename and comm in
237 // command. Might be neat?
238 let name = if comm.len() >= MAX_STAT_NAME_LEN {
239 binary_name_from_cmdline(&cmdline)
240 } else {
241 comm
242 };
243
244 (cmdline, name)
245 }
246 } else {
247 (comm.clone(), comm)
248 }
249 };
250
251 // We have moved command processing here.
252 // SAFETY: We are only replacing a single char (NUL) with another single char
253 // (space).
254
255 let mut command = command;
256 let buf_mut = unsafe { command.as_mut_vec() };
257
258 for byte in buf_mut {
259 if *byte == 0 {
260 const SPACE: u8 = ' '.to_ascii_lowercase() as u8;
261 *byte = SPACE;
262 }
263 }
264
265 Ok((
266 ProcessHarvest {
267 pid: process.pid,
268 parent_pid,
269 cpu_usage_percent,
270 mem_usage_percent,
271 mem_usage,
272 virtual_mem,
273 name,
274 command,
275 read_per_sec,
276 write_per_sec,
277 total_read,
278 total_write,
279 process_state,
280 uid,
281 user,
282 time,
283 #[cfg(feature = "gpu")]
284 gpu_mem: 0,
285 #[cfg(feature = "gpu")]
286 gpu_mem_percent: 0.0,
287 #[cfg(feature = "gpu")]
288 gpu_util: 0,
289 process_type,
290 #[cfg(unix)]
291 nice: stat.nice,
292 priority: stat.priority,
293 },
294 new_process_times,
295 ))
296 }
297
298 /// We follow something similar to how htop does it to identify a valid name
299 /// based on the cmdline.
300 /// - https://github.com/htop-dev/htop/blob/bcb18ef82269c68d54a160290e5f8b2e939674ec/Process.c#L268
301 /// (kinda)
302 /// - https://github.com/htop-dev/htop/blob/bcb18ef82269c68d54a160290e5f8b2e939674ec/Process.c#L573
303 ///
304 /// Also note that cmdline is (for us) separated by \0.
305 fn binary_name_from_cmdline(cmdline: &str) -> String {
306 // Normally `/proc/<pid>/cmdline` separates arguments with NUL bytes. Some
307 // processes rewrite it using spaces, though, so stop at the first option in
308 // that case. In particular, do this before looking for the final slash;
309 // otherwise a path in a later argument can be mistaken for the executable.
310 let argv0 = cmdline.split_once('\0').map_or(cmdline, |(argv0, _)| argv0);
311 let executable = argv0
312 .split_once(" -")
313 .map_or(argv0, |(executable, _)| executable);
314 let executable = executable
315 .split_once(':')
316 .map_or(executable, |(executable, _)| executable);
317
318 executable
319 .rsplit('/')
320 .next()
321 .unwrap_or(executable)
322 .to_string()
323 }
324
325 pub(crate) struct PrevProc<'a> {
326 pub prev_idle: &'a mut f64,
327 pub prev_non_idle: &'a mut f64,
328 }
329
330 pub(crate) struct ProcHarvestOptions {
331 pub use_current_cpu_total: bool,
332 pub unnormalized_cpu: bool,
333 pub get_process_threads: bool,
334 }
335
336 fn is_str_numeric(s: &str) -> bool {
337 s.chars().all(|c| c.is_ascii_digit())
338 }
339
340 /// General args to keep around for reading proc data.
341 #[derive(Copy, Clone)]
342 pub(crate) struct ReadProcArgs {
343 pub use_current_cpu_total: bool,
344 pub cpu_usage: f64,
345 pub cpu_fraction: f64,
346 pub total_memory: u64,
347 pub time_difference_in_secs: u64,
348 pub system_uptime: u64,
349 pub get_process_threads: bool,
350 }
351
352 pub(crate) fn linux_process_data(
353 collector: &mut DataCollector, time_difference_in_secs: u64,
354 ) -> CollectionResult<Vec<ProcessHarvest>> {
355 let total_memory = collector.total_memory();
356 let prev_proc = PrevProc {
357 prev_idle: &mut collector.prev_idle,
358 prev_non_idle: &mut collector.prev_non_idle,
359 };
360 let proc_harvest_options = ProcHarvestOptions {
361 use_current_cpu_total: collector.use_current_cpu_total,
362 unnormalized_cpu: collector.unnormalized_cpu,
363 get_process_threads: collector.get_process_threads,
364 };
365 let prev_process_details = &mut collector.prev_process_details;
366 let user_table = &mut collector.user_table;
367
368 let ProcHarvestOptions {
369 use_current_cpu_total,
370 unnormalized_cpu,
371 get_process_threads: get_threads,
372 } = proc_harvest_options;
373
374 let PrevProc {
375 prev_idle,
376 prev_non_idle,
377 } = prev_proc;
378
379 // TODO: [PROC THREADS] Add threads
380
381 let CpuUsage {
382 mut cpu_usage,
383 cpu_fraction,
384 } = cpu_usage_calculation(prev_idle, prev_non_idle)?;
385
386 if unnormalized_cpu {
387 let num_processors = collector
388 .cgroup_cpu_data
389 .cpu_quota
390 .unwrap_or_else(|| collector.sys.system.cpus().len() as f64);
391
392 // Note we *divide* here because the later calculation divides `cpu_usage` - in
393 // effect, multiplying over the number of cores.
394 cpu_usage /= num_processors;
395 }
396
397 // TODO: Could maybe use a double buffer hashmap to avoid allocating this each
398 // time? e.g. we swap which is prev and which is new.
399 let mut seen_pids: HashSet<Pid> = HashSet::default();
400
401 // Note this will only return PIDs of _processes_, not threads. You can get
402 // those from /proc/<PID>/task though.
403 let pids = fs::read_dir("/proc")?.flatten().filter_map(|dir| {
404 // Need to filter out non-PID entries.
405 if is_str_numeric(dir.file_name().to_string_lossy().trim()) {
406 Some(dir.path())
407 } else {
408 None
409 }
410 });
411
412 let args = ReadProcArgs {
413 use_current_cpu_total,
414 cpu_usage,
415 cpu_fraction,
416 total_memory,
417 time_difference_in_secs,
418 system_uptime: sysinfo::System::uptime(),
419 get_process_threads: get_threads,
420 };
421
422 // TODO: Maybe pre-allocate these buffers in the future w/ routine cleanup.
423 let mut buffer = String::new();
424 let mut process_threads_to_check = HashMap::default();
425
426 let mut process_vector: Vec<ProcessHarvest> = pids
427 .filter_map(|pid_path| {
428 if let Ok((process, threads)) =
429 Process::from_path(pid_path, &mut buffer, args.get_process_threads)
430 {
431 let pid = process.pid;
432 let prev_proc_details = prev_process_details.entry(pid).or_default();
433
434 #[cfg_attr(not(feature = "gpu"), expect(unused_mut))]
435 if let Ok((mut process_harvest, new_process_times)) =
436 read_proc(prev_proc_details, process, args, user_table, None)
437 {
438 #[cfg(feature = "gpu")]
439 if let Some(gpus) = &collector.gpu_pids {
440 gpus.iter().for_each(|gpu| {
441 // add mem/util for all gpus to pid
442 if let Some((mem, util)) = gpu.get(&pid) {
443 process_harvest.gpu_mem += mem;
444 process_harvest.gpu_util += util;
445 }
446 });
447 if let Some(gpu_total_mem) = &collector.gpus_total_mem {
448 process_harvest.gpu_mem_percent =
449 (process_harvest.gpu_mem as f64 / *gpu_total_mem as f64 * 100.0)
450 as f32;
451 }
452 }
453
454 prev_proc_details.cpu_time = new_process_times;
455 prev_proc_details.total_read_bytes = process_harvest.total_read;
456 prev_proc_details.total_write_bytes = process_harvest.total_write;
457
458 if !threads.is_empty() {
459 process_threads_to_check.insert(pid, threads);
460 }
461
462 seen_pids.insert(pid);
463 return Some(process_harvest);
464 }
465 }
466
467 None
468 })
469 .collect();
470
471 // Get thread data.
472 for (pid, tid_paths) in process_threads_to_check {
473 for tid_path in tid_paths {
474 if let Ok((process, _)) = Process::from_path(tid_path, &mut buffer, false) {
475 let tid = process.pid;
476 let prev_proc_details = prev_process_details.entry(tid).or_default();
477
478 if let Ok((process_harvest, new_process_times)) =
479 read_proc(prev_proc_details, process, args, user_table, Some(pid))
480 {
481 prev_proc_details.cpu_time = new_process_times;
482 prev_proc_details.total_read_bytes = process_harvest.total_read;
483 prev_proc_details.total_write_bytes = process_harvest.total_write;
484
485 seen_pids.insert(tid);
486 process_vector.push(process_harvest);
487 }
488 }
489 }
490 }
491
492 // Clean up values we don't care about anymore.
493 prev_process_details.retain(|pid, _| seen_pids.contains(pid));
494
495 // Occasional garbage collection.
496 if collector.should_run_less_routine_tasks {
497 prev_process_details.shrink_to_fit();
498 }
499
500 // TODO: This might be more efficient to just separate threads into their own
501 // list, but for now this works so it fits with existing code.
502 Ok(process_vector)
503 }
504
505 #[cfg(test)]
506 mod tests {
507 use super::*;
508
509 #[test]
510 fn test_proc_cpu_parse() {
511 assert_eq!(
512 (100_f64, 200_f64),
513 fetch_cpu_usage("100 0 100 100"),
514 "Failed to properly calculate idle/non-idle for /proc/stat CPU with 4 values"
515 );
516 assert_eq!(
517 (120_f64, 200_f64),
518 fetch_cpu_usage("100 0 100 100 20"),
519 "Failed to properly calculate idle/non-idle for /proc/stat CPU with 5 values"
520 );
521 assert_eq!(
522 (120_f64, 230_f64),
523 fetch_cpu_usage("100 0 100 100 20 30"),
524 "Failed to properly calculate idle/non-idle for /proc/stat CPU with 6 values"
525 );
526 assert_eq!(
527 (120_f64, 270_f64),
528 fetch_cpu_usage("100 0 100 100 20 30 40"),
529 "Failed to properly calculate idle/non-idle for /proc/stat CPU with 7 values"
530 );
531 assert_eq!(
532 (120_f64, 320_f64),
533 fetch_cpu_usage("100 0 100 100 20 30 40 50"),
534 "Failed to properly calculate idle/non-idle for /proc/stat CPU with 8 values"
535 );
536 assert_eq!(
537 (120_f64, 320_f64),
538 fetch_cpu_usage("100 0 100 100 20 30 40 50 100"),
539 "Failed to properly calculate idle/non-idle for /proc/stat CPU with 9 values"
540 );
541 assert_eq!(
542 (120_f64, 320_f64),
543 fetch_cpu_usage("100 0 100 100 20 30 40 50 100 200"),
544 "Failed to properly calculate idle/non-idle for /proc/stat CPU with 10 values"
545 );
546 }
547
548 #[test]
549 fn test_name_from_cmdline() {
550 assert_eq!(binary_name_from_cmdline("/usr/bin/btm"), "btm");
551 assert_eq!(
552 binary_name_from_cmdline("/usr/bin/btm\0--asdf\0--asdf/gkj"),
553 "btm"
554 );
555 assert_eq!(binary_name_from_cmdline("/usr/bin/btm:"), "btm");
556 assert_eq!(binary_name_from_cmdline("/usr/bin/b tm"), "b tm");
557 assert_eq!(binary_name_from_cmdline("/usr/bin/b tm:"), "b tm");
558 assert_eq!(binary_name_from_cmdline("/usr/bin/b tm\0--test"), "b tm");
559 assert_eq!(binary_name_from_cmdline("/usr/bin/b tm:\0--test"), "b tm");
560 assert_eq!(
561 binary_name_from_cmdline("/usr/bin/b t m:\0--\"test thing\""),
562 "b t m"
563 );
564 assert_eq!(
565 binary_name_from_cmdline("firefox -contentproc -isForBrowser -prefsHandle 0"),
566 "firefox"
567 );
568 assert_eq!(
569 binary_name_from_cmdline(
570 "/nix/store/discord/opt/Discord/.Discord-wrapped --type=renderer \
571 --openh264-library-path=/home/user/libopenh264-2.5.1-linux64.7.so"
572 ),
573 ".Discord-wrapped"
574 );
575 assert_eq!(binary_name_from_cmdline("こんにちは\0"), "こんにちは");
576 assert_eq!(
577 binary_name_from_cmdline("こんにちは -こんばんは"),
578 "こんにちは"
579 );
580 assert_eq!(
581 binary_name_from_cmdline("/usr/bin/こんにちは -こんばんは\0"),
582 "こんにちは"
583 );
584 }
585 }