use std::collections::VecDeque; use std::path::Path; use std::time::{Duration, Instant}; use forge_ci::proto::{RunnerMetricsBatch, RunnerSample}; use reqwest::StatusCode; use tokio_util::sync::CancellationToken; use crate::client::{ClientError, ForgeClient}; use crate::selflog::now_ms; pub const EVERY: Duration = Duration::from_secs(5); const FLUSH_EVERY: u64 = 2; pub const CAPACITY: usize = 360; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Snapshot { pub busy: u64, pub total: u64, pub mem_total: u64, pub mem_available: u64, pub rx: u64, pub tx: u64, pub disk_used: u64, pub disk_total: u64, } pub fn parse_cpu(text: &str) -> Option<(u64, u64)> { let line = text .lines() .find(|l| l.split_whitespace().next() == Some("cpu"))?; let fields: Vec = line .split_whitespace() .skip(1) .take(8) .map(str::parse) .collect::>() .ok()?; if fields.len() < 4 { return None; } let idle = fields[3].saturating_add(fields.get(4).copied().unwrap_or(0)); let total = fields.iter().fold(0_u64, |sum, f| sum.saturating_add(*f)); Some((total.saturating_sub(idle), total)) } pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> { let (mut rx, mut tx, mut seen) = (0_u64, 0_u64, false); for line in text.lines() { let Some((iface, rest)) = line.split_once(':') else { continue; }; let Ok(fields) = rest .split_whitespace() .map(str::parse::) .collect::, _>>() else { continue; }; if fields.len() < 9 { continue; } seen = true; if iface.trim() == "lo" { continue; } rx = rx.saturating_add(fields[0]); tx = tx.saturating_add(fields[8]); } seen.then_some((rx, tx)) } pub fn read_snapshot(work_dir: &Path) -> Option { let stat = std::fs::read_to_string("/proc/stat").ok()?; let mem = std::fs::read_to_string("/proc/meminfo").ok()?; let net = std::fs::read_to_string("/proc/net/dev").ok()?; let (busy, total) = parse_cpu(&stat)?; let info = crate::memory::meminfo(&mem); let (mem_total, mem_available) = (info.total?, info.available?); let (rx, tx) = parse_net_dev(&net)?; let (disk_used, disk_total) = disk_usage(work_dir).unwrap_or((0, 0)); Some(Snapshot { busy, total, mem_total, mem_available, rx, tx, disk_used, disk_total, }) } pub fn disk_usage(path: &Path) -> Option<(u64, u64)> { let stat = nix::sys::statvfs::statvfs(path).ok()?; let unit = stat.fragment_size(); let total = stat.blocks().checked_mul(unit)?; let free = stat.blocks_free().checked_mul(unit)?; Some((total.saturating_sub(free), total)) } #[derive(Default)] pub struct Sampler { prev: Option<(Instant, Snapshot)>, } impl Sampler { pub fn feed( &mut self, now: Instant, snap: Snapshot, running_jobs: u32, at_ms: i64, ) -> Option { let (at, before) = self.prev.replace((now, snap))?; let secs = now.saturating_duration_since(at).as_secs_f64(); if secs <= 0.0 { return None; } let dt = snap.total.saturating_sub(before.total); let db = snap.busy.saturating_sub(before.busy); let cpu = if dt == 0 { 0.0 } else { (db as f64 / dt as f64 * 100.0).clamp(0.0, 100.0) }; let rate = |now_v: u64, before_v: u64| (now_v.saturating_sub(before_v) as f64 / secs) as u64; Some(RunnerSample { at_ms, cpu_percent: cpu as f32, mem_used_bytes: snap.mem_total.saturating_sub(snap.mem_available), mem_total_bytes: snap.mem_total, net_rx_bytes_per_s: rate(snap.rx, before.rx), net_tx_bytes_per_s: rate(snap.tx, before.tx), disk_used_bytes: snap.disk_used, disk_total_bytes: snap.disk_total, running_jobs, }) } } pub async fn ship( client: ForgeClient, runner_secret: String, work_dir: std::path::PathBuf, running: impl Fn() -> u32 + Send + 'static, stop: CancellationToken, ) { let mut ticker = tokio::time::interval(EVERY); ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let mut sampler = Sampler::default(); let mut buffer: VecDeque = VecDeque::new(); let mut ticks = 0_u64; loop { let stopping = tokio::select! { _ = ticker.tick() => false, () = stop.cancelled() => true, }; if !stopping { ticks += 1; if let Some(snap) = read_snapshot(&work_dir) { let now = Instant::now(); if let Some(sample) = sampler.feed(now, snap, running(), now_ms()) { if buffer.len() >= CAPACITY { buffer.pop_front(); } buffer.push_back(sample); } } } if (stopping || ticks.is_multiple_of(FLUSH_EVERY)) && !buffer.is_empty() { let batch = RunnerMetricsBatch { samples: buffer.iter().copied().collect(), }; match client.post_runner_metrics(&runner_secret, &batch).await { Ok(()) => buffer.clear(), Err(ClientError::Status { status: StatusCode::NOT_FOUND, .. }) => return, Err(e) => tracing::debug!(error = %e, "cannot ship the runner metrics, retrying"), } } if stopping { return; } } } #[cfg(test)] mod tests { use super::*; #[test] fn cpu_busy_excludes_idle_and_iowait() { let text = "cpu 100 10 50 800 40 5 5 0 0 0\ncpu0 50 5 25 400 20 2 2 0 0 0\n"; assert_eq!(parse_cpu(text), Some((170, 1010))); } #[test] fn net_sums_every_interface_but_loopback() { let text = "Inter-| Receive | Transmit\n \ face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n\ lo: 900 1 0 0 0 0 0 0 900 1 0 0 0 0 0 0\n\ eth0: 1000 2 0 0 0 0 0 0 3000 4 0 0 0 0 0 0\n\ wlan0: 500 2 0 0 0 0 0 0 700 4 0 0 0 0 0 0\n"; assert_eq!(parse_net_dev(text), Some((1500, 3700))); } }