forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

runner_metrics.rs69 lines, 2.8 KiBHistoryRawDownload
1//! The host usage of each CI runner (CPU, memory, network), kept in memory for the graphs on its
2//! admin page. A runner ships its samples in batches (`POST /api/v1/ci/runners/metrics`); the forge
3//! keeps the last hour per runner, at most `MAX_SAMPLES`. Samples are not stored in the database:
4//! a restart of the forge drops them, and the runner keeps sending new ones.
5
6use std::collections::{HashMap, VecDeque};
7use std::sync::{Mutex, MutexGuard};
8
9use forge_ci::proto::{RunnerMetricsBatch, RunnerSample};
10
11/// How far back samples are kept, in milliseconds, counted from the newest sample.
12pub const KEEP_MS: i64 = 3_600_000;
13/// Most samples kept per runner. The oldest go first.
14const MAX_SAMPLES: usize = 800;
15
16/// The samples of every runner, by runner id. Shared through `AppState`.
17#[derive(Debug, Default)]
18pub struct RunnerMetrics {
19 runners: Mutex<HashMap<String, VecDeque<RunnerSample>>>,
20}
21
22impl RunnerMetrics {
23 /// Takes a batch from a runner. Samples are taken in time order, and a sample whose time is not
24 /// after the newest one kept is ignored, so a resent sample is not stored twice. A CPU value is
25 /// clamped to 0 to 100, and a sample with a NaN CPU value is skipped.
26 pub fn ingest(&self, runner_id: &str, batch: &RunnerMetricsBatch) {
27 let mut sorted: Vec<RunnerSample> = batch
28 .samples
29 .iter()
30 .filter(|s| !s.cpu_percent.is_nan())
31 .map(|s| RunnerSample {
32 cpu_percent: s.cpu_percent.clamp(0.0, 100.0),
33 ..*s
34 })
35 .collect();
36 sorted.sort_by_key(|s| s.at_ms);
37
38 let mut runners = self.lock();
39 let queue = runners.entry(runner_id.to_owned()).or_default();
40 for sample in sorted {
41 let newest = queue.back().map_or(i64::MIN, |s| s.at_ms);
42 if sample.at_ms > newest {
43 queue.push_back(sample);
44 }
45 }
46 if let Some(newest) = queue.back().map(|s| s.at_ms) {
47 let oldest_kept = newest.saturating_sub(KEEP_MS);
48 while queue.front().is_some_and(|s| s.at_ms < oldest_kept) {
49 queue.pop_front();
50 }
51 }
52 while queue.len() > MAX_SAMPLES {
53 queue.pop_front();
54 }
55 }
56
57 /// The samples of a runner, oldest first. Empty for a runner that never sent one.
58 pub fn samples(&self, runner_id: &str) -> Vec<RunnerSample> {
59 self.lock()
60 .get(runner_id)
61 .map(|queue| queue.iter().copied().collect())
62 .unwrap_or_default()
63 }
64
65 fn lock(&self) -> MutexGuard<'_, HashMap<String, VecDeque<RunnerSample>>> {
66 // A panic while the lock was held leaves the map usable, so a poisoned lock is taken as is.
67 self.runners.lock().unwrap_or_else(|e| e.into_inner())
68 }
69}