Skip to main content

tak_cli/
machine.rs

1//! The machine a run was measured on, for `tak run --export-json`.
2//!
3//! A comparison page has to say what it was measured on: the same two tools
4//! can swap places between a 4-core laptop and a 64-core server. Without this
5//! every consumer of the export shells out to `lscpu`, reads `/proc/meminfo`
6//! and asks for the CPU affinity itself, and gets it subtly different from
7//! the next one.
8//!
9//! This is description, not identity. Series are partitioned on the runner
10//! class ([`crate::record::Record::runner`]), and none of this goes into
11//! recorded notes: a kernel update would otherwise split a series that the
12//! runner class deliberately keeps whole.
13//!
14//! Every field is best effort. A value tak cannot read is `None` — exported as
15//! `null` — never an error: a run that measured correctly must not fail over
16//! how to describe the CPU. Nothing here spawns a process; it reads files on
17//! Linux and asks the kernel directly on macOS and Windows.
18
19use serde::Serialize;
20
21#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
22pub struct Machine {
23    /// As Rust names it: `linux`, `macos`, `windows`.
24    pub os: String,
25    /// The distribution or product version: `/etc/os-release`'s
26    /// `PRETTY_NAME` on Linux, `15.3.1` on macOS. `None` on Windows, whose
27    /// registry names Windows 11 as Windows 10; `kernel` has the build.
28    pub os_version: Option<String>,
29    /// Kernel release: `6.8.0-45-generic` on Linux, the Darwin release on
30    /// macOS, `10.0.<build>` on Windows.
31    pub kernel: Option<String>,
32    /// As Rust names it: `x86_64`, `aarch64`.
33    pub arch: String,
34    /// The CPU's model name, as the vendor brands it.
35    pub cpu: Option<String>,
36    /// Logical CPUs tak — and so every subject — could run on. Not the
37    /// machine's total: on Linux this honours the CPU affinity mask (`taskset`,
38    /// a container's cpuset) and a cgroup CPU quota, which is what bounds a
39    /// parallel tool's speed-up.
40    pub cpus: Option<usize>,
41    /// Total physical memory in bytes.
42    pub memory_bytes: Option<u64>,
43}
44
45/// Describe this machine.
46pub fn detect() -> Machine {
47    let os = imp::detect();
48    Machine {
49        os: std::env::consts::OS.to_string(),
50        os_version: os.os_version,
51        kernel: os.kernel,
52        arch: std::env::consts::ARCH.to_string(),
53        cpu: os.cpu,
54        cpus: std::thread::available_parallelism()
55            .ok()
56            .map(std::num::NonZero::get),
57        memory_bytes: os.memory_bytes,
58    }
59}
60
61/// What each platform has to find for itself.
62#[derive(Debug, Default)]
63struct Os {
64    os_version: Option<String>,
65    kernel: Option<String>,
66    cpu: Option<String>,
67    memory_bytes: Option<u64>,
68}
69
70/// Trimmed, and `None` when that leaves nothing: an empty string would read
71/// as a value to anything consuming the export.
72fn clean(s: &str) -> Option<String> {
73    let s = s.trim().trim_matches(char::from(0)).trim();
74    (!s.is_empty()).then(|| s.to_string())
75}
76
77#[cfg(any(target_os = "linux", test))]
78mod linux_parse {
79    //! Parsers for the Linux files, compiled everywhere so their tests run on
80    //! every host.
81
82    use super::clean;
83
84    /// The first `model name` in `/proc/cpuinfo`. x86 has one per logical
85    /// CPU; arm64 kernels usually print none, and then the CPU is unknown
86    /// rather than guessed from implementer and part numbers.
87    pub fn cpu_model(cpuinfo: &str) -> Option<String> {
88        cpuinfo.lines().find_map(|l| {
89            let (k, v) = l.split_once(':')?;
90            (k.trim() == "model name").then(|| clean(v)).flatten()
91        })
92    }
93
94    /// `MemTotal` from `/proc/meminfo`, which the kernel reports in KiB
95    /// whatever the unit says.
96    pub fn mem_total(meminfo: &str) -> Option<u64> {
97        let line = meminfo.lines().find(|l| l.starts_with("MemTotal:"))?;
98        let kib: u64 = line["MemTotal:".len()..]
99            .split_whitespace()
100            .next()?
101            .parse()
102            .ok()?;
103        kib.checked_mul(1024)
104    }
105
106    /// `PRETTY_NAME` from os-release, unquoted.
107    pub fn pretty_name(os_release: &str) -> Option<String> {
108        os_release.lines().find_map(|l| {
109            let v = l.strip_prefix("PRETTY_NAME=")?;
110            let v = v.trim();
111            let v = v
112                .strip_prefix('"')
113                .and_then(|v| v.strip_suffix('"'))
114                .or_else(|| v.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
115                .unwrap_or(v);
116            clean(v)
117        })
118    }
119}
120
121#[cfg(target_os = "linux")]
122mod imp {
123    use super::{Os, clean, linux_parse};
124
125    pub(super) fn detect() -> Os {
126        let read = |p: &str| std::fs::read_to_string(p).ok();
127        Os {
128            // /etc/os-release is the standard; /usr/lib/os-release is where
129            // it points on systems that keep /etc minimal.
130            os_version: read("/etc/os-release")
131                .or_else(|| read("/usr/lib/os-release"))
132                .and_then(|t| linux_parse::pretty_name(&t)),
133            kernel: read("/proc/sys/kernel/osrelease").and_then(|t| clean(&t)),
134            cpu: read("/proc/cpuinfo").and_then(|t| linux_parse::cpu_model(&t)),
135            memory_bytes: read("/proc/meminfo").and_then(|t| linux_parse::mem_total(&t)),
136        }
137    }
138}
139
140#[cfg(target_os = "macos")]
141mod imp {
142    use super::{Os, clean};
143    use std::ffi::CStr;
144
145    /// A string sysctl, read with `sysctlbyname` rather than by spawning
146    /// `sysctl`, which is not on every PATH.
147    fn string(name: &CStr) -> Option<String> {
148        let mut len: libc::size_t = 0;
149        // SAFETY: a null buffer asks only for the length.
150        let rc = unsafe {
151            libc::sysctlbyname(
152                name.as_ptr(),
153                std::ptr::null_mut(),
154                &mut len,
155                std::ptr::null_mut(),
156                0,
157            )
158        };
159        if rc != 0 || len == 0 {
160            return None;
161        }
162        let mut buf = vec![0u8; len];
163        // SAFETY: `buf` holds `len` bytes, and sysctl writes at most that.
164        let rc = unsafe {
165            libc::sysctlbyname(
166                name.as_ptr(),
167                buf.as_mut_ptr().cast(),
168                &mut len,
169                std::ptr::null_mut(),
170                0,
171            )
172        };
173        if rc != 0 {
174            return None;
175        }
176        buf.truncate(len);
177        clean(&String::from_utf8_lossy(&buf))
178    }
179
180    fn u64_value(name: &CStr) -> Option<u64> {
181        let mut v: u64 = 0;
182        let mut len = std::mem::size_of::<u64>();
183        // SAFETY: `v` is exactly the `len` bytes sysctl is told it may write.
184        let rc = unsafe {
185            libc::sysctlbyname(
186                name.as_ptr(),
187                (&raw mut v).cast(),
188                &mut len,
189                std::ptr::null_mut(),
190                0,
191            )
192        };
193        (rc == 0 && len == std::mem::size_of::<u64>()).then_some(v)
194    }
195
196    pub(super) fn detect() -> Os {
197        Os {
198            os_version: string(c"kern.osproductversion"),
199            kernel: string(c"kern.osrelease"),
200            cpu: string(c"machdep.cpu.brand_string"),
201            memory_bytes: u64_value(c"hw.memsize"),
202        }
203    }
204}
205
206#[cfg(windows)]
207mod imp {
208    use super::{Os, clean};
209    use windows_sys::Win32::System::Registry::{
210        HKEY_LOCAL_MACHINE, RRF_RT_REG_DWORD, RRF_RT_REG_SZ, RegGetValueW,
211    };
212    use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
213
214    fn wide(s: &str) -> Vec<u16> {
215        s.encode_utf16().chain(std::iter::once(0)).collect()
216    }
217
218    fn reg_string(key: &str, value: &str) -> Option<String> {
219        let (key, value) = (wide(key), wide(value));
220        let mut buf = [0u16; 512];
221        let mut len = std::mem::size_of_val(&buf) as u32;
222        // SAFETY: both names are NUL-terminated, and `len` is `buf`'s size in
223        // bytes, which RegGetValueW will not write past.
224        let rc = unsafe {
225            RegGetValueW(
226                HKEY_LOCAL_MACHINE,
227                key.as_ptr(),
228                value.as_ptr(),
229                RRF_RT_REG_SZ,
230                std::ptr::null_mut(),
231                buf.as_mut_ptr().cast(),
232                &mut len,
233            )
234        };
235        if rc != 0 {
236            return None;
237        }
238        let chars = (len as usize / 2).min(buf.len());
239        clean(&String::from_utf16_lossy(&buf[..chars]))
240    }
241
242    fn reg_dword(key: &str, value: &str) -> Option<u32> {
243        let (key, value) = (wide(key), wide(value));
244        let mut v: u32 = 0;
245        let mut len = std::mem::size_of::<u32>() as u32;
246        // SAFETY: as above, with `v` as the four-byte buffer.
247        let rc = unsafe {
248            RegGetValueW(
249                HKEY_LOCAL_MACHINE,
250                key.as_ptr(),
251                value.as_ptr(),
252                RRF_RT_REG_DWORD,
253                std::ptr::null_mut(),
254                (&raw mut v).cast(),
255                &mut len,
256            )
257        };
258        (rc == 0).then_some(v)
259    }
260
261    pub(super) fn detect() -> Os {
262        const CPU: &str = r"HARDWARE\DESCRIPTION\System\CentralProcessor\0";
263        const NT: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
264        let kernel = match (
265            reg_dword(NT, "CurrentMajorVersionNumber"),
266            reg_dword(NT, "CurrentMinorVersionNumber"),
267            reg_string(NT, "CurrentBuildNumber"),
268        ) {
269            (Some(major), Some(minor), Some(build)) => Some(format!("{major}.{minor}.{build}")),
270            _ => None,
271        };
272        // SAFETY: MEMORYSTATUSEX is plain data; dwLength must be set first.
273        let memory_bytes = unsafe {
274            let mut m: MEMORYSTATUSEX = std::mem::zeroed();
275            m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
276            (GlobalMemoryStatusEx(&mut m) != 0).then_some(m.ullTotalPhys)
277        };
278        Os {
279            os_version: None,
280            kernel,
281            cpu: reg_string(CPU, "ProcessorNameString"),
282            memory_bytes,
283        }
284    }
285}
286
287#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
288mod imp {
289    use super::Os;
290
291    pub(super) fn detect() -> Os {
292        Os::default()
293    }
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    /// Runs on every host CI has: whatever can and cannot be read, detection
301    /// returns, and what it returns is plausible.
302    #[test]
303    fn detection_describes_this_host_without_failing() {
304        let m = detect();
305        assert_eq!(m.os, std::env::consts::OS);
306        assert_eq!(m.arch, std::env::consts::ARCH);
307        assert!(m.cpus.is_some_and(|n| n >= 1), "{m:?}");
308        for s in [&m.os_version, &m.kernel, &m.cpu].into_iter().flatten() {
309            assert_eq!(s.trim(), s, "trimmed: {m:?}");
310            assert!(!s.is_empty(), "empty is None, not a value: {m:?}");
311        }
312        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
313            // More than 64 MiB and less than 64 PiB: a unit mistake either
314            // way lands outside.
315            let mem = m.memory_bytes.expect("memory is readable here");
316            assert!((64 << 20..64 << 50).contains(&mem), "{mem}");
317            assert!(m.kernel.is_some(), "{m:?}");
318        }
319        if cfg!(target_os = "macos") {
320            assert!(m.cpu.is_some() && m.os_version.is_some(), "{m:?}");
321        }
322    }
323
324    #[test]
325    fn cpuinfo_model_name_is_the_first_one() {
326        let x86 = "processor\t: 0\nvendor_id\t: AuthenticAMD\nmodel name\t: AMD Ryzen 9 7950X 16-Core Processor\n\nprocessor\t: 1\nmodel name\t: AMD Ryzen 9 7950X 16-Core Processor\n";
327        assert_eq!(
328            linux_parse::cpu_model(x86).as_deref(),
329            Some("AMD Ryzen 9 7950X 16-Core Processor")
330        );
331        let arm = "processor\t: 0\nBogoMIPS\t: 50.00\nCPU implementer\t: 0x41\nCPU part\t: 0xd0c\n";
332        assert_eq!(linux_parse::cpu_model(arm), None);
333    }
334
335    #[test]
336    fn meminfo_total_is_bytes() {
337        let m = "MemTotal:       65536000 kB\nMemFree:         1234 kB\n";
338        assert_eq!(linux_parse::mem_total(m), Some(65_536_000 * 1024));
339        assert_eq!(linux_parse::mem_total("MemFree: 1 kB\n"), None);
340        assert_eq!(linux_parse::mem_total("MemTotal: lots\n"), None);
341    }
342
343    #[test]
344    fn os_release_pretty_name_is_unquoted() {
345        let t = "NAME=\"Ubuntu\"\nPRETTY_NAME=\"Ubuntu 24.04.1 LTS\"\nID=ubuntu\n";
346        assert_eq!(
347            linux_parse::pretty_name(t).as_deref(),
348            Some("Ubuntu 24.04.1 LTS")
349        );
350        assert_eq!(
351            linux_parse::pretty_name("PRETTY_NAME=Arch\n").as_deref(),
352            Some("Arch")
353        );
354        assert_eq!(linux_parse::pretty_name("PRETTY_NAME=\"\"\n"), None);
355        assert_eq!(linux_parse::pretty_name("ID=alpine\n"), None);
356    }
357
358    #[test]
359    fn a_missing_value_is_null_in_the_export() {
360        let m = Machine {
361            os: "linux".into(),
362            os_version: None,
363            kernel: None,
364            arch: "x86_64".into(),
365            cpu: None,
366            cpus: None,
367            memory_bytes: None,
368        };
369        let v = serde_json::to_value(&m).unwrap();
370        assert!(v["cpu"].is_null() && v["memory_bytes"].is_null(), "{v}");
371        assert_eq!(v.as_object().unwrap().len(), 7, "every key present");
372    }
373}