Files
leleka/crates/deploy/src/facts.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 d84e1a12c9 feat(deploy): leleka up/run - preflight, profiles, assets, install, supervisor, readiness
New crate leleka-deploy (binary leleka): idempotent one-command deployment with
preflight (driver, sm_120/sm_86, VRAM/RAM/disk, WSL2, cuBLAS 12, memfd), memory
profiles, plan/dry-run, stamped asset steps, systemd unit, and a native supervisor
that seals the KAR archive itself and hands it to the engine (no Python holder).
leleka-inference gains --kar-archive-file for the low-RAM read-only archive form.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 14:34:49 +02:00

511 lines
18 KiB
Rust

//! Host facts for the preflight: pure parsers (unit-tested on any OS) and a Linux probe that fills `Facts`.
//!
//! `Facts` is plain data so that `preflight::evaluate` can be tested with synthetic hosts. Nothing here creates
//! a CUDA context; the GPU is read through `nvidia-smi`.
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Gpu {
pub index: u32,
pub name: String,
pub driver: String,
pub vram_total_mib: u64,
pub vram_free_mib: u64,
/// Compute capability times ten (12.0 -> 120, 8.6 -> 86).
pub sm: Option<u32>,
}
impl Gpu {
pub fn driver_major(&self) -> Option<u32> {
self.driver.split('.').next()?.parse().ok()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Memory {
pub total: u64,
pub available: u64,
pub swap_total: u64,
}
/// What `probe` reads about one directory the deployment will write to.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DirFact {
pub path: PathBuf,
/// Free bytes of the file system that holds (or would hold) the directory.
pub free_bytes: Option<u64>,
/// File system type of the mount that holds it (`ext4`, `9p`, `drvfs`, ...).
pub fs_type: Option<String>,
}
#[derive(Clone, Debug, Default)]
pub struct Facts {
pub os: String,
pub arch: String,
pub root: bool,
pub nvidia_smi_found: bool,
pub nvidia_smi_error: Option<String>,
pub gpus: Vec<Gpu>,
pub memory: Memory,
/// `memory.max` of the cgroup this process runs in, when limited.
pub cgroup_memory_max: Option<u64>,
pub wsl: bool,
pub systemd_system: bool,
pub proc_fd: bool,
pub memfd_ok: bool,
pub libs: BTreeMap<String, Option<PathBuf>>,
pub tools: BTreeMap<String, bool>,
pub dirs: BTreeMap<String, DirFact>,
pub busy_ports: Vec<u16>,
pub binaries: BTreeMap<String, bool>,
pub hf_token_set: bool,
}
impl Facts {
pub fn lib(&self, soname: &str) -> Option<&PathBuf> {
self.libs.get(soname).and_then(Option::as_ref)
}
pub fn tool(&self, name: &str) -> bool {
self.tools.get(name).copied().unwrap_or(false)
}
}
/// `nvidia-smi --query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap --format=csv,noheader,nounits`.
/// A missing or "[N/A]" compute capability falls back to a name table so older drivers still classify.
pub fn parse_nvidia_smi(csv: &str) -> Vec<Gpu> {
csv.lines()
.filter_map(|line| {
let fields: Vec<&str> = line.split(',').map(str::trim).collect();
if fields.len() < 5 {
return None;
}
let index = fields[0].parse().ok()?;
let name = fields[1].to_owned();
let sm = fields
.get(5)
.and_then(|cc| parse_compute_capability(cc))
.or_else(|| sm_from_name(&name));
Some(Gpu {
index,
driver: fields[2].to_owned(),
vram_total_mib: fields[3].parse().ok()?,
vram_free_mib: fields[4].parse().ok()?,
name,
sm,
})
})
.collect()
}
pub fn parse_compute_capability(text: &str) -> Option<u32> {
let (major, minor) = text.trim().split_once('.')?;
let (major, minor): (u32, u32) = (major.parse().ok()?, minor.parse().ok()?);
(minor < 10).then_some(major * 10 + minor)
}
fn sm_from_name(name: &str) -> Option<u32> {
const TABLE: [(&str, u32); 8] = [
("RTX 50", 120),
("RTX 40", 89),
("RTX 3090", 86),
("RTX 30", 86),
("RTX 20", 75),
("A100", 80),
("H100", 90),
("L40", 89),
];
TABLE
.iter()
.find(|(needle, _)| name.contains(needle))
.map(|(_, sm)| *sm)
}
/// `/proc/meminfo` in bytes. `MemAvailable` is required; a kernel without it yields zeros (the caller fails closed).
pub fn parse_meminfo(text: &str) -> Memory {
let value = |key: &str| -> u64 {
text.lines()
.find_map(|line| line.strip_prefix(key)?.strip_prefix(':'))
.and_then(|rest| rest.split_whitespace().next()?.parse::<u64>().ok())
.map_or(0, |kib| kib.saturating_mul(1024))
};
Memory {
total: value("MemTotal"),
available: value("MemAvailable"),
swap_total: value("SwapTotal"),
}
}
/// WSL2 identifies itself in the kernel version string (`...-microsoft-standard-WSL2`).
pub fn is_wsl(proc_version: &str) -> bool {
let lower = proc_version.to_ascii_lowercase();
lower.contains("microsoft") || lower.contains("wsl")
}
/// `memory.max` content: a byte count, or `max` for unlimited.
pub fn parse_cgroup_max(text: &str) -> Option<u64> {
text.trim().parse().ok()
}
/// File system type of the longest mount point that contains `path` (`/proc/mounts` format).
pub fn fs_type_for(mounts: &str, path: &Path) -> Option<String> {
let mut best: Option<(usize, String)> = None;
for line in mounts.lines() {
let mut fields = line.split_whitespace();
let (Some(_device), Some(mount), Some(kind)) =
(fields.next(), fields.next(), fields.next())
else {
continue;
};
let mount = mount.replace("\\040", " ");
let mount_path = Path::new(&mount);
if path.starts_with(mount_path) && best.as_ref().is_none_or(|(len, _)| mount.len() >= *len)
{
best = Some((mount.len(), kind.to_owned()));
}
}
best.map(|(_, kind)| kind)
}
/// File system types that are a Windows drive or a network share seen from WSL: far too slow for mapped reads.
pub fn is_slow_foreign_fs(kind: &str) -> bool {
matches!(
kind,
"9p" | "drvfs" | "virtiofs" | "cifs" | "smb3" | "nfs" | "nfs4" | "fuse.sshfs"
)
}
/// First directory in `dirs` that holds a file called `soname`, or the `ldconfig -p` entry for it.
pub fn find_library(soname: &str, dirs: &[PathBuf], ldconfig: &str) -> Option<PathBuf> {
for dir in dirs {
let candidate = dir.join(soname);
if candidate.exists() {
return Some(candidate);
}
}
ldconfig.lines().find_map(|line| {
let line = line.trim();
let (name, rest) = line.split_once(" (")?;
if name.trim() != soname {
return None;
}
let path = rest.split_once("=>")?.1.trim();
Some(PathBuf::from(path))
})
}
/// Parse `KEY=VALUE` lines of an environment file (systemd `EnvironmentFile` subset: no export, `#` comments).
pub fn parse_env_file(text: &str) -> BTreeMap<String, String> {
text.lines()
.filter_map(|line| {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return None;
}
let (key, value) = line.split_once('=')?;
let key = key.trim();
if key.is_empty() || !key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return None;
}
let value = value.trim();
let value = value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.unwrap_or(value);
Some((key.to_owned(), value.to_owned()))
})
.collect()
}
/// What `probe` must look at beyond the machine itself.
#[derive(Clone, Debug, Default)]
pub struct ProbeRequest {
pub dirs: Vec<(String, PathBuf)>,
pub ports: Vec<u16>,
pub binary_dir: Option<PathBuf>,
pub binaries: Vec<String>,
pub extra_library_dirs: Vec<PathBuf>,
}
#[cfg(target_os = "linux")]
pub fn probe(request: &ProbeRequest) -> Facts {
linux::probe(request)
}
#[cfg(not(target_os = "linux"))]
pub fn probe(_request: &ProbeRequest) -> Facts {
Facts {
os: std::env::consts::OS.to_owned(),
arch: std::env::consts::ARCH.to_owned(),
..Facts::default()
}
}
#[cfg(target_os = "linux")]
mod linux {
use super::*;
use std::{net::TcpListener, process::Command};
fn read(path: &str) -> String {
std::fs::read_to_string(path).unwrap_or_default()
}
fn which(name: &str, extra: &[&str]) -> Option<PathBuf> {
let path = std::env::var_os("PATH").unwrap_or_default();
std::env::split_paths(&path)
.chain(extra.iter().map(PathBuf::from))
.map(|dir| dir.join(name))
.find(|candidate| candidate.is_file())
}
fn nearest_existing(path: &Path) -> PathBuf {
let mut current = path.to_path_buf();
while !current.exists() {
if !current.pop() {
return PathBuf::from("/");
}
}
current
}
fn free_bytes(path: &Path) -> Option<u64> {
let stat = rustix::fs::statvfs(nearest_existing(path)).ok()?;
Some(stat.f_bavail.saturating_mul(stat.f_frsize))
}
fn memfd_works() -> bool {
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create};
let Ok(fd) = memfd_create(
"leleka-preflight",
MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC,
) else {
return false;
};
fcntl_add_seals(&fd, SealFlags::SEAL).is_ok()
}
pub fn probe(request: &ProbeRequest) -> Facts {
let mut facts = Facts {
os: std::env::consts::OS.to_owned(),
arch: std::env::consts::ARCH.to_owned(),
root: rustix::process::geteuid().is_root(),
hf_token_set: std::env::var_os("HF_TOKEN").is_some_and(|v| !v.is_empty()),
..Facts::default()
};
facts.wsl = is_wsl(&read("/proc/version"));
facts.memory = parse_meminfo(&read("/proc/meminfo"));
facts.cgroup_memory_max = parse_cgroup_max(&read("/sys/fs/cgroup/memory.max"));
facts.systemd_system = Path::new("/run/systemd/system").is_dir();
facts.proc_fd = Path::new("/proc/self/fd").is_dir();
facts.memfd_ok = memfd_works();
let smi = which(
"nvidia-smi",
&["/usr/lib/wsl/lib", "/usr/bin", "/usr/local/bin"],
);
match smi {
None => {
facts.nvidia_smi_error = Some("nvidia-smi was not found in PATH".into());
}
Some(smi) => {
facts.nvidia_smi_found = true;
match Command::new(smi)
.args([
"--query-gpu=index,name,driver_version,memory.total,memory.free,compute_cap",
"--format=csv,noheader,nounits",
])
.output()
{
Ok(output) if output.status.success() => {
facts.gpus = parse_nvidia_smi(&String::from_utf8_lossy(&output.stdout));
}
Ok(output) => {
// compute_cap is unknown to old drivers: retry without it.
let retry = Command::new("nvidia-smi")
.args([
"--query-gpu=index,name,driver_version,memory.total,memory.free",
"--format=csv,noheader,nounits",
])
.output();
match retry {
Ok(second) if second.status.success() => {
facts.gpus =
parse_nvidia_smi(&String::from_utf8_lossy(&second.stdout));
}
_ => {
let text = String::from_utf8_lossy(&output.stderr);
facts.nvidia_smi_error =
Some(text.lines().next().unwrap_or("nvidia-smi failed").to_owned());
}
}
}
Err(error) => facts.nvidia_smi_error = Some(error.to_string()),
}
}
}
let ldconfig = Command::new("ldconfig")
.arg("-p")
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
.unwrap_or_default();
let mut library_dirs: Vec<PathBuf> = request.extra_library_dirs.clone();
if let Some(paths) = std::env::var_os("LD_LIBRARY_PATH") {
library_dirs
.extend(std::env::split_paths(&paths).filter(|p| !p.as_os_str().is_empty()));
}
for fixed in [
"/usr/lib/wsl/lib",
"/usr/local/cuda/lib64",
"/usr/lib/x86_64-linux-gnu",
"/usr/lib64",
] {
library_dirs.push(PathBuf::from(fixed));
}
for soname in ["libcuda.so.1", "libcublas.so.12", "libcublasLt.so.12"] {
facts.libs.insert(
soname.to_owned(),
find_library(soname, &library_dirs, &ldconfig),
);
}
for tool in ["curl", "wget", "tar", "xz", "systemctl", "ldd"] {
facts.tools.insert(
tool.to_owned(),
which(tool, &["/usr/sbin", "/sbin"]).is_some(),
);
}
let mounts = read("/proc/mounts");
for (key, path) in &request.dirs {
facts.dirs.insert(
key.clone(),
DirFact {
path: path.clone(),
free_bytes: free_bytes(path),
fs_type: fs_type_for(&mounts, &nearest_existing(path)),
},
);
}
for port in &request.ports {
if TcpListener::bind(("127.0.0.1", *port)).is_err() {
facts.busy_ports.push(*port);
}
}
if let Some(dir) = &request.binary_dir {
for name in &request.binaries {
facts
.binaries
.insert(name.clone(), is_executable(&dir.join(name)));
}
}
facts
}
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
path.metadata()
.is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nvidia_smi_csv_for_server_and_laptop() {
let server =
parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, 12.0\n");
assert_eq!(server.len(), 1);
assert_eq!(server[0].sm, Some(120));
assert_eq!(server[0].driver_major(), Some(595));
assert_eq!(server[0].vram_free_mib, 32105);
let laptop =
parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234, 8.6\n");
assert_eq!(laptop[0].sm, Some(86));
assert_eq!(laptop[0].driver_major(), Some(617));
}
#[test]
fn missing_compute_capability_falls_back_to_the_name_table() {
let gpus =
parse_nvidia_smi("0, NVIDIA GeForce RTX 3080 Laptop GPU, 617.42, 16384, 15234\n");
assert_eq!(gpus[0].sm, Some(86));
let gpus = parse_nvidia_smi("0, NVIDIA GeForce RTX 5090, 595.99.02, 32607, 32105, [N/A]\n");
assert_eq!(gpus[0].sm, Some(120));
let gpus = parse_nvidia_smi("0, Mystery Board, 595.1, 8000, 8000, [N/A]\n");
assert_eq!(gpus[0].sm, None);
assert!(parse_nvidia_smi("garbage\n\n").is_empty());
}
#[test]
fn meminfo_bytes() {
let memory = parse_meminfo(
"MemTotal: 24447308 kB\nMemFree: 1 kB\nMemAvailable: 22000000 kB\nSwapTotal: 2097152 kB\n",
);
assert_eq!(memory.total, 24_447_308 * 1024);
assert_eq!(memory.available, 22_000_000 * 1024);
assert_eq!(memory.swap_total, 2_097_152 * 1024);
assert_eq!(parse_meminfo("nothing"), Memory::default());
}
#[test]
fn wsl_and_cgroup_detection() {
assert!(is_wsl(
"Linux version 5.15.167.4-microsoft-standard-WSL2 (root@x) (gcc)"
));
assert!(!is_wsl(
"Linux version 7.0.0-38-generic (buildd@lcy02) (gcc)"
));
assert_eq!(parse_cgroup_max("max\n"), None);
assert_eq!(parse_cgroup_max("68719476736\n"), Some(68_719_476_736));
}
#[test]
fn filesystem_type_uses_the_longest_mount_prefix() {
let mounts =
"/dev/sdc / ext4 rw 0 0\nC:\\134 /mnt/c 9p rw 0 0\n/dev/sdd /mnt/c/data ext4 rw 0 0\n";
assert_eq!(
fs_type_for(mounts, Path::new("/mnt/c/Users/x")).as_deref(),
Some("9p")
);
assert_eq!(
fs_type_for(mounts, Path::new("/mnt/c/data/models")).as_deref(),
Some("ext4")
);
assert_eq!(
fs_type_for(mounts, Path::new("/home/x")).as_deref(),
Some("ext4")
);
assert!(is_slow_foreign_fs("9p") && !is_slow_foreign_fs("ext4"));
}
#[test]
fn library_lookup_prefers_directories_then_ldconfig() {
let ldconfig = "\tlibcublas.so.12 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcublas.so.12\n\tlibcublasLt.so.13 (libc6,x86-64) => /usr/lib/libcublasLt.so.13\n";
assert_eq!(
find_library("libcublas.so.12", &[], ldconfig),
Some(PathBuf::from("/usr/lib/x86_64-linux-gnu/libcublas.so.12"))
);
assert_eq!(find_library("libcublasLt.so.12", &[], ldconfig), None);
}
#[test]
fn env_file_parser_handles_comments_and_quotes() {
let env = parse_env_file(
"# c\nA=1\n B = \"two words\" \nbad key=3\nexport X=1\nLD_LIBRARY_PATH=/a:/b\n",
);
assert_eq!(env.get("A").map(String::as_str), Some("1"));
assert_eq!(env.get("B").map(String::as_str), Some("two words"));
assert_eq!(
env.get("LD_LIBRARY_PATH").map(String::as_str),
Some("/a:/b")
);
assert!(!env.contains_key("bad key"));
assert!(!env.contains_key("export X"));
}
}