forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

metrics.rs248 lines, 8.7 KiBHistoryRawDownload
1//! Host metrics for the graphs on the runner's admin page. Every [`EVERY`] the runner reads
2//! `/proc` (CPU, memory, network) and turns the counters into a sample: CPU share and rates since
3//! the previous reading. [`ship`] posts the buffered samples every [`FLUSH_EVERY`] ticks. On a
4//! host without a readable `/proc` nothing is sampled and nothing is sent.
5
6use std::collections::VecDeque;
7use std::path::Path;
8use std::time::{Duration, Instant};
9
10use forge_ci::proto::{RunnerMetricsBatch, RunnerSample};
11use reqwest::StatusCode;
12use tokio_util::sync::CancellationToken;
13
14use crate::client::{ClientError, ForgeClient};
15use crate::selflog::now_ms;
16
17/// Time between two samples.
18pub const EVERY: Duration = Duration::from_secs(5);
19/// The buffer is posted on every this many ticks.
20const FLUSH_EVERY: u64 = 2;
21/// Most samples the buffer holds while the forge cannot be reached (an hour). The oldest go first.
22pub const CAPACITY: usize = 360;
23
24/// Counters read from `/proc` at one moment. Busy and total are CPU jiffies, the others are
25/// memory in bytes and network bytes since boot.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub 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/// `(busy, total)` jiffies of the first `cpu ` line of `/proc/stat`. Idle includes iowait.
39pub 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/// `(MemTotal, MemAvailable)` of `/proc/meminfo`, in bytes. The file reports kibibytes.
59pub 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/// `(rx, tx)` bytes summed over the interfaces of `/proc/net/dev` except `lo`. The two header
69/// lines have no colon and are skipped.
70pub 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/// Reads the three `/proc` files. `None` when any of them is missing or unreadable.
97pub 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/// Used and total bytes of the filesystem holding `path`.
118pub 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/// Turns successive snapshots into samples. The first snapshot only sets the baseline.
127#[derive(Default)]
128pub struct Sampler {
129 prev: Option<(Instant, Snapshot)>,
130}
131
132impl Sampler {
133 /// The sample for `snap`, taken at `now`, or `None` for the first reading.
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 // Saturating `as` casts keep a negative or huge rate in range.
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/// Samples the host every [`EVERY`] and posts the buffer every [`FLUSH_EVERY`] ticks. `running`
171/// gives the jobs on the runner now. A failed post keeps the buffer for the next one. An older
172/// forge without the endpoint answers 404, and then sampling stops for good. When `stop` is
173/// cancelled, the buffer gets one last post before returning.
174pub 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)]
223mod 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 // Total 1010, idle 840, so busy 170.
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}