Debian Codegraph @

src/collection/processes/linux/process.rs

raw symbols SCIP
1 //! Linux process code for getting process data via `/proc/`.
2 //! Based on the [procfs](https://github.com/eminence/procfs) crate.
3
4 use std::{
5 fs::File,
6 io::{self, BufRead, BufReader, Read},
7 path::PathBuf,
8 sync::OnceLock,
9 };
10
11 use anyhow::anyhow;
12 use libc::uid_t;
13 use rustix::{
14 fd::OwnedFd,
15 fs::{Mode, OFlags},
16 path::Arg,
17 };
18
19 use crate::collection::processes::{Pid, linux::is_str_numeric};
20
21 static PAGESIZE: OnceLock<u64> = OnceLock::new();
22
23 #[inline]
24 fn next_part<'a>(iter: &mut impl Iterator<Item = &'a str>) -> Result<&'a str, io::Error> {
25 iter.next()
26 .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))
27 }
28
29 /// A wrapper around the data in `/proc/<PID>/stat`. For documentation, see:
30 /// - <https://manpages.ubuntu.com/manpages/noble/man5/proc_pid_stat.5.html>
31 /// - <https://man7.org/linux/man-pages/man5/proc_pid_status.5.html>
32 ///
33 /// Note this does not necessarily get all fields, only the ones we use in
34 /// bottom.
35 pub(crate) struct Stat {
36 /// The filename of the executable without parentheses.
37 pub comm: String,
38
39 /// The current process state, represented by a char.
40 pub state: char,
41
42 /// The parent process PID.
43 pub ppid: Pid,
44
45 /// The amount of time this process has been scheduled in user mode in clock
46 /// ticks.
47 pub utime: u64,
48
49 /// The amount of time this process has been scheduled in kernel mode in
50 /// clock ticks.
51 pub stime: u64,
52
53 /// The resident set size, or the number of pages the process has in real
54 /// memory.
55 rss: u64,
56
57 /// The virtual memory size in bytes.
58 pub vsize: u64,
59
60 /// The start time of the process, represented in clock ticks.
61 pub start_time: u64,
62
63 /// Kernel thread
64 pub is_kernel_thread: bool,
65
66 /// The kernel scheduling priority.
67 pub priority: i32,
68
69 /// The nice value (user-settable scheduling hint).
70 #[cfg(unix)]
71 pub nice: i32,
72 }
73
74 impl Stat {
75 /// Get process stats from a file; this assumes the file is located at
76 /// `/proc/<PID>/stat`. For documentation, see
77 /// [here](https://manpages.ubuntu.com/manpages/noble/man5/proc_pid_stat.5.html) as a reference.
78 fn from_file(mut f: File, buffer: &mut String) -> anyhow::Result<Stat> {
79 // Since this is just one line, we can read it all at once. However, since it
80 // (technically) might have non-utf8 characters, we can't just use
81 // read_to_string.
82 f.read_to_end(unsafe { buffer.as_mut_vec() })?;
83
84 // TODO: Is this needed?
85 let line = buffer.trim();
86
87 // Comm is represented by a string in parentheses (e.g. `(foo)`, `((bar))`).
88 // To handle that second case, we need to find the "last" closing parentheses.
89 let (comm, rest) = {
90 let start_paren = line
91 .find('(')
92 .ok_or_else(|| anyhow!("start paren missing"))?;
93
94 // So, we _could_ try and be smart and only parse a limited slice of the string - however,
95 // there appears to be no ABI guarantees of comm length anymore, so we just take the hit and do an rsplit
96 // over the full string.
97 //
98 // Sources/discussion:
99 // - https://man.archlinux.org/man/proc_pid_stat.5.en
100 // - https://stackoverflow.com/questions/23534263/what-is-the-maximum-allowed-limit-on-the-length-of-a-process-name#comment138697304_23534499
101 // - https://elixir.bootlin.com/linux/v7.1.3/source/fs/proc/array.c#L100
102 // - https://github.com/ClementTsang/bottom/pull/2163#issuecomment-5017857303
103 let (comm, rest) = line[start_paren + 1..]
104 .rsplit_once(") ")
105 .ok_or_else(|| anyhow!("stat string is malformed"))?;
106
107 (comm.to_string(), rest)
108 };
109
110 let mut rest = rest.split(' ');
111 let state = next_part(&mut rest)?
112 .chars()
113 .next()
114 .ok_or_else(|| anyhow!("missing state"))?;
115 let ppid: Pid = next_part(&mut rest)?.parse()?;
116
117 // Skip 4 fields (pgrp, session, tty_nr, tpgid)
118 let mut rest = rest.skip(4);
119
120 // read flags for kernel thread (PF_KTHREAD from include/linux/sched.h)
121 let flags: u32 = next_part(&mut rest)?.parse()?;
122 let is_kernel_thread: bool = flags & 0x00200000 != 0;
123
124 // Skip 4 fields (minflt, cminflt, majflt, cmajflt)
125 let mut rest = rest.skip(4);
126 let utime: u64 = next_part(&mut rest)?.parse()?;
127 let stime: u64 = next_part(&mut rest)?.parse()?;
128
129 // cutime
130 let _ = next_part(&mut rest)?;
131 // cstime
132 let _ = next_part(&mut rest)?;
133 // priority
134 let priority: i32 = next_part(&mut rest)?.parse()?;
135 // nice
136 let nice: i32 = next_part(&mut rest)?.parse()?;
137 // num_threads
138 let _ = next_part(&mut rest)?;
139 // itrealvalue
140 let _ = next_part(&mut rest)?;
141
142 let start_time: u64 = next_part(&mut rest)?.parse()?;
143 let vsize: u64 = next_part(&mut rest)?.parse()?;
144 let rss: u64 = next_part(&mut rest)?.parse()?;
145
146 Ok(Stat {
147 comm,
148 state,
149 ppid,
150 utime,
151 stime,
152 rss,
153 vsize,
154 start_time,
155 is_kernel_thread,
156 priority,
157 nice,
158 })
159 }
160
161 /// Returns the Resident Set Size in bytes.
162 #[inline]
163 pub fn rss_bytes(&self) -> u64 {
164 self.rss * PAGESIZE.get_or_init(|| rustix::param::page_size() as u64)
165 }
166 }
167
168 /// A wrapper around the data in `/proc/<PID>/io`.
169 ///
170 /// Note this does not necessarily get all fields, only the ones we use in
171 /// bottom.
172 pub(crate) struct Io {
173 pub read_bytes: u64,
174 pub write_bytes: u64,
175 }
176
177 impl Io {
178 #[inline]
179 fn from_file(f: File, buffer: &mut String) -> anyhow::Result<Io> {
180 const NUM_FIELDS: u16 = 0; // Make sure to update this if you want more fields!
181 enum Fields {
182 ReadBytes,
183 WriteBytes,
184 }
185
186 let mut read_fields = 0;
187 let mut reader = BufReader::new(f);
188
189 let mut read_bytes = 0;
190 let mut write_bytes = 0;
191
192 // This saves us from doing a string allocation on each iteration compared to
193 // `lines()`.
194 while let Ok(bytes) = reader.read_line(buffer) {
195 if bytes > 0 {
196 if buffer.is_empty() {
197 // Empty, no need to clear.
198 continue;
199 }
200
201 let mut parts = buffer.split_whitespace();
202
203 if let Some(field) = parts.next() {
204 let curr_field = match field {
205 "read_bytes:" => Fields::ReadBytes,
206 "write_bytes:" => Fields::WriteBytes,
207 _ => {
208 buffer.clear();
209 continue;
210 }
211 };
212
213 if let Some(value) = parts.next() {
214 let value = value.parse::<u64>()?;
215 match curr_field {
216 Fields::ReadBytes => {
217 read_bytes = value;
218 read_fields += 1;
219 }
220 Fields::WriteBytes => {
221 write_bytes = value;
222 read_fields += 1;
223 }
224 }
225 }
226 }
227
228 // Quick short circuit if we have already read all the required fields.
229 if read_fields == NUM_FIELDS {
230 break;
231 }
232
233 buffer.clear();
234 } else {
235 break;
236 }
237 }
238
239 Ok(Io {
240 read_bytes,
241 write_bytes,
242 })
243 }
244 }
245
246 /// A wrapper around a Linux process operations in `/proc/<PID>`.
247 ///
248 /// Core documentation based on [proc's manpages](https://man7.org/linux/man-pages/man5/proc.5.html).
249 pub(crate) struct Process {
250 pub pid: Pid,
251 pub uid: Option<uid_t>,
252 pub stat: Stat,
253 pub io: Option<Io>,
254 pub cmdline: Option<String>,
255 }
256
257 #[inline]
258 fn reset(root: &mut PathBuf, buffer: &mut String) {
259 root.pop();
260 buffer.clear();
261 }
262
263 impl Process {
264 /// Creates a new [`Process`] given a `/proc/<PID>` path. This may fail if
265 /// the process no longer exists or there are permissions issues.
266 ///
267 /// Note that this pre-allocates fields on **creation**! As such, some data
268 /// might end up "outdated" depending on when you call some of the
269 /// methods. Therefore, this struct is only useful for either fields
270 /// that are unlikely to change, or are short-lived and
271 /// will be discarded quickly.
272 ///
273 /// This takes in a buffer to avoid allocs; this function will clear the
274 /// buffer.
275 #[inline]
276 pub(crate) fn from_path(
277 pid_path: PathBuf, buffer: &mut String, get_threads: bool,
278 ) -> anyhow::Result<(Process, Vec<PathBuf>)> {
279 buffer.clear();
280
281 let pid_dir = rustix::fs::openat(
282 rustix::fs::CWD,
283 pid_path.as_path(),
284 OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
285 Mode::empty(),
286 )?;
287
288 let pid = pid_path
289 .as_path()
290 .components()
291 .next_back()
292 .and_then(|s| s.to_string_lossy().parse::<Pid>().ok())
293 .or_else(|| {
294 rustix::fs::readlinkat(rustix::fs::CWD, pid_path.as_path(), vec![])
295 .ok()
296 .and_then(|s| s.to_string_lossy().parse::<Pid>().ok())
297 })
298 .ok_or_else(|| anyhow!("PID for {pid_path:?} was not found"))?;
299
300 let uid = {
301 let metadata = rustix::fs::fstat(&pid_dir);
302 match metadata {
303 Ok(md) => Some(md.st_uid),
304 Err(_) => None,
305 }
306 };
307
308 let mut root = pid_path;
309
310 // NB: Whenever you add a new stat, make sure to pop the root and clear the
311 // buffer!
312
313 // Stat is pretty long, do this first to pre-allocate up-front.
314 let stat =
315 open_at(&mut root, "stat", &pid_dir).and_then(|file| Stat::from_file(file, buffer))?;
316 reset(&mut root, buffer);
317
318 let cmdline = if cmdline(&mut root, &pid_dir, buffer).is_ok() {
319 // The clone will give a string with the capacity of the length of buffer, don't
320 // worry.
321 Some(buffer.clone())
322 } else {
323 None
324 };
325 reset(&mut root, buffer);
326
327 let io = open_at(&mut root, "io", &pid_dir)
328 .and_then(|file| Io::from_file(file, buffer))
329 .ok();
330
331 reset(&mut root, buffer);
332
333 let threads = threads(&mut root, pid, get_threads);
334
335 Ok((
336 Process {
337 pid,
338 uid,
339 stat,
340 io,
341 cmdline,
342 },
343 threads,
344 ))
345 }
346 }
347
348 #[inline]
349 fn cmdline(root: &mut PathBuf, fd: &OwnedFd, buffer: &mut String) -> anyhow::Result<()> {
350 let _ = open_at(root, "cmdline", fd).map(|mut file| file.read_to_string(buffer))?;
351
352 Ok(())
353 }
354
355 /// Opens a path. Note that this function takes in a mutable root - this will
356 /// mutate it to avoid allocations. You probably will want to pop the most
357 /// recent child after if you need to use the buffer again.
358 #[inline]
359 fn open_at(root: &mut PathBuf, child: &str, fd: &OwnedFd) -> anyhow::Result<File> {
360 root.push(child);
361 let new_fd = rustix::fs::openat(fd, &*root, OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty())?;
362
363 Ok(File::from(new_fd))
364 }
365
366 #[inline]
367 fn threads(root: &mut PathBuf, pid: Pid, get_threads: bool) -> Vec<PathBuf> {
368 if get_threads {
369 root.push("task");
370
371 let Ok(task_dir) = rustix::fs::openat(
372 rustix::fs::CWD,
373 root.as_path(),
374 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
375 Mode::empty(),
376 ) else {
377 return Vec::new();
378 };
379
380 if let Ok(task) = rustix::fs::Dir::read_from(task_dir) {
381 let pid_str = pid.to_string();
382
383 return task
384 .flatten()
385 .filter_map(|thread_dir| {
386 let file_name = thread_dir.file_name();
387 let file_name = file_name.to_string_lossy();
388 let file_name = file_name.trim();
389
390 if is_str_numeric(file_name) && file_name != pid_str {
391 Some(root.join(file_name).to_path_buf())
392 } else {
393 None
394 }
395 })
396 .collect::<Vec<_>>();
397 }
398 }
399
400 Vec::new()
401 }
402
403 #[cfg(test)]
404 mod tests {
405 use std::io::{Seek, Write};
406
407 use super::*;
408
409 fn stat_from_name(name: &str) -> anyhow::Result<Stat> {
410 // Kinda garbage data but it should be fine.
411 let stat = format!(
412 "0 ({name}) R 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"
413 );
414
415 stat_file(&stat)
416 }
417
418 fn stat_file(stat: &str) -> anyhow::Result<Stat> {
419 let mut file = tempfile::tempfile().unwrap();
420 file.write_all(stat.as_bytes()).unwrap();
421 file.rewind().unwrap();
422
423 Stat::from_file(file, &mut String::new())
424 }
425
426 #[test]
427 fn parse_short_comm() {
428 let stat = stat_from_name("kworker/u16:2").unwrap();
429 assert_eq!(stat.comm, "kworker/u16:2");
430 }
431
432 #[test]
433 fn parse_long_comm() {
434 let stat = stat_from_name("kworker/u16:2-events_unbound").unwrap();
435 assert_eq!(stat.comm, "kworker/u16:2-events_unbound");
436 }
437
438 #[test]
439 fn parse_64_char_comm() {
440 let comm = "a".repeat(64);
441 let stat = stat_from_name(comm.as_str()).unwrap();
442 assert_eq!(stat.comm, comm);
443 }
444
445 #[test]
446 fn parse_double_paren_comm() {
447 let stat = stat_from_name("(sd-pam)").unwrap();
448 assert_eq!(stat.comm, "(sd-pam)");
449 }
450
451 #[test]
452 fn parse_comm_with_space() {
453 let stat = stat_from_name("a test").unwrap();
454 assert_eq!(stat.comm, "a test");
455 }
456
457 #[test]
458 fn parse_invalid_stat() {
459 assert!(stat_file("1 (blah").is_err(), "missing end paren");
460 assert!(stat_file("1 (blah)").is_err(), "too short");
461 assert!(stat_file("1 )(").is_err(), "wrong order");
462 }
463 }