Skip to main content

readcon_core/
hostlabel.rs

1//! CPU model string used when a bench records one.
2//!
3//! The value is the `model name` line from `/proc/cpuinfo`, written the
4//! same way as `benches/cpu_model.py`: trademark marks removed, and any
5//! Xeon collapsed to one plain name. Missing input is `unknown`.
6
7use std::fs;
8
9/// Same spelling as `normalize_cpu` in `benches/cpu_model.py`.
10pub fn normalize_cpu(raw: &str) -> String {
11    let stripped = raw.replace("(R)", "").replace("(TM)", "").replace('®', "");
12    let cleaned = stripped.split_whitespace().collect::<Vec<_>>().join(" ");
13    if cleaned.contains("Xeon") {
14        return "Intel Xeon Processor".to_string();
15    }
16    if cleaned.is_empty() {
17        "unknown".to_string()
18    } else {
19        cleaned
20    }
21}
22
23/// CPU model from `/proc/cpuinfo`, or `unknown` when that line is absent.
24pub fn cpu_model() -> String {
25    if let Ok(text) = fs::read_to_string("/proc/cpuinfo") {
26        for line in text.lines() {
27            if line.to_ascii_lowercase().starts_with("model name")
28                && let Some((_, value)) = line.split_once(':')
29            {
30                let value = value.trim();
31                if !value.is_empty() {
32                    return normalize_cpu(value);
33                }
34            }
35        }
36    }
37    "unknown".to_string()
38}
39
40#[cfg(test)]
41mod tests {
42    use super::cpu_model;
43    use std::fs;
44
45    #[test]
46    fn cpu_model_value() {
47        println!("CPU_MODEL={}", cpu_model());
48    }
49
50    #[test]
51    fn normalize_cpu_matches_the_python_record_name() {
52        assert_eq!(
53            super::normalize_cpu("Intel(R) Xeon(R) Processor"),
54            "Intel Xeon Processor"
55        );
56        assert_eq!(
57            super::normalize_cpu("Intel(R) Core(TM) i7"),
58            "Intel Core i7"
59        );
60        assert_eq!(super::normalize_cpu("  AMD   EPYC  "), "AMD EPYC");
61        assert_eq!(super::normalize_cpu("   "), "unknown");
62    }
63
64    #[test]
65    fn cpu_model_is_not_a_hostname_token() {
66        let cpu = cpu_model();
67        assert!(!cpu.is_empty());
68        match fs::read_to_string("/etc/hostname") {
69            Ok(text) => {
70                let node = text.trim();
71                if !node.is_empty() {
72                    assert!(cpu.split('-').all(|token| token != node));
73                }
74            }
75            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
76            Err(err) => panic!("reading /etc/hostname failed: {err}"),
77        }
78    }
79}