1use std::collections::VecDeque;
15
16pub const REPORT_OVER_MS: u64 = 2_000;
18const KEEP_MS: u64 = 12_000;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub struct Sample {
24 pub at_ms: u64,
25 pub machine_busy: u64,
27 pub machine_total: u64,
29 pub srv_cpu: u64,
31 pub io_read_bytes: u64,
32 pub io_write_bytes: u64,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub struct Load {
38 pub over_ms: u64,
40 pub machine_cpu_pct: u32,
42 pub srv_cpu_pct: u32,
44 pub io_read_mb: u64,
45 pub io_write_mb: u64,
46 pub mem_load_pct: Option<u32>,
48}
49
50fn pct(part: u64, whole: u64) -> u32 {
51 ((part as u128 * 100 + whole as u128 / 2) / whole as u128).min(100) as u32
52}
53
54pub fn delta(from: &Sample, to: &Sample, mem_load_pct: Option<u32>) -> Option<Load> {
56 let total = to.machine_total.checked_sub(from.machine_total).filter(|t| *t > 0)?;
57 let over_ms = to.at_ms.checked_sub(from.at_ms).filter(|t| *t > 0)?;
58 Some(Load {
59 over_ms,
60 machine_cpu_pct: pct(to.machine_busy.saturating_sub(from.machine_busy), total),
61 srv_cpu_pct: pct(to.srv_cpu.saturating_sub(from.srv_cpu), total),
62 io_read_mb: to.io_read_bytes.saturating_sub(from.io_read_bytes) / (1024 * 1024),
63 io_write_mb: to.io_write_bytes.saturating_sub(from.io_write_bytes) / (1024 * 1024),
64 mem_load_pct,
65 })
66}
67
68#[derive(Debug, Default)]
70pub struct History {
71 samples: VecDeque<Sample>,
72}
73
74impl History {
75 pub fn push(&mut self, sample: Sample) {
77 while self.samples.front().is_some_and(|s| sample.at_ms.saturating_sub(s.at_ms) > KEEP_MS) {
78 self.samples.pop_front();
79 }
80 self.samples.push_back(sample);
81 }
82
83 pub fn load_over(&self, over_ms: u64, mem_load_pct: Option<u32>) -> Option<Load> {
86 let newest = self.samples.back()?;
87 let from = self
88 .samples
89 .iter()
90 .rev()
91 .find(|s| newest.at_ms.saturating_sub(s.at_ms) >= over_ms)
92 .or_else(|| self.samples.front())?;
93 delta(from, newest, mem_load_pct)
94 }
95}
96
97#[cfg(windows)]
99pub fn read(at_ms: u64) -> Option<Sample> {
100 use windows_sys::Win32::Foundation::FILETIME;
101 use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessIoCounters, GetProcessTimes, GetSystemTimes, IO_COUNTERS};
102 let value = |f: FILETIME| (u64::from(f.dwHighDateTime) << 32) | u64::from(f.dwLowDateTime);
103 let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
104 let (mut idle, mut kernel, mut user) = (zero, zero, zero);
105 if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
107 return None;
108 }
109 let (mut created, mut exited, mut proc_kernel, mut proc_user) = (zero, zero, zero, zero);
110 let process = unsafe { GetCurrentProcess() };
112 if unsafe { GetProcessTimes(process, &mut created, &mut exited, &mut proc_kernel, &mut proc_user) } == 0 {
113 return None;
114 }
115 let mut io: IO_COUNTERS = unsafe { std::mem::zeroed() };
117 let io_ok = unsafe { GetProcessIoCounters(process, &mut io) } != 0;
118 let total = value(kernel) + value(user);
119 Some(Sample {
120 at_ms,
121 machine_busy: total.saturating_sub(value(idle)),
122 machine_total: total,
123 srv_cpu: value(proc_kernel) + value(proc_user),
124 io_read_bytes: if io_ok { io.ReadTransferCount } else { 0 },
125 io_write_bytes: if io_ok { io.WriteTransferCount } else { 0 },
126 })
127}
128
129#[cfg(not(windows))]
130pub fn read(_at_ms: u64) -> Option<Sample> {
131 None
132}
133
134#[cfg(windows)]
136pub fn mem_load_pct() -> Option<u32> {
137 use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
138 let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
140 mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
141 (unsafe { GlobalMemoryStatusEx(&mut mem) } != 0).then_some(mem.dwMemoryLoad)
142}
143
144#[cfg(not(windows))]
145pub fn mem_load_pct() -> Option<u32> {
146 None
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152
153 fn sample(at_ms: u64, busy: u64, total: u64, srv: u64, read_mb: u64, write_mb: u64) -> Sample {
154 Sample { at_ms, machine_busy: busy, machine_total: total, srv_cpu: srv, io_read_bytes: read_mb << 20, io_write_bytes: write_mb << 20 }
155 }
156
157 #[test]
158 fn a_busy_machine_and_a_quiet_srv_read_as_such() {
159 let a = sample(1_000, 0, 0, 0, 10, 10);
161 let b = sample(3_000, 576_000_000, 640_000_000, 19_200_000, 10, 50);
162 let load = delta(&a, &b, Some(71)).unwrap();
163 assert_eq!(load, Load { over_ms: 2_000, machine_cpu_pct: 90, srv_cpu_pct: 3, io_read_mb: 0, io_write_mb: 40, mem_load_pct: Some(71) });
164 }
165
166 #[test]
167 fn no_time_between_two_readings_is_no_figure() {
168 let a = sample(1_000, 5, 10, 1, 0, 0);
169 assert_eq!(delta(&a, &a, None), None);
170 assert_eq!(delta(&sample(2_000, 5, 10, 1, 0, 0), &sample(1_000, 6, 11, 2, 0, 0), None), None);
171 assert_eq!(delta(&sample(1_000, 5, 10, 1, 0, 0), &sample(2_000, 5, 10, 1, 0, 0), None), None, "no CPU time passed");
172 }
173
174 #[test]
175 fn a_share_never_exceeds_a_hundred() {
176 let load = delta(&sample(0, 0, 0, 0, 0, 0), &sample(1_000, 300, 100, 500, 0, 0), None).unwrap();
177 assert_eq!((load.machine_cpu_pct, load.srv_cpu_pct), (100, 100));
178 }
179
180 #[test]
181 fn the_history_looks_back_the_span_asked_and_forgets_the_old() {
182 let mut h = History::default();
183 for i in 0..100u64 {
184 h.push(sample(i * 250, i * 10, i * 20, i, 0, 0));
185 }
186 let load = h.load_over(REPORT_OVER_MS, None).unwrap();
188 assert_eq!(load.over_ms, 2_000);
189 assert_eq!(load.machine_cpu_pct, 50);
190 assert!(h.samples.len() <= 50, "readings older than 12 s are dropped, kept {}", h.samples.len());
191 }
192
193 #[test]
194 fn a_short_history_reports_what_there_is() {
195 let mut h = History::default();
196 assert_eq!(h.load_over(REPORT_OVER_MS, None), None);
197 h.push(sample(0, 0, 0, 0, 0, 0));
198 assert_eq!(h.load_over(REPORT_OVER_MS, None), None, "one reading is no span");
199 h.push(sample(500, 5, 10, 1, 0, 0));
200 assert_eq!(h.load_over(REPORT_OVER_MS, None).unwrap().over_ms, 500);
201 }
202
203 #[cfg(windows)]
204 #[test]
205 fn the_counters_are_read_on_windows() {
206 let a = read(0).expect("a reading");
207 let mut x = 0u64;
208 for i in 0..50_000_000u64 {
209 x = x.wrapping_add(i);
210 }
211 std::hint::black_box(x);
212 let b = read(100).expect("a second reading");
213 assert!(b.machine_total >= a.machine_total && b.srv_cpu >= a.srv_cpu);
214 assert!(mem_load_pct().is_some_and(|p| p <= 100));
215 }
216}