use serde::{Deserialize, Serialize};
use super::{Entity, Ontology, Provenance, Unit};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Reading {
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<serde_json::Value>,
pub provenance: Provenance,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<Unit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
impl Reading {
fn measured(id: impl Into<String>, value: serde_json::Value, unit: Option<Unit>) -> Self {
Self {
id: id.into(),
value: Some(value),
provenance: Provenance::Measured,
unit,
note: None,
}
}
fn derived(id: impl Into<String>, value: serde_json::Value, unit: Option<Unit>) -> Self {
Self {
id: id.into(),
value: Some(value),
provenance: Provenance::Derived,
unit,
note: None,
}
}
fn spec(id: impl Into<String>, value: serde_json::Value, unit: Option<Unit>) -> Self {
Self {
id: id.into(),
value: Some(value),
provenance: Provenance::Specification,
unit,
note: None,
}
}
fn unavailable(id: impl Into<String>, unit: Option<Unit>, why: impl Into<String>) -> Self {
Self {
id: id.into(),
value: None,
provenance: Provenance::Unavailable,
unit,
note: Some(why.into()),
}
}
pub fn is_observation(&self) -> bool {
self.provenance.is_observation() && self.value.is_some()
}
}
pub fn snapshot() -> Vec<Reading> {
let ontology = Ontology::build();
let mut out = Vec::new();
resolve_cpu(&mut out);
resolve_memory(&mut out);
resolve_system(&mut out);
resolve_board(&mut out);
resolve_gpu(&mut out);
resolve_disk(&mut out);
resolve_network(&mut out);
resolve_process(&mut out);
resolve_thermal(&mut out);
resolve_power(&mut out);
resolve_rapl(&mut out);
resolve_sensors(&mut out);
resolve_displays(&mut out);
resolve_virtualization(&mut out);
resolve_numa(&mut out);
resolve_ecc(&mut out);
resolve_pci(&mut out);
resolve_usb(&mut out);
resolve_memory_bandwidth(&mut out);
resolve_microarch(&mut out);
resolve_crypto(&mut out);
resolve_input(&mut out);
resolve_audio(&mut out);
resolve_cameras(&mut out);
resolve_printers(&mut out);
resolve_services(&mut out);
resolve_kernel_params(&mut out);
resolve_secure_boot(&mut out);
resolve_boot_duration(&mut out);
resolve_bluetooth(&mut out);
resolve_storage_controllers(&mut out);
resolve_power_profiles(&mut out);
resolve_codecs(&mut out);
resolve_settings(&mut out);
let declined: Vec<(String, String)> = out
.iter()
.filter_map(|r| {
let prefix = r.id.strip_suffix(".<none>")?;
Some((format!("{prefix}."), r.note.clone()?))
})
.collect();
let produced: std::collections::HashSet<&str> = out.iter().map(|r| r.id.as_str()).collect();
let mut unbound: Vec<Reading> = ontology
.entities
.values()
.filter(|e| {
e.kind != super::EntityKind::Diagnostic
&& !Ontology::is_template(&e.id)
&& !produced.contains(e.id.as_str())
})
.map(|e| {
let inherited = declined
.iter()
.filter(|(prefix, _)| e.id.starts_with(prefix.as_str()))
.max_by_key(|(prefix, _)| prefix.len());
match inherited {
Some((_, why)) => Reading::unavailable(e.id.clone(), e.unit, why.clone()),
None => Reading::unavailable(
e.id.clone(),
e.unit,
"no resolver bound on this build — the entity is defined but ironmon \
does not yet read it here",
),
}
})
.collect();
out.append(&mut unbound);
let mut missing_domains: Vec<Reading> = Vec::new();
for domain in super::Domain::ALL {
let prefix = format!("{}.", domain.as_str());
if out.iter().any(|r| r.id.starts_with(&prefix)) {
continue;
}
let declares_any = ontology.entities.values().any(|e| e.domain == *domain);
if declares_any {
missing_domains.push(Reading::unavailable(
format!("{}.<none>", domain.as_str()),
None,
"no instance of this domain was found and no resolver reported why; \
the ontology declares entities here but nothing was enumerated",
));
}
}
out.append(&mut missing_domains);
for reading in out.iter_mut() {
let Some(value) = reading.value.as_ref().and_then(|v| v.as_f64()) else {
continue;
};
let Some(entity) = lookup_template(&ontology, &reading.id) else {
continue;
};
if let Some(problem) = entity.validate_range(value) {
reading.value = None;
reading.provenance = Provenance::Unavailable;
reading.note = Some(format!(
"reader produced a value the ontology rejects, so it is withheld \
rather than reported: {problem}"
));
}
}
for reading in out.iter_mut() {
if reading.provenance == Provenance::Unavailable {
continue;
}
let Some(text) = reading.value.as_ref().and_then(|v| v.as_str()) else {
continue;
};
if !names_an_absence(text) {
continue;
}
let quoted = text.trim().to_string();
reading.value = None;
reading.provenance = Provenance::Unavailable;
reading.note = Some(format!(
"reader returned {quoted:?}, which names an absence rather than a value, so it is reported as unavailable rather than as a reading"
));
}
out.sort_by(|a, b| a.id.cmp(&b.id));
out
}
pub fn get(id: &str) -> Option<Reading> {
if Ontology::is_template(id) {
return None;
}
snapshot().into_iter().find(|r| r.id == id)
}
pub fn coverage() -> Coverage {
coverage_of(&snapshot())
}
#[cfg(target_os = "windows")]
const FREQUENCY_ABSENT: &str = concat!(
"Windows reports the nominal clock through CallNtPowerInformation, not the ",
"current one — it returned the maximum unchanged for every core, so there is ",
"no per-core reading here to report. The real figure needs the ",
"'% Processor Performance' counter, which IronMonitor does not read yet",
);
#[cfg(not(target_os = "windows"))]
const FREQUENCY_ABSENT: &str = "no per-core clock reported";
pub fn coverage_of(readings: &[Reading]) -> Coverage {
let bound = readings.iter().filter(|r| r.value.is_some()).count();
Coverage {
total: readings.len(),
resolved: bound,
unavailable: readings.len() - bound,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Coverage {
pub total: usize,
pub resolved: usize,
pub unavailable: usize,
}
fn resolve_cpu(out: &mut Vec<Reading>) {
resolve_cpu_cache(out);
let stats = read_cpu_stats();
let stats = match stats {
Ok(s) => s,
Err(why) => {
out.push(Reading::unavailable(
"cpu.total.utilization",
Some(Unit::Percent),
format!("the platform CPU reader failed: {why}"),
));
return;
}
};
out.push(Reading::derived(
"cpu.total.utilization",
serde_json::json!(100.0 - stats.total.idle),
Some(Unit::Percent),
));
out.push(Reading::measured(
"cpu.total.idle",
serde_json::json!(stats.total.idle),
Some(Unit::Percent),
));
out.push(Reading::measured(
"cpu.cores.logical",
serde_json::json!(stats.cores.len()),
Some(Unit::Count),
));
match crate::cpu_microarch::CpuMicroarchMonitor::new() {
Ok(m) if m.report().physical_cores > 0 => out.push(Reading::measured(
"cpu.cores.physical",
serde_json::json!(m.report().physical_cores),
Some(Unit::Count),
)),
Ok(_) => out.push(Reading::unavailable(
"cpu.cores.physical",
Some(Unit::Count),
"the platform reported no physical core count distinct from the \
logical one",
)),
Err(e) => out.push(Reading::unavailable(
"cpu.cores.physical",
Some(Unit::Count),
format!("microarchitecture reader unavailable: {e}"),
)),
}
match stats.cores.first().map(|c| c.model.as_str()) {
Some(model) if !model.trim().is_empty() => push_text(out, "cpu.model", model),
_ => out.push(Reading::unavailable(
"cpu.model",
Some(Unit::Text),
"no core reported a model string",
)),
}
for core in &stats.cores {
let base = format!("cpu.core.{}", core.id);
match core.idle {
Some(idle) => {
out.push(Reading::measured(
format!("{base}.idle"),
serde_json::json!(idle),
Some(Unit::Percent),
));
out.push(Reading::derived(
format!("{base}.utilization"),
serde_json::json!(100.0 - idle),
Some(Unit::Percent),
));
}
_ => {
for suffix in ["idle", "utilization"] {
out.push(Reading::unavailable(
format!("{base}.{suffix}"),
Some(Unit::Percent),
"platform exposes no per-processor times; the system-wide \
average is not a per-core reading",
));
}
}
}
match &core.frequency {
Some(f) if f.current.is_some_and(|c| c > 0) && f.current_is_derived => {
out.push(Reading::derived(
format!("{base}.frequency"),
serde_json::json!(f.current),
Some(Unit::Megahertz),
))
}
Some(f) if f.current.is_some_and(|c| c > 0) => out.push(Reading::measured(
format!("{base}.frequency"),
serde_json::json!(f.current),
Some(Unit::Megahertz),
)),
_ => out.push(Reading::unavailable(
format!("{base}.frequency"),
Some(Unit::Megahertz),
FREQUENCY_ABSENT,
)),
}
push_spec_opt(
out,
format!("{base}.frequency.max"),
core.frequency
.as_ref()
.and_then(|f| f.max)
.map(|v| serde_json::json!(v)),
Some(Unit::Megahertz),
"platform reports no rated maximum for this core",
);
out.push(Reading::unavailable(
format!("{base}.frequency.min"),
Some(Unit::Megahertz),
"platform exposes no minimum core frequency; it is not inferable from \
the maximum",
));
}
}
fn resolve_memory(out: &mut Vec<Reading>) {
resolve_memory_dimms(out);
let stats = match read_memory_stats() {
Ok(s) => s,
Err(why) => {
for (id, unit) in [
("memory.total", Unit::Bytes),
("memory.used", Unit::Bytes),
("memory.utilization", Unit::Percent),
] {
out.push(Reading::unavailable(
id,
Some(unit),
format!("the platform memory reader failed: {why}"),
));
}
return;
}
};
let total = stats.ram.total.saturating_mul(1024);
let used = stats.ram.used.saturating_mul(1024);
out.push(Reading::measured(
"memory.total",
serde_json::json!(total),
Some(Unit::Bytes),
));
out.push(Reading::measured(
"memory.used",
serde_json::json!(used),
Some(Unit::Bytes),
));
match total {
0 => out.push(Reading::unavailable(
"memory.utilization",
Some(Unit::Percent),
"total memory reported as zero, so a percentage has no denominator",
)),
t => out.push(Reading::derived(
"memory.utilization",
serde_json::json!((used as f64 / t as f64) * 100.0),
Some(Unit::Percent),
)),
}
match stats.swap.total {
None => {
for id in ["memory.swap.total", "memory.swap.used"] {
out.push(Reading::unavailable(
id,
Some(Unit::Bytes),
"the platform did not report swap, so whether this machine has any is unknown",
));
}
}
Some(0) => {
for id in ["memory.swap.total", "memory.swap.used"] {
out.push(Reading::unavailable(
id,
Some(Unit::Bytes),
"no swap or pagefile configured",
));
}
}
Some(total_kb) => {
out.push(Reading::measured(
"memory.swap.total",
serde_json::json!(total_kb.saturating_mul(1024)),
Some(Unit::Bytes),
));
match stats.swap.used {
Some(used_kb) => out.push(Reading::measured(
"memory.swap.used",
serde_json::json!(used_kb.saturating_mul(1024)),
Some(Unit::Bytes),
)),
None => out.push(Reading::unavailable(
"memory.swap.used",
Some(Unit::Bytes),
"the platform reported a swap total and no used figure",
)),
}
}
}
}
fn resolve_system(out: &mut Vec<Reading>) {
match crate::os_info::OsInfoMonitor::new() {
Ok(monitor) => {
let info = monitor.info();
push_text(out, "system.os.name", &info.os_name);
push_id(out, "system.os.build", &info.os_build);
push_text(out, "system.hostname", &info.hostname);
push_text(out, "system.os.version", &info.os_version);
push_text(out, "system.kernel.version", &info.kernel_version);
push_id(out, "system.architecture", &info.architecture);
if info.uptime_seconds > 0 {
out.push(Reading::measured(
"system.uptime",
serde_json::json!(info.uptime_seconds),
Some(Unit::Seconds),
));
} else {
out.push(Reading::unavailable(
"system.uptime",
Some(Unit::Seconds),
"uptime read as zero, which would mean the machine booted this \
instant",
));
}
}
Err(e) => {
for (id, unit) in [
("system.os.name", Unit::Text),
("system.os.build", Unit::Identifier),
("system.uptime", Unit::Seconds),
] {
out.push(Reading::unavailable(
id,
Some(unit),
format!("OS info reader failed: {e}"),
));
}
}
}
}
fn resolve_board(out: &mut Vec<Reading>) {
match detect_board() {
Some(board) => {
push_text(out, "board.model", &board.hardware.model);
match &board.hardware.module {
Some(m) => push_text(out, "board.manufacturer", m),
None => out.push(Reading::unavailable(
"board.manufacturer",
Some(Unit::Text),
"SMBIOS reported no baseboard manufacturer",
)),
}
}
None => {
for id in ["board.model", "board.manufacturer"] {
out.push(Reading::unavailable(
id,
Some(Unit::Text),
"no board detection on this platform",
));
}
}
}
resolve_firmware(out);
resolve_tpm(out);
}
fn resolve_firmware(out: &mut Vec<Reading>) {
const IDS: [&str; 3] = [
"board.firmware.vendor",
"board.firmware.product",
"board.firmware.boot_mode",
];
let inventory = match crate::firmware::FirmwareInventory::new() {
Ok(i) => i,
Err(e) => {
for id in IDS {
out.push(Reading::unavailable(
id,
Some(Unit::Text),
format!("firmware inventory unavailable: {e}"),
));
}
return;
}
};
push_text(out, "board.firmware.vendor", inventory.system_vendor());
push_text(out, "board.firmware.product", inventory.system_product());
push_id(
out,
"board.firmware.boot_mode",
&format!("{:?}", inventory.boot_mode()).to_lowercase(),
);
for (i, entry) in inventory.items().iter().enumerate() {
push_id(
out,
format!("board.firmware.{i}.component"),
&format!("{:?}", entry.component).to_lowercase(),
);
push_text(out, format!("board.firmware.{i}.version"), &entry.version);
}
}
fn resolve_tpm(out: &mut Vec<Reading>) {
const DETAIL_IDS: [&str; 4] = [
"board.tpm.version",
"board.tpm.manufacturer",
"board.tpm.status",
"board.tpm.measured_boot",
];
let monitor = match crate::tpm::TpmMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"board.tpm.present",
None,
format!("TPM enumeration failed: {e}"),
));
for id in DETAIL_IDS {
out.push(Reading::unavailable(
id,
None,
format!("TPM enumeration failed: {e}"),
));
}
return;
}
};
out.push(Reading::measured(
"board.tpm.present",
serde_json::json!(monitor.has_tpm()),
None,
));
let Some(tpm) = monitor.tpm() else {
for id in DETAIL_IDS {
out.push(Reading::unavailable(
id,
None,
"no TPM present on this machine",
));
}
return;
};
use crate::tpm::{TpmStatus, TpmVersion};
match tpm.version {
TpmVersion::Unknown => out.push(Reading::unavailable(
"board.tpm.version",
Some(Unit::Identifier),
"a TPM is present but its specification version could not be determined",
)),
v => push_id(out, "board.tpm.version", &format!("{v:?}").to_lowercase()),
}
if tpm.manufacturer.trim().is_empty() {
out.push(Reading::unavailable(
"board.tpm.manufacturer",
Some(Unit::Identifier),
"the TPM's manufacturer is published only by `Win32_Tpm`, which requires elevation; the security device node carries a driver provider rather than the chip vendor",
));
} else {
push_text(out, "board.tpm.manufacturer", &tpm.manufacturer);
}
match tpm.status {
TpmStatus::Unknown => out.push(Reading::unavailable(
"board.tpm.status",
Some(Unit::Identifier),
"a TPM is present but whether it is enabled could not be determined",
)),
s => push_id(out, "board.tpm.status", &format!("{s:?}").to_lowercase()),
}
push_opt(
out,
"board.tpm.measured_boot".to_string(),
tpm.measured_boot.map(|b| serde_json::json!(b)),
None,
concat!(
"a TPM is present but whether platform integrity measurements ",
"are active could not be established"
),
);
}
fn resolve_virtualization(out: &mut Vec<Reading>) {
const IDS: [&str; 4] = [
"system.virtualization.platform",
"system.virtualization.hypervisor",
"system.virtualization.detection_method",
"system.virtualization.hardware_support",
];
let monitor = match crate::virtualization::VirtMonitor::new() {
Ok(m) => m,
Err(e) => {
for id in IDS {
out.push(Reading::unavailable(
id,
None,
format!("virtualization detection unavailable: {e}"),
));
}
return;
}
};
let hypervisor = monitor.hypervisor();
let is_hyperv = matches!(
hypervisor.as_ref().map(|h| &h.hypervisor),
Some(crate::virtualization::Hypervisor::HyperV)
);
let platform = if monitor.is_container() {
"container"
} else if monitor.is_virtual_machine() {
"virtual_machine"
} else {
"bare_metal"
};
push_id(out, "system.virtualization.platform", platform);
match hypervisor {
Some(h) => {
push_id(
out,
"system.virtualization.hypervisor",
&format!("{:?}", h.hypervisor).to_lowercase(),
);
push_text(
out,
"system.virtualization.detection_method",
&h.detection_method,
);
}
None => {
out.push(Reading::unavailable(
"system.virtualization.hypervisor",
Some(Unit::Identifier),
"no hypervisor detected; this machine appears to be bare metal",
));
out.push(Reading::unavailable(
"system.virtualization.detection_method",
Some(Unit::Text),
"no hypervisor was detected, so no detection method applied",
));
}
}
match monitor.cpu_capabilities() {
Some(c) if !is_hyperv => out.push(Reading::measured(
"system.virtualization.hardware_support",
serde_json::json!(c.hardware_virt),
None,
)),
Some(_) => out.push(Reading::unavailable(
"system.virtualization.hardware_support",
None,
"a hypervisor is masking the CPU virtualization bits from CPUID; \
absence here would not mean the hardware lacks them",
)),
None => out.push(Reading::unavailable(
"system.virtualization.hardware_support",
None,
"the platform did not report CPU virtualization capabilities",
)),
}
}
fn resolve_numa(out: &mut Vec<Reading>) {
let monitor = match crate::numa::NumaMonitor::new() {
Ok(m) => m,
Err(e) => {
for id in ["memory.numa.nodes", "memory.numa.is_numa"] {
out.push(Reading::unavailable(
id,
None,
format!("NUMA topology unavailable: {e}"),
));
}
return;
}
};
let summary = monitor.summary();
out.push(Reading::measured(
"memory.numa.nodes",
serde_json::json!(summary.node_count),
Some(Unit::Count),
));
out.push(Reading::measured(
"memory.numa.is_numa",
serde_json::json!(summary.is_numa),
None,
));
for node in monitor.nodes() {
let base = format!("memory.numa.{}", node.id);
out.push(Reading::measured(
format!("{base}.cpus"),
serde_json::json!(node.cpus.len()),
Some(Unit::Count),
));
push_opt(
out,
format!("{base}.memory"),
node.memory_total_bytes.map(|b| serde_json::json!(b)),
Some(Unit::Bytes),
"the platform reported no memory total for this node",
);
}
}
fn resolve_ecc(out: &mut Vec<Reading>) {
const IDS: [&str; 3] = [
"memory.ecc.active",
"memory.ecc.correctable_errors",
"memory.ecc.uncorrectable_errors",
];
let monitor = match crate::edac::EdacMonitor::new() {
Ok(m) => m,
Err(e) => {
for id in IDS {
out.push(Reading::unavailable(
id,
None,
format!("no ECC error reporting interface available here: {e}"),
));
}
return;
}
};
let overview = monitor.overview();
if overview.total_controllers == 0 {
for id in IDS {
out.push(Reading::unavailable(
id,
None,
"no memory controller exposed ECC reporting; the platform interface \
exists but enumerated nothing",
));
}
return;
}
out.push(Reading::measured(
"memory.ecc.active",
serde_json::json!(overview.ecc_active),
None,
));
match overview.total_ce {
Some(count) => out.push(Reading::measured(
"memory.ecc.correctable_errors",
serde_json::json!(count),
Some(Unit::Count),
)),
None => out.push(Reading::unavailable(
"memory.ecc.correctable_errors",
Some(Unit::Count),
"a memory controller's correctable-error counter could not be read; a total over partly-unknown inputs would understate it",
)),
}
match overview.total_ue {
Some(count) => out.push(Reading::measured(
"memory.ecc.uncorrectable_errors",
serde_json::json!(count),
Some(Unit::Count),
)),
None => out.push(Reading::unavailable(
"memory.ecc.uncorrectable_errors",
Some(Unit::Count),
"a memory controller's uncorrectable-error counter could not be read; a total over partly-unknown inputs would understate it",
)),
}
}
fn resolve_pci(out: &mut Vec<Reading>) {
let monitor = match crate::pci_devices::PciDeviceMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"pci.<none>",
None,
format!("PCI enumeration failed: {e}"),
));
return;
}
};
if monitor.devices().is_empty() {
out.push(Reading::unavailable(
"pci.<none>",
None,
"no PCI devices enumerated on this machine",
));
return;
}
for dev in monitor.devices() {
let base = format!("pci.{}", id_segment(&dev.address));
push_text(out, format!("{base}.vendor"), &dev.vendor_name);
push_text(out, format!("{base}.device"), &dev.device_name);
push_id(
out,
format!("{base}.class"),
&format!("{:?}", dev.class).to_lowercase(),
);
push_opt(
out,
format!("{base}.driver"),
(!dev.driver.trim().is_empty()).then(|| serde_json::json!(dev.driver)),
Some(Unit::Text),
"no driver is bound to this device",
);
match &dev.link_info {
Some(link) => {
for (suffix, value) in [
("link.width", &link.width),
("link.max_width", &link.max_width),
("link.speed", &link.speed),
("link.max_speed", &link.max_speed),
] {
push_opt(
out,
format!("{base}.{suffix}"),
(!value.trim().is_empty()).then(|| serde_json::json!(value)),
Some(Unit::Identifier),
"the device did not report this link property",
);
}
}
None => {
for suffix in [
"link.width",
"link.max_width",
"link.speed",
"link.max_speed",
] {
out.push(Reading::unavailable(
format!("{base}.{suffix}"),
Some(Unit::Identifier),
"Windows populates the PCIe link properties on the device \
node for endpoints only. Bridges, switch ports and host \
bridges carry none, and neither do devices that are not \
PCIe at all; this is one of those. Measured on a 64-device \
host: 23 carry the properties, and IronMonitor reports all 23",
));
}
}
}
push_opt(
out,
format!("{base}.numa_node"),
(dev.numa_node >= 0).then(|| serde_json::json!(dev.numa_node)),
Some(Unit::Count),
"the platform reports no NUMA affinity for this device",
);
}
}
fn resolve_usb(out: &mut Vec<Reading>) {
let monitor = match crate::usb::UsbMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"usb.<none>",
None,
format!("USB enumeration failed: {e}"),
));
return;
}
};
if monitor.devices().is_empty() {
out.push(Reading::unavailable(
"usb.<none>",
None,
"no USB devices enumerated on this machine",
));
return;
}
for dev in monitor.devices() {
let base = format!("usb.{}", id_segment(&dev.address));
push_opt(
out,
format!("{base}.product"),
dev.product
.as_ref()
.or(dev.description.as_ref())
.map(|p| serde_json::json!(p)),
Some(Unit::Text),
"the device publishes no product string",
);
push_opt(
out,
format!("{base}.manufacturer"),
dev.manufacturer.as_ref().map(|m| serde_json::json!(m)),
Some(Unit::Text),
"the device publishes no manufacturer string",
);
push_opt(
out,
format!("{base}.vendor_id"),
dev.vendor_id.map(|v| serde_json::json!(format!("{v:04x}"))),
Some(Unit::Identifier),
"this entry carries no USB vendor id; root hubs and virtual devices have none",
);
push_opt(
out,
format!("{base}.product_id"),
dev.product_id
.map(|p| serde_json::json!(format!("{p:04x}"))),
Some(Unit::Identifier),
"this entry carries no USB product id; root hubs and virtual devices have none",
);
use crate::usb::{UsbDeviceClass, UsbSpeed};
match dev.class {
UsbDeviceClass::Unknown => out.push(Reading::unavailable(
format!("{base}.class"),
Some(Unit::Identifier),
concat!(
"no class was recorded for this node: no device-descriptor ",
"class, no interface class, and no hub identifier, in ",
"either its hardware or its compatible ids. The usual cases ",
"are a composite parent, which declares class 00 to say the ",
"class is defined per interface and leaves its interfaces to ",
"answer, and a node enumerated on another bus -- a USBSTOR ",
"disk or a USB4 router -- which has no USB device descriptor ",
"to declare one from"
),
)),
c => push_id(
out,
format!("{base}.class"),
&format!("{c:?}").to_lowercase(),
),
}
match dev.speed {
UsbSpeed::Unknown => out.push(Reading::unavailable(
format!("{base}.speed"),
Some(Unit::Identifier),
concat!(
"no hub reported a negotiated speed for this device. The ",
"speed is a property of a link, so a node that sits on no ",
"upstream hub port has none to report -- a root hub is the ",
"usual case, and reporting one for it would be describing a ",
"link that does not exist. A device on a bus this reader ",
"does not walk reaches the same answer by a different route"
),
)),
s => push_id(
out,
format!("{base}.speed"),
&format!("{s:?}").to_lowercase(),
),
}
}
}
fn resolve_memory_dimms(out: &mut Vec<Reading>) {
const PER_SLOT: [&str; 10] = [
"capacity",
"speed",
"configured_speed",
"type",
"manufacturer",
"part_number",
"ecc",
"data_width",
"total_width",
"voltage",
];
let monitor = match crate::memory_topology::MemoryTopologyMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"memory.dimm.0.locator",
Some(Unit::Text),
format!("memory topology unavailable: {e}"),
));
return;
}
};
for (i, dimm) in monitor.topology().dimms.iter().enumerate() {
let base = format!("memory.dimm.{i}");
push_spec_text(out, format!("{base}.locator"), &dimm.locator);
push_spec_opt(
out,
format!("{base}.populated"),
dimm.populated.map(|p| serde_json::json!(p)),
None,
concat!(
"nothing the platform reported establishes whether this slot holds a ",
"module: no size could be read, and no status or part number says"
),
);
if dimm.populated == Some(false) {
for suffix in PER_SLOT {
out.push(Reading::unavailable(
format!("{base}.{suffix}"),
None,
"this slot is empty",
));
}
continue;
}
push_spec_opt(
out,
format!("{base}.capacity"),
dimm.capacity_bytes.map(|b| serde_json::json!(b)),
Some(Unit::Bytes),
"no module size was read for this slot",
);
push_spec_opt(
out,
format!("{base}.speed"),
dimm.speed_mts.map(|v| serde_json::json!(v)),
Some(Unit::MegatransfersPerSecond),
"SMBIOS reported no rated speed",
);
push_spec_opt(
out,
format!("{base}.configured_speed"),
dimm.configured_speed_mts.map(|v| serde_json::json!(v)),
Some(Unit::MegatransfersPerSecond),
"SMBIOS reported no configured speed",
);
push_spec_id(
out,
format!("{base}.type"),
&format!("{:?}", dimm.memory_type).to_lowercase(),
);
push_spec_text(out, format!("{base}.manufacturer"), &dimm.manufacturer);
push_spec_text(out, format!("{base}.part_number"), &dimm.part_number);
push_spec_opt(
out,
format!("{base}.data_width"),
dimm.data_width_bits
.filter(|w| *w > 0)
.map(|w| serde_json::json!(w)),
Some(Unit::Count),
"SMBIOS reported no data width",
);
push_spec_opt(
out,
format!("{base}.total_width"),
dimm.total_width_bits
.filter(|w| *w > 0)
.map(|w| serde_json::json!(w)),
Some(Unit::Count),
"SMBIOS reported no total width",
);
if let Some(ecc) = dimm.is_ecc() {
out.push(Reading::derived(
format!("{base}.ecc"),
serde_json::json!(ecc),
None,
));
} else {
out.push(Reading::unavailable(
format!("{base}.ecc"),
None,
"ECC is inferred from the data and total widths, and one is unknown",
));
}
push_spec_opt(
out,
format!("{base}.voltage"),
dimm.voltage.map(|v| serde_json::json!(v)),
Some(Unit::Volts),
"SMBIOS reported no operating voltage",
);
}
}
fn resolve_cpu_cache(out: &mut Vec<Reading>) {
const TOTALS: [&str; 4] = [
"cpu.cache.l1d",
"cpu.cache.l1i",
"cpu.cache.l2",
"cpu.cache.l3",
];
let monitor = match crate::cpu_cache::CpuCacheMonitor::new() {
Ok(m) => m,
Err(e) => {
for id in TOTALS {
out.push(Reading::unavailable(
id,
Some(Unit::Bytes),
format!("cache topology unavailable: {e}"),
));
}
return;
}
};
let topology = monitor.topology();
let kib = |v: u64| (v > 0).then(|| serde_json::json!(v * 1024));
for (id, value) in TOTALS.iter().zip([
topology.total_l1d_kb,
topology.total_l1i_kb,
topology.total_l2_kb,
topology.total_l3_kb,
]) {
push_opt(
out,
*id,
kib(value),
Some(Unit::Bytes),
"no aggregate was reported for this level; some platforms publish a \
combined L1 rather than separate data and instruction figures, in \
which case the per-instance entities below carry the sizes",
);
}
for (i, cache) in monitor.caches().iter().enumerate() {
let base = format!("cpu.cache.{i}");
push_id(
out,
format!("{base}.level"),
&format!("{:?}", cache.level).to_lowercase(),
);
push_opt(
out,
format!("{base}.size"),
kib(cache.size_kb),
Some(Unit::Bytes),
"the platform reported no size for this cache",
);
push_opt(
out,
format!("{base}.line_size"),
cache.line_size.map(|b| serde_json::json!(b)),
Some(Unit::Bytes),
"the platform reported no line size for this cache",
);
push_opt(
out,
format!("{base}.shared_cpus"),
(!cache.shared_cpu_list.trim().is_empty())
.then(|| serde_json::json!(cache.shared_cpu_list)),
Some(Unit::Text),
"the platform does not publish which processors share this cache",
);
}
}
fn resolve_gpu(out: &mut Vec<Reading>) {
let Ok(monitor) = crate::UnifiedMonitor::new() else {
out.push(Reading::unavailable(
"gpu.<none>",
None,
"GPU enumeration failed",
));
return;
};
let gpus = monitor.gpus().snapshot_all_partial();
if gpus.is_empty() {
out.push(Reading::unavailable(
"gpu.<none>",
None,
"no GPU detected on this machine",
));
return;
}
const NO_ADAPTER_TEMPERATURE: &str = concat!(
"no temperature was read for this adapter. NVML answers for NVIDIA ",
"cards; on Windows an AMD or Intel adapter has no source in ironmon but ",
"an OpenHardwareMonitor or LibreHardwareMonitor WMI namespace, which ",
"exists only where one of those tools is installed. An adapter with no ",
"sensor and a ironmon with no binding to the vendor SDK are ",
"indistinguishable from here"
);
const NO_ADAPTER_THERMAL_LIMIT: &str = concat!(
"no thermal limit was read for this adapter. NVML publishes one for ",
"NVIDIA cards; the Windows AMD and Intel backends fill this field with ",
"nothing, without asking the driver whether it has one"
);
const NO_ADAPTER_SHUTDOWN_THRESHOLD: &str = concat!(
"no shutdown threshold was read for this adapter. NVML publishes one ",
"for NVIDIA cards; the Windows AMD and Intel backends fill this field ",
"with nothing, without asking the driver whether it has one"
);
const NO_ADAPTER_POWER_DRAW: &str = concat!(
"no power draw was read for this adapter. NVML reports it for NVIDIA ",
"cards; the Windows AMD and Intel backends set this field to nothing ",
"without consulting the driver, and both vendors expose it through a ",
"library IronMonitor does not bind"
);
const NO_ADAPTER_POWER_CAP: &str = concat!(
"no enforced power cap was read for this adapter. See the power draw ",
"beside it: on Windows the AMD and Intel backends consult nothing for ",
"either figure"
);
const NO_ADAPTER_CLOCK: &str = concat!(
"no graphics clock was read for this adapter. NVML reports it for ",
"NVIDIA cards, the Linux sysfs readers report it for AMD and Intel, ",
"and the Windows AMD and Intel backends consult nothing -- there is no ",
"clock in the Windows GPU performance counters, and the vendor ",
"libraries that do carry one are not bound"
);
const NO_ADAPTER_CLOCK_CEILING: &str = concat!(
"no graphics clock ceiling was read for this adapter. See the clock ",
"beside it"
);
const NO_ADAPTER_UTILIZATION: &str = concat!(
"no utilization counter was read for this adapter; the backend that ",
"queried it reports none, which is not the same as an idle engine"
);
for (i, gpu) in gpus.iter().enumerate() {
let gpu = match gpu {
Ok(gpu) => gpu,
Err(e) => {
out.push(Reading::unavailable(
format!("gpu.{i}.<unreadable>"),
None,
format!("this adapter was enumerated but its query failed: {e}"),
));
continue;
}
};
let base = format!("gpu.{i}");
push_text(out, format!("{base}.name"), &gpu.static_info.name);
out.push(Reading::measured(
format!("{base}.vendor"),
serde_json::json!(format!("{:?}", gpu.static_info.vendor).to_lowercase()),
Some(Unit::Identifier),
));
let dynamic = &gpu.dynamic_info;
push_opt(
out,
format!("{base}.utilization"),
dynamic.utilization.map(|u| serde_json::json!(u)),
Some(Unit::Percent),
NO_ADAPTER_UTILIZATION,
);
push_opt(
out,
format!("{base}.thermal.temperature"),
dynamic.thermal.temperature.map(|t| serde_json::json!(t)),
Some(Unit::Celsius),
NO_ADAPTER_TEMPERATURE,
);
push_opt(
out,
format!("{base}.thermal.max_temperature"),
dynamic
.thermal
.max_temperature
.map(|t| serde_json::json!(t)),
Some(Unit::Celsius),
NO_ADAPTER_THERMAL_LIMIT,
);
push_opt(
out,
format!("{base}.thermal.critical_temperature"),
dynamic
.thermal
.critical_temperature
.map(|t| serde_json::json!(t)),
Some(Unit::Celsius),
NO_ADAPTER_SHUTDOWN_THRESHOLD,
);
push_opt(
out,
format!("{base}.power.draw"),
dynamic.power.draw.map(|p| serde_json::json!(p)),
Some(Unit::Milliwatts),
NO_ADAPTER_POWER_DRAW,
);
push_opt(
out,
format!("{base}.power.limit"),
dynamic.power.limit.map(|p| serde_json::json!(p)),
Some(Unit::Milliwatts),
NO_ADAPTER_POWER_CAP,
);
push_opt(
out,
format!("{base}.clocks.graphics"),
dynamic.clocks.graphics.map(|c| serde_json::json!(c)),
Some(Unit::Megahertz),
NO_ADAPTER_CLOCK,
);
push_opt(
out,
format!("{base}.clocks.graphics.max"),
dynamic.clocks.graphics_max.map(|c| serde_json::json!(c)),
Some(Unit::Megahertz),
NO_ADAPTER_CLOCK_CEILING,
);
let mem = &dynamic.memory;
for (suffix, value) in [("total", mem.total), ("used", mem.used)] {
match value {
Some(bytes) => out.push(Reading::measured(
format!("{base}.memory.{suffix}"),
serde_json::json!(bytes),
Some(Unit::Bytes),
)),
None => out.push(Reading::unavailable(
format!("{base}.memory.{suffix}"),
Some(Unit::Bytes),
"the driver reported no figure for it. Unified-memory parts \
have no discrete video memory to report, and some adapters \
publish usage without publishing a capacity",
)),
}
}
}
}
pub(crate) fn id_segment(raw: &str) -> String {
let cleaned: String = raw
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect();
let mut out = String::with_capacity(cleaned.len());
let mut last_underscore = false;
for c in cleaned.chars() {
if c == '_' {
if !last_underscore {
out.push(c);
}
last_underscore = true;
} else {
out.push(c);
last_underscore = false;
}
}
let trimmed = out.trim_matches('_').to_string();
if trimmed.is_empty() {
"unnamed".to_string()
} else {
trimmed
}
}
const ABSENCE_WORDS: [&str; 5] = ["unknown", "unspecified", "undetermined", "n/a", "none"];
pub fn names_an_absence(value: &str) -> bool {
let v = value.trim().to_ascii_lowercase();
ABSENCE_WORDS.contains(&v.as_str())
}
fn push_text(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
push_str_as(out, id, value, Unit::Text, Provenance::Measured);
}
fn push_spec_text(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
push_str_as(out, id, value, Unit::Text, Provenance::Specification);
}
fn push_id(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
push_str_as(out, id, value, Unit::Identifier, Provenance::Measured);
}
fn push_spec_id(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
push_str_as(out, id, value, Unit::Identifier, Provenance::Specification);
}
fn push_str_as(
out: &mut Vec<Reading>,
id: impl Into<String>,
value: &str,
unit: Unit,
provenance: Provenance,
) {
let id = id.into();
if value.trim().is_empty() {
out.push(Reading::unavailable(
id,
Some(unit),
"reader returned an empty string",
));
return;
}
if names_an_absence(value) {
out.push(Reading::unavailable(
id,
Some(unit),
format!(
"reader returned {:?}, which names an absence rather than a value",
value.trim()
),
));
return;
}
let json = serde_json::json!(value);
out.push(match provenance {
Provenance::Specification => Reading::spec(id, json, Some(unit)),
Provenance::Derived => Reading::derived(id, json, Some(unit)),
_ => Reading::measured(id, json, Some(unit)),
});
}
fn push_opt(
out: &mut Vec<Reading>,
id: impl Into<String>,
value: Option<serde_json::Value>,
unit: Option<Unit>,
why_absent: &str,
) {
match value {
Some(v) if v.as_str().is_some_and(names_an_absence) => {
out.push(Reading::unavailable(
id,
unit,
format!(
"reader returned {}, which names an absence rather than a value",
v
),
));
}
Some(v) => out.push(Reading::measured(id, v, unit)),
None => out.push(Reading::unavailable(id, unit, why_absent)),
}
}
fn read_cpu_stats() -> Result<crate::core::cpu::CpuStats, String> {
#[cfg(windows)]
{
crate::platform::windows::read_cpu_stats().map_err(|e| e.to_string())
}
#[cfg(target_os = "linux")]
{
crate::platform::linux::read_cpu_stats().map_err(|e| e.to_string())
}
#[cfg(target_os = "macos")]
{
crate::platform::macos::read_cpu_stats().map_err(|e| e.to_string())
}
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
{
Err("no CPU reader is implemented for this platform".to_string())
}
}
fn read_memory_stats() -> Result<crate::core::memory::MemoryStats, String> {
#[cfg(windows)]
{
crate::platform::windows::read_memory_stats().map_err(|e| e.to_string())
}
#[cfg(target_os = "linux")]
{
crate::platform::linux::read_memory_stats().map_err(|e| e.to_string())
}
#[cfg(target_os = "macos")]
{
crate::platform::macos::read_memory_stats().map_err(|e| e.to_string())
}
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
{
Err("no memory reader is implemented for this platform".to_string())
}
}
fn detect_board() -> Option<crate::core::platform_info::BoardInfo> {
#[cfg(windows)]
{
crate::platform::windows::detect_platform().ok()
}
#[cfg(not(windows))]
{
None
}
}
pub fn validate(readings: &[Reading]) -> Vec<String> {
let ontology = Ontology::build();
let mut problems = Vec::new();
for r in readings {
let Some(value) = r.value.as_ref().and_then(|v| v.as_f64()) else {
continue;
};
if let Some(entity) = lookup_template(&ontology, &r.id) {
if let Some(problem) = entity.validate_range(value) {
problems.push(problem);
}
}
}
problems
}
fn lookup_template<'a>(ontology: &'a Ontology, concrete: &str) -> Option<&'a Entity> {
ontology.template_for(concrete)
}
const PROCESS_LIMIT: usize = 10;
const PROCESS_CPU_INTERVAL_MS: u64 = 250;
fn resolve_disk(out: &mut Vec<Reading>) {
let disks = match crate::disk::enumerate_disks() {
Ok(d) => d,
Err(e) => {
out.push(Reading::unavailable(
"disk.<none>",
None,
format!("disk enumeration failed: {e}"),
));
return;
}
};
if disks.is_empty() {
out.push(Reading::unavailable(
"disk.<none>",
None,
"no block devices enumerated on this machine",
));
return;
}
for (i, disk) in disks.iter().enumerate() {
let base = format!("disk.{i}");
match disk.info() {
Ok(info) => {
push_text(out, format!("{base}.model"), &info.model);
match info.capacity {
Some(bytes) if bytes > 0 => out.push(Reading::measured(
format!("{base}.capacity"),
serde_json::json!(bytes),
Some(Unit::Bytes),
)),
Some(_) => out.push(Reading::unavailable(
format!("{base}.capacity"),
Some(Unit::Bytes),
"device reported zero capacity",
)),
None => out.push(Reading::unavailable(
format!("{base}.capacity"),
Some(Unit::Bytes),
"capacity was not read from this device",
)),
}
}
Err(e) => {
for suffix in ["model", "capacity"] {
out.push(Reading::unavailable(
format!("{base}.{suffix}"),
None,
format!("device info read failed: {e}"),
));
}
}
}
match disk.io_stats() {
Ok(io) => {
push_opt(
out,
format!("{base}.read_rate"),
io.read_throughput.map(|v| serde_json::json!(v)),
Some(Unit::BytesPerSecond),
"a throughput needs two samples; this query took one",
);
push_opt(
out,
format!("{base}.write_rate"),
io.write_throughput.map(|v| serde_json::json!(v)),
Some(Unit::BytesPerSecond),
"a throughput needs two samples; this query took one",
);
}
Err(e) => {
for suffix in ["read_rate", "write_rate"] {
out.push(Reading::unavailable(
format!("{base}.{suffix}"),
Some(Unit::BytesPerSecond),
format!("I/O statistics read failed: {e}"),
));
}
}
}
resolve_disk_health(out, &base, disk.as_ref());
}
}
fn resolve_disk_health(out: &mut Vec<Reading>, base: &str, disk: &dyn crate::disk::DiskDevice) {
use crate::disk::DiskType;
let kind = match disk.disk_type() {
DiskType::NvmeSsd => Some("nvme_ssd"),
DiskType::SataSsd => Some("sata_ssd"),
DiskType::SataHdd => Some("sata_hdd"),
DiskType::Scsi => Some("scsi"),
DiskType::Usb => Some("usb"),
DiskType::Virtual => Some("virtual"),
DiskType::Unknown => None,
};
push_opt(
out,
format!("{base}.kind"),
kind.map(|k| serde_json::json!(k)),
Some(Unit::Text),
"the platform did not classify this device's transport or medium",
);
match disk.info() {
Ok(info) => push_opt(
out,
format!("{base}.serial"),
info.serial.as_ref().map(|s| serde_json::json!(s)),
Some(Unit::Text),
"the platform did not disclose a serial number for this device",
),
Err(e) => out.push(Reading::unavailable(
format!("{base}.serial"),
Some(Unit::Text),
format!("device info read failed: {e}"),
)),
}
use crate::disk::DiskHealth;
match disk.health() {
Ok(DiskHealth::Unknown) => out.push(Reading::unavailable(
format!("{base}.health"),
Some(Unit::Text),
"no counter this device exposes yielded a health verdict",
)),
Ok(h) => push_text(
out,
format!("{base}.health"),
&format!("{h:?}").to_lowercase(),
),
Err(e) => out.push(Reading::unavailable(
format!("{base}.health"),
Some(Unit::Text),
format!("health read failed: {e}"),
)),
}
const SMART_FIELDS: [&str; 7] = [
"temperature",
"smart.passed",
"smart.power_on_hours",
"smart.power_cycles",
"smart.reallocated_sectors",
"smart.pending_sectors",
"smart.uncorrectable_sectors",
];
match disk.smart_info() {
Ok(s) => {
use crate::disk::SmartSource;
let from_the_drive = matches!(
s.source,
SmartSource::NvmeLogPage | SmartSource::AtaAttributes
);
let counter_absent = |what: &str| -> String {
if from_the_drive {
format!("the drive did not report a {what}")
} else {
format!(
"no {what} was read: this drive's counters come from the \
operating system's storage stack rather than from the \
drive -- `Get-StorageReliabilityCounter` on Windows, which \
needs Administrator -- and it returned nothing here. The \
drive was not asked"
)
}
};
push_opt(
out,
format!("{base}.temperature"),
s.temperature.map(|t| serde_json::json!(t)),
Some(Unit::Celsius),
if from_the_drive {
"this device exposes no thermal sensor"
} else {
"no temperature was read: it would come from the storage \
stack's reliability counters, which returned nothing here. \
Whether the device has a sensor is not established either way"
},
);
push_opt(
out,
format!("{base}.smart.passed"),
s.passed.map(|v| serde_json::json!(v)),
None,
concat!(
"the drive's own verdict was not obtained: neither the NVMe ",
"critical warning bits nor the ATA failure prediction was ",
"readable, and this field is not a judgement computed from ",
"the counters"
),
);
push_opt(
out,
format!("{base}.smart.power_on_hours"),
s.power_on_hours.map(|v| serde_json::json!(v)),
Some(Unit::Hours),
&counter_absent("power-on hour count"),
);
push_opt(
out,
format!("{base}.smart.power_cycles"),
s.power_cycle_count.map(|v| serde_json::json!(v)),
Some(Unit::Count),
&counter_absent("power cycle count"),
);
let sector_absent = |attribute: u8, what: &str| -> String {
match s.source {
SmartSource::NvmeLogPage => format!(
"not an NVMe concept: this drive answered from its NVMe \
SMART/Health log page, which has no {what} -- attribute \
{attribute} is an ATA notion and does not exist here"
),
SmartSource::AtaAttributes => format!(
"the drive returned an ATA attribute table of {} attributes \
and none of them is {attribute} ({what})",
s.attributes.len()
),
SmartSource::StorageStack => format!(
"no {what} was read: no ATA attribute table was obtained \
from this drive at all, so attribute {attribute} was \
neither present nor absent -- it was never looked for"
),
}
};
push_opt(
out,
format!("{base}.smart.reallocated_sectors"),
s.reallocated_sectors.map(|v| serde_json::json!(v)),
Some(Unit::Count),
§or_absent(5, "reallocated sector count"),
);
push_opt(
out,
format!("{base}.smart.pending_sectors"),
s.pending_sectors.map(|v| serde_json::json!(v)),
Some(Unit::Count),
§or_absent(197, "pending sector count"),
);
push_opt(
out,
format!("{base}.smart.uncorrectable_sectors"),
s.uncorrectable_sectors.map(|v| serde_json::json!(v)),
Some(Unit::Count),
&counter_absent("uncorrectable sector count"),
);
}
Err(e) => {
for suffix in SMART_FIELDS {
out.push(Reading::unavailable(
format!("{base}.{suffix}"),
None,
format!("SMART read failed: {e}"),
));
}
}
}
const NVME_FIELDS: [&str; 6] = [
"nvme.version",
"nvme.percentage_used",
"nvme.data_units_written",
"nvme.data_units_read",
"nvme.power_state",
"nvme.critical_warnings",
];
match disk.nvme_info() {
Ok(n) => {
push_opt(
out,
format!("{base}.nvme.version"),
n.nvme_version.as_ref().map(|v| serde_json::json!(v)),
Some(Unit::Text),
"the controller did not report a specification version",
);
push_opt(
out,
format!("{base}.nvme.percentage_used"),
n.percentage_used.map(|v| serde_json::json!(v)),
Some(Unit::Percent),
"the controller did not report a wear figure",
);
push_opt(
out,
format!("{base}.nvme.data_units_written"),
n.data_units_written.map(|v| serde_json::json!(v)),
Some(Unit::Count),
"the controller did not report a written data unit count",
);
push_opt(
out,
format!("{base}.nvme.data_units_read"),
n.data_units_read.map(|v| serde_json::json!(v)),
Some(Unit::Count),
"the controller did not report a read data unit count",
);
push_opt(
out,
format!("{base}.nvme.power_state"),
n.power_state.map(|v| serde_json::json!(v)),
Some(Unit::Count),
"the controller does not implement Get Features for power management",
);
push_opt(
out,
format!("{base}.nvme.critical_warnings"),
n.critical_warnings.map(|v| serde_json::json!(v)),
Some(Unit::Count),
"the controller did not serve the SMART/Health log page",
);
}
Err(e) => {
for suffix in NVME_FIELDS {
out.push(Reading::unavailable(
format!("{base}.{suffix}"),
None,
format!("no NVMe controller data: {e}"),
));
}
}
}
}
fn resolve_network(out: &mut Vec<Reading>) {
let mut monitor = match crate::network_monitor::NetworkMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"network.<none>",
None,
format!("network monitor unavailable: {e}"),
));
return;
}
};
let interfaces = match monitor.interfaces() {
Ok(i) => i,
Err(e) => {
out.push(Reading::unavailable(
"network.<none>",
None,
format!("interface enumeration failed: {e}"),
));
return;
}
};
if interfaces.is_empty() {
out.push(Reading::unavailable(
"network.<none>",
None,
"no network interfaces enumerated",
));
return;
}
for iface in &interfaces {
let base = format!("network.{}", id_segment(&iface.name));
out.push(Reading::measured(
format!("{base}.rx_bytes"),
serde_json::json!(iface.rx_bytes),
Some(Unit::Bytes),
));
out.push(Reading::measured(
format!("{base}.tx_bytes"),
serde_json::json!(iface.tx_bytes),
Some(Unit::Bytes),
));
for dir in ["rx", "tx"] {
out.push(Reading::unavailable(
format!("{base}.{dir}_rate"),
Some(Unit::BytesPerSecond),
"a rate needs two samples; this query took one — differentiate \
rx_bytes/tx_bytes across two snapshots",
));
}
push_opt(
out,
format!("{base}.link_speed"),
iface.speed_mbps.map(|s| serde_json::json!(s)),
Some(Unit::Count),
"driver reports no negotiated link rate for this interface",
);
}
}
fn resolve_process(out: &mut Vec<Reading>) {
let mut monitor = match crate::process_monitor::ProcessMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"process.<none>",
None,
format!("process monitor unavailable: {e}"),
));
return;
}
};
if let Err(e) = monitor.sample_cpu_times() {
out.push(Reading::unavailable(
"process.<none>",
None,
format!("process enumeration failed: {e}"),
));
return;
}
std::thread::sleep(std::time::Duration::from_millis(PROCESS_CPU_INTERVAL_MS));
let procs = match monitor.processes_by_memory() {
Ok(p) => p,
Err(e) => {
out.push(Reading::unavailable(
"process.<none>",
None,
format!("process enumeration failed: {e}"),
));
return;
}
};
if procs.is_empty() {
out.push(Reading::unavailable(
"process.<none>",
None,
"no processes enumerated",
));
return;
}
let total = procs.len();
for p in procs.iter().take(PROCESS_LIMIT) {
let base = format!("process.{}", p.pid);
push_text(out, format!("{base}.name"), &p.name);
out.push(Reading::measured(
format!("{base}.cpu"),
serde_json::json!(p.cpu_percent),
Some(Unit::Percent),
));
out.push(Reading::measured(
format!("{base}.memory"),
serde_json::json!(p.memory_bytes),
Some(Unit::Bytes),
));
}
if total > PROCESS_LIMIT {
out.push(Reading::unavailable(
"process.<truncated>",
Some(Unit::Count),
format!(
"{total} processes exist; this snapshot reports the {PROCESS_LIMIT} \
largest by memory. Absence from this list is not absence from the \
machine — use `ironmon cli processes` for the full table"
),
));
}
}
fn resolve_thermal(out: &mut Vec<Reading>) {
let temps = match crate::motherboard::get_system_temperatures() {
Ok(t) => t,
Err(e) => {
out.push(Reading::unavailable(
"thermal.<none>",
Some(Unit::Celsius),
format!("temperature read failed: {e}"),
));
return;
}
};
for (name, value) in [
("cpu", temps.cpu),
("gpu", temps.gpu),
("motherboard", temps.motherboard),
] {
match value {
Some(v) => out.push(Reading::measured(
format!("thermal.{name}.temperature"),
serde_json::json!(v),
Some(Unit::Celsius),
)),
None => out.push(Reading::unavailable(
format!("thermal.{name}.temperature"),
Some(Unit::Celsius),
"no sensor exposed for this component — on Windows most board \
sensors require a signed kernel driver, and a virtual machine \
usually exposes none at all",
)),
}
}
for (device, value) in temps.storage.iter().chain(temps.network.iter()) {
out.push(Reading::measured(
format!("thermal.{}.temperature", id_segment(device)),
serde_json::json!(value),
Some(Unit::Celsius),
));
}
}
fn resolve_displays(out: &mut Vec<Reading>) {
let monitor = match crate::display::DisplayMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"board.display.<none>",
None,
format!("display enumeration failed: {e}"),
));
return;
}
};
let displays = monitor.displays();
if displays.is_empty() {
out.push(Reading::unavailable(
"board.display.<none>",
None,
concat!(
"no display is attached, or none is visible to this session — a ",
"headless server and a locked-down service account both look like this",
),
));
return;
}
for (i, d) in displays.iter().enumerate() {
let base = format!("board.display.{i}");
push_opt(
out,
format!("{base}.name"),
d.name.as_ref().map(|n| serde_json::json!(n)),
Some(Unit::Text),
"this display publishes no name",
);
push_id(
out,
format!("{base}.connection"),
&format!("{:?}", d.connection).to_lowercase(),
);
const NOT_A_MODE: &str = "the display is attached and its current mode was not readable; zero is not a resolution";
push_opt(
out,
format!("{base}.width"),
d.width.filter(|w| *w > 0).map(|w| serde_json::json!(w)),
Some(Unit::Count),
NOT_A_MODE,
);
push_opt(
out,
format!("{base}.height"),
d.height.filter(|h| *h > 0).map(|h| serde_json::json!(h)),
Some(Unit::Count),
NOT_A_MODE,
);
push_opt(
out,
format!("{base}.refresh_rate"),
d.refresh_rate
.filter(|r| *r > 0.0)
.map(|r| serde_json::json!(r)),
Some(Unit::Hertz),
NOT_A_MODE,
);
out.push(Reading::measured(
format!("{base}.primary"),
serde_json::json!(d.is_primary),
None,
));
}
}
fn resolve_sensors(out: &mut Vec<Reading>) {
let monitor = match crate::sensors::SensorMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"board.sensor.<none>",
None,
format!("sensor enumeration failed: {e}"),
));
return;
}
};
let items = monitor.sensors();
if items.is_empty() {
out.push(Reading::unavailable(
"board.sensor.<none>",
None,
match monitor.note() {
Some(why) => why.to_string(),
None => "the platform enumerated no sensors on this machine".to_string(),
},
));
return;
}
for (i, sensor) in items.iter().enumerate() {
let base = format!("board.sensor.{i}");
push_text(out, format!("{base}.name"), &sensor.name);
push_id(
out,
format!("{base}.type"),
&format!("{:?}", sensor.sensor_type).to_lowercase(),
);
out.push(Reading::measured(
format!("{base}.active"),
serde_json::json!(sensor.active),
None,
));
}
}
fn looks_like_pci_address(value: &str) -> bool {
let value = value.trim();
let (bus_dev, function) = match value.rsplit_once('.') {
Some(parts) => parts,
None => return false,
};
if function.is_empty() || !function.chars().all(|c| c.is_ascii_hexdigit()) {
return false;
}
let fields: Vec<&str> = bus_dev.split(':').collect();
if !matches!(fields.len(), 2 | 3) {
return false;
}
fields
.iter()
.all(|f| !f.is_empty() && f.chars().all(|c| c.is_ascii_hexdigit()))
}
fn resolve_storage_controllers(out: &mut Vec<Reading>) {
let monitor = match crate::storage_controller::StorageControllerMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"disk.controller.<none>",
None,
format!("storage controllers could not be enumerated here: {e}"),
));
return;
}
};
let controllers = monitor.controllers();
if controllers.is_empty() {
out.push(Reading::unavailable(
"disk.controller.<none>",
None,
"controller enumeration succeeded and found none, which on a machine with \
disks means the enumeration is incomplete rather than that the disks are \
attached to nothing",
));
return;
}
for (i, c) in controllers.iter().enumerate() {
let base = format!("disk.controller.{i}");
push_text(out, format!("{base}.name"), &c.name);
push_text(out, format!("{base}.vendor"), &c.vendor);
push_text(out, format!("{base}.model"), &c.model);
push_id(out, format!("{base}.driver"), &c.driver);
push_id(
out,
format!("{base}.interface"),
&format!("{:?}", c.interface),
);
push_opt(
out,
format!("{base}.pci_address"),
looks_like_pci_address(&c.pci_address).then(|| serde_json::json!(c.pci_address)),
Some(Unit::Identifier),
if c.pci_address.trim().is_empty() {
"this controller reports no bus address".to_string()
} else {
format!(
"the platform reports `{}` for this controller, which is not a PCI \
address and cannot be joined against `pci.*`",
c.pci_address.trim()
)
}
.as_str(),
);
push_opt(
out,
format!("{base}.ports"),
(c.ports > 0).then(|| serde_json::json!(c.ports)),
Some(Unit::Count),
"this controller reports no port count",
);
}
}
fn resolve_settings(out: &mut Vec<Reading>) {
for handler in crate::profile::apply::builtin_handlers() {
let id = format!(
"{}.setting.{}",
super::setting_domain(handler.subsystem()).as_str(),
handler.setting_id()
);
match crate::profile::apply::read_current_with_retry(handler.as_ref()) {
Some(crate::profile::SettingValue::Unreadable(why)) => out.push(Reading::unavailable(
id,
Some(Unit::Identifier),
format!("the handler for this setting reported it unreadable: {why}"),
)),
Some(value) => {
use crate::profile::SettingValue as V;
let text = match &value {
V::Bool(b) => b.to_string(),
V::Int(i) => i.to_string(),
V::Uint(u) => u.to_string(),
V::Float(x) => x.to_string(),
V::Text(s) | V::Hex(s) => s.clone(),
V::Unreadable(_) => unreachable!("handled above"),
};
push_id(out, id, &text);
}
None => out.push(Reading::unavailable(
id,
Some(Unit::Identifier),
concat!(
"this setting has a write handler and no reader: the handler ",
"implements no `read_current`, so IronMonitor can change it and ",
"cannot say what it currently holds. That also makes the ",
"write one-way -- `revert_setting` refuses rather than ",
"writing a default it never read"
),
)),
}
}
}
fn resolve_power_profiles(out: &mut Vec<Reading>) {
let monitor = match crate::power_profile::PowerProfileMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"power.profile.<none>",
None,
format!("power plans could not be enumerated here: {e}"),
));
return;
}
};
let plans = monitor.power_plans();
if plans.is_empty() {
out.push(Reading::unavailable(
"power.profile.<none>",
None,
"no power plan was enumerated; this platform may manage power without \
presenting named plans",
));
return;
}
for (i, p) in plans.iter().enumerate() {
let base = format!("power.profile.{i}");
push_text(out, format!("{base}.name"), &p.name);
out.push(Reading::measured(
format!("{base}.active"),
serde_json::json!(p.active),
None,
));
}
}
fn resolve_codecs(out: &mut Vec<Reading>) {
use crate::codec::{BitDepth, CapabilitySource, MaxResolution};
let monitor = match crate::codec::CodecMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"gpu.codec.<none>",
None,
format!("hardware codec support could not be determined here: {e}"),
));
return;
}
};
let caps = monitor.capabilities();
if caps.is_empty() {
out.push(Reading::unavailable(
"gpu.codec.<none>",
None,
"no hardware codec capability was found; the GPU may have no media engine",
));
return;
}
for (i, c) in caps.iter().enumerate() {
let base = format!("gpu.codec.{i}");
let queried = c.source == CapabilitySource::DirectQuery;
let push_str = |out: &mut Vec<Reading>, id: String, v: &str| {
if queried {
push_id(out, id, v);
} else {
push_spec_id(out, id, v);
}
};
if queried {
push_text(out, format!("{base}.device"), &c.device);
} else {
push_spec_text(out, format!("{base}.device"), &c.device);
}
push_str(out, format!("{base}.codec"), &format!("{:?}", c.codec));
push_str(
out,
format!("{base}.direction"),
&format!("{:?}", c.direction),
);
push_str(out, format!("{base}.engine"), &c.engine);
push_str(
out,
format!("{base}.max_resolution"),
&format!("{:?}", c.max_resolution),
);
let pixels = match c.max_resolution {
MaxResolution::SD => Some((720, 480)),
MaxResolution::HD => Some((1280, 720)),
MaxResolution::FullHD => Some((1920, 1080)),
MaxResolution::QHD => Some((2560, 1440)),
MaxResolution::UHD4K => Some((3840, 2160)),
MaxResolution::UHD8K => Some((7680, 4320)),
MaxResolution::Unknown => None,
};
match pixels {
Some((w, h)) => {
out.push(Reading::derived(
format!("{base}.max_width"),
serde_json::json!(w),
Some(Unit::Count),
));
out.push(Reading::derived(
format!("{base}.max_height"),
serde_json::json!(h),
Some(Unit::Count),
));
}
None => {
for suffix in ["max_width", "max_height"] {
out.push(Reading::unavailable(
format!("{base}.{suffix}"),
Some(Unit::Count),
"the engine reports no frame class, so no dimensions follow from it",
));
}
}
}
let depth = match c.max_bit_depth {
BitDepth::Bit8 => Some(8),
BitDepth::Bit10 => Some(10),
BitDepth::Bit12 => Some(12),
BitDepth::Unknown => None,
};
match depth {
Some(d) if queried => out.push(Reading::measured(
format!("{base}.max_bit_depth"),
serde_json::json!(d),
Some(Unit::Count),
)),
Some(d) => out.push(Reading::spec(
format!("{base}.max_bit_depth"),
serde_json::json!(d),
Some(Unit::Count),
)),
None => out.push(Reading::unavailable(
format!("{base}.max_bit_depth"),
Some(Unit::Count),
"the engine reports no bit depth",
)),
}
push_opt(
out,
format!("{base}.max_fps"),
c.max_fps.map(|fps| serde_json::json!(fps)),
Some(Unit::Count),
"no driver reports a frame rate and this crate does not estimate one",
);
out.push(Reading::derived(
format!("{base}.confidence"),
serde_json::json!(c.confidence * 100.0),
Some(Unit::Percent),
));
}
}
fn resolve_input(out: &mut Vec<Reading>) {
let monitor = match crate::input::InputMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"board.input.<none>",
None,
format!("input devices could not be enumerated here: {e}"),
));
return;
}
};
let devices = monitor.devices();
if devices.is_empty() {
out.push(Reading::unavailable(
"board.input.<none>",
None,
"input enumeration succeeded and found no device, which is ordinary on a \
headless machine",
));
return;
}
for (i, d) in devices.iter().enumerate() {
let base = format!("board.input.{i}");
push_text(out, format!("{base}.name"), &d.name);
push_id(out, format!("{base}.type"), &format!("{:?}", d.device_type));
push_id(
out,
format!("{base}.interface"),
&format!("{:?}", d.interface),
);
push_text(out, format!("{base}.vendor"), &d.vendor);
push_text(out, format!("{base}.product"), &d.product);
push_opt(
out,
format!("{base}.active"),
d.is_active.map(|a| serde_json::json!(a)),
None,
"the platform did not report whether this device is connected and usable",
);
}
}
fn resolve_audio(out: &mut Vec<Reading>) {
let monitor = match crate::audio::AudioMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"board.audio.<none>",
None,
format!("audio endpoints could not be enumerated here: {e}"),
));
return;
}
};
let devices = monitor.devices();
if devices.is_empty() {
out.push(Reading::unavailable(
"board.audio.<none>",
None,
"audio enumeration succeeded and found no endpoint",
));
return;
}
for (i, d) in devices.iter().enumerate() {
let base = format!("board.audio.{i}");
push_text(out, format!("{base}.name"), &d.name);
push_id(
out,
format!("{base}.direction"),
&format!("{:?}", d.device_type),
);
push_opt(
out,
format!("{base}.state"),
d.state
.map(|s| serde_json::json!(format!("{s:?}").to_lowercase())),
Some(Unit::Identifier),
"the platform did not report an endpoint state for this device",
);
push_opt(
out,
format!("{base}.default"),
d.is_default.map(|v| serde_json::json!(v)),
None,
concat!(
"which endpoint the system routes to by default is a COM call ",
"this crate does not make; it was previously whichever row the ",
"enumeration returned first"
),
);
const NO_MIXER: &str =
"IronMonitor has no mixer binding on this platform, so no level is read from this endpoint";
push_opt(
out,
format!("{base}.volume"),
d.volume.map(|v| serde_json::json!(v)),
Some(Unit::Percent),
NO_MIXER,
);
push_opt(
out,
format!("{base}.muted"),
d.muted.map(|m| serde_json::json!(m)),
None,
NO_MIXER,
);
}
}
fn resolve_cameras(out: &mut Vec<Reading>) {
let monitor = match crate::camera::CameraMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"board.camera.<none>",
None,
format!("cameras could not be enumerated here: {e}"),
));
return;
}
};
let cameras = monitor.cameras();
if cameras.is_empty() {
out.push(Reading::unavailable(
"board.camera.<none>",
None,
"camera enumeration succeeded and found no device",
));
return;
}
for (i, c) in cameras.iter().enumerate() {
let base = format!("board.camera.{i}");
push_text(out, format!("{base}.name"), &c.name);
push_id(
out,
format!("{base}.connection"),
&format!("{:?}", c.connection),
);
push_id(out, format!("{base}.driver"), &c.driver);
const NO_MODE_LIST: &str = concat!(
"no reader asks this camera for its mode list on any platform: the ",
"Linux path would need the VIDIOC_ENUM_FRAMESIZES ioctl and the ",
"Windows path the Media Foundation frame-size attribute, and ",
"neither is implemented. This is ironmon not looking, not a camera ",
"that answered with nothing"
);
push_opt(
out,
format!("{base}.max_width"),
(c.max_width > 0).then(|| serde_json::json!(c.max_width)),
Some(Unit::Count),
NO_MODE_LIST,
);
push_opt(
out,
format!("{base}.max_height"),
(c.max_height > 0).then(|| serde_json::json!(c.max_height)),
Some(Unit::Count),
NO_MODE_LIST,
);
push_opt(
out,
format!("{base}.active"),
c.is_active.map(|a| serde_json::json!(a)),
None,
concat!(
"whether this camera is streaming was not established: only ",
"Linux probes the device node, and the Windows consent store ",
"attributes use to an application rather than to a device"
),
);
}
}
fn resolve_boot_duration(out: &mut Vec<Reading>) {
let boot_time = match crate::boot_config::BootMonitor::read_boot_time() {
Ok(t) => t,
Err(e) => {
out.push(Reading::unavailable(
"system.boot.duration",
Some(Unit::Seconds),
format!("the boot timing could not be read: {e}"),
));
return;
}
};
let secs = boot_time.total.as_secs_f64();
if secs > 0.0 {
out.push(Reading::measured(
"system.boot.duration",
serde_json::json!(secs),
Some(Unit::Seconds),
));
return;
}
#[cfg(target_os = "windows")]
let reason = concat!(
"Windows records a boot duration only in ",
"Microsoft-Windows-Diagnostics-Performance/Operational event 100, which ",
"is not readable without Administrator — this is a privilege ",
"boundary, not a missing reader",
);
#[cfg(target_os = "linux")]
let reason = concat!(
"`systemd-analyze` reported no total, which is what a machine without ",
"systemd or with an incomplete boot transaction looks like",
);
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
let reason = "this platform publishes no boot duration IronMonitor knows how to read";
out.push(Reading::unavailable(
"system.boot.duration",
Some(Unit::Seconds),
reason,
));
}
fn resolve_secure_boot(out: &mut Vec<Reading>) {
#[cfg(target_os = "windows")]
{
match crate::platform::windows::secure_boot_enabled() {
Some(on) => {
out.push(Reading::measured(
"system.boot.secure_boot",
serde_json::json!(on),
None,
));
}
None => {
out.push(Reading::unavailable(
"system.boot.secure_boot",
None,
"the SecureBoot state key is absent, which is what a BIOS/CSM \
machine looks like — it is not the same as Secure Boot being \
turned off",
));
}
}
}
#[cfg(not(target_os = "windows"))]
{
resolve_secure_boot_from_firmware(out);
}
}
#[cfg(not(target_os = "windows"))]
fn resolve_secure_boot_from_firmware(out: &mut Vec<Reading>) {
use crate::firmware::SecureBootStatus;
let status = match crate::firmware::FirmwareInventory::read_secure_boot() {
Ok(s) => s,
Err(e) => {
out.push(Reading::unavailable(
"system.boot.secure_boot",
None,
format!("the firmware inventory could not be read: {e}"),
));
return;
}
};
match status {
SecureBootStatus::Enabled => out.push(Reading::measured(
"system.boot.secure_boot",
serde_json::json!(true),
None,
)),
SecureBootStatus::Disabled => out.push(Reading::measured(
"system.boot.secure_boot",
serde_json::json!(false),
None,
)),
SecureBootStatus::NotSupported => out.push(Reading::unavailable(
"system.boot.secure_boot",
None,
"this firmware does not implement Secure Boot, which is not the same \
as having it disabled",
)),
SecureBootStatus::Unknown => out.push(Reading::unavailable(
"system.boot.secure_boot",
None,
"the firmware flag was not readable here",
)),
}
}
fn resolve_kernel_params(out: &mut Vec<Reading>) {
let monitor = match crate::kernel_params::KernelParamsMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"system.kernel_param.<none>",
None,
format!("kernel parameters could not be read here: {e}"),
));
return;
}
};
let params = &monitor.report().params;
if params.is_empty() {
out.push(Reading::unavailable(
"system.kernel_param.<none>",
None,
"no kernel parameter was readable here; on Windows the reader knows \
one setting and reports nothing when the query returns empty",
));
return;
}
for (i, p) in params.iter().enumerate() {
let base = format!("system.kernel_param.{i}");
push_id(out, format!("{base}.name"), &p.name);
push_id(out, format!("{base}.value"), &p.value);
push_id(
out,
format!("{base}.category"),
&format!("{:?}", p.category),
);
}
}
fn resolve_services(out: &mut Vec<Reading>) {
let monitor = match crate::services::ServiceMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"system.service.<none>",
None,
format!("the service manager could not be reached: {e}"),
));
return;
}
};
let services = monitor.services();
if services.is_empty() {
out.push(Reading::unavailable(
"system.service.<none>",
None,
"the service manager was reached and reported no services, which on \
a running machine means the enumeration is incomplete rather than \
that nothing is installed",
));
return;
}
let running = services.iter().filter(|s| s.is_active()).count();
let failed: Vec<&str> = services
.iter()
.filter(|s| s.is_failed())
.map(|s| s.name.as_str())
.collect();
for (id, n) in [
("system.service.count.total", services.len()),
("system.service.count.running", running),
("system.service.count.failed", failed.len()),
] {
out.push(Reading::measured(
id,
serde_json::json!(n),
Some(Unit::Count),
));
}
for (i, name) in failed.iter().enumerate() {
push_id(out, format!("system.service.failed.{i}"), name);
}
}
fn resolve_printers(out: &mut Vec<Reading>) {
let monitor = match crate::printer::PrinterMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"system.printer.<none>",
None,
format!("printers could not be enumerated here: {e}"),
));
return;
}
};
let printers = monitor.printers();
if printers.is_empty() {
out.push(Reading::unavailable(
"system.printer.<none>",
None,
"the spooler was reachable and holds no queue",
));
return;
}
for (i, p) in printers.iter().enumerate() {
let base = format!("system.printer.{i}");
push_text(out, format!("{base}.name"), &p.name);
push_text(out, format!("{base}.description"), &p.description);
push_id(
out,
format!("{base}.connection"),
&format!("{:?}", p.connection),
);
push_id(out, format!("{base}.status"), &format!("{:?}", p.status));
out.push(Reading::measured(
format!("{base}.default"),
serde_json::json!(p.is_default),
None,
));
push_opt(
out,
format!("{base}.accepting_jobs"),
p.accepting_jobs.map(|a| serde_json::json!(a)),
None,
concat!(
"whether the queue takes new work is reported by CUPS and has ",
"no equivalent in Win32_Printer; deriving it from the printer ",
"status is the one thing this field exists not to do"
),
);
push_opt(
out,
format!("{base}.color"),
p.color.map(|c| serde_json::json!(c)),
None,
concat!(
"the spooler listed no capabilities for this printer, so whether ",
"it prints in colour was not reported",
),
);
}
}
fn resolve_bluetooth(out: &mut Vec<Reading>) {
let monitor = match crate::bluetooth::BluetoothMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"network.bluetooth.<none>",
None,
format!("Bluetooth adapters could not be enumerated here: {e}"),
));
return;
}
};
let adapters = monitor.adapters();
if adapters.is_empty() {
out.push(Reading::unavailable(
"network.bluetooth.<none>",
None,
"Bluetooth enumeration succeeded and found no adapter",
));
return;
}
for (i, a) in adapters.iter().enumerate() {
let base = format!("network.bluetooth.{i}");
push_text(out, format!("{base}.name"), &a.name);
push_opt(
out,
format!("{base}.powered"),
a.powered.map(|p| serde_json::json!(p)),
None,
"the platform's adapter record carries no radio power state",
);
}
}
fn resolve_microarch(out: &mut Vec<Reading>) {
let monitor = match crate::cpu_microarch::CpuMicroarchMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"cpu.microarch.<none>",
None,
format!("the processor could not be identified here: {e}"),
));
return;
}
};
push_microarch(out, monitor.report());
}
fn push_microarch(out: &mut Vec<Reading>, report: &crate::cpu_microarch::CpuMicroarchReport) {
let uarch = &report.microarch;
push_spec_id(out, "cpu.microarch.name", &uarch.name);
push_spec_id(out, "cpu.microarch.codename", &uarch.codename);
push_spec_id(out, "cpu.microarch.vendor", &format!("{:?}", uarch.vendor));
push_spec_id(out, "cpu.microarch.isa", &uarch.arch);
push_spec_opt(
out,
"cpu.microarch.process",
(uarch.process_nm > 0).then(|| serde_json::json!(uarch.process_nm)),
Some(Unit::Count),
"IronMonitor holds no process node for this microarchitecture",
);
push_spec_opt(
out,
"cpu.microarch.year",
(uarch.year > 0).then(|| serde_json::json!(uarch.year)),
Some(Unit::Count),
"IronMonitor holds no introduction date for this microarchitecture",
);
out.push(Reading::spec(
"cpu.microarch.hybrid",
serde_json::json!(uarch.hybrid),
None,
));
let cpuid_read = report.family.is_some();
for (suffix, value) in [
("family", report.family),
("model", report.model),
("stepping", report.stepping),
] {
push_spec_opt(
out,
format!("cpu.microarch.{suffix}"),
cpuid_read
.then_some(value)
.flatten()
.map(|v| serde_json::json!(v)),
Some(Unit::Count),
"the CPUID family/model/stepping triple was not read on this platform",
);
}
for (suffix, value) in [
("physical_cores", report.physical_cores),
("logical_cores", report.logical_cores),
] {
push_spec_opt(
out,
format!("cpu.microarch.{suffix}"),
(value > 0).then(|| serde_json::json!(value)),
Some(Unit::Count),
"the platform's processor description did not include this count",
);
}
push_opt(
out,
"cpu.microarch.smt_enabled",
(report.physical_cores > 0 && report.logical_cores > 0)
.then(|| serde_json::json!(report.smt_enabled)),
None,
"SMT is judged by comparing logical to physical cores, and one of the two was not read",
);
let supported: Vec<_> = report.extensions.iter().filter(|x| x.supported).collect();
if supported.is_empty() {
out.push(Reading::unavailable(
"cpu.microarch.extension.<none>",
None,
"the processor was identified and reported no instruction set extensions, \
which means the extension probe failed rather than that the CPU has none",
));
return;
}
for (i, x) in supported.iter().enumerate() {
let base = format!("cpu.microarch.extension.{i}");
push_spec_id(out, format!("{base}.name"), &x.name);
push_spec_id(
out,
format!("{base}.category"),
&format!("{:?}", x.category),
);
push_spec_text(out, format!("{base}.description"), &x.description);
}
}
fn resolve_crypto(out: &mut Vec<Reading>) {
let monitor = match crate::crypto_accel::CryptoAccelMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"cpu.crypto.<none>",
None,
format!("hardware crypto support could not be determined here: {e}"),
));
return;
}
};
let report = monitor.report();
let accelerated: Vec<_> = report
.features
.iter()
.filter(|f| f.hardware_accelerated)
.collect();
if accelerated.is_empty() {
out.push(Reading::unavailable(
"cpu.crypto.<none>",
None,
"the processor reports no hardware-accelerated cryptographic primitive",
));
}
for (i, f) in accelerated.iter().enumerate() {
let base = format!("cpu.crypto.feature.{i}");
push_spec_id(out, format!("{base}.name"), &f.name);
push_spec_id(out, format!("{base}.flag"), &f.cpu_flag);
push_spec_id(
out,
format!("{base}.category"),
&format!("{:?}", f.category),
);
match f.estimated_throughput_gbs {
Some(gbs) => out.push(Reading::derived(
format!("{base}.throughput"),
serde_json::json!(gbs * 1_000_000_000.0),
Some(Unit::BytesPerSecond),
)),
None => out.push(Reading::unavailable(
format!("{base}.throughput"),
Some(Unit::BytesPerSecond),
"IronMonitor holds no throughput estimate for this primitive",
)),
}
}
let sources: Vec<_> = report.rng_sources.iter().filter(|r| r.available).collect();
if sources.is_empty() {
let instruction_present = accelerated.iter().any(|f| {
matches!(
f.category,
crate::crypto_accel::CryptoCategory::RandomNumberGen
)
});
out.push(Reading::unavailable(
"cpu.crypto.rng.<none>",
None,
if instruction_present {
"the hardware random source probe enumerated nothing, but the feature \
list above reports a random number instruction - this is a gap in the \
probe on this platform rather than a machine without an RNG"
} else {
"no hardware random source was found, and no random number instruction \
was reported either"
},
));
return;
}
for (i, r) in sources.iter().enumerate() {
let base = format!("cpu.crypto.rng.{i}");
push_spec_id(out, format!("{base}.name"), &r.name);
push_spec_id(
out,
format!("{base}.source"),
&format!("{:?}", r.source_type),
);
push_spec_opt(
out,
format!("{base}.quality"),
r.quality.map(|q| serde_json::json!(q)),
Some(Unit::Count),
"this source declares no entropy figure, and assuming one would be worse \
than saying nothing",
);
}
}
fn resolve_memory_bandwidth(out: &mut Vec<Reading>) {
let monitor = match crate::memory_bandwidth::MemoryBandwidthMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"memory.bandwidth.<none>",
None,
format!(
"the memory configuration needed for an estimate is not readable here: {e}"
),
));
return;
}
};
let est = monitor.estimate();
push_spec_id(
out,
"memory.bandwidth.generation",
&format!("{:?}", est.generation),
);
let unidentified = est.generation == crate::memory_bandwidth::MemoryGeneration::Unknown;
const NO_GENERATION: &str = "the memory generation was not identified, so the transfer \
rate and every bandwidth figure below it would be a built-in \
default rather than a property of this machine";
if unidentified {
for id in [
"memory.bandwidth.speed",
"memory.bandwidth.peak",
"memory.bandwidth.achievable",
"memory.bandwidth.stream_triad",
] {
let unit = if id == "memory.bandwidth.speed" {
Unit::Count
} else {
Unit::BytesPerSecond
};
out.push(Reading::unavailable(id, Some(unit), NO_GENERATION));
}
out.push(Reading::spec(
"memory.bandwidth.channels",
serde_json::json!(est.channels.active_channels),
Some(Unit::Count),
));
out.push(Reading::spec(
"memory.bandwidth.max_channels",
serde_json::json!(est.channels.max_channels),
Some(Unit::Count),
));
return;
}
let (Some(speed), Some(peak), Some(achievable), Some(triad)) = (
est.speed_mts,
est.peak_bandwidth_gbs,
est.achievable_bandwidth_gbs,
est.stream_triad_estimate_gbs,
) else {
const NO_SPEED: &str = concat!(
"no DIMM reported a transfer rate, so the speed and every bandwidth ",
"figure derived from it would be a built-in default"
);
out.push(Reading::unavailable(
"memory.bandwidth.speed",
Some(Unit::Count),
NO_SPEED,
));
for id in [
"memory.bandwidth.peak",
"memory.bandwidth.achievable",
"memory.bandwidth.stream_triad",
] {
out.push(Reading::unavailable(
id,
Some(Unit::BytesPerSecond),
NO_SPEED,
));
}
out.push(Reading::spec(
"memory.bandwidth.channels",
serde_json::json!(est.channels.active_channels),
Some(Unit::Count),
));
out.push(Reading::spec(
"memory.bandwidth.max_channels",
serde_json::json!(est.channels.max_channels),
Some(Unit::Count),
));
return;
};
out.push(Reading::spec(
"memory.bandwidth.speed",
serde_json::json!(speed),
Some(Unit::Count),
));
out.push(Reading::spec(
"memory.bandwidth.channels",
serde_json::json!(est.channels.active_channels),
Some(Unit::Count),
));
out.push(Reading::spec(
"memory.bandwidth.max_channels",
serde_json::json!(est.channels.max_channels),
Some(Unit::Count),
));
const GB: f64 = 1_000_000_000.0;
out.push(Reading::derived(
"memory.bandwidth.peak",
serde_json::json!(peak * GB),
Some(Unit::BytesPerSecond),
));
out.push(Reading::derived(
"memory.bandwidth.achievable",
serde_json::json!(achievable * GB),
Some(Unit::BytesPerSecond),
));
out.push(Reading::derived(
"memory.bandwidth.stream_triad",
serde_json::json!(triad * GB),
Some(Unit::BytesPerSecond),
));
}
fn push_spec_opt(
out: &mut Vec<Reading>,
id: impl Into<String>,
value: Option<serde_json::Value>,
unit: Option<Unit>,
why_absent: &str,
) {
match value {
Some(v) if v.as_str().is_some_and(names_an_absence) => {
out.push(Reading::unavailable(
id,
unit,
format!("reader returned {v}, which names an absence rather than a value"),
));
}
Some(v) => out.push(Reading::spec(id, v, unit)),
None => out.push(Reading::unavailable(id, unit, why_absent)),
}
}
fn resolve_rapl(out: &mut Vec<Reading>) {
let mut monitor = match crate::rapl::RaplMonitor::new() {
Ok(m) => m,
Err(e) => {
out.push(Reading::unavailable(
"power.rapl.<none>",
None,
format!("RAPL is not readable here: {e}"),
));
return;
}
};
if let Err(e) = monitor.refresh() {
out.push(Reading::unavailable(
"power.rapl.<none>",
None,
format!("RAPL is not readable here: {e}"),
));
return;
}
let readings = monitor.readings();
if readings.is_empty() {
out.push(Reading::unavailable(
"power.rapl.<none>",
None,
"the RAPL interface is present and enumerated no energy domains",
));
return;
}
for (i, r) in readings.iter().enumerate() {
let base = format!("power.rapl.{i}");
push_text(out, format!("{base}.name"), &r.name);
out.push(Reading::measured(
format!("{base}.energy"),
serde_json::json!(r.energy_uj),
Some(Unit::Count),
));
push_opt(
out,
format!("{base}.max_energy_range"),
r.max_energy_range_uj.map(|v| serde_json::json!(v)),
Some(Unit::Count),
"the domain's max_energy_range_uj attribute could not be read",
);
push_opt(
out,
format!("{base}.power_limit"),
r.power_limit_uw
.map(|uw| serde_json::json!(uw as f64 / 1_000_000.0)),
Some(Unit::Watts),
"this RAPL domain publishes no power constraint",
);
out.push(Reading::measured(
format!("{base}.enabled"),
serde_json::json!(r.enabled),
None,
));
}
}
fn resolve_power(out: &mut Vec<Reading>) {
match crate::battery::BatteryMonitor::new() {
Ok(monitor) => {
let batteries = monitor.batteries();
if batteries.is_empty() {
out.push(Reading::unavailable(
"power.battery.percentage",
Some(Unit::Percent),
"no battery present (desktop or always-AC machine)",
));
} else {
push_opt(
out,
"power.battery.percentage".to_string(),
batteries[0].charge_percent.map(|p| serde_json::json!(p)),
Some(Unit::Percent),
"a battery is present but its charge gauge could not be read",
);
}
}
Err(e) => out.push(Reading::unavailable(
"power.battery.percentage",
Some(Unit::Percent),
format!("battery monitor unavailable: {e}"),
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unread_core_counts_are_not_zero_cores_and_do_not_decide_smt() {
use crate::cpu_microarch::{CpuMicroarchMonitor, CpuVendor};
let mut report = CpuMicroarchMonitor::default().report().clone();
report.microarch.vendor = CpuVendor::Unknown;
report.physical_cores = 0;
report.logical_cores = 16;
report.smt_enabled = false;
let mut out = Vec::new();
push_microarch(&mut out, &report);
let get = |id: &str| out.iter().find(|r| r.id == id).cloned().expect(id);
let physical = get("cpu.microarch.physical_cores");
assert_eq!(physical.provenance, Provenance::Unavailable);
assert!(physical.value.is_none());
let logical = get("cpu.microarch.logical_cores");
assert_eq!(logical.value, Some(serde_json::json!(16)));
let smt = get("cpu.microarch.smt_enabled");
assert_eq!(
smt.provenance,
Provenance::Unavailable,
"SMT was decided from an unread count"
);
}
#[test]
fn unavailable_readings_carry_no_value_and_state_a_reason() {
for r in snapshot() {
if r.provenance == Provenance::Unavailable {
assert!(
r.value.is_none(),
"{} is unavailable but carries a value: {:?}",
r.id,
r.value
);
assert!(
r.note.as_ref().is_some_and(|n| !n.trim().is_empty()),
"{} is unavailable with no reason given",
r.id
);
} else {
assert!(
r.value.is_some(),
"{} claims provenance {:?} but has no value",
r.id,
r.provenance
);
}
}
}
#[test]
fn only_measured_readings_count_as_observations() {
for r in snapshot() {
let expected = r.provenance == Provenance::Measured && r.value.is_some();
assert_eq!(r.is_observation(), expected, "{}", r.id);
}
}
#[test]
fn every_reading_maps_to_a_declared_entity() {
let ontology = Ontology::build();
for r in snapshot() {
assert!(
lookup_template(&ontology, &r.id).is_some(),
"{} was resolved but is not declared in the ontology",
r.id
);
assert!(
!Ontology::is_template(&r.id),
"{} is a template, not a concrete reading",
r.id
);
}
}
#[test]
fn live_readings_are_physically_possible() {
let problems = validate(&snapshot());
assert!(problems.is_empty(), "impossible readings: {problems:#?}");
}
#[test]
fn out_of_range_values_are_withheld_with_the_offending_value_named() {
use crate::ontology::{Domain, EntityKind};
let ontology = Ontology::build();
let entity = ontology.get("cpu.total.utilization").unwrap();
assert_eq!(entity.domain, Domain::Cpu);
assert_eq!(entity.kind, EntityKind::Measurement);
let problem = entity
.validate_range(103.0)
.expect("103 percent should be rejected");
assert!(
problem.contains("103"),
"the rejection must name the offending value so it can be diagnosed, \
got: {problem}"
);
assert!(entity.validate_range(99.9).is_none());
}
#[test]
fn every_id_is_shell_safe_and_well_structured() {
for r in snapshot() {
assert!(
!r.id.contains(char::is_whitespace),
"{} contains whitespace, so it cannot be passed as a bare argument",
r.id
);
assert!(
!r.id.contains("..") && !r.id.starts_with('.') && !r.id.ends_with('.'),
"malformed id: {}",
r.id
);
for segment in r.id.split('.') {
assert!(!segment.is_empty(), "{} has an empty path segment", r.id);
}
}
}
#[test]
fn id_segments_are_sanitised_without_collapsing_distinct_names() {
assert_eq!(
id_segment("Bluetooth Network Connection"),
"Bluetooth_Network_Connection"
);
assert_eq!(id_segment("eth0.100"), "eth0_100");
assert_eq!(id_segment(" spaced "), "spaced");
assert_eq!(id_segment("///"), "unnamed");
assert_ne!(id_segment("eth0"), id_segment("eth1"));
}
#[test]
fn diagnostics_do_not_contradict_the_readings_beside_them() {
let readings = snapshot();
for domain in crate::ontology::Domain::ALL {
let none_id = format!("{}.<none>", domain.as_str());
let has_none = readings.iter().any(|r| r.id == none_id);
if !has_none {
continue;
}
let real_rows: Vec<&str> = readings
.iter()
.filter(|r| {
r.id.starts_with(&format!("{}.", domain.as_str()))
&& !r.id.contains('<')
&& r.is_observation()
})
.map(|r| r.id.as_str())
.collect();
assert!(
real_rows.is_empty(),
"{none_id} claims the domain enumerated nothing, but these {} rows are present alongside it: {real_rows:?}",
real_rows.len(),
);
}
}
#[test]
fn no_declared_domain_is_silently_absent() {
let readings = snapshot();
for domain in crate::ontology::Domain::ALL {
let prefix = format!("{}.", domain.as_str());
assert!(
readings.iter().any(|r| r.id.starts_with(&prefix)),
"domain {} produced no rows at all — an agent cannot distinguish an \
absent device from an unimplemented reader",
domain.as_str()
);
}
}
#[test]
fn ids_are_unique_within_a_snapshot() {
let readings = snapshot();
let mut seen = std::collections::HashSet::new();
for r in &readings {
assert!(seen.insert(r.id.clone()), "duplicate reading id: {}", r.id);
}
}
#[test]
fn get_rejects_templates_and_finds_concrete_ids() {
assert!(
get("gpu.{n}.name").is_none(),
"a template is not a question with an answer"
);
assert!(get("memory.total").is_some());
assert!(get("no.such.entity").is_none());
}
#[test]
fn coverage_accounts_for_every_reading() {
let readings = snapshot();
let c = coverage_of(&readings);
assert_eq!(c.total, c.resolved + c.unavailable);
assert_eq!(c.total, readings.len());
}
}