ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (c) 2026 nervosys

//! Server Chassis Information via DMI/SMBIOS

use serde::{Deserialize, Serialize};
#[allow(unused_imports)]
use std::fs;

/// Chassis type from SMBIOS Type 3
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChassisType {
    Desktop,
    LowProfileDesktop,
    PizzaBox,
    MiniTower,
    Tower,
    Portable,
    Laptop,
    Notebook,
    Handheld,
    DockingStation,
    AllInOne,
    SubNotebook,
    LunchBox,
    MainServer,
    Expansion,
    SubChassis,
    BusExpansion,
    Peripheral,
    RaidChassis,
    RackMount,
    SealedCase,
    MultiSystem,
    CompactPci,
    AdvancedTca,
    Blade,
    BladeEnclosure,
    Tablet,
    Convertible,
    Detachable,
    IoTGateway,
    EmbeddedPc,
    MiniPc,
    StickPc,
    Other,
    Unknown,
}

/// Form factor derived from chassis type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FormFactor {
    RackMount,
    Tower,
    Blade,
    Desktop,
    Laptop,
    MiniPc,
    Tablet,
    Embedded,
    Other,
    Unknown,
}

/// Physical location in rack
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerLocation {
    pub rack_id: Option<String>,
    pub rack_unit: Option<u32>,
    pub datacenter: Option<String>,
    pub room: Option<String>,
}

/// Whether a firmware-supplied string is a template or an empty slot rather
/// than a value someone entered. OEM boards ship these in their DMI/SMBIOS
/// tables ("To Be Filled By O.E.M.", "Default string"), and a reader that
/// passes them through reports the template as the machine's identity.
///
/// Empty strings and all-zero or all-F strings count too, since that is how an
/// unset field reads. Shared with the ontology, which applies the same test to
/// firmware identity fields it reads elsewhere.
pub(crate) fn is_firmware_placeholder(value: &str) -> bool {
    const PLACEHOLDERS: [&str; 13] = [
        "to be filled by o.e.m.",
        "default string",
        "system serial number",
        "system product name",
        "system version",
        "chassis serial number",
        "chassis asset tag",
        "base board serial number",
        "not specified",
        "not applicable",
        "undefined",
        "invalid",
        "123456789",
    ];
    let lower = value.trim().to_ascii_lowercase();
    lower.is_empty()
        || PLACEHOLDERS.contains(&lower.as_str())
        || lower.chars().all(|c| c == '0' || c == '-')
        || lower.chars().all(|c| c == 'f' || c == '-')
}

/// A firmware string as a reading: trimmed, and `None` when it is empty or a
/// placeholder.
fn firmware_value(value: Option<String>) -> Option<String> {
    value
        .map(|v| v.trim().to_string())
        .filter(|v| !is_firmware_placeholder(v))
}

/// Complete chassis info. Every identity field is `None` unless a reader
/// obtained a real value; a placeholder is never reported as one.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChassisInfo {
    pub chassis_type: ChassisType,
    /// `None` where the form factor was not read. Used to report Desktop for
    /// every Mac, and Unknown where no source named one.
    pub form_factor: Option<FormFactor>,
    /// `None` where nothing was read. Used to report "Apple" on every Mac,
    /// which was never read from the machine.
    pub manufacturer: Option<String>,
    pub product_name: Option<String>,
    pub serial_number: Option<String>,
    pub asset_tag: Option<String>,
    pub version: Option<String>,
    pub sku: Option<String>,
    pub location: ServerLocation,
}

impl ChassisInfo {
    pub fn detect() -> Result<Self, super::DatacenterError> {
        #[cfg(target_os = "linux")]
        {
            Self::detect_linux()
        }
        #[cfg(target_os = "windows")]
        {
            Self::detect_windows()
        }
        #[cfg(target_os = "macos")]
        {
            Self::detect_macos()
        }
        #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
        {
            Err(super::DatacenterError::Other("Unsupported platform".into()))
        }
    }

    #[cfg(target_os = "linux")]
    fn detect_linux() -> Result<Self, super::DatacenterError> {
        let dmi = "/sys/class/dmi/id";
        let read = |name: &str| -> String {
            fs::read_to_string(format!("{}/{}", dmi, name))
                .unwrap_or_default()
                .trim()
                .to_string()
        };
        // Every field goes through the placeholder filter. The manufacturer and
        // product name used to be read raw, so a board that shipped
        // "To Be Filled By O.E.M." reported exactly that as its identity.
        let read_opt = |name: &str| -> Option<String> { firmware_value(Some(read(name))) };

        let chassis_type_byte: u8 = fs::read_to_string(format!("{}/chassis_type", dmi))
            .unwrap_or_default()
            .trim()
            .parse()
            .unwrap_or(2);

        let chassis_type = Self::from_smbios_byte(chassis_type_byte);
        // Unknown means no source named a form factor, so it is not reported.
        let form_factor =
            Some(Self::infer_form_factor(chassis_type)).filter(|f| *f != FormFactor::Unknown);

        Ok(ChassisInfo {
            chassis_type,
            form_factor,
            manufacturer: read_opt("sys_vendor"),
            product_name: read_opt("product_name"),
            serial_number: read_opt("product_serial"),
            asset_tag: read_opt("chassis_asset_tag"),
            version: read_opt("product_version"),
            sku: read_opt("product_sku"),
            location: ServerLocation {
                rack_id: std::env::var("IRONMON_RACK_ID").ok(),
                rack_unit: std::env::var("IRONMON_RACK_UNIT")
                    .ok()
                    .and_then(|v| v.parse().ok()),
                datacenter: std::env::var("IRONMON_DATACENTER").ok(),
                room: std::env::var("IRONMON_ROOM").ok(),
            },
        })
    }

    #[cfg(target_os = "windows")]
    fn detect_windows() -> Result<Self, super::DatacenterError> {
        // SMBIOS system identity as the firmware published it at boot. This used to
        // shell out to `wmic`, which Microsoft removed in Windows 11 24H2 — the
        // subprocess failed to spawn and every field came back an empty string, so a
        // named chassis was indistinguishable from an unnamed one.
        const BIOS_KEY: &str = r"HARDWARE\DESCRIPTION\System\BIOS";
        // A missing value and a placeholder are both `None`; neither is passed on.
        let smbios = |value: &str| -> Option<String> {
            firmware_value(crate::platform::windows::read_registry_string(
                BIOS_KEY, value,
            ))
        };

        // The registry carries system make and model but not the serial, which lives
        // only in SMBIOS as WMI surfaces it.
        let wmi_info = crate::motherboard::get_system_info().ok();

        Ok(ChassisInfo {
            chassis_type: ChassisType::Unknown,
            // The registry does not carry a form factor. Used to report Unknown.
            form_factor: None,
            manufacturer: smbios("SystemManufacturer"),
            product_name: smbios("SystemProductName"),
            serial_number: firmware_value(wmi_info.as_ref().and_then(|i| i.serial_number.clone())),
            asset_tag: None,
            version: None,
            sku: None,
            location: ServerLocation {
                rack_id: None,
                rack_unit: None,
                datacenter: None,
                room: None,
            },
        })
    }

    #[cfg(target_os = "macos")]
    fn detect_macos() -> Result<Self, super::DatacenterError> {
        let sp = std::process::Command::new("system_profiler")
            .args(["SPHardwareDataType", "-detailLevel", "mini"])
            .output()
            .map_err(|e| super::DatacenterError::Other(e.to_string()))?;
        let stdout = String::from_utf8_lossy(&sp.stdout);
        let get = |key: &str| -> String {
            stdout
                .lines()
                .find(|l| l.contains(key))
                .and_then(|l| l.split(':').nth(1))
                .unwrap_or("")
                .trim()
                .to_string()
        };

        Ok(ChassisInfo {
            chassis_type: ChassisType::Unknown,
            // Not read. Used to report Desktop for every Mac, laptops included.
            form_factor: None,
            // `system_profiler` names no manufacturer line, so none is reported.
            // The literal "Apple" used to stand here for every Mac.
            manufacturer: None,
            product_name: firmware_value(Some(get("Model Name"))),
            serial_number: firmware_value(Some(get("Serial Number"))),
            asset_tag: None,
            version: None,
            sku: firmware_value(Some(get("Model Identifier"))),
            location: ServerLocation {
                rack_id: None,
                rack_unit: None,
                datacenter: None,
                room: None,
            },
        })
    }

    #[allow(dead_code)]
    fn from_smbios_byte(b: u8) -> ChassisType {
        match b {
            3 => ChassisType::Desktop,
            4 => ChassisType::LowProfileDesktop,
            5 => ChassisType::PizzaBox,
            6 => ChassisType::MiniTower,
            7 => ChassisType::Tower,
            8 => ChassisType::Portable,
            9 => ChassisType::Laptop,
            10 => ChassisType::Notebook,
            11 => ChassisType::Handheld,
            12 => ChassisType::DockingStation,
            13 => ChassisType::AllInOne,
            14 => ChassisType::SubNotebook,
            17 => ChassisType::MainServer,
            23 => ChassisType::RackMount,
            24 => ChassisType::SealedCase,
            25 => ChassisType::MultiSystem,
            28 => ChassisType::Blade,
            29 => ChassisType::BladeEnclosure,
            30 => ChassisType::Tablet,
            31 => ChassisType::Convertible,
            32 => ChassisType::Detachable,
            33 => ChassisType::IoTGateway,
            34 => ChassisType::EmbeddedPc,
            35 => ChassisType::MiniPc,
            36 => ChassisType::StickPc,
            1 => ChassisType::Other,
            _ => ChassisType::Unknown,
        }
    }

    /// The form factor the chassis type names. A type the table does not place
    /// is `Unknown`: the product name used to be searched for "rack", "server",
    /// "blade", "nuc" or "mini" and the match reported as the form factor, a
    /// guess from a name rather than a reading.
    #[allow(dead_code)]
    fn infer_form_factor(ct: ChassisType) -> FormFactor {
        match ct {
            ChassisType::RackMount | ChassisType::MainServer => FormFactor::RackMount,
            ChassisType::Tower | ChassisType::MiniTower => FormFactor::Tower,
            ChassisType::Blade | ChassisType::BladeEnclosure => FormFactor::Blade,
            ChassisType::Laptop | ChassisType::Notebook | ChassisType::SubNotebook => {
                FormFactor::Laptop
            }
            ChassisType::Tablet | ChassisType::Convertible | ChassisType::Detachable => {
                FormFactor::Tablet
            }
            ChassisType::MiniPc | ChassisType::StickPc => FormFactor::MiniPc,
            ChassisType::EmbeddedPc | ChassisType::IoTGateway => FormFactor::Embedded,
            ChassisType::Desktop | ChassisType::LowProfileDesktop | ChassisType::AllInOne => {
                FormFactor::Desktop
            }
            _ => FormFactor::Unknown,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Strings OEM firmware writes into unset identity fields. None of them is
    /// a value, so none may reach a reading.
    #[test]
    fn firmware_templates_are_placeholders() {
        for template in [
            "To Be Filled By O.E.M.",
            "Default string",
            "System Product Name",
            "System Version",
            "Not Specified",
            "",
            "   ",
            "0000000000",
            "FFFFFFFFFFFFFFFF",
        ] {
            assert!(is_firmware_placeholder(template), "{template:?}");
            assert_eq!(firmware_value(Some(template.into())), None, "{template:?}");
        }
    }

    /// A chassis type the table does not place has no form factor, whatever its
    /// product name says.
    #[test]
    fn form_factor_is_not_guessed_from_the_product_name() {
        assert_eq!(
            ChassisInfo::infer_form_factor(ChassisType::Unknown),
            FormFactor::Unknown
        );
        assert_eq!(
            ChassisInfo::infer_form_factor(ChassisType::Other),
            FormFactor::Unknown
        );
        assert_eq!(
            ChassisInfo::infer_form_factor(ChassisType::Tower),
            FormFactor::Tower
        );
    }

    /// Real identity strings pass through, trimmed. A serial that happens to
    /// contain a placeholder word is still a serial.
    #[test]
    fn real_identity_strings_are_kept() {
        assert!(!is_firmware_placeholder("Dell Inc."));
        assert!(!is_firmware_placeholder("PowerEdge R750"));
        assert!(!is_firmware_placeholder("MXL1234ABC"));
        assert_eq!(
            firmware_value(Some("  ASUSTeK COMPUTER INC.\n".into())).as_deref(),
            Some("ASUSTeK COMPUTER INC.")
        );
        assert_eq!(firmware_value(None), None);
    }
}