Debian Codegraph @

src/collection/processes/windows.rs

raw symbols SCIP
1 //! Process data collection for Windows. Uses sysinfo.
2
3 use std::time::Duration;
4
5 use anyhow::bail;
6 use itertools::Itertools;
7 use windows::Win32::{
8 Foundation::{CloseHandle, HANDLE},
9 System::Threading::{GetPriorityClass, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION},
10 };
11
12 use super::{ProcessHarvest, process_status_str};
13 use crate::collection::{DataCollector, error::CollectionResult};
14
15 /// See [here](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getpriorityclass)
16 /// for more information on the core Windows API being called and the meaning of
17 /// the priorities, as well as the access rights needed.
18 fn get_priority(pid: u32) -> anyhow::Result<i32> {
19 // SAFETY: We check validity of each step and bail on errors. We also close the
20 // handle.
21 unsafe {
22 let process_handle: HANDLE = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid)?;
23 if process_handle.is_invalid() {
24 bail!("Failed to open process with PID {pid} to get priority class");
25 }
26
27 // From docs: "If the function fails, the return value is zero."
28 let priority = GetPriorityClass(process_handle);
29 if priority == 0 {
30 bail!("Failed to get priority class for process with PID {pid}");
31 }
32
33 let handle_result = CloseHandle(process_handle);
34 if let Err(err) = handle_result {
35 bail!(err);
36 }
37
38 Ok(priority as i32)
39 }
40 }
41
42 // TODO: There's a lot of shared code with this and the unix impl.
43 pub fn sysinfo_process_data(
44 collector: &mut DataCollector,
45 ) -> CollectionResult<Vec<ProcessHarvest>> {
46 let sys = &collector.sys.system;
47 let users = &collector.sys.users;
48 let use_current_cpu_total = collector.use_current_cpu_total;
49 let unnormalized_cpu = collector.unnormalized_cpu;
50 let total_memory = collector.total_memory();
51
52 let mut process_vector: Vec<ProcessHarvest> = Vec::new();
53 let process_hashmap = sys.processes();
54 let cpu_usage = sys.global_cpu_usage() / 100.0;
55 let num_processors = sys.cpus().len();
56
57 for process in process_hashmap.values() {
58 let name = if process.name().is_empty() {
59 let process_cmd = process.cmd();
60 if process_cmd.len() > 1 {
61 process_cmd[0].to_string_lossy().to_string()
62 } else {
63 process
64 .exe()
65 .and_then(|exe| exe.file_stem())
66 .and_then(|stem| stem.to_str())
67 .map(|s| s.to_string())
68 .unwrap_or(String::new())
69 }
70 } else {
71 process.name().to_string_lossy().to_string()
72 };
73 let command = {
74 let command = process.cmd().iter().map(|s| s.to_string_lossy()).join(" ");
75 if command.is_empty() {
76 name.clone()
77 } else {
78 command
79 }
80 };
81
82 let process_cpu_usage = {
83 let pcu = {
84 let usage = process.cpu_usage();
85 if unnormalized_cpu || num_processors == 0 {
86 usage
87 } else {
88 usage / num_processors as f32
89 }
90 };
91
92 if use_current_cpu_total && cpu_usage > 0.0 {
93 pcu / cpu_usage
94 } else {
95 pcu
96 }
97 };
98
99 let disk_usage = process.disk_usage();
100 let process_state = (process_status_str(process.status()), 'R');
101
102 #[cfg(feature = "gpu")]
103 let (gpu_mem, gpu_util, gpu_mem_percent) = {
104 let mut gpu_mem = 0;
105 let mut gpu_util = 0;
106 let mut gpu_mem_percent = 0.0;
107 if let Some(gpus) = &collector.gpu_pids {
108 use crate::collection::processes::Pid;
109
110 gpus.iter().for_each(|gpu| {
111 // add mem/util for all gpus to pid
112 if let Some((mem, util)) = gpu.get(&(process.pid().as_u32() as Pid)) {
113 gpu_mem += mem;
114 gpu_util += util;
115 }
116 });
117 }
118 if let Some(gpu_total_mem) = &collector.gpus_total_mem {
119 gpu_mem_percent = (gpu_mem as f64 / *gpu_total_mem as f64 * 100.0) as f32;
120 }
121 (gpu_mem, gpu_util, gpu_mem_percent)
122 };
123
124 let pid = process.pid().as_u32();
125 let priority = get_priority(pid).unwrap_or(0);
126
127 process_vector.push(ProcessHarvest {
128 pid: pid as _,
129 parent_pid: process.parent().map(|p| p.as_u32() as _),
130 name,
131 command,
132 mem_usage_percent: if total_memory > 0 {
133 process.memory() as f64 * 100.0 / total_memory as f64
134 } else {
135 0.0
136 } as f32,
137 mem_usage: process.memory(),
138 virtual_mem: process.virtual_memory(),
139 cpu_usage_percent: process_cpu_usage,
140 read_per_sec: disk_usage.read_bytes,
141 write_per_sec: disk_usage.written_bytes,
142 total_read: disk_usage.total_read_bytes,
143 total_write: disk_usage.total_written_bytes,
144 process_state,
145 user: process
146 .user_id()
147 .and_then(|uid| users.get_user_by_id(uid).map(|user| user.name().into())),
148 time: if process.start_time() == 0 {
149 // Workaround for sysinfo occasionally returning a start time equal to UNIX
150 // epoch, giving a run time in the range of 50+ years. We just
151 // return a time of zero in this case for simplicity.
152 //
153 // TODO: Maybe return an option instead?
154 Duration::ZERO
155 } else {
156 Duration::from_secs(process.run_time())
157 },
158 #[cfg(feature = "gpu")]
159 gpu_mem,
160 #[cfg(feature = "gpu")]
161 gpu_util,
162 #[cfg(feature = "gpu")]
163 gpu_mem_percent,
164 priority, // TODO: Translate this to Windows priority names?
165 });
166 }
167
168 Ok(process_vector)
169 }