Something went wrong. Try again.
usage — Vidya I/O gauges for disk & network throughput
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441//! Sample Linux disk, network, and per-process I/O counters from `/proc`.
use std::collections::{BTreeMap, HashMap};use std::fs;use std::time::Instant;
/// Raw cumulative counters for one block device or net interface.#[derive(Debug, Clone, Default)]pub struct Counters { pub read_bytes: u64, pub write_bytes: u64,}
/// Instantaneous rates (bytes per second) after a delta sample.#[derive(Debug, Clone, Default)]pub struct Rates { pub read_bps: f64, pub write_bps: f64,}
/// One named source (disk or iface) with live rates.#[derive(Debug, Clone)]pub struct DeviceIo { pub name: String, pub rates: Rates,}
/// Per-process disk I/O activity (from `/proc/[pid]/io`).#[derive(Debug, Clone)]pub struct ProcIo { pub pid: u32, pub name: String, /// Executable path (`/proc/[pid]/exe` or cmdline argv0). pub path: String, /// Storage read rate (`read_bytes` delta / s). pub read_bps: f64, /// Storage write rate (`write_bytes` delta / s). pub write_bps: f64, /// Write syscall rate (`syscw` delta / s) — write frequency. pub write_freq: f64,}
#[derive(Debug, Clone, Default)]struct ProcCounters { read_bytes: u64, write_bytes: u64, syscw: u64, name: String, path: String,}
/// Full system snapshot of I/O rates.#[derive(Debug, Clone, Default)]pub struct IoSnapshot { pub disk_total: Rates, pub net_total: Rates, pub disks: Vec<DeviceIo>, pub nets: Vec<DeviceIo>, /// Processes sorted by write rate (highest first). pub processes: Vec<ProcIo>,}
#[derive(Default)]pub struct IoSampler { prev_disks: BTreeMap<String, Counters>, prev_nets: BTreeMap<String, Counters>, prev_procs: HashMap<u32, ProcCounters>, prev_at: Option<Instant>,}
impl IoSampler { pub fn new() -> Self { Self::default() }
/// Read counters, compute rates vs previous sample, store for next call. pub fn sample(&mut self) -> IoSnapshot { let now = Instant::now(); let disks = read_disk_counters(); let nets = read_net_counters(); let procs = read_proc_counters();
let dt = self .prev_at .map(|t| now.duration_since(t).as_secs_f64()) .filter(|&d| d > 0.0) .unwrap_or(0.0);
let disk_devices = rates_for(&disks, &self.prev_disks, dt); let net_devices = rates_for(&nets, &self.prev_nets, dt); let processes = proc_rates(&procs, &self.prev_procs, dt);
let disk_total = sum_rates(&disk_devices); let net_total = sum_rates(&net_devices);
self.prev_disks = disks; self.prev_nets = nets; self.prev_procs = procs; self.prev_at = Some(now);
IoSnapshot { disk_total, net_total, disks: disk_devices, nets: net_devices, processes, } }}
fn rates_for( current: &BTreeMap<String, Counters>, prev: &BTreeMap<String, Counters>, dt: f64,) -> Vec<DeviceIo> { let mut out: Vec<DeviceIo> = current .iter() .map(|(name, c)| { let rates = if dt > 0.0 { if let Some(p) = prev.get(name) { Rates { read_bps: delta_bps(p.read_bytes, c.read_bytes, dt), write_bps: delta_bps(p.write_bytes, c.write_bytes, dt), } } else { Rates::default() } } else { Rates::default() }; DeviceIo { name: name.clone(), rates, } }) .collect(); out.sort_by(|a, b| { let ta = a.rates.read_bps + a.rates.write_bps; let tb = b.rates.read_bps + b.rates.write_bps; tb.partial_cmp(&ta).unwrap_or(std::cmp::Ordering::Equal) }); out}
fn sum_rates(devices: &[DeviceIo]) -> Rates { devices.iter().fold(Rates::default(), |acc, d| Rates { read_bps: acc.read_bps + d.rates.read_bps, write_bps: acc.write_bps + d.rates.write_bps, })}
fn delta_bps(prev: u64, cur: u64, dt: f64) -> f64 { if cur < prev || dt <= 0.0 { return 0.0; } (cur - prev) as f64 / dt}
/// Whole disks only (skip partitions, loop, ram, zram, md partitions-ish).fn read_disk_counters() -> BTreeMap<String, Counters> { let Ok(raw) = fs::read_to_string("/proc/diskstats") else { return BTreeMap::new(); }; let mut map = BTreeMap::new(); for line in raw.lines() { let fields: Vec<&str> = line.split_whitespace().collect(); // major minor name reads … sectors_read … writes … sectors_written if fields.len() < 14 { continue; } let name = fields[2]; if !is_whole_disk(name) { continue; } // fields[5] = sectors read, fields[9] = sectors written (512-byte) let sectors_read: u64 = fields[5].parse().unwrap_or(0); let sectors_written: u64 = fields[9].parse().unwrap_or(0); map.insert( name.to_string(), Counters { read_bytes: sectors_read.saturating_mul(512), write_bytes: sectors_written.saturating_mul(512), }, ); } map}
fn is_whole_disk(name: &str) -> bool { if name.starts_with("loop") || name.starts_with("ram") || name.starts_with("zram") || name.starts_with("sr") || name.starts_with("fd") || name.starts_with("dm-") || name.starts_with("md") || name.starts_with("nbd") { return false; } // Skip partitions: sda1, nvme0n1p1,mmcblk0p1 — keep sda, nvme0n1, mmcblk0 if name.chars().last().is_some_and(|c| c.is_ascii_digit()) { // nvme0n1 is a whole disk ending in digit if name.contains("nvme") && name.contains('n') && !name.contains('p') { return true; } // mmcblk0 whole; mmcblk0p1 partition if name.starts_with("mmcblk") && !name.contains('p') { return true; } // sda1, vda2, xvda3 → partition return false; } true}
fn read_net_counters() -> BTreeMap<String, Counters> { let Ok(raw) = fs::read_to_string("/proc/net/dev") else { return BTreeMap::new(); }; let mut map = BTreeMap::new(); for line in raw.lines().skip(2) { let line = line.trim(); let Some((iface, rest)) = line.split_once(':') else { continue; }; let iface = iface.trim(); if iface == "lo" || iface.starts_with("docker") || iface.starts_with("veth") || iface.starts_with("br-") || iface.starts_with("virbr") { continue; } let fields: Vec<&str> = rest.split_whitespace().collect(); if fields.len() < 9 { continue; } let rx: u64 = fields[0].parse().unwrap_or(0); let tx: u64 = fields[8].parse().unwrap_or(0); // Skip idle virtual ifaces that never moved (still show active ones) map.insert( iface.to_string(), Counters { read_bytes: rx, write_bytes: tx, }, ); } map}
fn proc_rates( current: &HashMap<u32, ProcCounters>, prev: &HashMap<u32, ProcCounters>, dt: f64,) -> Vec<ProcIo> { let mut out: Vec<ProcIo> = current .iter() .map(|(&pid, c)| { let (read_bps, write_bps, write_freq) = if dt > 0.0 { if let Some(p) = prev.get(&pid) { ( delta_bps(p.read_bytes, c.read_bytes, dt), delta_bps(p.write_bytes, c.write_bytes, dt), delta_bps(p.syscw, c.syscw, dt), ) } else { (0.0, 0.0, 0.0) } } else { (0.0, 0.0, 0.0) }; ProcIo { pid, name: c.name.clone(), path: c.path.clone(), read_bps, write_bps, write_freq, } }) .collect(); // Highest write throughput first; break ties on write frequency / read. out.sort_by(|a, b| { b.write_bps .partial_cmp(&a.write_bps) .unwrap_or(std::cmp::Ordering::Equal) .then_with(|| { b.write_freq .partial_cmp(&a.write_freq) .unwrap_or(std::cmp::Ordering::Equal) }) .then_with(|| { b.read_bps .partial_cmp(&a.read_bps) .unwrap_or(std::cmp::Ordering::Equal) }) .then_with(|| a.pid.cmp(&b.pid)) }); out}
/// Process with the highest storage read rate this sample.pub fn top_reader(procs: &[ProcIo]) -> Option<&ProcIo> { procs .iter() .filter(|p| p.read_bps > 0.0) .max_by(|a, b| { a.read_bps .partial_cmp(&b.read_bps) .unwrap_or(std::cmp::Ordering::Equal) })}
/// Process with the highest storage write rate this sample.pub fn top_writer(procs: &[ProcIo]) -> Option<&ProcIo> { procs .iter() .filter(|p| p.write_bps > 0.0) .max_by(|a, b| { a.write_bps .partial_cmp(&b.write_bps) .unwrap_or(std::cmp::Ordering::Equal) })}
/// Enumerate `/proc/[pid]/io` + command name.fn read_proc_counters() -> HashMap<u32, ProcCounters> { let Ok(entries) = fs::read_dir("/proc") else { return HashMap::new(); }; let mut map = HashMap::new(); for ent in entries.flatten() { let name = ent.file_name(); let name = name.to_string_lossy(); let Ok(pid) = name.parse::<u32>() else { continue; }; let base = ent.path(); let Ok(io_raw) = fs::read_to_string(base.join("io")) else { // Other users' processes often deny access without elevated caps. continue; }; let mut read_bytes = 0u64; let mut write_bytes = 0u64; let mut syscw = 0u64; for line in io_raw.lines() { if let Some(v) = line.strip_prefix("read_bytes:") { read_bytes = v.trim().parse().unwrap_or(0); } else if let Some(v) = line.strip_prefix("write_bytes:") { write_bytes = v.trim().parse().unwrap_or(0); } else if let Some(v) = line.strip_prefix("syscw:") { syscw = v.trim().parse().unwrap_or(0); } } let comm = fs::read_to_string(base.join("comm")) .map(|s| s.trim().to_string()) .unwrap_or_else(|_| format!("[{pid}]"));
// Full path: prefer resolved /proc/[pid]/exe, else argv0 from cmdline. let exe_path = fs::read_link(base.join("exe")) .ok() .map(|p| p.to_string_lossy().into_owned()) .filter(|s| !s.is_empty()); let cmdline0 = match fs::read(base.join("cmdline")) { Ok(bytes) if !bytes.is_empty() => { let first = bytes.split(|&b| b == 0).next().unwrap_or(&bytes); let s = String::from_utf8_lossy(first).trim().to_string(); if s.is_empty() { None } else { Some(s) } } _ => None, }; let path = exe_path .or_else(|| cmdline0.clone()) .unwrap_or_default(); // Short name for the Name column (basename of path or comm). let name = if !path.is_empty() { path.rsplit('/').next().unwrap_or(&path).to_string() } else { comm }; // If basename still has spaces (rare), take first token. let name = name .split_whitespace() .next() .unwrap_or(&name) .to_string();
map.insert( pid, ProcCounters { read_bytes, write_bytes, syscw, name, path, }, ); } map}
/// Human-readable throughput for gauges (prefer `vidya::metric_bps` in tables).pub fn format_bps(bps: f64) -> String { vidya::format_bps(bps)}
/// Local wall-clock 12-hour stamp for anomaly labels (`3:04:05 PM`).pub fn format_local_hms() -> String { // %l = space-padded hour 1–12; trim so we get "3:04:05 PM" not " 3:…". if let Ok(out) = std::process::Command::new("date") .arg("+%l:%M:%S %p") .output() { if out.status.success() { let s = String::from_utf8_lossy(&out.stdout).trim().to_string(); if !s.is_empty() { return s; } } } // Fallback: 12-hour from epoch seconds (UTC-ish). use std::time::{SystemTime, UNIX_EPOCH}; let secs = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); let h24 = (secs / 3600) % 24; let m = (secs / 60) % 60; let s = secs % 60; let ampm = if h24 < 12 { "AM" } else { "PM" }; let h12 = match h24 % 12 { 0 => 12, h => h, }; format!("{h12}:{m:02}:{s:02} {ampm}")}