| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use std::collections::VecDeque; |
| 7 | use std::path::Path; |
| 8 | use std::time::{Duration, Instant}; |
| 9 | |
| 10 | use forge_ci::proto::{RunnerMetricsBatch, RunnerSample}; |
| 11 | use reqwest::StatusCode; |
| 12 | use tokio_util::sync::CancellationToken; |
| 13 | |
| 14 | use crate::client::{ClientError, ForgeClient}; |
| 15 | use crate::selflog::now_ms; |
| 16 | |
| 17 | |
| 18 | pub const EVERY: Duration = Duration::from_secs(5); |
| 19 | |
| 20 | const FLUSH_EVERY: u64 = 2; |
| 21 | |
| 22 | pub const CAPACITY: usize = 360; |
| 23 | |
| 24 | |
| 25 | |
| 26 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 27 | pub struct Snapshot { |
| 28 | pub busy: u64, |
| 29 | pub total: u64, |
| 30 | pub mem_total: u64, |
| 31 | pub mem_available: u64, |
| 32 | pub rx: u64, |
| 33 | pub tx: u64, |
| 34 | pub disk_used: u64, |
| 35 | pub disk_total: u64, |
| 36 | } |
| 37 | |
| 38 | |
| 39 | pub fn parse_cpu(text: &str) -> Option<(u64, u64)> { |
| 40 | let line = text |
| 41 | .lines() |
| 42 | .find(|l| l.split_whitespace().next() == Some("cpu"))?; |
| 43 | let fields: Vec<u64> = line |
| 44 | .split_whitespace() |
| 45 | .skip(1) |
| 46 | .take(8) |
| 47 | .map(str::parse) |
| 48 | .collect::<Result<_, _>>() |
| 49 | .ok()?; |
| 50 | if fields.len() < 4 { |
| 51 | return None; |
| 52 | } |
| 53 | let idle = fields[3].saturating_add(fields.get(4).copied().unwrap_or(0)); |
| 54 | let total = fields.iter().fold(0_u64, |sum, f| sum.saturating_add(*f)); |
| 55 | Some((total.saturating_sub(idle), total)) |
| 56 | } |
| 57 | |
| 58 | |
| 59 | pub fn parse_mem(text: &str) -> Option<(u64, u64)> { |
| 60 | let find = |key: &str| { |
| 61 | let line = text.lines().find(|l| l.starts_with(key))?; |
| 62 | let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; |
| 63 | kib.checked_mul(1024) |
| 64 | }; |
| 65 | Some((find("MemTotal:")?, find("MemAvailable:")?)) |
| 66 | } |
| 67 | |
| 68 | |
| 69 | |
| 70 | pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> { |
| 71 | let (mut rx, mut tx, mut seen) = (0_u64, 0_u64, false); |
| 72 | for line in text.lines() { |
| 73 | let Some((iface, rest)) = line.split_once(':') else { |
| 74 | continue; |
| 75 | }; |
| 76 | let Ok(fields) = rest |
| 77 | .split_whitespace() |
| 78 | .map(str::parse::<u64>) |
| 79 | .collect::<Result<Vec<_>, _>>() |
| 80 | else { |
| 81 | continue; |
| 82 | }; |
| 83 | if fields.len() < 9 { |
| 84 | continue; |
| 85 | } |
| 86 | seen = true; |
| 87 | if iface.trim() == "lo" { |
| 88 | continue; |
| 89 | } |
| 90 | rx = rx.saturating_add(fields[0]); |
| 91 | tx = tx.saturating_add(fields[8]); |
| 92 | } |
| 93 | seen.then_some((rx, tx)) |
| 94 | } |
| 95 | |
| 96 | |
| 97 | pub fn read_snapshot(work_dir: &Path) -> Option<Snapshot> { |
| 98 | let stat = std::fs::read_to_string("/proc/stat").ok()?; |
| 99 | let mem = std::fs::read_to_string("/proc/meminfo").ok()?; |
| 100 | let net = std::fs::read_to_string("/proc/net/dev").ok()?; |
| 101 | let (busy, total) = parse_cpu(&stat)?; |
| 102 | let (mem_total, mem_available) = parse_mem(&mem)?; |
| 103 | let (rx, tx) = parse_net_dev(&net)?; |
| 104 | let (disk_used, disk_total) = disk_usage(work_dir).unwrap_or((0, 0)); |
| 105 | Some(Snapshot { |
| 106 | busy, |
| 107 | total, |
| 108 | mem_total, |
| 109 | mem_available, |
| 110 | rx, |
| 111 | tx, |
| 112 | disk_used, |
| 113 | disk_total, |
| 114 | }) |
| 115 | } |
| 116 | |
| 117 | |
| 118 | pub fn disk_usage(path: &Path) -> Option<(u64, u64)> { |
| 119 | let stat = nix::sys::statvfs::statvfs(path).ok()?; |
| 120 | let unit = stat.fragment_size(); |
| 121 | let total = stat.blocks().checked_mul(unit)?; |
| 122 | let free = stat.blocks_free().checked_mul(unit)?; |
| 123 | Some((total.saturating_sub(free), total)) |
| 124 | } |
| 125 | |
| 126 | |
| 127 | #[derive(Default)] |
| 128 | pub struct Sampler { |
| 129 | prev: Option<(Instant, Snapshot)>, |
| 130 | } |
| 131 | |
| 132 | impl Sampler { |
| 133 | |
| 134 | pub fn feed( |
| 135 | &mut self, |
| 136 | now: Instant, |
| 137 | snap: Snapshot, |
| 138 | running_jobs: u32, |
| 139 | at_ms: i64, |
| 140 | ) -> Option<RunnerSample> { |
| 141 | let (at, before) = self.prev.replace((now, snap))?; |
| 142 | let secs = now.saturating_duration_since(at).as_secs_f64(); |
| 143 | if secs <= 0.0 { |
| 144 | return None; |
| 145 | } |
| 146 | let dt = snap.total.saturating_sub(before.total); |
| 147 | let db = snap.busy.saturating_sub(before.busy); |
| 148 | let cpu = if dt == 0 { |
| 149 | 0.0 |
| 150 | } else { |
| 151 | (db as f64 / dt as f64 * 100.0).clamp(0.0, 100.0) |
| 152 | }; |
| 153 | |
| 154 | let rate = |
| 155 | |now_v: u64, before_v: u64| (now_v.saturating_sub(before_v) as f64 / secs) as u64; |
| 156 | Some(RunnerSample { |
| 157 | at_ms, |
| 158 | cpu_percent: cpu as f32, |
| 159 | mem_used_bytes: snap.mem_total.saturating_sub(snap.mem_available), |
| 160 | mem_total_bytes: snap.mem_total, |
| 161 | net_rx_bytes_per_s: rate(snap.rx, before.rx), |
| 162 | net_tx_bytes_per_s: rate(snap.tx, before.tx), |
| 163 | disk_used_bytes: snap.disk_used, |
| 164 | disk_total_bytes: snap.disk_total, |
| 165 | running_jobs, |
| 166 | }) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | pub async fn ship( |
| 175 | client: ForgeClient, |
| 176 | runner_secret: String, |
| 177 | work_dir: std::path::PathBuf, |
| 178 | running: impl Fn() -> u32 + Send + 'static, |
| 179 | stop: CancellationToken, |
| 180 | ) { |
| 181 | let mut ticker = tokio::time::interval(EVERY); |
| 182 | ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 183 | let mut sampler = Sampler::default(); |
| 184 | let mut buffer: VecDeque<RunnerSample> = VecDeque::new(); |
| 185 | let mut ticks = 0_u64; |
| 186 | loop { |
| 187 | let stopping = tokio::select! { |
| 188 | _ = ticker.tick() => false, |
| 189 | () = stop.cancelled() => true, |
| 190 | }; |
| 191 | if !stopping { |
| 192 | ticks += 1; |
| 193 | if let Some(snap) = read_snapshot(&work_dir) { |
| 194 | let now = Instant::now(); |
| 195 | if let Some(sample) = sampler.feed(now, snap, running(), now_ms()) { |
| 196 | if buffer.len() >= CAPACITY { |
| 197 | buffer.pop_front(); |
| 198 | } |
| 199 | buffer.push_back(sample); |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | if (stopping || ticks.is_multiple_of(FLUSH_EVERY)) && !buffer.is_empty() { |
| 204 | let batch = RunnerMetricsBatch { |
| 205 | samples: buffer.iter().copied().collect(), |
| 206 | }; |
| 207 | match client.post_runner_metrics(&runner_secret, &batch).await { |
| 208 | Ok(()) => buffer.clear(), |
| 209 | Err(ClientError::Status { |
| 210 | status: StatusCode::NOT_FOUND, |
| 211 | .. |
| 212 | }) => return, |
| 213 | Err(e) => tracing::debug!(error = %e, "cannot ship the runner metrics, retrying"), |
| 214 | } |
| 215 | } |
| 216 | if stopping { |
| 217 | return; |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | #[cfg(test)] |
| 223 | mod tests { |
| 224 | use super::*; |
| 225 | |
| 226 | #[test] |
| 227 | fn cpu_busy_excludes_idle_and_iowait() { |
| 228 | 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"; |
| 229 | |
| 230 | assert_eq!(parse_cpu(text), Some((170, 1010))); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn mem_reads_total_and_available_in_bytes() { |
| 235 | let text = "MemTotal: 16000000 kB\nMemFree: 1000000 kB\nMemAvailable: 4000000 kB\n"; |
| 236 | assert_eq!(parse_mem(text), Some((16_000_000 * 1024, 4_000_000 * 1024))); |
| 237 | } |
| 238 | |
| 239 | #[test] |
| 240 | fn net_sums_every_interface_but_loopback() { |
| 241 | let text = "Inter-| Receive | Transmit\n \ |
| 242 | face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n\ |
| 243 | lo: 900 1 0 0 0 0 0 0 900 1 0 0 0 0 0 0\n\ |
| 244 | eth0: 1000 2 0 0 0 0 0 0 3000 4 0 0 0 0 0 0\n\ |
| 245 | wlan0: 500 2 0 0 0 0 0 0 700 4 0 0 0 0 0 0\n"; |
| 246 | assert_eq!(parse_net_dev(text), Some((1500, 3700))); |
| 247 | } |
| 248 | } |