Show the detected machine type in device inventory

This commit is contained in:
2026-11-18 17:39:43 +01:00
parent 6963ad332c
commit c599baa494
9 changed files with 231 additions and 16 deletions
+66 -8
View File
@@ -4,6 +4,7 @@ use crate::{
actions::{ServiceUnit, reboot_required},
process,
};
use rmm_domain::inventory_document::DeviceType;
use std::{
collections::BTreeMap,
ffi::{CStr, CString},
@@ -257,6 +258,8 @@ pub struct UpdateStatus {
#[derive(Debug, Clone, serde::Serialize)]
pub struct Hardware {
pub readable_dmi: BTreeMap<String, String>,
pub device_type: Option<DeviceType>,
pub proxmox_ve: bool,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct LinuxInventory {
@@ -1116,7 +1119,36 @@ pub fn updates() -> Observation<UpdateStatus> {
}
result
}
fn virtualization_type(output: &process::Output) -> Option<DeviceType> {
if output.timed_out || output.truncated {
return None;
}
match (
output.code,
std::str::from_utf8(&output.stdout).ok()?.trim(),
) {
(Some(1), "none") => Some(DeviceType::Physical),
(Some(0), name) if !name.is_empty() && name != "none" => Some(DeviceType::Virtual),
_ => None,
}
}
fn machine_type(proxmox_ve: bool) -> Option<DeviceType> {
if proxmox_ve {
return Some(DeviceType::Hypervisor);
}
let output = process::run(
"/usr/bin/systemd-detect-virt",
&[],
Duration::from_secs(2),
512,
)
.ok()?;
virtualization_type(&output)
}
pub fn hardware() -> Observation<Hardware> {
const SOURCE: &str = "linux.dmi:/sys/class/dmi/id;systemd-detect-virt;pve-manager";
let mut readable_dmi = BTreeMap::new();
for field in [
"sys_vendor",
@@ -1132,15 +1164,21 @@ pub fn hardware() -> Observation<Hardware> {
readable_dmi.insert(field.into(), value);
}
}
if readable_dmi.is_empty() {
Observation::unavailable(
"linux.dmi:/sys/class/dmi/id",
Quality::Unsupported,
"DMI_UNAVAILABLE",
)
let proxmox_ve =
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
let device_type = machine_type(proxmox_ve);
if readable_dmi.is_empty() && device_type.is_none() {
Observation::unavailable(SOURCE, Quality::Unsupported, "HARDWARE_UNAVAILABLE")
} else {
Observation::valid("linux.dmi:/sys/class/dmi/id", Hardware { readable_dmi })
.partial("READABLE_DMI_ONLY_NO_SMART_OR_ENCRYPTION_PROOF")
Observation::valid(
SOURCE,
Hardware {
readable_dmi,
device_type,
proxmox_ve,
},
)
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
}
}
@@ -1362,6 +1400,26 @@ mod tests {
assert_eq!(request.since_filter, "@100.123457");
assert_eq!(request.until_filter, "@101.987654");
}
#[test]
fn machine_types_distinguish_proxmox_guests_and_probe_failures() {
assert_eq!(machine_type(true), Some(DeviceType::Hypervisor));
let mut output = process::Output {
code: Some(0),
stdout: b"kvm\n".to_vec(),
stderr: vec![],
truncated: false,
timed_out: false,
interrupted: false,
};
assert_eq!(virtualization_type(&output), Some(DeviceType::Virtual));
output.code = Some(1);
assert_eq!(virtualization_type(&output), None);
output.stdout = b"none\n".to_vec();
assert_eq!(virtualization_type(&output), Some(DeviceType::Physical));
output.timed_out = true;
assert_eq!(virtualization_type(&output), None);
}
#[test]
fn harmless_native_read_providers() {
assert_eq!(memory().quality, Quality::Valid);
+110 -2
View File
@@ -2,6 +2,7 @@
//! uninstall commands; registry entries are evidence, not verified MSI state.
use anyhow::{Result, ensure};
use chrono::Utc;
use rmm_domain::inventory_document::DeviceType;
use serde_json::{Value, json};
use std::{
mem::{size_of, zeroed},
@@ -64,6 +65,82 @@ fn text(key: HKEY, name: &str) -> Result<Option<String>> {
Ok(Some(String::from_utf16(&data[..count - 1])?))
}
#[cfg(target_arch = "x86_64")]
fn non_microsoft_hypervisor() -> bool {
use std::arch::x86_64::__cpuid;
if __cpuid(1).ecx & (1 << 31) == 0 {
return false;
}
let vendor = __cpuid(0x4000_0000);
// The Microsoft hypervisor can also be active on physical VBS machines.
[vendor.ebx, vendor.ecx, vendor.edx]
!= [
u32::from_le_bytes(*b"Micr"),
u32::from_le_bytes(*b"osof"),
u32::from_le_bytes(*b"t Hv"),
]
}
#[cfg(not(target_arch = "x86_64"))]
fn non_microsoft_hypervisor() -> bool {
false
}
fn classify_machine(
hyper_v_host: bool,
guest_hypervisor: bool,
manufacturer: Option<&str>,
product: Option<&str>,
) -> Option<DeviceType> {
if hyper_v_host {
return Some(DeviceType::Hypervisor);
}
let manufacturer = manufacturer.unwrap_or_default().trim().to_ascii_lowercase();
let product = product.unwrap_or_default().trim().to_ascii_lowercase();
let virtual_firmware = [
"qemu",
"vmware",
"virtualbox",
"xen",
"parallels",
"bhyve",
"kvm",
"virtual machine",
"virtual platform",
]
.iter()
.any(|prefix| manufacturer.starts_with(prefix) || product.starts_with(prefix));
if guest_hypervisor || virtual_firmware {
return Some(DeviceType::Virtual);
}
(!manufacturer.is_empty() && !product.is_empty()).then_some(DeviceType::Physical)
}
fn machine_type() -> Option<DeviceType> {
let hyper_v_host = open(
HKEY_LOCAL_MACHINE,
r"SYSTEM\CurrentControlSet\Services\vmms",
KEY_WOW64_64KEY,
)
.is_ok();
let bios = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\BIOS",
KEY_WOW64_64KEY,
)
.ok();
let read = |name| {
bios.as_ref()
.and_then(|key| text(key.0, name).ok().flatten())
};
classify_machine(
hyper_v_host,
non_microsoft_hypervisor(),
read("SystemManufacturer").as_deref(),
read("SystemProductName").as_deref(),
)
}
fn hardware() -> Result<Value> {
let mut system: SYSTEM_INFO = unsafe { zeroed() };
unsafe {
@@ -91,7 +168,7 @@ fn hardware() -> Result<Value> {
Ok(
json!({"cpu_model":cpu_model, "logical_processors_visible":system.dwNumberOfProcessors,
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
"memory_load_percent":memory.dwMemoryLoad}),
"memory_load_percent":memory.dwMemoryLoad,"device_type":machine_type()}),
)
}
@@ -197,7 +274,7 @@ pub fn observations() -> Vec<Value> {
[
(
"windows.hardware",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor,BIOS,vmms;cpuid",
hardware as Provider,
),
(
@@ -226,3 +303,34 @@ pub fn observations() -> Vec<Value> {
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn machine_type_distinguishes_hyper_v_hosts_from_guests() {
let guest = (Some("Microsoft Corporation"), Some("Virtual Machine"));
assert_eq!(
classify_machine(false, false, guest.0, guest.1),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(true, false, guest.0, guest.1),
Some(DeviceType::Hypervisor)
);
assert_eq!(
classify_machine(false, false, Some("QEMU"), Some("Standard PC")),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(false, true, None, None),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(false, false, Some("Dell Inc."), Some("Precision")),
Some(DeviceType::Physical)
);
assert_eq!(classify_machine(false, false, None, None), None);
}
}
+10 -1
View File
@@ -1,7 +1,16 @@
//! Additive bounded passive metadata; the strict original Inventory stays intact.
use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DeviceType {
Physical,
Virtual,
Hypervisor,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Observation {
+29 -1
View File
@@ -10,6 +10,7 @@ use axum::{
http::{HeaderMap, HeaderValue, StatusCode},
};
use chrono::{DateTime, Utc};
use rmm_domain::inventory_document::DeviceType;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
@@ -289,7 +290,17 @@ fn volumes(data: &Value) -> Value {
}
items.into()
}
fn device_type(hardware: &Value) -> Option<DeviceType> {
DeviceType::deserialize(&hardware["device_type"]).ok()
}
fn os_label(data: &Value) -> Option<String> {
let linux_hardware = observed(data, "linux.hardware");
if linux_hardware["proxmox_ve"].as_bool() == Some(true)
&& device_type(linux_hardware) == Some(DeviceType::Hypervisor)
{
return Some("Proxmox VE".to_owned());
}
let raw = data["os"].as_str()?;
if let Some(pretty) = observed(data, "linux.os")["release"]["PRETTY_NAME"].as_str() {
return Some(pretty.to_owned());
@@ -341,6 +352,8 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
let cpu = observed(&data, "linux.cpu");
let windows = observed(&data, "windows.hardware");
let device_type =
device_type(observed(&data, "linux.hardware")).or_else(|| device_type(windows));
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
@@ -355,7 +368,7 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
"agent_id":row.get::<Uuid,_>("agent_id"),"asset_id":row.get::<Uuid,_>("asset_id"),
"status":row.get::<String,_>("status"),"lifecycle":row.get::<String,_>("lifecycle"),
"archived_at":row.get::<Option<DateTime<Utc>>,_>("archived_at"),"revoked_at":revoked,
"hostname":data["hostname"].as_str(),"os":os_label(&data),
"hostname":data["hostname"].as_str(),"device_type":device_type,"os":os_label(&data),
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()),
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()),
@@ -411,6 +424,21 @@ mod tests {
assert!(os_label(&Value::Null).is_none());
}
#[test]
fn proxmox_os_label_requires_a_valid_hypervisor_observation() {
let mut snapshot = json!({
"os": "Debian",
"observations": [{"scope":"linux.hardware","quality":"valid",
"data":{"device_type":"hypervisor","proxmox_ve":true}}]
});
assert_eq!(os_label(&snapshot).as_deref(), Some("Proxmox VE"));
snapshot["observations"][0]["data"]["device_type"] = json!("virtual");
assert_eq!(os_label(&snapshot).as_deref(), Some("Debian"));
snapshot["observations"][0]["quality"] = json!("error");
assert_eq!(device_type(observed(&snapshot, "linux.hardware")), None);
assert_eq!(device_type(&json!({"device_type":"desktop"})), None);
}
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn visibility_is_filtered_before_the_cursor_limit() {