BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / host_load.rs

host_load.rs

host_load.rs 10.3 KiB Download Raw
1use std::collections::HashMap;
2
3/// One thread and the CPU time it has used since the process started, in milliseconds.
4/// `id` is the kernel thread id, not the Mach port and not the pthread name.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct ThreadCpu {
7 pub id: u64,
8 pub name: String,
9 pub cpu_ms: u64,
10}
11
12pub fn recorded_on_this_platform() -> bool {
13 cfg!(target_os = "macos")
14}
15
16/// CPU used since the previous sample, summed by thread name. The first sample reports the
17/// time already used. Threads that share a name (tokio workers) stay separate in `previous`
18/// and add up on the line.
19pub fn cpu_deltas(current: &[ThreadCpu], previous: &mut HashMap<u64, u64>) -> Vec<(String, u64)> {
20 let mut seen = Vec::with_capacity(current.len());
21 let mut totals: HashMap<String, u64> = HashMap::new();
22 for thread in current {
23 let before = previous.get(&thread.id).copied().unwrap_or(0);
24 *totals.entry(thread.name.clone()).or_default() += thread.cpu_ms.saturating_sub(before);
25 previous.insert(thread.id, thread.cpu_ms);
26 seen.push(thread.id);
27 }
28 previous.retain(|id, _| seen.contains(id));
29 let mut deltas: Vec<(String, u64)> = totals.into_iter().collect();
30 deltas.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
31 deltas
32}
33
34const SHOWN_THREADS: usize = 8;
35
36pub fn host_load_line(deltas: &[(String, u64)], effects: &str, thermal: &str) -> String {
37 let active: Vec<_> = deltas.iter().filter(|(_, cpu_ms)| *cpu_ms > 0).collect();
38 let threads = if active.is_empty() {
39 "no thread cpu".to_owned()
40 } else {
41 let shown = active.len().min(SHOWN_THREADS);
42 let mut parts: Vec<String> = active[..shown]
43 .iter()
44 .map(|(name, cpu_ms)| format!("{name} {cpu_ms}ms"))
45 .collect();
46 if active.len() > SHOWN_THREADS {
47 let rest: u64 = active[SHOWN_THREADS..]
48 .iter()
49 .map(|(_, cpu_ms)| *cpu_ms)
50 .sum();
51 parts.push(format!("others {rest}ms"));
52 }
53 parts.join(", ")
54 };
55 format!("{threads}; {effects}; thermal {thermal}")
56}
57
58/// Cumulative CPU time per thread. Empty off macOS, and empty when the kernel call fails.
59pub fn thread_cpu() -> Vec<ThreadCpu> {
60 #[cfg(target_os = "macos")]
61 {
62 macos::thread_cpu()
63 }
64 #[cfg(not(target_os = "macos"))]
65 {
66 Vec::new()
67 }
68}
69
70pub fn thermal_state() -> &'static str {
71 #[cfg(target_os = "macos")]
72 {
73 macos::thermal_state()
74 }
75 #[cfg(not(target_os = "macos"))]
76 {
77 "unavailable"
78 }
79}
80
81#[cfg(target_os = "macos")]
82mod macos {
83 use super::ThreadCpu;
84
85 unsafe extern "C" {
86 fn mach_port_deallocate(
87 task: libc::mach_port_t,
88 name: libc::mach_port_t,
89 ) -> libc::kern_return_t;
90 }
91
92 pub fn thermal_state() -> &'static str {
93 let state = objc2_foundation::NSProcessInfo::processInfo().thermalState();
94 match state {
95 objc2_foundation::NSProcessInfoThermalState::Nominal => "nominal",
96 objc2_foundation::NSProcessInfoThermalState::Fair => "fair",
97 objc2_foundation::NSProcessInfoThermalState::Serious => "serious",
98 objc2_foundation::NSProcessInfoThermalState::Critical => "critical",
99 _ => "unknown",
100 }
101 }
102
103 pub fn thread_cpu() -> Vec<ThreadCpu> {
104 unsafe {
105 let task = libc::mach_task_self();
106 let mut threads: libc::thread_act_array_t = std::ptr::null_mut();
107 let mut count: libc::mach_msg_type_number_t = 0;
108 if libc::task_threads(task, &mut threads, &mut count) != libc::KERN_SUCCESS {
109 return Vec::new();
110 }
111 let mut found = Vec::with_capacity(count as usize);
112 for index in 0..count {
113 let thread = *threads.add(index as usize);
114 let mut info: libc::thread_basic_info = std::mem::zeroed();
115 let mut info_count = libc::THREAD_BASIC_INFO_COUNT;
116 let status = libc::thread_info(
117 thread,
118 libc::THREAD_BASIC_INFO,
119 &mut info as *mut libc::thread_basic_info as libc::thread_info_t,
120 &mut info_count,
121 );
122 if status == libc::KERN_SUCCESS
123 && let Some(id) = thread_id(thread)
124 {
125 found.push(ThreadCpu {
126 id,
127 name: thread_name(thread),
128 cpu_ms: cpu_ms(&info),
129 });
130 }
131 // task_threads hands back a send right per thread. Freeing the array does not release those.
132 let _ = mach_port_deallocate(task, thread);
133 }
134 let bytes = count as libc::vm_size_t
135 * std::mem::size_of::<libc::thread_act_t>() as libc::vm_size_t;
136 let _ = libc::vm_deallocate(task, threads as libc::vm_address_t, bytes);
137 found
138 }
139 }
140
141 fn cpu_ms(info: &libc::thread_basic_info) -> u64 {
142 let part = |time: libc::time_value_t| {
143 let seconds = i64::from(time.seconds).max(0);
144 let micros = i64::from(time.microseconds).max(0);
145 seconds.saturating_mul(1000) + micros / 1000
146 };
147 part(info.user_time).saturating_add(part(info.system_time)) as u64
148 }
149
150 /// Stable across samples. The Mach port from `task_threads` is reused after
151 /// `mach_port_deallocate`, so it cannot key the previous sample.
152 fn thread_id(thread: libc::thread_act_t) -> Option<u64> {
153 unsafe {
154 let mut info: libc::thread_identifier_info = std::mem::zeroed();
155 let mut count = libc::THREAD_IDENTIFIER_INFO_COUNT;
156 let status = libc::thread_info(
157 thread,
158 libc::THREAD_IDENTIFIER_INFO,
159 &mut info as *mut libc::thread_identifier_info as libc::thread_info_t,
160 &mut count,
161 );
162 if status == libc::KERN_SUCCESS && info.thread_id != 0 {
163 Some(info.thread_id)
164 } else {
165 None
166 }
167 }
168 }
169
170 fn thread_name(thread: libc::thread_act_t) -> String {
171 unsafe {
172 let pthread = libc::pthread_from_mach_thread_np(thread);
173 if !pthread.is_null() {
174 let mut buffer = [0u8; 64];
175 if libc::pthread_getname_np(pthread, buffer.as_mut_ptr().cast(), buffer.len()) == 0
176 {
177 let end = buffer
178 .iter()
179 .position(|byte| *byte == 0)
180 .unwrap_or(buffer.len());
181 if let Ok(name) = std::str::from_utf8(&buffer[..end]) {
182 let name = name.trim();
183 if !name.is_empty() {
184 return name.to_owned();
185 }
186 }
187 }
188 }
189 format!("tid-{thread}")
190 }
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn a_host_load_line_names_the_hot_thread_the_effects_and_the_thermal_state() {
200 let mut previous = HashMap::new();
201 let first = cpu_deltas(
202 &[
203 ThreadCpu {
204 id: 1,
205 name: "camera".into(),
206 cpu_ms: 40,
207 },
208 ThreadCpu {
209 id: 2,
210 name: "camera effects".into(),
211 cpu_ms: 5,
212 },
213 ],
214 &mut previous,
215 );
216 let line = host_load_line(
217 &first,
218 "blur=off standout=off framing=off brightness=off soft_focus=off",
219 "nominal",
220 );
221 assert_eq!(
222 line,
223 "camera 40ms, camera effects 5ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal nominal"
224 );
225 let second = cpu_deltas(
226 &[
227 ThreadCpu {
228 id: 1,
229 name: "camera".into(),
230 cpu_ms: 90,
231 },
232 ThreadCpu {
233 id: 2,
234 name: "camera effects".into(),
235 cpu_ms: 5,
236 },
237 ],
238 &mut previous,
239 );
240 assert_eq!(
241 second,
242 vec![("camera".into(), 50), ("camera effects".into(), 0)]
243 );
244 }
245
246 #[test]
247 fn shared_thread_names_sum_and_idle_threads_fold_out_of_the_line() {
248 let mut previous = HashMap::new();
249 let first = cpu_deltas(
250 &[
251 ThreadCpu {
252 id: 10,
253 name: "teams-net".into(),
254 cpu_ms: 5_000,
255 },
256 ThreadCpu {
257 id: 11,
258 name: "teams-net".into(),
259 cpu_ms: 300,
260 },
261 ],
262 &mut previous,
263 );
264 assert_eq!(first, vec![("teams-net".into(), 5_300)]);
265 let second = cpu_deltas(
266 &[
267 ThreadCpu {
268 id: 10,
269 name: "teams-net".into(),
270 cpu_ms: 5_300,
271 },
272 ThreadCpu {
273 id: 11,
274 name: "teams-net".into(),
275 cpu_ms: 800,
276 },
277 ],
278 &mut previous,
279 );
280 assert_eq!(second, vec![("teams-net".into(), 800)]);
281 let mut busy = Vec::new();
282 for index in 0..10 {
283 busy.push((format!("t{index}"), 10 - index));
284 }
285 busy.push(("idle".into(), 0));
286 let line = host_load_line(
287 &busy,
288 "blur=off standout=off framing=off brightness=off soft_focus=off",
289 "unknown",
290 );
291 assert_eq!(
292 line,
293 "t0 10ms, t1 9ms, t2 8ms, t3 7ms, t4 6ms, t5 5ms, t6 4ms, t7 3ms, others 3ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal unknown"
294 );
295 }
296
297 #[test]
298 fn host_load_is_recorded_only_on_macos() {
299 assert_eq!(recorded_on_this_platform(), cfg!(target_os = "macos"));
300 if !recorded_on_this_platform() {
301 assert!(thread_cpu().is_empty());
302 assert_eq!(thermal_state(), "unavailable");
303 }
304 }
305}