290 lines
9.0 KiB
Rust
290 lines
9.0 KiB
Rust
use serde::{Deserialize, Serialize};
|
|
use std::{
|
|
process::Stdio,
|
|
time::{Duration, SystemTime, UNIX_EPOCH},
|
|
};
|
|
use tokio::{io::AsyncReadExt, process::Command};
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Memory {
|
|
pub total_bytes: Option<u64>,
|
|
pub available_bytes: Option<u64>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum MemoryKind {
|
|
Dedicated,
|
|
Shared,
|
|
Unknown,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Accelerator {
|
|
pub id: String,
|
|
pub name: String,
|
|
pub vendor: String,
|
|
pub memory_kind: MemoryKind,
|
|
/// For shared GPUs this is an independent device allocation limit, not RAM.
|
|
pub memory: Memory,
|
|
pub driver: Option<String>,
|
|
pub source: String,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Hardware {
|
|
pub schema_version: u32,
|
|
pub sampled_at_unix_ms: u64,
|
|
pub os: String,
|
|
pub architecture: String,
|
|
pub cpu_name: String,
|
|
pub logical_cpus: usize,
|
|
pub cpu_features: Vec<String>,
|
|
pub memory: Memory,
|
|
pub accelerators: Vec<Accelerator>,
|
|
pub warnings: Vec<String>,
|
|
}
|
|
|
|
pub async fn inventory() -> Hardware {
|
|
let mut system = sysinfo::System::new();
|
|
system.refresh_memory();
|
|
system.refresh_cpu_all();
|
|
let total = system.total_memory();
|
|
let mut h = Hardware {
|
|
schema_version: 1,
|
|
sampled_at_unix_ms: SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map(|t| t.as_millis() as u64)
|
|
.unwrap_or(0),
|
|
os: std::env::consts::OS.into(),
|
|
architecture: std::env::consts::ARCH.into(),
|
|
cpu_name: system
|
|
.cpus()
|
|
.first()
|
|
.map(|c| c.brand().to_owned())
|
|
.unwrap_or_default(),
|
|
logical_cpus: system.cpus().len(),
|
|
cpu_features: cpu_features(),
|
|
memory: Memory {
|
|
total_bytes: (total > 0).then_some(total),
|
|
available_bytes: (total > 0).then_some(system.available_memory().min(total)),
|
|
},
|
|
accelerators: vec![],
|
|
warnings: vec![
|
|
"NPU and inference provider availability are not probed in this version.".into(),
|
|
],
|
|
};
|
|
if cfg!(target_os = "macos") {
|
|
match probe(
|
|
"/usr/sbin/system_profiler",
|
|
&["SPDisplaysDataType", "-json"],
|
|
Duration::from_secs(5),
|
|
)
|
|
.await
|
|
{
|
|
Ok(data) => match parse_macos(&data, cfg!(target_arch = "aarch64")) {
|
|
Ok(gpus) => h.accelerators = gpus,
|
|
Err(e) => h.warnings.push(e),
|
|
},
|
|
Err(e) => h.warnings.push(format!("Apple display inventory: {e}")),
|
|
}
|
|
} else {
|
|
match probe(
|
|
"nvidia-smi",
|
|
&[
|
|
"--query-gpu=name,memory.total,memory.free,driver_version",
|
|
"--format=csv,noheader,nounits",
|
|
],
|
|
Duration::from_secs(3),
|
|
)
|
|
.await
|
|
{
|
|
Ok(data) => match parse_nvidia(&data) {
|
|
Ok(gpus) => h.accelerators = gpus,
|
|
Err(e) => h.warnings.push(e),
|
|
},
|
|
Err(e) => h
|
|
.warnings
|
|
.push(format!("NVIDIA inventory unavailable: {e}")),
|
|
}
|
|
h.warnings.push(
|
|
"Non-NVIDIA GPU inventory is not implemented; an empty list does not mean no GPU."
|
|
.into(),
|
|
);
|
|
}
|
|
h
|
|
}
|
|
|
|
fn cpu_features() -> Vec<String> {
|
|
let mut result = Vec::new();
|
|
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
|
{
|
|
if std::is_x86_feature_detected!("avx2") {
|
|
result.push("avx2".into());
|
|
}
|
|
if std::is_x86_feature_detected!("avx512f") {
|
|
result.push("avx512f".into());
|
|
}
|
|
if std::is_x86_feature_detected!("fma") {
|
|
result.push("fma".into());
|
|
}
|
|
}
|
|
#[cfg(target_arch = "aarch64")]
|
|
{
|
|
if std::arch::is_aarch64_feature_detected!("neon") {
|
|
result.push("neon".into());
|
|
}
|
|
if std::arch::is_aarch64_feature_detected!("dotprod") {
|
|
result.push("dotprod".into());
|
|
}
|
|
}
|
|
result
|
|
}
|
|
|
|
/// Fixed program/arguments from inventory only; no shell, prompts or process list.
|
|
async fn probe(program: &str, args: &[&str], limit: Duration) -> Result<String, String> {
|
|
let mut child = Command::new(program)
|
|
.args(args)
|
|
.stdin(Stdio::null())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::null())
|
|
.kill_on_drop(true)
|
|
.spawn()
|
|
.map_err(|_| "probe could not start".to_string())?;
|
|
let stdout = child.stdout.take().ok_or("missing probe output")?;
|
|
let mut data = Vec::new();
|
|
let read = async {
|
|
stdout
|
|
.take(65537)
|
|
.read_to_end(&mut data)
|
|
.await
|
|
.map_err(|_| "probe read failed")?;
|
|
if data.len() > 65536 {
|
|
return Err("probe output too large");
|
|
}
|
|
let status = child.wait().await.map_err(|_| "probe wait failed")?;
|
|
if !status.success() {
|
|
return Err("probe exited unsuccessfully");
|
|
}
|
|
Ok(())
|
|
};
|
|
match tokio::time::timeout(limit, read).await {
|
|
Ok(Ok(())) => String::from_utf8(data).map_err(|_| "probe output is not UTF-8".into()),
|
|
outcome => {
|
|
let _ = child.kill().await;
|
|
Err(match outcome {
|
|
Ok(Err(e)) => e,
|
|
_ => "probe timed out",
|
|
}
|
|
.into())
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn parse_nvidia(data: &str) -> Result<Vec<Accelerator>, String> {
|
|
data.lines()
|
|
.filter(|l| !l.trim().is_empty())
|
|
.enumerate()
|
|
.map(|(i, line)| {
|
|
let parts: Vec<_> = line.split(',').map(str::trim).collect();
|
|
if parts.len() != 4 {
|
|
return Err("invalid NVIDIA inventory row".into());
|
|
}
|
|
let mib = |s: &str| {
|
|
s.parse::<u64>()
|
|
.ok()
|
|
.and_then(|n| n.checked_mul(1024 * 1024))
|
|
};
|
|
let total = mib(parts[1]);
|
|
let free = mib(parts[2]);
|
|
if let (Some(t), Some(f)) = (total, free)
|
|
&& f > t
|
|
{
|
|
return Err("inconsistent NVIDIA memory".into());
|
|
}
|
|
Ok(Accelerator {
|
|
id: format!("nvidia-{i}"),
|
|
name: parts[0].into(),
|
|
vendor: "NVIDIA".into(),
|
|
memory_kind: MemoryKind::Dedicated,
|
|
memory: Memory {
|
|
total_bytes: total,
|
|
available_bytes: free,
|
|
},
|
|
driver: (!parts[3].is_empty()).then(|| parts[3].into()),
|
|
source: "nvidia-smi".into(),
|
|
})
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn parse_macos(data: &str, apple_silicon: bool) -> Result<Vec<Accelerator>, String> {
|
|
let value: serde_json::Value =
|
|
serde_json::from_str(data).map_err(|_| "invalid display JSON")?;
|
|
let rows = value
|
|
.get("SPDisplaysDataType")
|
|
.and_then(|v| v.as_array())
|
|
.ok_or("missing display inventory")?;
|
|
Ok(rows
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(i, r)| {
|
|
let name = r.get("sppci_model").or_else(|| r.get("_name"))?.as_str()?;
|
|
Some(Accelerator {
|
|
id: format!("display-{i}"),
|
|
name: name.into(),
|
|
vendor: if apple_silicon { "Apple" } else { "unknown" }.into(),
|
|
memory_kind: if apple_silicon {
|
|
MemoryKind::Shared
|
|
} else {
|
|
MemoryKind::Unknown
|
|
},
|
|
memory: Memory {
|
|
total_bytes: None,
|
|
available_bytes: None,
|
|
},
|
|
driver: None,
|
|
source: "system_profiler".into(),
|
|
})
|
|
})
|
|
.collect())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn nvidia_unknown_is_not_zero_and_mib_is_binary() {
|
|
let g = parse_nvidia("RTX test, 8192, 7168, 580.65.06\nGPU test, [N/A], [N/A], unknown")
|
|
.unwrap();
|
|
assert_eq!(g[0].memory.total_bytes, Some(8 * 1024 * 1024 * 1024));
|
|
assert_eq!(g[1].memory.available_bytes, None);
|
|
assert!(parse_nvidia("GPU, 1, 2, v").is_err());
|
|
}
|
|
#[test]
|
|
fn shared_gpu_does_not_invent_a_second_ram_pool() {
|
|
let g = parse_macos(
|
|
r#"{"SPDisplaysDataType":[{"sppci_model":"Apple test"}]}"#,
|
|
true,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(g[0].memory_kind, MemoryKind::Shared);
|
|
assert_eq!(g[0].memory.available_bytes, None);
|
|
}
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn command_timeout_is_bounded() {
|
|
let start = std::time::Instant::now();
|
|
assert_eq!(
|
|
probe("/bin/sleep", &["5"], Duration::from_millis(20))
|
|
.await
|
|
.unwrap_err(),
|
|
"probe timed out"
|
|
);
|
|
assert!(start.elapsed() < Duration::from_secs(2));
|
|
}
|
|
}
|