Expand the passive inventory shown in device details
Rust development slice / linux (push) Failing after 9s

This commit is contained in:
2026-11-18 20:02:41 +01:00
parent 38f43f887a
commit aea2d5b379
15 changed files with 701 additions and 45 deletions
+122 -8
View File
@@ -4,7 +4,7 @@ use crate::{
actions::{ServiceUnit, reboot_required},
process,
};
use rmm_domain::inventory_document::{CpuTimes, DeviceType};
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
use std::{
collections::BTreeMap,
ffi::{CStr, CString},
@@ -169,6 +169,9 @@ pub struct OperatingSystem {
pub hostname: String,
pub boot_id: String,
pub uptime_seconds: f64,
pub booted_at: Option<chrono::DateTime<chrono::Utc>>,
pub installed_at: Option<chrono::DateTime<chrono::Utc>>,
pub install_date_source: Option<&'static str>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Interface {
@@ -260,6 +263,8 @@ pub struct Hardware {
pub readable_dmi: BTreeMap<String, String>,
pub device_type: Option<DeviceType>,
pub proxmox_ve: bool,
pub manufacturer: Option<String>,
pub bios_serial_number: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct LinuxInventory {
@@ -271,6 +276,7 @@ pub struct LinuxInventory {
pub dns: Observation<Dns>,
pub volumes: Observation<Vec<Observation<Volume>>>,
pub software: Observation<Vec<SoftwarePackage>>,
pub users: Observation<Vec<String>>,
pub updates: Observation<UpdateStatus>,
pub hardware: Observation<Hardware>,
pub smart: Observation<()>,
@@ -285,6 +291,7 @@ pub fn collect_native() -> LinuxInventory {
dns: dns(),
volumes: volumes(),
software: software(),
users: logged_in_users(),
updates: updates(),
hardware: hardware(),
smart: Observation::unavailable(
@@ -380,6 +387,22 @@ pub fn capabilities() -> BTreeMap<String, Observation<bool>> {
);
result
}
fn installed_at() -> Option<(chrono::DateTime<chrono::Utc>, &'static str)> {
for (path, source) in [
("/var/log/installer", "installer_directory"),
("/", "root_filesystem"),
] {
if let Some(time) = fs::metadata(path)
.ok()
.and_then(|data| data.created().ok())
.filter(|time| *time > SystemTime::UNIX_EPOCH && *time <= SystemTime::now())
{
return Some((time.into(), source));
}
}
None
}
pub fn operating_system() -> Observation<OperatingSystem> {
let release = read("/etc/os-release", 32 * 1024);
let kernel = read("/proc/sys/kernel/osrelease", 4096);
@@ -417,8 +440,21 @@ pub fn operating_system() -> Observation<OperatingSystem> {
.map(|(k, v)| (k.into(), v.trim_matches('"').into()))
})
.collect();
let booted_at = read("/proc/stat", 256 * 1024)
.data
.as_deref()
.and_then(|stat| {
let seconds = stat
.lines()
.find_map(|line| line.strip_prefix("btime "))?
.trim()
.parse()
.ok()?;
chrono::DateTime::from_timestamp(seconds, 0)
});
let installed = installed_at();
Observation::valid(
"linux.os:/etc/os-release,/proc",
"linux.os:/etc/os-release,/proc,filesystem-birth",
OperatingSystem {
release,
kernel: kernel.trim().into(),
@@ -426,12 +462,74 @@ pub fn operating_system() -> Observation<OperatingSystem> {
hostname: hostname.trim().into(),
boot_id,
uptime_seconds,
booted_at,
installed_at: installed.map(|(time, _)| time),
install_date_source: installed.map(|(_, source)| source),
},
)
} else {
Observation::unavailable("linux.os", Quality::Error, "OS_SOURCE_UNAVAILABLE")
}
}
fn logged_in_users() -> Observation<Vec<String>> {
const LOGINCTL: &str = "/usr/bin/loginctl";
let listed = command(
LOGINCTL,
&["--no-legend", "--no-pager", "list-sessions"],
16 * 1024,
);
let Some(rows) = &listed.data else {
return map(listed, |_| None);
};
let mut ids = rows
.lines()
.filter_map(|line| line.split_whitespace().next());
let mut args = vec![
"--no-pager",
"--all",
"--property=Name,Class,State",
"show-session",
"--",
];
args.extend(
ids.by_ref()
.take(64)
.filter(|id| id.bytes().all(|c| c.is_ascii_alphanumeric())),
);
let limited = listed.truncated || ids.next().is_some();
if args.len() == 5 {
return Observation::valid("linux.logind:loginctl", Vec::new());
}
let mut report = map(command(LOGINCTL, &args, 16 * 1024), |text| {
let users: std::collections::BTreeSet<_> = text
.split("\n\n")
.filter_map(|block| {
let fields: BTreeMap<_, _> = block
.lines()
.filter_map(|line| line.split_once('='))
.collect();
let class = *fields.get("Class")?;
let state = *fields.get("State")?;
let name = *fields.get("Name")?;
(matches!(
class,
"user" | "user-early" | "user-light" | "user-early-light"
) && matches!(state, "online" | "active")
&& !name.is_empty()
&& name.len() <= 255)
.then(|| name.to_owned())
})
.collect();
Some(users.into_iter().collect())
});
report.source_id = "linux.logind:loginctl".into();
if limited && report.data.is_some() {
report = report.partial("SESSION_LIMIT");
report.truncated = true;
}
report
}
fn aggregate_jiffies(stat: &str) -> Option<Vec<u64>> {
stat.lines()
.find(|line| line.starts_with("cpu "))
@@ -583,11 +681,12 @@ pub fn interfaces() -> Observation<Vec<Interface>> {
}
libc::AF_INET6 => {
let addr = &*item.ifa_addr.cast::<libc::sockaddr_in6>();
addresses.push(format!(
"{}%{}",
Ipv6Addr::from(addr.sin6_addr.s6_addr),
addr.sin6_scope_id
));
let ip = Ipv6Addr::from(addr.sin6_addr.s6_addr);
addresses.push(if addr.sin6_scope_id == 0 {
ip.to_string()
} else {
format!("{ip}%{}", addr.sin6_scope_id)
});
}
_ => {}
}
@@ -1194,7 +1293,20 @@ pub fn hardware() -> Observation<Hardware> {
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() {
let manufacturer = readable_dmi
.get("sys_vendor")
.and_then(|value| firmware_identifier(value));
let serial_credential = std::env::var_os("CREDENTIALS_DIRECTORY")
.map(|directory| std::path::PathBuf::from(directory).join("rmm-bios-serial"));
let bios_serial_number = [
Some("/sys/class/dmi/id/product_serial"),
Some("/proc/device-tree/serial-number"),
serial_credential.as_deref().and_then(Path::to_str),
]
.into_iter()
.flatten()
.find_map(|path| sys_text(path).and_then(|value| firmware_identifier(&value)));
if readable_dmi.is_empty() && device_type.is_none() && bios_serial_number.is_none() {
Observation::unavailable(SOURCE, Quality::Unsupported, "HARDWARE_UNAVAILABLE")
} else {
Observation::valid(
@@ -1203,6 +1315,8 @@ pub fn hardware() -> Observation<Hardware> {
readable_dmi,
device_type,
proxmox_ve,
manufacturer,
bios_serial_number,
},
)
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
+14 -4
View File
@@ -1,5 +1,5 @@
//! Additive JSON observation mapping inside the existing snapshot payload. This
//! does not introduce a protobuf tag, a fabricated receive time or a new scope.
//! does not introduce a protobuf tag or a fabricated receive time.
use anyhow::Result;
use serde_json::{Value, json};
@@ -14,7 +14,12 @@ pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<
observation["scope"] = json!(format!("linux.{name}"));
// Bound each scope independently. Never drop unsupported/error metadata
// or imply that absent/truncated rows were deleted from a device.
while serde_json::to_vec(&observation)?.len() > 32768 {
let max_bytes = if name == "software" {
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
while serde_json::to_vec(&observation)?.len() > max_bytes {
observation["truncated"] = json!(true);
observation["completeness"] = json!("partial");
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
@@ -49,7 +54,7 @@ mod tests {
fn native_wire_scopes_preserve_quality_time_and_unsupported() {
let native = crate::inventory::collect_native();
let mapped = observations(&native).unwrap();
assert_eq!(mapped.len(), 11);
assert_eq!(mapped.len(), 12);
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
assert_eq!(smart["quality"], "unsupported");
assert!(smart["data"].is_null());
@@ -61,7 +66,12 @@ mod tests {
);
assert!(!observation["source_id"].as_str().unwrap().is_empty());
assert!(observation.get("received_at").is_none());
assert!(serde_json::to_vec(observation).unwrap().len() <= 32768);
let limit = if observation["scope"] == "linux.software" {
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
assert!(serde_json::to_vec(observation).unwrap().len() <= limit);
}
let base = snapshot(false).unwrap();
assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok());