use core::time::Duration;
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use crate::{
Error, Result, cpu,
disk::{self, Disk, ListOptions},
host::Processes,
linux::{self as tree, Root},
mem::{self, MemWant},
net,
origin::{Host, Origin},
};
const MAX_PROCESSES: u64 = 4_000_000;
#[derive(Clone, Debug)]
pub struct Probe {
host: Arc<Host>,
base: PathBuf,
mountinfo: &'static str,
}
impl Probe {
pub fn with_root(root: impl Into<PathBuf>) -> Result<Probe> {
let base: PathBuf = root.into();
let tree = Root::at(&base);
if tree.text("/proc/stat").is_none() {
return Err(Error::NotFound {
what: "probe root",
source: "<root>/proc/stat",
});
}
let net_dev = if tree.exists("/proc/1/net/dev") {
"/proc/1/net/dev"
} else {
"/proc/net/dev"
};
let mountinfo = if tree.exists("/proc/1/mountinfo") {
"/proc/1/mountinfo"
} else {
"/proc/self/mountinfo"
};
Ok(Probe {
host: Arc::new(Host {
root: tree,
net_dev,
}),
base,
mountinfo,
})
}
fn root(&self) -> &Root {
&self.host.root
}
fn origin(&self) -> Origin {
Origin::host(Arc::clone(&self.host))
}
pub fn memory(&self) -> Result<mem::Memory> {
tree::mem::read(self.root(), None, false, MemWant::ALL).map(mem::from_raw)
}
pub fn cpu_sampler(&self) -> Result<cpu::Sampler> {
cpu::Sampler::from(self.origin())
}
pub fn load(&self) -> Result<Option<cpu::Load>> {
tree::stat::load(self.root())
}
pub fn uptime(&self) -> Result<Duration> {
tree::stat::uptime(self.root())
}
pub fn disks(&self) -> Result<Vec<Disk>> {
let mounts = tree::disk::mounts_at(self.root(), self.mountinfo, &ListOptions::default())?;
Ok(mounts
.into_iter()
.map(|m| {
let inside = self.base.join(
m.mount_point
.strip_prefix("/")
.unwrap_or(Path::new(&m.mount_point)),
);
Disk {
space: crate::sys::disk_space(&inside).ok(),
mount_point: m.mount_point,
device: m.device,
label: None,
filesystem: m.filesystem,
kind: m.kind,
read_only: m.read_only,
removable: m.removable,
}
})
.collect())
}
pub fn disk_io(&self) -> Result<disk::IoSampler> {
disk::IoSampler::from(self.origin())
}
pub fn net(&self) -> Result<net::Sampler> {
net::Sampler::from(self.origin())
}
pub fn processes(&self) -> Result<Processes> {
let total = self.root().count_entries("/proc", MAX_PROCESSES, |name| {
name.bytes().all(|b| b.is_ascii_digit())
})?;
Ok(Processes {
total,
threads: tree::stat::threads(self.root()),
running: tree::stat::procs_running(self.root()),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::linux::fixtures;
fn fixture() -> PathBuf {
PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/wsl2"))
}
#[test]
fn test_probe_rejects_a_root_without_proc() {
let err = Probe::with_root(std::env::temp_dir().join("sys-lib-no-such-root")).unwrap_err();
assert!(matches!(err, Error::NotFound { .. }), "{err}");
}
#[test]
fn test_probe_reads_a_fixture_host() {
let p = Probe::with_root(fixture()).unwrap();
let m = p.memory().unwrap();
let expect = tree::mem::read(&fixtures::root("wsl2"), None, false, MemWant::ALL)
.map(mem::from_raw)
.unwrap();
assert_eq!(m.total, expect.total);
assert!(p.load().unwrap().is_some());
assert!(p.uptime().unwrap() > Duration::ZERO);
let mut s = p.cpu_sampler().unwrap();
assert!(matches!(s.sample(), Err(Error::TooSoon { .. })));
assert!(p.disk_io().is_ok());
assert!(p.net().is_ok());
assert!(p.processes().is_ok());
let _ = p.disks();
}
}