Debian Codegraph @

src/collection/processes/unix/process_ext.rs

raw symbols SCIP
1 //! Shared process data harvesting code from macOS and FreeBSD via sysinfo.
2
3 use std::{io, time::Duration};
4
5 use itertools::Itertools;
6 use sysinfo::{ProcessStatus, System};
7
8 use super::{ProcessHarvest, process_status_str};
9 #[cfg(target_os = "macos")]
10 use crate::collection::processes::macos::sysctl_bindings;
11 use crate::{
12 collection::{Pid, error::CollectionResult, processes::UserTable},
13 utils::int_hash::IntHashMap,
14 };
15
16 fn get_nice(pid: Pid) -> i32 {
17 // SAFETY: getpriority takes no user pointers; pid is passed as a value
18 // and errors are reported via the return value.
19 cfg_select! {
20 target_os = "freebsd" => {
21 unsafe { libc::getpriority(libc::PRIO_PROCESS, pid) }
22 }
23 target_os = "macos" => {
24 unsafe { libc::getpriority(libc::PRIO_PROCESS, pid as u32) }
25 }
26 _ => {
27 0
28 }
29 }
30 }
31
32 fn get_priority(pid: Pid) -> i32 {
33 cfg_select! {
34 target_os = "macos" => {
35 if let Ok(kinfo) = sysctl_bindings::kinfo_process(pid) {
36 kinfo.kp_proc.p_priority as i32
37 } else {
38 0
39 }
40 }
41 target_os = "freebsd" => {
42 use libc::{c_int, c_void};
43 use std::{mem, ptr};
44
45 let mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_PID, pid as c_int];
46 let mut kp: libc::kinfo_proc = unsafe { mem::zeroed() };
47 let mut size = mem::size_of::<libc::kinfo_proc>();
48
49 // SAFETY: sysctl takes the following pointer arguments
50 // - mib is valid for KERN_PROC_PID.
51 // - kp is a properly sized output buffer.
52 // - newp is null for a read-only sysctl.
53 let ret = unsafe {
54 libc::sysctl(
55 mib.as_ptr(),
56 mib.len() as u32,
57 &mut kp as *mut _ as *mut c_void,
58 &mut size,
59 ptr::null_mut(),
60 0,
61 )
62 };
63
64 if ret == 0 { kp.ki_pri.pri_level as i32 } else { 0 }
65 }
66 _ => {
67 0
68 }
69 }
70 }
71
72 pub(crate) trait UnixProcessExt {
73 fn sysinfo_process_data(
74 sys: &System, use_current_cpu_total: bool, unnormalized_cpu: bool, total_memory: u64,
75 user_table: &mut UserTable,
76 ) -> CollectionResult<Vec<ProcessHarvest>> {
77 let mut process_vector: Vec<ProcessHarvest> = Vec::new();
78 let process_hashmap = sys.processes();
79 let cpu_usage = sys.global_cpu_usage() / 100.0;
80 let num_processors = sys.cpus().len();
81
82 for process_val in process_hashmap.values() {
83 let name = if process_val.name().is_empty() {
84 let process_cmd = process_val.cmd();
85 if let Some(name) = process_cmd.first() {
86 name.to_string_lossy().to_string()
87 } else {
88 process_val
89 .exe()
90 .and_then(|exe| exe.file_stem())
91 .and_then(|stem| stem.to_str())
92 .map(|s| s.to_string())
93 .unwrap_or(String::new())
94 }
95 } else {
96 process_val.name().to_string_lossy().to_string()
97 };
98 let command = {
99 let command = process_val
100 .cmd()
101 .iter()
102 .map(|s| s.to_string_lossy())
103 .join(" ");
104 if command.is_empty() {
105 name.clone()
106 } else {
107 command
108 }
109 };
110
111 let pcu = {
112 let usage = process_val.cpu_usage();
113 if unnormalized_cpu || num_processors == 0 {
114 usage
115 } else {
116 usage / num_processors as f32
117 }
118 };
119 let process_cpu_usage = if use_current_cpu_total && cpu_usage > 0.0 {
120 pcu / cpu_usage
121 } else {
122 pcu
123 };
124
125 let disk_usage = process_val.disk_usage();
126 let process_state = {
127 let ps = process_val.status();
128 (process_status_str(ps), convert_process_status_to_char(ps))
129 };
130 let uid = process_val.user_id().map(|u| **u);
131 let pid = process_val.pid().as_u32() as Pid;
132 let nice = get_nice(pid);
133 let priority = get_priority(pid);
134
135 process_vector.push(ProcessHarvest {
136 pid,
137 parent_pid: Self::parent_pid(process_val),
138 name,
139 command,
140 mem_usage_percent: if total_memory > 0 {
141 (process_val.memory() as f64 * 100.0 / total_memory as f64) as f32
142 } else {
143 0.0
144 },
145 mem_usage: process_val.memory(),
146 virtual_mem: process_val.virtual_memory(),
147 cpu_usage_percent: process_cpu_usage,
148 read_per_sec: disk_usage.read_bytes,
149 write_per_sec: disk_usage.written_bytes,
150 total_read: disk_usage.total_read_bytes,
151 total_write: disk_usage.total_written_bytes,
152 process_state,
153 uid,
154 user: uid.and_then(|uid| user_table.uid_to_username(uid).ok()),
155 time: if process_val.start_time() == 0 {
156 Duration::ZERO
157 } else {
158 Duration::from_secs(process_val.run_time())
159 },
160 #[cfg(feature = "gpu")]
161 gpu_mem: 0,
162 #[cfg(feature = "gpu")]
163 gpu_mem_percent: 0.0,
164 #[cfg(feature = "gpu")]
165 gpu_util: 0,
166 #[cfg(unix)]
167 nice,
168 priority,
169 });
170 }
171
172 if Self::has_backup_proc_cpu_fn() {
173 let unknown_state = ProcessStatus::Unknown(0).to_string();
174 let cpu_usage_unknown_pids: Vec<Pid> = process_vector
175 .iter()
176 .filter(|process| process.process_state.0 == unknown_state)
177 .map(|process| process.pid)
178 .collect();
179 let cpu_usages = Self::backup_proc_cpu(&cpu_usage_unknown_pids)?;
180 for process in &mut process_vector {
181 if let Some(&cpu_usage) = cpu_usages.get(&process.pid) {
182 process.cpu_usage_percent = if unnormalized_cpu || num_processors == 0 {
183 cpu_usage
184 } else {
185 cpu_usage / num_processors as f32
186 };
187 }
188 }
189 }
190
191 Ok(process_vector)
192 }
193
194 #[inline]
195 fn has_backup_proc_cpu_fn() -> bool {
196 false
197 }
198
199 fn backup_proc_cpu(_pids: &[Pid]) -> io::Result<IntHashMap<Pid, f32>> {
200 Ok(IntHashMap::default())
201 }
202
203 fn parent_pid(process_val: &sysinfo::Process) -> Option<Pid> {
204 process_val.parent().map(|p| p.as_u32() as _)
205 }
206 }
207
208 fn convert_process_status_to_char(status: ProcessStatus) -> char {
209 // TODO: Based on https://github.com/GuillaumeGomez/sysinfo/blob/baa46efb46d82f21b773088603720262f4a34646/src/unix/freebsd/process.rs#L13?
210 cfg_select! {
211 target_os = "macos" => {
212 // SAFETY: These are all const and should be valid characters.
213 const SIDL: char = unsafe { char::from_u32_unchecked(libc::SIDL) };
214
215 // SAFETY: These are all const and should be valid characters.
216 const SRUN: char = unsafe { char::from_u32_unchecked(libc::SRUN) };
217
218 // SAFETY: These are all const and should be valid characters.
219 const SSLEEP: char = unsafe { char::from_u32_unchecked(libc::SSLEEP) };
220
221 // SAFETY: These are all const and should be valid characters.
222 const SSTOP: char = unsafe { char::from_u32_unchecked(libc::SSTOP) };
223
224 // SAFETY: These are all const and should be valid characters.
225 const SZOMB: char = unsafe { char::from_u32_unchecked(libc::SZOMB) };
226
227 match status {
228 ProcessStatus::Idle => SIDL,
229 ProcessStatus::Run => SRUN,
230 ProcessStatus::Sleep => SSLEEP,
231 ProcessStatus::Stop => SSTOP,
232 ProcessStatus::Zombie => SZOMB,
233 _ => '?'
234 }
235 }
236 target_os = "freebsd" => {
237 const fn assert_u8(val: libc::c_char) -> u8 {
238 if val < 0 { panic!("there was an invalid i8 constant that is supposed to be a char") } else { val as u8 }
239 }
240
241 const SIDL: u8 = assert_u8(libc::SIDL);
242 const SRUN: u8 = assert_u8(libc::SRUN);
243 const SSLEEP: u8 = assert_u8(libc::SSLEEP);
244 const SSTOP: u8 = assert_u8(libc::SSTOP);
245 const SZOMB: u8 = assert_u8(libc::SZOMB);
246 const SWAIT: u8 = assert_u8(libc::SWAIT);
247 const SLOCK: u8 = assert_u8(libc::SLOCK);
248
249 match status {
250 ProcessStatus::Idle => SIDL as char,
251 ProcessStatus::Run => SRUN as char,
252 ProcessStatus::Sleep => SSLEEP as char,
253 ProcessStatus::Stop => SSTOP as char,
254 ProcessStatus::Zombie => SZOMB as char,
255 ProcessStatus::Dead => SWAIT as char,
256 ProcessStatus::LockBlocked => SLOCK as char,
257 _ => '?'
258 }
259 }
260 _ => {
261 '?'
262 }
263 }
264 }