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 {
pub(super) 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,
}
}
pub(super) 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,
}
}
pub(super) 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,
}
}
pub(super) 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()
}
}
#[derive(Debug, Clone)]
pub(super) struct Scope {
segments: Option<std::collections::BTreeSet<String>>,
}
impl Scope {
fn all() -> Self {
Self { segments: None }
}
fn of(segments: std::collections::BTreeSet<String>) -> Self {
Self {
segments: Some(segments),
}
}
pub(super) fn contains(&self, segment: &str) -> bool {
match &self.segments {
None => true,
Some(segments) => segments.contains(segment),
}
}
pub(super) fn wants(&self, emits: &[&str]) -> bool {
emits.iter().any(|segment| self.contains(segment))
}
}
fn run_readers(out: &mut Vec<Reading>, scope: &Scope) {
run(scope, &["cpu"], out, resolve_cpu);
run(scope, &["memory"], out, resolve_memory);
run(scope, &["system"], out, resolve_system);
run(scope, &["board"], out, resolve_board);
run(scope, &["gpu"], out, resolve_gpu);
run(scope, &["disk"], out, resolve_disk);
run(scope, &["network"], out, resolve_network);
run(scope, &["process"], out, resolve_process);
run(scope, &["thermal"], out, resolve_thermal);
run(scope, &["power"], out, resolve_power);
run(scope, &["power"], out, resolve_rapl);
run(scope, &["board"], out, resolve_sensors);
run(scope, &["board"], out, resolve_displays);
run(scope, &["system"], out, resolve_virtualization);
run(scope, &["memory"], out, resolve_numa);
run(scope, &["memory"], out, resolve_ecc);
run(scope, &["pci"], out, resolve_pci);
run(scope, &["usb"], out, resolve_usb);
run(scope, &["memory"], out, resolve_memory_bandwidth);
run(scope, &["cpu"], out, resolve_microarch);
run(scope, &["cpu"], out, resolve_crypto);
run(scope, &["board"], out, resolve_input);
run(scope, &["board"], out, resolve_audio);
run(scope, &["board"], out, resolve_cameras);
run(scope, &["system"], out, resolve_printers);
run(scope, &["system"], out, resolve_services);
run(scope, &["system"], out, resolve_kernel_params);
run(scope, &["system"], out, resolve_secure_boot);
run(scope, &["system"], out, resolve_boot_duration);
run(scope, &["network"], out, resolve_bluetooth);
run(scope, &["disk"], out, resolve_storage_controllers);
run(scope, &["power"], out, resolve_power_profiles);
run(scope, &["gpu"], out, resolve_codecs);
run(scope, &settings_segments(), out, resolve_settings);
super::extended::resolve(out, scope);
run(scope, &["inference"], out, resolve_inference);
run(scope, &["agents"], out, resolve_agents);
}
fn run(scope: &Scope, emits: &[&str], out: &mut Vec<Reading>, reader: fn(&mut Vec<Reading>)) {
if scope.wants(emits) {
reader(out);
}
}
pub fn snapshot() -> Vec<Reading> {
pipeline(&Ontology::build(), &Scope::all())
}
pub fn ontology() -> &'static Ontology {
static ONTOLOGY: std::sync::OnceLock<Ontology> = std::sync::OnceLock::new();
ONTOLOGY.get_or_init(Ontology::build)
}
pub fn snapshot_document(readings: &[Reading], problems: &[String]) -> serde_json::Value {
let resolved = readings.iter().filter(|r| r.value.is_some()).count();
serde_json::json!({
"ontology_version": super::ONTOLOGY_VERSION,
"resolved": resolved,
"unavailable": readings.len() - resolved,
"impossible": problems,
"readings": readings,
})
}
pub fn owning_segment(id: &str) -> Option<String> {
if Ontology::is_template(id) {
return None;
}
ontology().template_for(id)?;
Some(first_segment(id).to_string())
}
pub fn sample_segment(segment: &str) -> Vec<Reading> {
let ontology = ontology();
let mut segments = std::collections::BTreeSet::new();
segments.insert(segment.to_string());
for entity in ontology
.entities
.values()
.filter(|e| first_segment(&e.id) == segment)
{
segments.extend(needed_segments(ontology, &entity.id, entity));
}
close_over_consumes(&mut segments);
pipeline(ontology, &Scope::of(segments))
.into_iter()
.filter(|r| first_segment(&r.id) == segment)
.collect()
}
fn pipeline(ontology: &Ontology, scope: &Scope) -> Vec<Reading> {
let _pass = crate::pipeline::reader_pass();
let mut out = Vec::new();
run_readers(&mut out, scope);
let mut unbound = unbound_rows(ontology, &out, scope);
out.append(&mut unbound);
let mut missing = missing_domain_rows(ontology, &out, scope);
out.append(&mut missing);
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
}
fn unbound_rows(ontology: &Ontology, out: &[Reading], scope: &Scope) -> Vec<Reading> {
let declined: Vec<(String, String)> = out
.iter()
.filter_map(|r| {
let prefix =
r.id.strip_suffix(".<none>")
.or_else(|| r.id.strip_suffix(".<unreadable>"))?;
Some((format!("{prefix}."), r.note.clone()?))
})
.collect();
let produced: std::collections::HashSet<&str> = out.iter().map(|r| r.id.as_str()).collect();
let unbound: Vec<Reading> = ontology
.entities
.values()
.filter(|e| {
scope.contains(first_segment(&e.id))
&& 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();
unbound
}
fn missing_domain_rows(ontology: &Ontology, out: &[Reading], scope: &Scope) -> Vec<Reading> {
let mut missing_domains: Vec<Reading> = Vec::new();
for domain in super::Domain::ALL {
if !scope.contains(domain.as_str()) {
continue;
}
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",
));
}
}
missing_domains
}
const CONSUMES: &[(&str, &str)] = &[("inference", "gpu")];
fn first_segment(id: &str) -> &str {
id.split('.').next().unwrap_or(id)
}
fn needed_segments(
ontology: &Ontology,
id: &str,
entity: &Entity,
) -> std::collections::BTreeSet<String> {
let mut segments = std::collections::BTreeSet::new();
segments.insert(first_segment(id).to_string());
let mut seen = std::collections::BTreeSet::new();
let mut pending = vec![entity];
while let Some(current) = pending.pop() {
if !seen.insert(current.id.as_str()) {
continue;
}
for input in ¤t.derived_from {
segments.insert(first_segment(input).to_string());
if let Some(next) = ontology.template_for(input) {
pending.push(next);
}
}
}
close_over_consumes(&mut segments);
segments
}
fn close_over_consumes(segments: &mut std::collections::BTreeSet<String>) {
loop {
let before = segments.len();
for (reader, read) in CONSUMES {
if segments.contains(*reader) {
segments.insert(read.to_string());
}
}
if segments.len() == before {
break;
}
}
}
pub fn get(id: &str) -> Option<Reading> {
if Ontology::is_template(id) {
return None;
}
let ontology = Ontology::build();
let entity = ontology.template_for(id)?;
let scope = Scope::of(needed_segments(&ontology, id, entity));
pipeline(&ontology, &scope).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().map(|m| m.report().physical_cores) {
Ok(Some(physical)) => out.push(Reading::measured(
"cpu.cores.physical",
serde_json::json!(physical),
Some(Unit::Count),
)),
Ok(None) => 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().and_then(|c| c.model.as_deref()) {
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);
match info.uptime_seconds {
Some(secs) => out.push(Reading::measured(
"system.uptime",
serde_json::json!(secs),
Some(Unit::Seconds),
)),
None => out.push(Reading::unavailable(
"system.uptime",
Some(Unit::Seconds),
"the platform's uptime source could not be read",
)),
}
}
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;
}
};
match inventory.system_vendor() {
Some(vendor) => push_text(out, "board.firmware.vendor", vendor),
None => out.push(Reading::unavailable(
"board.firmware.vendor",
Some(Unit::Text),
"the firmware did not report a system vendor",
)),
}
match inventory.system_product() {
Some(product) => push_text(out, "board.firmware.product", product),
None => out.push(Reading::unavailable(
"board.firmware.product",
Some(Unit::Text),
"the firmware did not report a product name",
)),
}
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(),
);
match &entry.version {
Some(version) => push_text(out, format!("board.firmware.{i}.version"), version),
None => out.push(Reading::unavailable(
format!("board.firmware.{i}.version"),
Some(Unit::Text),
"the firmware source did not report a 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 is_container = monitor.is_container();
let is_vm = monitor.is_virtual_machine();
match (is_container, is_vm) {
(Some(true), _) => push_id(out, "system.virtualization.platform", "container"),
(_, Some(true)) => push_id(out, "system.virtualization.platform", "virtual_machine"),
(Some(false), Some(false)) => push_id(out, "system.virtualization.platform", "bare_metal"),
(None, _) | (_, None) => {
let reason = if is_vm.is_none() {
"neither CPUID nor DMI could be read to tell whether this is a virtual machine"
} else {
"container detection is not implemented on this platform, so bare metal \
cannot be told apart from a container"
};
out.push(Reading::unavailable(
"system.virtualization.platform",
Some(Unit::Identifier),
reason,
));
}
}
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",
));
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);
push_opt(
out,
format!("{base}.cpus"),
node.cpus.as_ref().map(|c| serde_json::json!(c.len())),
Some(Unit::Count),
"this node's processor list was not read: this platform's reader does not map processors to NUMA nodes here, or the node's cpulist could not be read",
);
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;
}
match overview.ecc_active {
Some(active) => out.push(Reading::measured(
"memory.ecc.active",
serde_json::json!(active),
None,
)),
None => out.push(Reading::unavailable(
"memory.ecc.active",
None,
"no memory controller was read, so ECC state is unknown",
)),
}
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;
}
let mut unlocated = 0usize;
for dev in monitor.devices() {
let Some(address) = dev.address.as_deref() else {
unlocated += 1;
continue;
};
let base = format!("pci.{}", id_segment(address));
push_text(out, format!("{base}.vendor"), &dev.vendor_name);
push_text(out, format!("{base}.device"), &dev.device_name);
match &dev.class {
Some(class) => push_id(
out,
format!("{base}.class"),
&format!("{class:?}").to_lowercase(),
),
None => out.push(Reading::unavailable(
format!("{base}.class"),
Some(Unit::Identifier),
PCI_CLASS_UNREAD_WHY,
)),
}
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", Some(link.width.as_str())),
("link.max_width", link.max_width.as_deref()),
("link.speed", Some(link.speed.as_str())),
("link.max_speed", link.max_speed.as_deref()),
] {
push_opt(
out,
format!("{base}.{suffix}"),
value
.filter(|v| !v.trim().is_empty())
.map(|v| serde_json::json!(v)),
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.map(|n| serde_json::json!(n)),
Some(Unit::Count),
"the platform reports no NUMA affinity for this device",
);
}
if unlocated > 0 {
out.push(Reading::unavailable(
"pci.<unlocated>",
None,
format!(
concat!(
"{} PCI device(s) have no bus address recorded, so they have no ",
"pci.<address> key and are not listed; the platform recorded no bus ",
"location for them"
),
unlocated
),
));
}
}
const PCI_CLASS_UNREAD_WHY: &str = concat!(
"the PCI class was not read for this device. Linux reads it from the class file, ",
"Windows from the CC_ entry in the device's hardware IDs, and macOS does not expose ",
"a class register"
);
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,
value.and_then(kib),
Some(Unit::Bytes),
"no total for this level: the platform did not list every cache at it \
with a size (macOS publishes one representative size per level), or \
lists none, or publishes a combined L1 rather than separate data and \
instruction caches; 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"),
cache.size_kb.and_then(kib),
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 push_gpu_enumeration_failure(out: &mut Vec<Reading>, e: &crate::IronError) {
if let crate::IronError::GpuDetectionFailed(failures) = e {
push_backend_failures(out, failures);
}
out.push(Reading::unavailable(
"gpu.<unreadable>",
None,
format!("GPU enumeration failed: {e}"),
));
}
fn push_backend_failures(out: &mut Vec<Reading>, failures: &[(&'static str, String)]) {
let mut vendors: Vec<&'static str> = Vec::new();
for (vendor, _) in failures {
if !vendors.contains(vendor) {
vendors.push(vendor);
}
}
for vendor in vendors {
let reasons: Vec<&str> = failures
.iter()
.filter(|(v, _)| *v == vendor)
.map(|(_, e)| e.as_str())
.collect();
out.push(Reading::unavailable(
format!("gpu.backend.{vendor}.<unreadable>"),
None,
format!(
"the {vendor} GPU backend could not read its adapters, so any {vendor} GPU is not counted: {}",
reasons.join("; ")
),
));
}
}
fn resolve_gpu(out: &mut Vec<Reading>) {
let monitor = match crate::UnifiedMonitor::new() {
Ok(monitor) => monitor,
Err(e) => {
push_gpu_enumeration_failure(out, &e);
return;
}
};
let failures = monitor.gpus().detection_failures();
push_backend_failures(out, failures);
let gpus = monitor.gpus().snapshot_all_partial();
if gpus.is_empty() {
if failures.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) => {
if let Some(info) = monitor
.gpus()
.gpus()
.get(i)
.and_then(|device| device.static_info().ok())
{
push_text(out, format!("gpu.{i}.name"), &info.name);
push_id(
out,
format!("gpu.{i}.vendor"),
&format!("{:?}", info.vendor).to_lowercase(),
);
}
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())
}
pub(super) fn push_text(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
push_str_as(out, id, value, Unit::Text, Provenance::Measured);
}
pub(super) fn push_spec_text(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
push_str_as(out, id, value, Unit::Text, Provenance::Specification);
}
pub(super) fn push_id(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
push_str_as(out, id, value, Unit::Identifier, Provenance::Measured);
}
pub(super) fn push_spec_id(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
push_str_as(out, id, value, Unit::Identifier, Provenance::Specification);
}
pub(super) 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)),
});
}
pub(super) 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();
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 resolve_agents(out: &mut Vec<Reading>) {
use crate::agents::ironobs::{self, Cycle};
use crate::agents::report::{cycle_text, none_reason};
use crate::agents::KNOWN_PRODUCERS;
use crate::agents::{REMOTE_COST_POINTER, REMOTE_NOT_READ};
use serde_json::json;
let st = ironobs::AgentsState::query();
let scan = st.scan_or_empty();
let dir = st.recordings_dir.display().to_string();
push_text(out, "agents.recordings.dir", &dir);
let reason = none_reason(&scan);
let recordings = scan.recordings();
let whole = scan.is_complete() && recordings > 0;
let counted = |n: usize| whole.then(|| json!(n));
if !scan.dir_exists || scan.files == 0 {
out.push(Reading::unavailable(
"agents.recordings.<none>",
None,
reason.clone(),
));
}
push_opt(
out,
"agents.recordings.files",
scan.dir_exists.then(|| json!(scan.files)),
Some(Unit::Count),
"the recordings directory does not exist",
);
push_opt(
out,
"agents.recordings.rejected",
scan.dir_exists
.then(|| json!(scan.refused_count() + scan.corrupt_files)),
Some(Unit::Count),
"the recordings directory does not exist",
);
if scan.files_truncated > 0 {
out.push(Reading::unavailable(
"agents.recordings.<truncated>",
None,
format!(
"read {} of {} recording file(s) within the read bound; {} were not read",
scan.files,
scan.files + scan.files_truncated,
scan.files_truncated
),
));
}
match &st.ironobs {
Some(bin) if bin.probed => push_opt(
out,
"agents.ironobs.version",
bin.version.clone().map(|v| json!(v)),
Some(Unit::Text),
"ironobs is installed but printed no usable version",
),
Some(_) => out.push(Reading::unavailable(
"agents.ironobs.version",
Some(Unit::Text),
"ironobs is installed; the background reader probes it, and a one-shot read does not",
)),
None => {
out.push(Reading::unavailable(
"agents.ironobs.<none>",
None,
ironobs::NOT_INSTALLED,
));
out.push(Reading::unavailable(
"agents.ironobs.version",
Some(Unit::Text),
"ironobs is not on PATH",
));
}
}
match &st.cycle {
Cycle::Blocked(why) => out.push(Reading::unavailable(
"agents.import.state",
Some(Unit::Text),
why.clone(),
)),
_ => push_text(
out,
"agents.import.state",
&cycle_text(&st, chrono::Utc::now()),
),
}
for imp in &st.imports {
let id = format!("agents.import.{}.state", imp.importer.key());
if !imp.source_exists {
out.push(Reading::unavailable(
id,
Some(Unit::Text),
format!(
"not run: no `{}` folder to import",
imp.importer.source_folder()
),
));
continue;
}
let last = match &imp.last {
Some(l) => format!("last import at {}: {}", l.at.to_rfc3339(), l.text),
None => "no import has finished".to_string(),
};
let selection = match (imp.watermark, imp.first_since) {
(Some(w), _) => format!(
"sessions modified since {} are selected; sessions not written in the 7 days before the first import are not imported",
w.to_rfc3339()
),
(None, Some(t)) => format!(
"sessions not written in the 7 days before the first import (from {}) are not imported",
t.to_rfc3339()
),
(None, None) => "the first import selects sessions written in the 7 days before it runs; older sessions are not imported".to_string(),
};
push_text(out, id, &format!("{last}; {selection}"));
}
push_opt(
out,
"agents.import.last_written",
scan.newest_written.map(|t| json!(t.to_rfc3339())),
Some(Unit::Text),
"no recording file has been written yet",
);
push_opt(
out,
"agents.sessions.count",
counted(scan.sessions_count()),
Some(Unit::Count),
reason.as_str(),
);
push_opt(
out,
"agents.sessions.active",
counted(scan.active_count()),
Some(Unit::Count),
reason.as_str(),
);
push_opt(
out,
"agents.sessions.in_progress_unevidenced",
counted(scan.unevidenced_count()),
Some(Unit::Count),
reason.as_str(),
);
push_opt(
out,
"agents.sessions.subagents",
counted(scan.subagent_count()),
Some(Unit::Count),
reason.as_str(),
);
push_opt(
out,
"agents.workflows.count",
counted(scan.workflow_count()),
Some(Unit::Count),
reason.as_str(),
);
let tokens_why = if whole {
"no recording reports token usage"
} else {
reason.as_str()
};
push_opt(
out,
"agents.sessions.input_tokens",
whole
.then(|| scan.input_tokens().map(|v| json!(v)))
.flatten(),
Some(Unit::Count),
tokens_why,
);
push_opt(
out,
"agents.sessions.output_tokens",
whole
.then(|| scan.output_tokens().map(|v| json!(v)))
.flatten(),
Some(Unit::Count),
tokens_why,
);
for p in KNOWN_PRODUCERS {
let id = format!("agents.producer.{}.sessions", p.key);
if let Some(why) = p.not_read {
out.push(Reading::unavailable(id, Some(Unit::Count), why));
continue;
}
let n = scan.producer_count(p.key);
let why = if whole {
format!("no {} recordings were read", p.label)
} else {
reason.clone()
};
push_opt(
out,
id,
counted(n).filter(|_| n > 0),
Some(Unit::Count),
&why,
);
}
if whole {
for key in scan.producers() {
if KNOWN_PRODUCERS.iter().any(|p| p.key == key) {
continue;
}
let n = scan.producer_count(&key);
out.push(Reading::measured(
format!("agents.producer.{key}.sessions"),
json!(n),
Some(Unit::Count),
));
}
}
out.push(Reading::unavailable(
"agents.remote.<none>",
None,
format!("not read: {REMOTE_NOT_READ}; {REMOTE_COST_POINTER}"),
));
let not_polled = "the engine's request figures come from the Inference tab's poller, which a one-shot read does not run";
out.push(Reading::unavailable(
"agents.engine.requests.active",
Some(Unit::Count),
not_polled,
));
out.push(Reading::unavailable(
"agents.engine.requests.recent",
Some(Unit::Count),
not_polled,
));
}
const INFERENCE_SNAPSHOT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(300);
const COUNTER_ABSENT: &str = "the engine does not report this counter";
const FIGURE_ABSENT: &str = "the engine does not report this figure";
const RATE_NEEDS_TWO: &str = "a rate needs two samples; this query took one";
const RATIO_NEEDS_TWO: &str =
"a hit ratio is taken over the window between two samples; this query took one";
fn resolve_inference(out: &mut Vec<Reading>) {
resolve_ironworks(out, &crate::inference::ironworks::endpoint_from_env());
resolve_local_inference(out);
resolve_remote_inference(out);
}
fn resolve_remote_inference(out: &mut Vec<Reading>) {
use crate::inference::ProviderKind;
const WHERE: &str = "read only by the background poller of the TUI and GUI, once configured; snapshot and get do not request remote providers";
for kind in [ProviderKind::OpenAi, ProviderKind::Anthropic] {
let p = kind.as_str();
out.push(Reading::unavailable(
format!("inference.{p}.<none>"),
None,
WHERE,
));
out.push(Reading::unavailable(
format!("inference.{p}.models_listed"),
Some(Unit::Count),
WHERE,
));
out.push(Reading::unavailable(
format!("inference.{p}.cost.currency"),
Some(Unit::Text),
WHERE,
));
out.push(Reading::unavailable(
format!("inference.{p}.cost.period_start"),
Some(Unit::Text),
WHERE,
));
out.push(Reading::unavailable(
format!("inference.{p}.cost.period_end"),
Some(Unit::Text),
WHERE,
));
}
out.push(Reading::unavailable(
"inference.openai.cost.month_to_date",
Some(Unit::Amount),
WHERE,
));
out.push(Reading::unavailable(
"inference.anthropic.cost.month_to_date_cents",
Some(Unit::Amount),
WHERE,
));
}
fn resolve_local_inference(out: &mut Vec<Reading>) {
use crate::inference::local::{all_from_env, reason};
use crate::inference::{ProviderKind, ProviderSample, SourceError};
let sources = all_from_env();
let results: Vec<(ProviderKind, String, Result<ProviderSample, SourceError>)> =
std::thread::scope(|scope| {
let handles: Vec<_> = sources
.iter()
.map(|source| {
scope.spawn(move || {
let read = source.poll(INFERENCE_SNAPSHOT_TIMEOUT);
(source.kind(), source.endpoint(), read)
})
})
.collect();
handles
.into_iter()
.filter_map(|handle| handle.join().ok())
.collect()
});
for (kind, endpoint, read) in results {
match read {
Ok(sample) => push_local_sample(out, kind, &sample),
Err(error) => out.push(Reading::unavailable(
format!("inference.{}.<none>", kind.as_str()),
None,
reason(kind, &endpoint, &error),
)),
}
}
}
fn push_local_sample(
out: &mut Vec<Reading>,
kind: crate::inference::ProviderKind,
sample: &crate::inference::ProviderSample,
) {
use crate::inference::ProviderKind as K;
use serde_json::json;
let counter = |name: &str| sample.counters.get(name).map(|v| json!(v));
let gauge_count = |name: &str| sample.gauges.get(name).map(|v| json!(*v as u64));
let text = |v: &Option<String>| v.as_ref().map(|s| json!(s));
const NOT_REPORTED: &str = "the server does not report this value";
const NOTHING_LOADED: &str = "the server reports no model loaded";
match kind {
K::Ollama => {
push_opt(
out,
"inference.ollama.version",
text(&sample.identity.version),
Some(Unit::Text),
NOT_REPORTED,
);
push_opt(
out,
"inference.ollama.model",
text(&sample.identity.model),
Some(Unit::Text),
NOTHING_LOADED,
);
push_opt(
out,
"inference.ollama.models_loaded",
gauge_count("models_loaded"),
Some(Unit::Count),
NOT_REPORTED,
);
}
K::LmStudio => {
push_opt(
out,
"inference.lmstudio.model",
text(&sample.identity.model),
Some(Unit::Text),
NOTHING_LOADED,
);
push_opt(
out,
"inference.lmstudio.models_loaded",
gauge_count("models_loaded"),
Some(Unit::Count),
NOT_REPORTED,
);
}
K::MlxLm => {
push_opt(
out,
"inference.mlx.health",
text(&sample.identity.status),
Some(Unit::Text),
NOT_REPORTED,
);
}
K::LlamaCpp => {
push_opt(
out,
"inference.llamacpp.prompt_tokens_total",
counter("prompt_tokens_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.llamacpp.predicted_tokens_total",
counter("tokens_predicted_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.llamacpp.decodes_total",
counter("n_decode_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.llamacpp.requests_processing",
gauge_count("requests_processing"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.llamacpp.requests_deferred",
gauge_count("requests_deferred"),
Some(Unit::Count),
NOT_REPORTED,
);
out.push(Reading::unavailable(
"inference.llamacpp.prompt_tok_s",
Some(Unit::TokensPerSecond),
RATE_NEEDS_TWO,
));
out.push(Reading::unavailable(
"inference.llamacpp.predicted_tok_s",
Some(Unit::TokensPerSecond),
RATE_NEEDS_TWO,
));
}
K::Vllm => {
push_opt(
out,
"inference.vllm.model",
text(&sample.identity.model),
Some(Unit::Text),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.generation_tokens_total",
counter("generation_tokens_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.prompt_tokens_total",
counter("prompt_tokens_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.request_success_total",
counter("request_success_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.num_preemptions_total",
counter("num_preemptions_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.prefix_cache_hits_total",
counter("prefix_cache_hits_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.prefix_cache_queries_total",
counter("prefix_cache_queries_total"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.requests_running",
gauge_count("num_requests_running"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.requests_waiting",
gauge_count("num_requests_waiting"),
Some(Unit::Count),
NOT_REPORTED,
);
push_opt(
out,
"inference.vllm.kv_cache_usage",
sample
.gauges
.get("kv_cache_usage_perc")
.map(|f| json!(f * 100.0)),
Some(Unit::Percent),
NOT_REPORTED,
);
out.push(Reading::unavailable(
"inference.vllm.prefix_cache_hit_ratio",
Some(Unit::Percent),
RATIO_NEEDS_TWO,
));
out.push(Reading::unavailable(
"inference.vllm.generation_tok_s",
Some(Unit::TokensPerSecond),
RATE_NEEDS_TWO,
));
out.push(Reading::unavailable(
"inference.vllm.prompt_tok_s",
Some(Unit::TokensPerSecond),
RATE_NEEDS_TWO,
));
}
K::IronWorks | K::OpenAi | K::Anthropic => {}
}
}
fn resolve_ironworks(out: &mut Vec<Reading>, base: &str) {
use crate::inference::ironworks::{fetch, metrics_url, Tier};
use serde_json::json;
let url = metrics_url(base);
let sample = match fetch(base, INFERENCE_SNAPSHOT_TIMEOUT) {
Ok(metrics) => metrics.into_sample(),
Err(e) => {
out.push(Reading::unavailable(
"inference.ironworks.<none>",
None,
match &e {
crate::inference::SourceError::Unreachable(why) => {
format!("no IronWorks engine answered at {url}: {why}")
}
other => other.summary(&url),
},
));
return;
}
};
let Some(section) = sample.ironworks.as_ref() else {
out.push(Reading::unavailable(
"inference.ironworks.<none>",
None,
"the metrics body carried no IronWorks section, so nothing from it is reported",
));
return;
};
let id = &sample.identity;
push_opt(
out,
"inference.ironworks.engine.model",
id.model.clone().map(|v| json!(v)),
Some(Unit::Text),
"the engine does not report the model it is serving",
);
push_opt(
out,
"inference.ironworks.engine.backend",
id.backend.clone().map(|v| json!(v)),
Some(Unit::Text),
"the engine does not report its compute backend",
);
push_counter(out, &sample, "requests.total", Unit::Count);
push_opt(
out,
"inference.ironworks.requests.active",
section.requests_active.map(|v| json!(v)),
Some(Unit::Count),
FIGURE_ABSENT,
);
push_counter(out, &sample, "decode.prompt_tokens_total", Unit::Count);
push_counter(out, &sample, "decode.completion_tokens_total", Unit::Count);
out.push(Reading::unavailable(
"inference.ironworks.decode.prompt_tok_s",
Some(Unit::TokensPerSecond),
RATE_NEEDS_TWO,
));
out.push(Reading::unavailable(
"inference.ironworks.decode.completion_tok_s",
Some(Unit::TokensPerSecond),
RATE_NEEDS_TWO,
));
match §ion.vram {
None => out.push(Reading::unavailable(
"inference.ironworks.tier.vram.<none>",
None,
"the engine's metrics carry no VRAM tier object",
)),
Some(Tier::NotConfigured { reason }) => out.push(Reading::unavailable(
"inference.ironworks.tier.vram.<none>",
None,
not_configured("the VRAM expert cache", reason),
)),
Some(Tier::Configured(v)) => {
push_opt(
out,
"inference.ironworks.tier.vram.policy",
v.policy.clone().map(|p| json!(p)),
Some(Unit::Text),
"the engine does not report its VRAM eviction policy",
);
push_opt(
out,
"inference.ironworks.tier.vram.experts_resident",
v.experts_resident.map(|x| json!(x)),
Some(Unit::Count),
FIGURE_ABSENT,
);
push_opt(
out,
"inference.ironworks.tier.vram.capacity_experts",
v.capacity_experts.map(|x| json!(x)),
Some(Unit::Count),
FIGURE_ABSENT,
);
push_opt(
out,
"inference.ironworks.tier.vram.bytes_resident",
v.bytes_resident.map(|x| json!(x)),
Some(Unit::Bytes),
FIGURE_ABSENT,
);
for key in [
"tier.vram.hits_total",
"tier.vram.fills_total",
"tier.vram.bypass_total",
"tier.vram.not_admitted_total",
"tier.vram.evictions_total",
"tier.vram.warm_total",
"tier.vram.fills_aborted_total",
] {
push_counter(out, &sample, key, Unit::Count);
}
push_counter(out, &sample, "tier.vram.fill_bytes_total", Unit::Bytes);
out.push(Reading::unavailable(
"inference.ironworks.tier.vram.hit_ratio",
Some(Unit::Percent),
RATIO_NEEDS_TWO,
));
}
}
match §ion.ram {
None => out.push(Reading::unavailable(
"inference.ironworks.tier.ram.<none>",
None,
"the engine's metrics carry no host RAM tier object",
)),
Some(Tier::NotConfigured { reason }) => out.push(Reading::unavailable(
"inference.ironworks.tier.ram.<none>",
None,
not_configured("the host RAM expert cache", reason),
)),
Some(Tier::Configured(r)) => {
push_opt(
out,
"inference.ironworks.tier.ram.experts_resident",
r.experts_resident.map(|x| json!(x)),
Some(Unit::Count),
FIGURE_ABSENT,
);
push_opt(
out,
"inference.ironworks.tier.ram.pinned_bytes",
r.pinned_bytes.map(|x| json!(x)),
Some(Unit::Bytes),
FIGURE_ABSENT,
);
for key in [
"tier.ram.hits_total",
"tier.ram.misses_total",
"tier.ram.waits_total",
"tier.ram.evictions_total",
"tier.ram.puts_total",
"tier.ram.discards_total",
"tier.ram.loads_abandoned_total",
] {
push_counter(out, &sample, key, Unit::Count);
}
push_counter(out, &sample, "tier.ram.bytes_loaded_total", Unit::Bytes);
out.push(Reading::unavailable(
"inference.ironworks.tier.ram.hit_ratio",
Some(Unit::Percent),
RATIO_NEEDS_TWO,
));
}
}
match §ion.nvme {
None => out.push(Reading::unavailable(
"inference.ironworks.tier.nvme.<none>",
None,
"the engine's metrics carry no NVMe tier object",
)),
Some(Tier::NotConfigured { reason }) => out.push(Reading::unavailable(
"inference.ironworks.tier.nvme.<none>",
None,
not_configured("the NVMe expert store", reason),
)),
Some(Tier::Configured(n)) => {
push_counter(out, &sample, "tier.nvme.reads_total", Unit::Count);
push_counter(out, &sample, "tier.nvme.bytes_total", Unit::Bytes);
push_counter(out, &sample, "tier.nvme.batches_total", Unit::Count);
let ms = |ns: Option<u64>| ns.map(|v| json!(v as f64 / 1e6));
push_opt(
out,
"inference.ironworks.tier.nvme.inflight_peak",
n.inflight_peak.map(|v| json!(v)),
Some(Unit::Count),
FIGURE_ABSENT,
);
push_opt(
out,
"inference.ironworks.tier.nvme.latency_p50_ms",
ms(n.latency_p50_ns),
Some(Unit::Milliseconds),
FIGURE_ABSENT,
);
push_opt(
out,
"inference.ironworks.tier.nvme.latency_p99_ms",
ms(n.latency_p99_ns),
Some(Unit::Milliseconds),
FIGURE_ABSENT,
);
push_opt(
out,
"inference.ironworks.tier.nvme.latency_max_ms",
ms(n.latency_max_ns),
Some(Unit::Milliseconds),
FIGURE_ABSENT,
);
push_opt(
out,
"inference.ironworks.tier.nvme.queue_depth",
n.queue_depth.map(|v| json!(v)),
Some(Unit::Count),
"the engine does not report its NVMe queue depth",
);
}
}
match §ion.prefetch {
None => out.push(Reading::unavailable(
"inference.ironworks.tier.prefetch.<none>",
None,
"the engine's metrics carry no prefetch object; the engine includes one only when an expert store is configured",
)),
Some(_) => {
for key in [
"tier.prefetch.requested_total",
"tier.prefetch.scheduled_total",
"tier.prefetch.dropped_total",
"tier.prefetch.loaded_total",
"tier.prefetch.useful_total",
"tier.prefetch.wasted_total",
"tier.prefetch.errors_total",
] {
push_counter(out, &sample, key, Unit::Count);
}
push_opt(
out,
"inference.ironworks.tier.prefetch.queue_peak",
section
.prefetch
.as_ref()
.and_then(|p| p.queue_peak)
.map(|v| json!(v)),
Some(Unit::Count),
FIGURE_ABSENT,
);
}
}
push_opt(
out,
"inference.ironworks.memory.host.engine_pinned_bytes",
section.host_pinned_bytes.map(|v| json!(v)),
Some(Unit::Bytes),
"the engine's metrics carry no host memory figure",
);
match §ion.per_gpu {
None => out.push(Reading::unavailable(
"inference.ironworks.gpu.<none>",
None,
"the engine's metrics carry no per-GPU memory section",
)),
Some(gpus) if gpus.is_empty() => out.push(Reading::unavailable(
"inference.ironworks.gpu.<none>",
None,
"the engine reports no GPU that it is running on",
)),
Some(gpus) => {
let monitors = monitor_gpus(out);
for gpu in gpus {
let index = match crate::inference::ironworks::match_gpu(gpu, &monitors) {
Ok(n) => n,
Err(why) => {
out.push(Reading::unavailable(
"inference.ironworks.gpu.<unmatched>",
None,
why,
));
continue;
}
};
let base = format!("inference.ironworks.gpu.{index}");
push_opt(
out,
format!("{base}.vram_used_bytes"),
gpu.engine_vram_used_bytes.map(|v| json!(v)),
Some(Unit::Bytes),
FIGURE_ABSENT,
);
push_opt(
out,
format!("{base}.pci_bus_id"),
gpu.pci_bus_id.clone().map(|v| json!(v)),
Some(Unit::Identifier),
"the engine does not report this GPU's PCI bus address",
);
push_opt(
out,
format!("{base}.uuid"),
gpu.uuid.clone().map(|v| json!(v)),
Some(Unit::Identifier),
"the engine does not report this GPU's UUID",
);
}
}
}
}
fn push_counter(
out: &mut Vec<Reading>,
sample: &crate::inference::ProviderSample,
key: &str,
unit: Unit,
) {
push_opt(
out,
format!("inference.ironworks.{key}"),
sample.counters.get(key).map(|v| serde_json::json!(v)),
Some(unit),
COUNTER_ABSENT,
);
}
fn not_configured(what: &str, reason: &Option<String>) -> String {
match reason.as_deref().map(str::trim).filter(|r| !r.is_empty()) {
Some(why) => why.to_string(),
None => format!("{what} is not configured on this engine, and the engine gives no reason"),
}
}
fn monitor_gpus(out: &[Reading]) -> Vec<crate::inference::ironworks::MonitorGpu> {
use crate::inference::ironworks::MonitorGpu;
let mut by_index: std::collections::BTreeMap<usize, MonitorGpu> =
std::collections::BTreeMap::new();
for reading in out {
let parts: Vec<&str> = reading.id.split('.').collect();
let ["gpu", n, field] = parts.as_slice() else {
continue;
};
let Ok(index) = n.parse::<usize>() else {
continue;
};
if !matches!(*field, "pci_bus_id" | "uuid") {
continue;
}
let Some(text) = reading
.value
.as_ref()
.and_then(|v| v.as_str())
.map(str::to_string)
else {
continue;
};
let entry = by_index.entry(index).or_insert(MonitorGpu {
index,
pci_bus_id: None,
uuid: None,
});
if *field == "pci_bus_id" {
entry.pci_bus_id = Some(text);
} else {
entry.uuid = Some(text);
}
}
by_index.into_values().collect()
}
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_opt(
out,
format!("{base}.model"),
info.model.as_deref().map(|m| serde_json::json!(m)),
Some(Unit::Text),
"the device did not report a 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::MegabitsPerSecond),
"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);
push_opt(
out,
format!("{base}.cpu"),
p.cpu_percent.map(|c| serde_json::json!(c)),
Some(Unit::Percent),
concat!(
"the process started within the sampling interval, so there is no ",
"earlier sample to measure its CPU share against"
),
);
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_opt(
out,
format!("{base}.connector"),
d.connector.as_ref().map(|c| serde_json::json!(c)),
Some(Unit::Text),
"the platform gave this display no connector 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,
);
push_opt(
out,
format!("{base}.primary"),
d.is_primary.map(|p| serde_json::json!(p)),
None,
"the platform reports no primary flag for this display",
);
}
}
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(match sensor.active {
Some(active) => {
Reading::measured(format!("{base}.active"), serde_json::json!(active), None)
}
None => Reading::unavailable(
format!("{base}.active"),
None,
"this platform does not report whether the sensor is active",
),
});
}
}
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_opt(
out,
format!("{base}.driver"),
c.driver.as_deref().map(|d| serde_json::json!(d)),
Some(Unit::Identifier),
"the platform reports no driver for this controller",
);
push_opt(
out,
format!("{base}.interface"),
(c.interface != crate::storage_controller::StorageInterface::Unknown)
.then(|| serde_json::json!(format!("{:?}", c.interface))),
Some(Unit::Identifier),
"no evidence in the platform's controller data identifies this controller's 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.filter(|n| *n > 0).map(|n| serde_json::json!(n)),
Some(Unit::Count),
"this controller reports no port count",
);
}
}
fn settings_segments() -> Vec<&'static str> {
crate::profile::apply::builtin_handlers()
.iter()
.map(|handler| super::setting_domain(handler.subsystem()).as_str())
.collect()
}
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();
let unmatched = monitor.unmatched_gpus();
if caps.is_empty() {
let reason = if unmatched.is_empty() {
"no hardware codec capability was found; the GPU may have no media engine".to_string()
} else {
unmatched_reason(unmatched)
};
out.push(Reading::unavailable("gpu.codec.<none>", None, reason));
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);
match &c.max_resolution {
Some(res) if *res != MaxResolution::Unknown => {
push_str(out, format!("{base}.max_resolution"), &format!("{res:?}"))
}
_ => out.push(Reading::unavailable(
format!("{base}.max_resolution"),
Some(Unit::Identifier),
"the platform reports no frame class for this engine, and none is inferred",
)),
}
let pixels = match &c.max_resolution {
Some(MaxResolution::SD) => Some((720, 480)),
Some(MaxResolution::HD) => Some((1280, 720)),
Some(MaxResolution::FullHD) => Some((1920, 1080)),
Some(MaxResolution::QHD) => Some((2560, 1440)),
Some(MaxResolution::UHD4K) => Some((3840, 2160)),
Some(MaxResolution::UHD8K) => Some((7680, 4320)),
Some(MaxResolution::Unknown) | None => 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),
));
}
if !unmatched.is_empty() {
out.push(Reading::unavailable(
"gpu.codec.<none>",
None,
unmatched_reason(unmatched),
));
}
}
fn unmatched_reason(names: &[String]) -> String {
format!(
"no codec rules match {}; the model name does not place it in a generation this reader knows",
names.join(", ")
)
}
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_opt(
out,
format!("{base}.type"),
d.device_type.map(|t| serde_json::json!(format!("{t:?}"))),
Some(Unit::Identifier),
"the platform did not report what kind of device this is",
);
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_opt(
out,
format!("{base}.name"),
d.name
.as_deref()
.filter(|n| !n.trim().is_empty())
.map(|n| serde_json::json!(n)),
Some(Unit::Text),
"the platform gave this endpoint no name",
);
push_opt(
out,
format!("{base}.direction"),
d.device_type.map(|t| serde_json::json!(format!("{t:?}"))),
Some(Unit::Identifier),
"the platform did not establish whether this endpoint plays, captures or both",
);
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_opt(
out,
format!("{base}.name"),
c.name
.as_deref()
.filter(|n| !n.trim().is_empty())
.map(|n| serde_json::json!(n)),
Some(Unit::Text),
"the platform gave this camera no name",
);
push_opt(
out,
format!("{base}.connection"),
c.connection.map(|k| serde_json::json!(format!("{k:?}"))),
Some(Unit::Identifier),
"the platform did not establish how this camera is attached: macOS does not name the bus for a built-in camera, and Windows and Linux matched no known bus",
);
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_opt(
out,
format!("{base}.value"),
p.value.as_ref().map(|v| serde_json::json!(v)),
Some(Unit::Identifier),
"the parameter was not readable here, so it has no 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));
push_opt(
out,
format!("{base}.default"),
p.is_default.map(|d| serde_json::json!(d)),
None,
"the default queue could not be read: `lpstat -d` did not succeed",
);
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_opt(
out,
format!("{base}.name"),
a.name.as_ref().map(|n| serde_json::json!(n)),
Some(Unit::Text),
"the platform reported no name for this adapter",
);
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_opt(
out,
"cpu.microarch.name",
uarch.name.as_deref().map(|n| serde_json::json!(n)),
Some(Unit::Identifier),
"the processor was not identified as a known microarchitecture",
);
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.map(|nm| serde_json::json!(nm)),
Some(Unit::Count),
"IronMonitor holds no process node for this microarchitecture",
);
push_spec_opt(
out,
"cpu.microarch.year",
uarch.year.map(|y| serde_json::json!(y)),
Some(Unit::Count),
"IronMonitor holds no introduction date for this microarchitecture",
);
push_spec_opt(
out,
"cpu.microarch.hybrid",
uarch.hybrid.map(|h| serde_json::json!(h)),
None,
"the processor was not identified, so whether it is a hybrid design is not known",
);
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.map(|v| serde_json::json!(v)),
Some(Unit::Count),
"the platform's processor description did not include this count",
);
}
push_opt(
out,
"cpu.microarch.smt_enabled",
report.smt_enabled.map(|smt| serde_json::json!(smt)),
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 == Some(true))
.collect();
let unread = report
.extensions
.iter()
.filter(|x| x.supported.is_none())
.count();
if unread > 0 {
out.push(Reading::unavailable(
"cpu.microarch.extension.<unread>",
None,
format!(
"{unread} instruction set extensions were not checked: this platform \
offers neither CPUID for them nor a complete feature list, so their \
absence is unknown rather than established"
),
));
}
if supported.is_empty() {
if unread == 0 {
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),
);
out.push(Reading::unavailable(
format!("{base}.throughput"),
Some(Unit::BytesPerSecond),
"no throughput is measured; the figure was a per-primitive constant",
));
}
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 push_channel_counts(out: &mut Vec<Reading>, channels: &crate::memory_bandwidth::ChannelConfig) {
push_spec_opt(
out,
"memory.bandwidth.channels",
channels.active_channels.map(|c| serde_json::json!(c)),
Some(Unit::Count),
"no DIMM locator names a channel, and a module count does not establish one",
);
push_spec_opt(
out,
"memory.bandwidth.max_channels",
channels.max_channels.map(|c| serde_json::json!(c)),
Some(Unit::Count),
"no platform reader establishes the controller's channel limit",
);
}
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),
);
push_channel_counts(out, &est.channels);
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));
}
return;
}
let Some(speed) = est.speed_mts 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,
));
}
return;
};
out.push(Reading::spec(
"memory.bandwidth.speed",
serde_json::json!(speed),
Some(Unit::Count),
));
const NO_EFFICIENCY: &str = concat!(
"no efficiency figure is read from this machine and no benchmark is run; ",
"the achievable and STREAM Triad figures used to be the peak times a fixed ",
"per-generation factor, which is a rule of thumb rather than a measurement"
);
let Some(peak) = est.peak_bandwidth_gbs else {
const NO_CHANNELS: &str = concat!(
"the active channel count was not read from DIMM locators, so every ",
"bandwidth figure derived from it would be a guess at the channel count"
);
out.push(Reading::unavailable(
"memory.bandwidth.peak",
Some(Unit::BytesPerSecond),
NO_CHANNELS,
));
for id in [
"memory.bandwidth.achievable",
"memory.bandwidth.stream_triad",
] {
out.push(Reading::unavailable(
id,
Some(Unit::BytesPerSecond),
NO_EFFICIENCY,
));
}
return;
};
const GB: f64 = 1_000_000_000.0;
out.push(Reading::derived(
"memory.bandwidth.peak",
serde_json::json!(peak * GB),
Some(Unit::BytesPerSecond),
));
for id in [
"memory.bandwidth.achievable",
"memory.bandwidth.stream_triad",
] {
out.push(Reading::unavailable(
id,
Some(Unit::BytesPerSecond),
NO_EFFICIENCY,
));
}
}
pub(super) 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",
);
push_opt(
out,
format!("{base}.enabled"),
r.enabled.map(|e| serde_json::json!(e)),
None,
"the domain's enabled attribute could not be read",
);
}
}
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 a_failed_gpu_backend_is_an_unavailable_row_with_its_reasons() {
let failures = vec![
("amd", "0000:03:00.0: ROCm: no HIP runtime".to_string()),
("nvidia", "NVML: driver not loaded".to_string()),
("amd", "0000:04:00.0: sysfs: permission denied".to_string()),
];
let mut out = Vec::new();
push_backend_failures(&mut out, &failures);
assert_eq!(out.len(), 2, "one row per failing backend: {out:?}");
let amd = out
.iter()
.find(|r| r.id == "gpu.backend.amd.<unreadable>")
.expect("amd row");
assert_eq!(amd.provenance, Provenance::Unavailable);
assert!(amd.value.is_none());
let note = amd.note.as_deref().expect("a reason");
assert!(note.contains("no HIP runtime"), "{note}");
assert!(note.contains("permission denied"), "{note}");
let nvidia = out
.iter()
.find(|r| r.id == "gpu.backend.nvidia.<unreadable>")
.expect("nvidia row");
assert!(nvidia
.note
.as_deref()
.unwrap()
.contains("driver not loaded"));
}
#[test]
fn an_all_failed_gpu_enumeration_reports_each_backend() {
let err = crate::IronError::GpuDetectionFailed(vec![
("nvidia", "NVML: driver not loaded".to_string()),
("amd", "0000:03:00.0: ROCm: no HIP runtime".to_string()),
]);
let mut out = Vec::new();
push_gpu_enumeration_failure(&mut out, &err);
let ids: Vec<&str> = out.iter().map(|r| r.id.as_str()).collect();
assert_eq!(ids.len(), 3, "{ids:?}");
for id in [
"gpu.<unreadable>",
"gpu.backend.nvidia.<unreadable>",
"gpu.backend.amd.<unreadable>",
] {
assert!(ids.contains(&id), "missing {id}: {ids:?}");
}
for r in &out {
assert_eq!(r.provenance, Provenance::Unavailable, "{}", r.id);
assert!(r.value.is_none(), "{}", r.id);
}
let nvidia = out
.iter()
.find(|r| r.id == "gpu.backend.nvidia.<unreadable>")
.expect("nvidia row");
assert!(nvidia
.note
.as_deref()
.unwrap()
.contains("driver not loaded"));
let aggregate = out
.iter()
.find(|r| r.id == "gpu.<unreadable>")
.expect("aggregate row");
assert!(aggregate
.note
.as_deref()
.unwrap()
.contains("ROCm: no HIP runtime"));
}
#[test]
fn an_unstructured_gpu_enumeration_failure_has_no_backend_rows() {
let err = crate::IronError::Other("boom".to_string());
let mut out = Vec::new();
push_gpu_enumeration_failure(&mut out, &err);
assert_eq!(out.len(), 1, "{out:?}");
assert_eq!(out[0].id, "gpu.<unreadable>");
}
#[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 = None;
report.logical_cores = Some(16);
report.smt_enabled = None;
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());
}
}
#[cfg(test)]
mod inference_resolve_tests {
use super::*;
#[test]
fn unreachable_engine_is_a_named_absence_not_an_idle_engine() {
let port = std::net::TcpListener::bind("127.0.0.1:0")
.expect("bind")
.local_addr()
.expect("addr")
.port();
let mut out = Vec::new();
resolve_ironworks(&mut out, &format!("http://127.0.0.1:{port}"));
let none = out
.iter()
.find(|r| r.id == "inference.ironworks.<none>")
.expect("the absence row");
assert_eq!(none.provenance, Provenance::Unavailable);
assert!(none.value.is_none());
let note = none.note.as_deref().unwrap_or("");
assert!(
note.starts_with(&format!(
"no IronWorks engine answered at http://127.0.0.1:{port}/metrics:"
)),
"{note}"
);
assert_eq!(out.len(), 1, "only the absence row is emitted: {out:?}");
}
#[test]
fn monitor_gpus_collects_identifiers_by_index() {
let out = vec![
Reading::measured(
"gpu.0.pci_bus_id",
serde_json::json!("0000:01:00.0"),
Some(Unit::Identifier),
),
Reading::unavailable("gpu.1.uuid", Some(Unit::Identifier), "no uuid"),
Reading::measured(
"gpu.1.uuid",
serde_json::json!("GPU-abc"),
Some(Unit::Identifier),
),
Reading::unavailable("gpu.<none>", None, "none found here"),
];
let gpus = monitor_gpus(&out);
assert_eq!(gpus.len(), 2);
assert_eq!(gpus[0].index, 0);
assert_eq!(gpus[0].pci_bus_id.as_deref(), Some("0000:01:00.0"));
assert_eq!(gpus[1].index, 1);
assert_eq!(gpus[1].uuid.as_deref(), Some("GPU-abc"));
assert_eq!(gpus[1].pci_bus_id, None);
}
}
#[cfg(test)]
mod inference_resolver_tests {
use super::*;
use crate::inference::poller_tests::{Stub, A_BODY, METRICS_OFF_BODY};
fn reading<'a>(out: &'a [Reading], id: &str) -> Option<&'a Reading> {
out.iter().find(|r| r.id == id)
}
#[test]
fn a_metrics_off_engine_is_named_apart_from_no_engine() {
let stub = Stub::start(404, METRICS_OFF_BODY);
let mut out = Vec::new();
resolve_ironworks(&mut out, &stub.url());
stub.stop();
let none = reading(&out, "inference.ironworks.<none>").expect("the state is reported");
assert_eq!(none.provenance, Provenance::Unavailable);
let note = none.note.as_deref().unwrap_or_default();
assert!(
note.starts_with("engine running, metrics not enabled — start it with --metrics"),
"{note}"
);
assert!(!note.contains("no engine answered"), "{note}");
}
#[test]
fn an_absent_engine_says_no_engine_answered_with_the_endpoint() {
let port = std::net::TcpListener::bind("127.0.0.1:0")
.expect("bind")
.local_addr()
.expect("addr")
.port();
let base = format!("http://127.0.0.1:{port}");
let mut out = Vec::new();
resolve_ironworks(&mut out, &base);
let none = reading(&out, "inference.ironworks.<none>").expect("the state is reported");
let note = none.note.as_deref().unwrap_or_default();
assert!(
note.starts_with("no IronWorks engine answered at http://127.0.0.1:"),
"{note}"
);
assert!(!note.contains("metrics not enabled"), "{note}");
}
#[test]
fn a_404_with_another_body_is_not_claimed_as_metrics_off() {
let stub = Stub::start(404, "<html>nope</html>");
let mut out = Vec::new();
resolve_ironworks(&mut out, &stub.url());
stub.stop();
let note = reading(&out, "inference.ironworks.<none>")
.and_then(|r| r.note.clone())
.unwrap_or_default();
assert!(!note.contains("metrics not enabled"), "{note}");
assert!(note.contains("HTTP 404"), "{note}");
}
#[test]
fn a_good_body_reports_counters_and_marks_rates_as_needing_two_samples() {
let stub = Stub::start(200, A_BODY);
let mut out = Vec::new();
resolve_ironworks(&mut out, &stub.url());
stub.stop();
let hits = reading(&out, "inference.ironworks.tier.vram.hits_total")
.expect("the VRAM hit counter is reported");
assert_eq!(hits.value, Some(serde_json::json!(1840221)));
assert_eq!(hits.provenance, Provenance::Measured);
let rate = reading(&out, "inference.ironworks.decode.completion_tok_s")
.expect("the rate is reported");
assert_eq!(rate.provenance, Provenance::Unavailable);
assert!(rate
.note
.as_deref()
.unwrap_or_default()
.contains("two samples"));
let ratio = reading(&out, "inference.ironworks.tier.vram.hit_ratio")
.expect("the ratio is reported");
assert_eq!(ratio.provenance, Provenance::Unavailable);
assert!(reading(&out, "inference.ironworks.tier.prefetch.requested_total").is_some());
assert!(reading(&out, "inference.ironworks.tier.nvme.latency_p50_ms").is_some());
}
}
#[cfg(test)]
mod scoped_get_tests {
use super::*;
use std::collections::{BTreeMap, BTreeSet};
fn scope_of(segments: &[&str]) -> Scope {
Scope::of(
segments
.iter()
.map(|s| s.to_string())
.collect::<BTreeSet<_>>(),
)
}
#[test]
fn an_empty_scope_runs_no_reader() {
let ontology = Ontology::build();
let rows = pipeline(&ontology, &scope_of(&[]));
assert!(rows.is_empty(), "an empty scope produced {rows:?}");
}
#[test]
fn unknown_and_template_ids_resolve_to_nothing() {
assert!(get("definitely.not.an.entity").is_none());
assert!(get("gpu.{n}.name").is_none());
}
#[test]
fn derived_entities_need_the_segments_of_their_inputs() {
let ontology = Ontology::build();
let derived: Vec<&Entity> = ontology
.entities
.values()
.filter(|e| !e.derived_from.is_empty())
.collect();
assert!(!derived.is_empty(), "no derived entities to check");
for entity in derived {
let needed = needed_segments(&ontology, &entity.id, entity);
for input in &entity.derived_from {
assert!(
needed.contains(first_segment(input)),
"{} is derived from {input}, but a get would not run the {} readers",
entity.id,
first_segment(input)
);
}
}
}
#[test]
fn inference_ids_need_the_gpu_readers() {
let ontology = Ontology::build();
let entity = ontology
.entities
.values()
.find(|e| e.domain == super::super::Domain::Inference)
.expect("the ontology declares inference entities");
let needed = needed_segments(&ontology, &entity.id, entity);
assert!(needed.contains("inference"));
assert!(
needed.contains("gpu"),
"{} needs the gpu segment to match its engine's GPUs: {needed:?}",
entity.id
);
}
#[test]
fn missing_domain_rows_follow_the_scope() {
let ontology = Ontology::build();
let rows = missing_domain_rows(&ontology, &[], &scope_of(&["disk"]));
assert!(
rows.iter().any(|r| r.id == "disk.<none>"),
"no disk.<none> row: {rows:?}"
);
assert!(rows.iter().all(|r| first_segment(&r.id) == "disk"));
}
#[test]
fn unbound_rows_are_limited_to_the_scope() {
let ontology = Ontology::build();
let rows = unbound_rows(&ontology, &[], &scope_of(&["memory"]));
assert!(rows.iter().any(|r| r.id == "memory.total"), "{rows:?}");
assert!(rows.iter().all(|r| first_segment(&r.id) == "memory"));
assert!(rows.iter().all(|r| !r.id.contains('<')));
}
fn mask(text: &str) -> String {
text.chars()
.map(|c| if c.is_ascii_digit() { '#' } else { c })
.collect()
}
fn is_process_instance(id: &str) -> bool {
id.strip_prefix("process.")
.is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit()))
}
fn is_primed_clock(id: &str) -> bool {
id.strip_prefix("cpu.core.")
.and_then(|rest| rest.strip_suffix(".frequency"))
.is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
}
fn same_reading(full: &Reading, scoped: &Reading) -> Result<(), String> {
let mut differences = Vec::new();
if full.provenance != scoped.provenance {
differences.push(format!(
"provenance {:?} in the full pass, {:?} in the segment pass",
full.provenance, scoped.provenance
));
}
if full.unit != scoped.unit {
differences.push(format!(
"unit {:?} in the full pass, {:?} in the segment pass",
full.unit, scoped.unit
));
}
if full.value.is_some() != scoped.value.is_some() {
differences.push(format!(
"value present={} in the full pass, present={} in the segment pass",
full.value.is_some(),
scoped.value.is_some()
));
}
let note = |r: &Reading| r.note.as_deref().map(mask);
if note(full) != note(scoped) {
differences.push(format!(
"note {:?} in the full pass, {:?} in the segment pass",
note(full),
note(scoped)
));
}
if differences.is_empty() {
Ok(())
} else {
Err(format!("{}: {}", full.id, differences.join("; ")))
}
}
#[test]
fn every_segment_pass_agrees_with_the_full_pass() {
let ontology = Ontology::build();
let full = pipeline(&ontology, &Scope::all());
let full_by_id: BTreeMap<&str, &Reading> =
full.iter().map(|r| (r.id.as_str(), r)).collect();
let segments: BTreeSet<&str> = full.iter().map(|r| first_segment(&r.id)).collect();
assert!(!segments.is_empty(), "the full pass produced no rows");
let mut problems = Vec::new();
for &segment in &segments {
let mut scope_segments = BTreeSet::new();
scope_segments.insert(segment.to_string());
close_over_consumes(&mut scope_segments);
let scoped = pipeline(&ontology, &Scope::of(scope_segments));
let scoped_by_id: BTreeMap<&str, &Reading> =
scoped.iter().map(|r| (r.id.as_str(), r)).collect();
for row in full.iter().filter(|r| {
first_segment(&r.id) == segment
&& !is_process_instance(&r.id)
&& !is_primed_clock(&r.id)
}) {
match scoped_by_id.get(row.id.as_str()) {
None => problems.push(format!(
"{}: in the full pass, absent from the {segment} pass",
row.id
)),
Some(other) => {
if let Err(problem) = same_reading(row, other) {
problems.push(problem);
}
}
}
}
for row in scoped
.iter()
.filter(|r| first_segment(&r.id) == segment && !is_process_instance(&r.id))
{
if !full_by_id.contains_key(row.id.as_str()) {
problems.push(format!(
"{}: in the {segment} pass, absent from the full pass",
row.id
));
}
}
}
assert!(
problems.is_empty(),
"{} rows disagree between the full pass and a segment pass:\n{}",
problems.len(),
problems.join("\n")
);
}
}