forge
Explore
Log in

Don't you dare go Hollow

A runner's page answers what it is working on and how its host is doing: a Jobs tab lists the jobs it runs now and its last 20 finished ones, each with its run, how long it ran and how long it waited in the queue (the Running jobs stat links there, and ci_jobs gets an index on runner_id, started_at)

Browse files at this commit

42861fb5920826ad7717b60d817fb1dbfd265271Ahmet Kaan GümüşParent: 5fbac66
Some checks failed
Show checks
  • feat
    • a runner's page answers what it is working on and how its host is doing: a Jobs tab lists the jobs it runs now and its last 20 finished ones, each with its run, how long it ran and how long it waited in the queue (the Running jobs stat links there, and ci_jobs gets an index on runner_id, started_at)
    • a Metrics tab graphs the last hour of CPU (with the time jobs ran shaded), memory against the total and network received and sent, from samples the runner takes from /proc every 5 s and sends every 10 s
    • the graphs are server-drawn SVG in the accent colour with a hover readout per 30 s and a table view, and the forge keeps the samples in memory
Show full message
✨ feat(ci): a runner's page answers what it is working on and how its host is doing: a Jobs tab lists the jobs it runs now and its last 20 finished ones, each with its run, how long it ran and how long it waited in the queue (the Running jobs stat links there, and ci_jobs gets an index on runner_id, started_at); a Metrics tab graphs the last hour of CPU (with the time jobs ran shaded), memory against the total and network received and sent, from samples the runner takes from /proc every 5 s and sends every 10 s; the graphs are server-drawn SVG in the accent colour with a hover readout per 30 s and a table view, and the forge keeps the samples in memory
crates/forge-ci/src/proto.rsmodified+27 -0
@@ -130,6 +130,33 @@ pub struct RunnerLogAck {
130 pub next_seq: u64,130 pub next_seq: u64,
131 }131 }
132 132
133+/// The capability of a runner that sends [`RunnerMetricsBatch`].
134+pub const CAP_RUNNER_METRICS: &str = "runner_metrics";
135+
136+/// `POST /api/v1/ci/runners/metrics`: host usage samples, oldest first, for the graphs on the
137+/// runner's admin page. Answered with 204.
138+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
139+pub struct RunnerMetricsBatch {
140+ pub samples: Vec<RunnerSample>,
141+}
142+
143+/// One sample of the runner's host. Rates cover the time since the previous sample.
144+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
145+pub struct RunnerSample {
146+ /// Unix time in milliseconds.
147+ pub at_ms: i64,
148+ /// Busy share of all CPUs, 0 to 100.
149+ pub cpu_percent: f32,
150+ /// Memory in use (total minus available), in bytes.
151+ pub mem_used_bytes: u64,
152+ pub mem_total_bytes: u64,
153+ /// Received and sent bytes per second over every interface but loopback.
154+ pub net_rx_bytes_per_s: u64,
155+ pub net_tx_bytes_per_s: u64,
156+ /// Jobs running on the runner.
157+ pub running_jobs: u32,
158+}
159+
133 /// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish160 /// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish
134 /// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops161 /// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops
135 /// claiming, restarts the way a self-update does (exit 75), and the forge clears162 /// claiming, restarts the way a self-update does (exit 75), and the forge clears
crates/forge-core/migrations/0068_ci_jobs_runner.sqladded+4 -0
@@ -0,0 +1,4 @@
1+-- A runner's admin page lists the jobs it ran, newest first (the Jobs tab). Applied by
2+-- store/migrate.rs.
3+
4+CREATE INDEX ci_jobs_runner ON ci_jobs(runner_id, started_at);
crates/forge-core/src/ci.rsmodified+14 -0
@@ -557,6 +557,20 @@ pub struct CiJob {
557 pub oom_kills: Option<u32>,557 pub oom_kills: Option<u32>,
558 }558 }
559 559
560+/// A job of one runner, with the run and repo it belongs to, for the runner's admin page. The
561+/// run's page is `/{owner}/{repo}/ci/runs/{run_number}`.
562+#[derive(Debug, Clone, PartialEq, Eq)]
563+pub struct RunnerJob {
564+ /// The job itself.
565+ pub job: CiJob,
566+ /// The number of the job's run, within its repo.
567+ pub run_number: i64,
568+ /// The username of the repo's owner.
569+ pub owner: String,
570+ /// The repo's name.
571+ pub repo: String,
572+}
573+
560 /// An artifact uploaded by a job. The file itself is stored outside the database.574 /// An artifact uploaded by a job. The file itself is stored outside the database.
561 #[derive(Debug, Clone, PartialEq, Eq)]575 #[derive(Debug, Clone, PartialEq, Eq)]
562 pub struct CiArtifact {576 pub struct CiArtifact {
crates/forge-core/src/store/ci.rsmodified+50 -2
@@ -15,8 +15,8 @@ use super::{
15 };15 };
16 use crate::ci::{16 use crate::ci::{
17 CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY,17 CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY,
18- MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerReport,18+ MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerJob,
19- RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field,19+ RunnerReport, RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field,
20 };20 };
21 use crate::error::{Error, Result};21 use crate::error::{Error, Result};
22 use crate::secret;22 use crate::secret;
@@ -33,6 +33,12 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled,
33 (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \33 (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \
34 reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \34 reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \
35 reported_memory_budget, reported_memory_free, reported_memory_reserve";35 reported_memory_budget, reported_memory_free, reported_memory_reserve";
36+/// The job columns of `runner_jobs`, then the run's number and the repo's owner and name.
37+const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \
38+ j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \
39+ j.log_bytes, j.oom_kills, r.number, u.username, p.name";
40+const RUNNER_JOB_FROM: &str = "FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id \
41+ JOIN repos p ON p.id = r.repo_id JOIN users u ON u.id = p.owner_id";
36 const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at";42 const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at";
37 43
38 /// Longest runner name, in bytes.44 /// Longest runner name, in bytes.
@@ -155,6 +161,15 @@ fn map_job(row: &Row) -> Result<CiJob> {
155 })161 })
156 }162 }
157 163
164+fn map_runner_job(row: &Row) -> Result<RunnerJob> {
165+ Ok(RunnerJob {
166+ job: map_job(row)?,
167+ run_number: col_int(row, 15)?,
168+ owner: col_text(row, 16)?,
169+ repo: col_text(row, 17)?,
170+ })
171+}
172+
158 fn map_artifact(row: &Row) -> Result<CiArtifact> {173 fn map_artifact(row: &Row) -> Result<CiArtifact> {
159 Ok(CiArtifact {174 Ok(CiArtifact {
160 id: col_text(row, 0)?,175 id: col_text(row, 0)?,
@@ -1663,6 +1678,39 @@ impl Store {
1663 jobs_of_run(&conn, run_id).await1678 jobs_of_run(&conn, run_id).await
1664 }1679 }
1665 1680
1681+ /// The jobs a runner holds or held: every running one, then its `recent` newest finished jobs
1682+ /// (by start time). Each carries its run's number and its repo's owner and name.
1683+ pub async fn runner_jobs(&self, runner_id: &str, recent: usize) -> Result<Vec<RunnerJob>> {
1684+ let conn = self.read_conn().await;
1685+ let mut jobs = fetch_all(
1686+ &conn,
1687+ &format!(
1688+ "SELECT {RUNNER_JOB_COLS} {RUNNER_JOB_FROM} \
1689+ WHERE j.runner_id = ?1 AND j.state = 'running' ORDER BY j.started_at DESC"
1690+ ),
1691+ (runner_id.to_string(),),
1692+ map_runner_job,
1693+ )
1694+ .await?;
1695+ let finished = fetch_all(
1696+ &conn,
1697+ &format!(
1698+ "SELECT {RUNNER_JOB_COLS} {RUNNER_JOB_FROM} \
1699+ WHERE j.runner_id = ?1 \
1700+ AND j.state IN ('success', 'failure', 'cancelled', 'error', 'skipped') \
1701+ ORDER BY j.started_at DESC LIMIT ?2"
1702+ ),
1703+ (
1704+ runner_id.to_string(),
1705+ i64::try_from(recent).unwrap_or(i64::MAX),
1706+ ),
1707+ map_runner_job,
1708+ )
1709+ .await?;
1710+ jobs.extend(finished);
1711+ Ok(jobs)
1712+ }
1713+
1666 pub async fn job_by_id(&self, id: &str) -> Result<Option<CiJob>> {1714 pub async fn job_by_id(&self, id: &str) -> Result<Option<CiJob>> {
1667 let conn = self.read_conn().await;1715 let conn = self.read_conn().await;
1668 load_job(&conn, id).await1716 load_job(&conn, id).await
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -107,6 +107,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
107 (65, include_str!("../../migrations/0065_hue_colours.sql")),107 (65, include_str!("../../migrations/0065_hue_colours.sql")),
108 (66, include_str!("../../migrations/0066_session_ip.sql")),108 (66, include_str!("../../migrations/0066_session_ip.sql")),
109 (67, include_str!("../../migrations/0067_coauthored_commits.sql")),109 (67, include_str!("../../migrations/0067_coauthored_commits.sql")),
110+ (68, include_str!("../../migrations/0068_ci_jobs_runner.sql")),
110 ];111 ];
111 112
112 /// The highest migration version this binary knows about.113 /// The highest migration version this binary knows about.
crates/forge-runner/src/client.rsmodified+29 -4
@@ -7,10 +7,11 @@ use std::path::Path;
7 use std::time::Duration;7 use std::time::Duration;
8 8
9 use forge_ci::proto::{9 use forge_ci::proto::{
10- BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CAP_RUNNER_LOG, CONCURRENCY_HEADER, ClaimRequest,10+ BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CAP_RUNNER_LOG, CAP_RUNNER_METRICS, CONCURRENCY_HEADER,
11- FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER,11+ ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER,
12- RESTART_HEADER, RegisterRequest, RegisterResponse, RequeueRequest, RestartMode,12+ RESERVE_MEMORY_HEADER, RESTART_HEADER, RegisterRequest, RegisterResponse, RequeueRequest,
13- RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch,13+ RestartMode, RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch,
14+ RunnerMetricsBatch,
14 };15 };
15 use reqwest::StatusCode;16 use reqwest::StatusCode;
16 use reqwest::header::{CONTENT_LENGTH, HeaderMap};17 use reqwest::header::{CONTENT_LENGTH, HeaderMap};
@@ -35,6 +36,8 @@ const BINARY_PATH: &str = "/api/v1/ci/runners/binary";
35 const CONFIG_PATH: &str = "/api/v1/ci/runners/config";36 const CONFIG_PATH: &str = "/api/v1/ci/runners/config";
36 /// `POST`: lines of the runner's own log, see [`crate::selflog`].37 /// `POST`: lines of the runner's own log, see [`crate::selflog`].
37 const RUNNER_LOG_PATH: &str = "/api/v1/ci/runners/log";38 const RUNNER_LOG_PATH: &str = "/api/v1/ci/runners/log";
39+/// `POST`: host samples for the runner's graphs, see [`crate::metrics`].
40+const RUNNER_METRICS_PATH: &str = "/api/v1/ci/runners/metrics";
38 41
39 /// Errors from talking to the forge.42 /// Errors from talking to the forge.
40 #[derive(Debug, thiserror::Error)]43 #[derive(Debug, thiserror::Error)]
@@ -152,6 +155,7 @@ impl ForgeClient {
152 CAP_RESTART.to_owned(),155 CAP_RESTART.to_owned(),
153 CAP_REQUEUE.to_owned(),156 CAP_REQUEUE.to_owned(),
154 CAP_RUNNER_LOG.to_owned(),157 CAP_RUNNER_LOG.to_owned(),
158+ CAP_RUNNER_METRICS.to_owned(),
155 ],159 ],
156 free_memory_bytes: memory.map(|m| m.free),160 free_memory_bytes: memory.map(|m| m.free),
157 memory_budget_bytes: memory.map(|m| m.budget),161 memory_budget_bytes: memory.map(|m| m.budget),
@@ -243,6 +247,27 @@ impl ForgeClient {
243 json_or_error(resp).await247 json_or_error(resp).await
244 }248 }
245 249
250+ /// `POST /api/v1/ci/runners/metrics`: ships host samples. Answered with 204.
251+ pub async fn post_runner_metrics(
252+ &self,
253+ runner_secret: &str,
254+ batch: &RunnerMetricsBatch,
255+ ) -> Result<(), ClientError> {
256+ let resp = self
257+ .http
258+ .post(self.url(RUNNER_METRICS_PATH))
259+ .bearer_auth(runner_secret)
260+ .json(batch)
261+ .timeout(REQUEST_TIMEOUT)
262+ .send()
263+ .await?;
264+ if resp.status().is_success() {
265+ Ok(())
266+ } else {
267+ Err(status_error(resp).await)
268+ }
269+ }
270+
246 /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the271 /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the
247 /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised272 /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised
248 /// value and syncs the file.273 /// value and syncs the file.
crates/forge-runner/src/lib.rsmodified+1 -0
@@ -14,6 +14,7 @@ pub mod disk;
14 pub mod executor;14 pub mod executor;
15 pub mod limiter;15 pub mod limiter;
16 pub mod logs;16 pub mod logs;
17+pub mod metrics;
17 pub mod memory;18 pub mod memory;
18 pub mod oci;19 pub mod oci;
19 pub mod oom;20 pub mod oom;
crates/forge-runner/src/metrics.rsadded+230 -0
@@ -0,0 +1,230 @@
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+
6+use std::collections::VecDeque;
7+use std::time::{Duration, Instant};
8+
9+use forge_ci::proto::{RunnerMetricsBatch, RunnerSample};
10+use reqwest::StatusCode;
11+use tokio_util::sync::CancellationToken;
12+
13+use crate::client::{ClientError, ForgeClient};
14+use crate::selflog::now_ms;
15+
16+/// Time between two samples.
17+pub const EVERY: Duration = Duration::from_secs(5);
18+/// The buffer is posted on every this many ticks.
19+const FLUSH_EVERY: u64 = 2;
20+/// Most samples the buffer holds while the forge cannot be reached (an hour). The oldest go first.
21+pub const CAPACITY: usize = 360;
22+
23+/// Counters read from `/proc` at one moment. Busy and total are CPU jiffies, the others are
24+/// memory in bytes and network bytes since boot.
25+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26+pub struct Snapshot {
27+ pub busy: u64,
28+ pub total: u64,
29+ pub mem_total: u64,
30+ pub mem_available: u64,
31+ pub rx: u64,
32+ pub tx: u64,
33+}
34+
35+/// `(busy, total)` jiffies of the first `cpu ` line of `/proc/stat`. Idle includes iowait.
36+pub fn parse_cpu(text: &str) -> Option<(u64, u64)> {
37+ let line = text
38+ .lines()
39+ .find(|l| l.split_whitespace().next() == Some("cpu"))?;
40+ let fields: Vec<u64> = line
41+ .split_whitespace()
42+ .skip(1)
43+ .take(8)
44+ .map(str::parse)
45+ .collect::<Result<_, _>>()
46+ .ok()?;
47+ if fields.len() < 4 {
48+ return None;
49+ }
50+ let idle = fields[3].saturating_add(fields.get(4).copied().unwrap_or(0));
51+ let total = fields.iter().fold(0_u64, |sum, f| sum.saturating_add(*f));
52+ Some((total.saturating_sub(idle), total))
53+}
54+
55+/// `(MemTotal, MemAvailable)` of `/proc/meminfo`, in bytes. The file reports kibibytes.
56+pub fn parse_mem(text: &str) -> Option<(u64, u64)> {
57+ let find = |key: &str| {
58+ let line = text.lines().find(|l| l.starts_with(key))?;
59+ let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
60+ kib.checked_mul(1024)
61+ };
62+ Some((find("MemTotal:")?, find("MemAvailable:")?))
63+}
64+
65+/// `(rx, tx)` bytes summed over the interfaces of `/proc/net/dev` except `lo`. The two header
66+/// lines have no colon and are skipped.
67+pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> {
68+ let (mut rx, mut tx, mut seen) = (0_u64, 0_u64, false);
69+ for line in text.lines() {
70+ let Some((iface, rest)) = line.split_once(':') else {
71+ continue;
72+ };
73+ let Ok(fields) = rest
74+ .split_whitespace()
75+ .map(str::parse::<u64>)
76+ .collect::<Result<Vec<_>, _>>()
77+ else {
78+ continue;
79+ };
80+ if fields.len() < 9 {
81+ continue;
82+ }
83+ seen = true;
84+ if iface.trim() == "lo" {
85+ continue;
86+ }
87+ rx = rx.saturating_add(fields[0]);
88+ tx = tx.saturating_add(fields[8]);
89+ }
90+ seen.then_some((rx, tx))
91+}
92+
93+/// Reads the three `/proc` files. `None` when any of them is missing or unreadable.
94+pub fn read_snapshot() -> Option<Snapshot> {
95+ let stat = std::fs::read_to_string("/proc/stat").ok()?;
96+ let mem = std::fs::read_to_string("/proc/meminfo").ok()?;
97+ let net = std::fs::read_to_string("/proc/net/dev").ok()?;
98+ let (busy, total) = parse_cpu(&stat)?;
99+ let (mem_total, mem_available) = parse_mem(&mem)?;
100+ let (rx, tx) = parse_net_dev(&net)?;
101+ Some(Snapshot {
102+ busy,
103+ total,
104+ mem_total,
105+ mem_available,
106+ rx,
107+ tx,
108+ })
109+}
110+
111+/// Turns successive snapshots into samples. The first snapshot only sets the baseline.
112+#[derive(Default)]
113+pub struct Sampler {
114+ prev: Option<(Instant, Snapshot)>,
115+}
116+
117+impl Sampler {
118+ /// The sample for `snap`, taken at `now`, or `None` for the first reading.
119+ pub fn feed(
120+ &mut self,
121+ now: Instant,
122+ snap: Snapshot,
123+ running_jobs: u32,
124+ at_ms: i64,
125+ ) -> Option<RunnerSample> {
126+ let (at, before) = self.prev.replace((now, snap))?;
127+ let secs = now.saturating_duration_since(at).as_secs_f64();
128+ if secs <= 0.0 {
129+ return None;
130+ }
131+ let dt = snap.total.saturating_sub(before.total);
132+ let db = snap.busy.saturating_sub(before.busy);
133+ let cpu = if dt == 0 {
134+ 0.0
135+ } else {
136+ (db as f64 / dt as f64 * 100.0).clamp(0.0, 100.0)
137+ };
138+ // Saturating `as` casts keep a negative or huge rate in range.
139+ let rate =
140+ |now_v: u64, before_v: u64| (now_v.saturating_sub(before_v) as f64 / secs) as u64;
141+ Some(RunnerSample {
142+ at_ms,
143+ cpu_percent: cpu as f32,
144+ mem_used_bytes: snap.mem_total.saturating_sub(snap.mem_available),
145+ mem_total_bytes: snap.mem_total,
146+ net_rx_bytes_per_s: rate(snap.rx, before.rx),
147+ net_tx_bytes_per_s: rate(snap.tx, before.tx),
148+ running_jobs,
149+ })
150+ }
151+}
152+
153+/// Samples the host every [`EVERY`] and posts the buffer every [`FLUSH_EVERY`] ticks. `running`
154+/// gives the jobs on the runner now. A failed post keeps the buffer for the next one. An older
155+/// forge without the endpoint answers 404, and then sampling stops for good. When `stop` is
156+/// cancelled, the buffer gets one last post before returning.
157+pub async fn ship(
158+ client: ForgeClient,
159+ runner_secret: String,
160+ running: impl Fn() -> u32 + Send + 'static,
161+ stop: CancellationToken,
162+) {
163+ let mut ticker = tokio::time::interval(EVERY);
164+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
165+ let mut sampler = Sampler::default();
166+ let mut buffer: VecDeque<RunnerSample> = VecDeque::new();
167+ let mut ticks = 0_u64;
168+ loop {
169+ let stopping = tokio::select! {
170+ _ = ticker.tick() => false,
171+ () = stop.cancelled() => true,
172+ };
173+ if !stopping {
174+ ticks += 1;
175+ if let Some(snap) = read_snapshot() {
176+ let now = Instant::now();
177+ if let Some(sample) = sampler.feed(now, snap, running(), now_ms()) {
178+ if buffer.len() >= CAPACITY {
179+ buffer.pop_front();
180+ }
181+ buffer.push_back(sample);
182+ }
183+ }
184+ }
185+ if (stopping || ticks.is_multiple_of(FLUSH_EVERY)) && !buffer.is_empty() {
186+ let batch = RunnerMetricsBatch {
187+ samples: buffer.iter().copied().collect(),
188+ };
189+ match client.post_runner_metrics(&runner_secret, &batch).await {
190+ Ok(()) => buffer.clear(),
191+ Err(ClientError::Status {
192+ status: StatusCode::NOT_FOUND,
193+ ..
194+ }) => return,
195+ Err(e) => tracing::debug!(error = %e, "cannot ship the runner metrics, retrying"),
196+ }
197+ }
198+ if stopping {
199+ return;
200+ }
201+ }
202+}
203+
204+#[cfg(test)]
205+mod tests {
206+ use super::*;
207+
208+ #[test]
209+ fn cpu_busy_excludes_idle_and_iowait() {
210+ 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";
211+ // Total 1010, idle 840, so busy 170.
212+ assert_eq!(parse_cpu(text), Some((170, 1010)));
213+ }
214+
215+ #[test]
216+ fn mem_reads_total_and_available_in_bytes() {
217+ let text = "MemTotal: 16000000 kB\nMemFree: 1000000 kB\nMemAvailable: 4000000 kB\n";
218+ assert_eq!(parse_mem(text), Some((16_000_000 * 1024, 4_000_000 * 1024)));
219+ }
220+
221+ #[test]
222+ fn net_sums_every_interface_but_loopback() {
223+ let text = "Inter-| Receive | Transmit\n \
224+ face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\n\
225+ lo: 900 1 0 0 0 0 0 0 900 1 0 0 0 0 0 0\n\
226+ eth0: 1000 2 0 0 0 0 0 0 3000 4 0 0 0 0 0 0\n\
227+ wlan0: 500 2 0 0 0 0 0 0 700 4 0 0 0 0 0 0\n";
228+ assert_eq!(parse_net_dev(text), Some((1500, 3700)));
229+ }
230+}
crates/forge-runner/src/runner.rsmodified+13 -0
@@ -20,6 +20,7 @@ use crate::executor::{ExecRequest, ExecResult, Executor};
20 use crate::limiter::Limiter;20 use crate::limiter::Limiter;
21 use crate::logs::{self, PumpConfig};21 use crate::logs::{self, PumpConfig};
22 use crate::memory::MemoryGate;22 use crate::memory::MemoryGate;
23+use crate::metrics;
23 use crate::oom::OomSink;24 use crate::oom::OomSink;
24 use crate::pressure::Pressure;25 use crate::pressure::Pressure;
25 use crate::restart::{self, RestartState, Step};26 use crate::restart::{self, RestartState, Step};
@@ -168,6 +169,17 @@ impl Runner {
168 self.config.runner_secret.clone(),169 self.config.runner_secret.clone(),
169 ship_stop.clone(),170 ship_stop.clone(),
170 ));171 ));
172+ // Host samples for the graphs, stopped with the same token. Jobs in use = slots taken.
173+ let limiter = self.limiter.clone();
174+ let metrics_shipper = tokio::spawn(metrics::ship(
175+ self.client.clone(),
176+ self.config.runner_secret.clone(),
177+ move || {
178+ let busy = limiter.current().saturating_sub(limiter.free_slots());
179+ u32::try_from(busy).unwrap_or(u32::MAX)
180+ },
181+ ship_stop.clone(),
182+ ));
171 // The reason the claim loop last logged for not claiming, see `not_claiming`.183 // The reason the claim loop last logged for not claiming, see `not_claiming`.
172 let mut blocked: Option<String> = None;184 let mut blocked: Option<String> = None;
173 let end = loop {185 let end = loop {
@@ -361,6 +373,7 @@ impl Runner {
361 // The last lines go out too, but a dead forge must not hold up the exit.373 // The last lines go out too, but a dead forge must not hold up the exit.
362 ship_stop.cancel();374 ship_stop.cancel();
363 let _ = tokio::time::timeout(LOG_FLUSH, shipper).await;375 let _ = tokio::time::timeout(LOG_FLUSH, shipper).await;
376+ let _ = tokio::time::timeout(LOG_FLUSH, metrics_shipper).await;
364 end377 end
365 }378 }
366 379
crates/forge-runner/src/selflog.rsmodified+2 -3
@@ -33,8 +33,7 @@ static RING: OnceLock<Arc<Ring>> = OnceLock::new();
33 33
34 /// The ring shared by the layer and the shipper.34 /// The ring shared by the layer and the shipper.
35 pub fn ring() -> Arc<Ring> {35 pub fn ring() -> Arc<Ring> {
36- RING.get_or_init(|| Arc::new(Ring::new(CAPACITY)))36+ RING.get_or_init(|| Arc::new(Ring::new(CAPACITY))).clone()
37- .clone()
38 }37 }
39 38
40 /// The layer that fills the ring. Add it to the subscriber with `.with(selflog::layer())`.39 /// The layer that fills the ring. Add it to the subscriber with `.with(selflog::layer())`.
@@ -173,7 +172,7 @@ fn level_name(level: Level) -> &'static str {
173 }172 }
174 }173 }
175 174
176-fn now_ms() -> i64 {175+pub(crate) fn now_ms() -> i64 {
177 SystemTime::now()176 SystemTime::now()
178 .duration_since(UNIX_EPOCH)177 .duration_since(UNIX_EPOCH)
179 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))178 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
crates/forge-web/src/boot.rsmodified+1 -0
@@ -136,6 +136,7 @@ pub async fn serve(
136 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),136 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
137 ci_live: Arc::new(crate::ci::CiLive::default()),137 ci_live: Arc::new(crate::ci::CiLive::default()),
138 runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()),138 runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()),
139+ runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()),
139 live: Arc::new(crate::live::LiveHub::default()),140 live: Arc::new(crate::live::LiveHub::default()),
140 push_live: Arc::new(crate::web_push::PushLive::default()),141 push_live: Arc::new(crate::web_push::PushLive::default()),
141 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),142 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),
crates/forge-web/src/ci/api.rsmodified+38 -1
@@ -12,7 +12,7 @@ use forge_ci::proto::{
12 BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,12 BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,
13 JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER,13 JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER,
14 RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart,14 RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart,
15- RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch,15+ RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch,
16 };16 };
17 use forge_core::Error as CoreError;17 use forge_core::Error as CoreError;
18 use forge_core::ci::{18 use forge_core::ci::{
@@ -47,6 +47,10 @@ const MAX_LOG_CHUNK: usize = 1024 * 1024;
47 const MAX_JSON_BODY: usize = 64 * 1024;47 const MAX_JSON_BODY: usize = 64 * 1024;
48 /// Largest runner log batch, in bytes. A batch holds at most 1000 lines of up to 4 KiB each.48 /// Largest runner log batch, in bytes. A batch holds at most 1000 lines of up to 4 KiB each.
49 const MAX_LOG_BATCH: usize = 1024 * 1024;49 const MAX_LOG_BATCH: usize = 1024 * 1024;
50+/// Largest metrics batch read: 400 samples of about 150 bytes each fit well inside it.
51+const MAX_METRICS_BATCH: usize = 256 * 1024;
52+/// Most samples one metrics batch may carry.
53+const MAX_METRICS_SAMPLES: usize = 400;
50 /// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say.54 /// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say.
51 const DEFAULT_RESERVE: u64 = 1 << 30;55 const DEFAULT_RESERVE: u64 = 1 << 30;
52 /// Longest runner name or label, in bytes.56 /// Longest runner name or label, in bytes.
@@ -351,6 +355,39 @@ async fn runner_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
351 Ok(api::json(StatusCode::OK, &ack))355 Ok(api::json(StatusCode::OK, &ack))
352 }356 }
353 357
358+/// `POST /api/v1/ci/runners/metrics`: host usage samples of the runner, for the graphs on its admin
359+/// page. Answers 204 with no body.
360+#[route(POST "/api/v1/ci/runners/metrics")]
361+async fn runner_metrics(cx: &Cx, body: Body) -> topcoat::Result<Response> {
362+ let state = app_context::<AppState>(cx);
363+ let runner = match runner_from(state, headers(cx)).await {
364+ Ok(runner) => runner,
365+ Err(res) => return Ok(*res),
366+ };
367+ let bytes = match api::read_body(body, MAX_METRICS_BATCH).await {
368+ Ok(bytes) => bytes,
369+ Err(res) => return Ok(*res),
370+ };
371+ let batch: RunnerMetricsBatch = match serde_json::from_slice(&bytes) {
372+ Ok(batch) => batch,
373+ Err(e) => {
374+ return Ok(api::error(
375+ StatusCode::BAD_REQUEST,
376+ &format!("invalid JSON body: {e}"),
377+ ));
378+ }
379+ };
380+ if batch.samples.len() > MAX_METRICS_SAMPLES {
381+ return Ok(api::error(
382+ StatusCode::UNPROCESSABLE_ENTITY,
383+ "too many samples in one batch",
384+ ));
385+ }
386+ state.runner_metrics.ingest(&runner.id, &batch);
387+ state.ci_live.bump_runners();
388+ Ok(empty(StatusCode::NO_CONTENT))
389+}
390+
354 /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it391 /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it
355 /// starts, applies them to its in-memory config, then reports its effective config here.392 /// starts, applies them to its in-memory config, then reports its effective config here.
356 #[route(GET "/api/v1/ci/runners/config")]393 #[route(GET "/api/v1/ci/runners/config")]
crates/forge-web/src/ci/metrics_chart.rsadded+290 -0
@@ -0,0 +1,290 @@
1+//! The geometry of the runner metrics graphs on the runner's admin page. Pure functions: samples go
2+//! in, plain numbers and SVG path data come out, and the view in `pages::admin_runners` writes the
3+//! markup. The plot covers the last hour in 30 s buckets (120 points). A bucket with no sample is
4+//! `None`, and a line breaks where two kept buckets are more than 30 s apart.
5+
6+use forge_ci::proto::RunnerSample;
7+
8+/// The width of the chart's viewBox. The SVG scales to its container with the aspect kept.
9+pub const VIEW_W: f64 = 700.0;
10+/// The height of the chart's viewBox.
11+pub const VIEW_H: f64 = 110.0;
12+/// Where the plot starts and ends on the x axis, and its top and bottom on the y axis.
13+pub const X0: f64 = 40.0;
14+pub const X1: f64 = 696.0;
15+pub const Y0: f64 = 6.0;
16+pub const Y1: f64 = 94.0;
17+/// The time one bucket covers, in milliseconds.
18+pub const BUCKET_MS: i64 = 30_000;
19+/// The number of buckets across the hour.
20+pub const BUCKETS: usize = 120;
21+/// The longest gap between two samples that a line bridges, in milliseconds.
22+const GAP_MS: i64 = 30_000;
23+/// The hover tooltip's size and its distance from the crosshair, in viewBox units.
24+const TIP_W: f64 = 128.0;
25+const TIP_H: f64 = 40.0;
26+const TIP_GAP: f64 = 8.0;
27+
28+/// The averages of the samples in one bucket.
29+#[derive(Clone, Copy, Debug, PartialEq)]
30+pub struct Bucket {
31+ /// Start of the bucket, Unix milliseconds.
32+ pub at_ms: i64,
33+ /// The first and last sample times in the bucket, used to break a line at a gap.
34+ pub first_ms: i64,
35+ pub last_ms: i64,
36+ pub cpu: f64,
37+ pub mem_used: f64,
38+ pub mem_total: f64,
39+ pub rx: f64,
40+ pub tx: f64,
41+ /// The most jobs running in any sample of the bucket.
42+ pub running: u32,
43+}
44+
45+/// One line of the chart: its SVG path data and its CSS class.
46+#[derive(Clone, Debug, PartialEq)]
47+pub struct Path {
48+ pub d: String,
49+ pub class: &'static str,
50+}
51+
52+/// The hover target of one bucket: a band over the bucket, a crosshair at its centre, and a tooltip
53+/// box beside the crosshair.
54+#[derive(Clone, Debug, PartialEq)]
55+pub struct Hit {
56+ pub x: f64,
57+ pub w: f64,
58+ pub cx: f64,
59+ pub bucket: Bucket,
60+ pub tip_x: f64,
61+ pub tip_y: f64,
62+ pub tip_w: f64,
63+ pub tip_h: f64,
64+}
65+
66+/// One line of a chart: how to read its value from a bucket, and its CSS class.
67+pub type Series = (fn(&Bucket) -> f64, &'static str);
68+
69+/// Everything one chart draws, apart from its axis labels.
70+#[derive(Clone, Debug, PartialEq)]
71+pub struct Svg {
72+ /// The y positions of the gridlines.
73+ pub grids: Vec<f64>,
74+ /// The y position and the value of each y label.
75+ pub ticks: Vec<(f64, f64)>,
76+ /// The x position and width of each band that marks running jobs.
77+ pub bands: Vec<(f64, f64)>,
78+ pub paths: Vec<Path>,
79+ pub hits: Vec<Hit>,
80+}
81+
82+/// Averages the samples of the last hour into `BUCKETS` buckets, oldest first. Samples before the
83+/// window or after `now_ms` are left out.
84+pub fn chart_points(samples: &[RunnerSample], now_ms: i64) -> Vec<Option<Bucket>> {
85+ let start = now_ms - BUCKET_MS * BUCKETS as i64;
86+ let mut sums: Vec<Option<(Bucket, f64)>> = vec![None; BUCKETS];
87+ for s in samples {
88+ if s.at_ms < start || s.at_ms > now_ms {
89+ continue;
90+ }
91+ let index = (((s.at_ms - start) / BUCKET_MS) as usize).min(BUCKETS - 1);
92+ let at_ms = start + index as i64 * BUCKET_MS;
93+ let (bucket, count) = sums[index].get_or_insert((
94+ Bucket {
95+ at_ms,
96+ first_ms: s.at_ms,
97+ last_ms: s.at_ms,
98+ cpu: 0.0,
99+ mem_used: 0.0,
100+ mem_total: 0.0,
101+ rx: 0.0,
102+ tx: 0.0,
103+ running: 0,
104+ },
105+ 0.0,
106+ ));
107+ bucket.first_ms = bucket.first_ms.min(s.at_ms);
108+ bucket.last_ms = bucket.last_ms.max(s.at_ms);
109+ bucket.cpu += f64::from(s.cpu_percent);
110+ bucket.mem_used += s.mem_used_bytes as f64;
111+ bucket.mem_total = bucket.mem_total.max(s.mem_total_bytes as f64);
112+ bucket.rx += s.net_rx_bytes_per_s as f64;
113+ bucket.tx += s.net_tx_bytes_per_s as f64;
114+ bucket.running = bucket.running.max(s.running_jobs);
115+ *count += 1.0;
116+ }
117+ sums.into_iter()
118+ .map(|slot| {
119+ slot.map(|(mut bucket, count)| {
120+ bucket.cpu /= count;
121+ bucket.mem_used /= count;
122+ bucket.rx /= count;
123+ bucket.tx /= count;
124+ bucket
125+ })
126+ })
127+ .collect()
128+}
129+
130+/// The smallest "nice" number (1, 2, 2.5 or 5 times a power of ten) that is at least `value`.
131+/// Zero gives 1.
132+pub fn nice_max(value: u64) -> u64 {
133+ if value <= 1 {
134+ return 1;
135+ }
136+ let mut unit = 1u64;
137+ while unit.saturating_mul(10) <= value {
138+ unit *= 10;
139+ }
140+ [unit, unit * 2, unit * 5 / 2, unit * 5, unit * 10]
141+ .into_iter()
142+ .find(|candidate| *candidate >= value)
143+ .unwrap_or(unit * 10)
144+}
145+
146+/// The largest value of a series over the buckets, as a whole number of bytes per second, at least
147+/// 1 KiB/s so a quiet network gets a readable scale.
148+pub fn net_max(points: &[Option<Bucket>]) -> f64 {
149+ let peak = points
150+ .iter()
151+ .flatten()
152+ .map(|b| b.rx.max(b.tx))
153+ .fold(0.0_f64, f64::max);
154+ nice_max((peak.ceil() as u64).max(1024)) as f64
155+}
156+
157+/// Builds the chart of `points`. `max` is the top of the y axis; `series` gives each line's value
158+/// and CSS class. `band` marks the buckets where jobs ran.
159+pub fn svg(points: &[Option<Bucket>], max: f64, series: &[Series], band: bool) -> Svg {
160+ let max = if max > 0.0 { max } else { 1.0 };
161+ let bw = bucket_width();
162+ let bands = if band {
163+ points
164+ .iter()
165+ .enumerate()
166+ .filter(|(_, p)| p.is_some_and(|b| b.running > 0))
167+ .map(|(i, _)| (X0 + i as f64 * bw, bw))
168+ .collect()
169+ } else {
170+ Vec::new()
171+ };
172+ let paths = series
173+ .iter()
174+ .map(|(value, class)| Path {
175+ d: line_d(points, *value, max),
176+ class,
177+ })
178+ .collect();
179+ let hits = points
180+ .iter()
181+ .enumerate()
182+ .filter_map(|(i, p)| {
183+ let bucket = (*p)?;
184+ let cx = X0 + (i as f64 + 0.5) * bw;
185+ let tip_x = if cx > (X0 + X1) / 2.0 {
186+ cx - TIP_GAP - TIP_W
187+ } else {
188+ cx + TIP_GAP
189+ };
190+ Some(Hit {
191+ x: X0 + i as f64 * bw,
192+ w: bw,
193+ cx,
194+ bucket,
195+ tip_x,
196+ tip_y: Y0 + 2.0,
197+ tip_w: TIP_W,
198+ tip_h: TIP_H,
199+ })
200+ })
201+ .collect();
202+ Svg {
203+ grids: vec![y_of(max / 2.0, max), y_of(max, max)],
204+ ticks: vec![
205+ (y_of(0.0, max), 0.0),
206+ (y_of(max / 2.0, max), max / 2.0),
207+ (y_of(max, max), max),
208+ ],
209+ bands,
210+ paths,
211+ hits,
212+ }
213+}
214+
215+fn bucket_width() -> f64 {
216+ (X1 - X0) / BUCKETS as f64
217+}
218+
219+fn y_of(value: f64, max: f64) -> f64 {
220+ Y1 - (value / max).clamp(0.0, 1.0) * (Y1 - Y0)
221+}
222+
223+/// The path of one series. A line is one `M` and `L` run; a bucket with no sample, or a gap of more
224+/// than `GAP_MS` between two samples, starts a new `M`.
225+fn line_d(points: &[Option<Bucket>], value: fn(&Bucket) -> f64, max: f64) -> String {
226+ let bw = bucket_width();
227+ let mut d = String::new();
228+ let mut prev: Option<Bucket> = None;
229+ for (i, point) in points.iter().enumerate() {
230+ let Some(b) = point else {
231+ prev = None;
232+ continue;
233+ };
234+ let joined = prev.is_some_and(|q| b.first_ms - q.last_ms <= GAP_MS);
235+ let x = X0 + (i as f64 + 0.5) * bw;
236+ let y = y_of(value(b), max);
237+ d.push_str(if joined { " L" } else { " M" });
238+ d.push_str(&format!("{x:.1} {y:.1}"));
239+ prev = Some(*b);
240+ }
241+ d.trim_start().to_owned()
242+}
243+
244+#[cfg(test)]
245+mod tests {
246+ use super::*;
247+
248+ fn sample(at_ms: i64, cpu: f32) -> RunnerSample {
249+ RunnerSample {
250+ at_ms,
251+ cpu_percent: cpu,
252+ mem_used_bytes: 0,
253+ mem_total_bytes: 0,
254+ net_rx_bytes_per_s: 0,
255+ net_tx_bytes_per_s: 0,
256+ running_jobs: 0,
257+ }
258+ }
259+
260+ /// Samples in one bucket are averaged, an empty bucket is `None`, and a gap of over 30 s starts a
261+ /// new line segment.
262+ #[test]
263+ fn buckets_average_and_a_gap_breaks_the_line() {
264+ let now = 7_200_000;
265+ let start = now - BUCKET_MS * BUCKETS as i64;
266+ let samples = [
267+ sample(start, 10.0),
268+ sample(start + 5_000, 30.0),
269+ // Bucket 1 is empty: the next sample comes 60 s after the last one above.
270+ sample(start + 65_000, 50.0),
271+ ];
272+ let points = chart_points(&samples, now);
273+ assert_eq!(points[0].map(|b| b.cpu), Some(20.0));
274+ assert_eq!(points[1], None);
275+ assert_eq!(points[2].map(|b| b.cpu), Some(50.0));
276+ let d = line_d(&points, |b| b.cpu, 100.0);
277+ assert_eq!(d.matches('M').count(), 2, "{d}");
278+ assert_eq!(d.matches('L').count(), 0, "{d}");
279+ }
280+
281+ #[test]
282+ fn nice_max_rounds_up_to_one_two_two_and_a_half_or_five() {
283+ assert_eq!(nice_max(0), 1);
284+ assert_eq!(nice_max(10), 10);
285+ assert_eq!(nice_max(11), 20);
286+ assert_eq!(nice_max(1500), 2000);
287+ assert_eq!(nice_max(2400), 2500);
288+ assert_eq!(nice_max(3_145_728), 5_000_000);
289+ }
290+}
crates/forge-web/src/ci/mod.rsmodified+2 -0
@@ -14,7 +14,9 @@ pub mod api;
14 pub mod live;14 pub mod live;
15 pub mod reaper;15 pub mod reaper;
16 pub mod release;16 pub mod release;
17+pub mod metrics_chart;
17 pub mod runner_log;18 pub mod runner_log;
19+pub mod runner_metrics;
18 pub mod schedule;20 pub mod schedule;
19 pub mod scheduled;21 pub mod scheduled;
20 22
crates/forge-web/src/ci/runner_log.rsmodified+4 -1
@@ -196,7 +196,10 @@ mod tests {
196 #[test]196 #[test]
197 fn ingest_skips_what_is_known_and_marks_gaps() {197 fn ingest_skips_what_is_known_and_marks_gaps() {
198 let logs = RunnerLogs::default();198 let logs = RunnerLogs::default();
199- assert_eq!(logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b"])), 2);199+ assert_eq!(
200+ logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b"])),
201+ 2
202+ );
200 // Resend of 0..=2: only "c" is new.203 // Resend of 0..=2: only "c" is new.
201 assert_eq!(204 assert_eq!(
202 logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b", "c"])),205 logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b", "c"])),
crates/forge-web/src/ci/runner_metrics.rsadded+69 -0
@@ -0,0 +1,69 @@
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+
6+use std::collections::{HashMap, VecDeque};
7+use std::sync::{Mutex, MutexGuard};
8+
9+use forge_ci::proto::{RunnerMetricsBatch, RunnerSample};
10+
11+/// How far back samples are kept, in milliseconds, counted from the newest sample.
12+pub const KEEP_MS: i64 = 3_600_000;
13+/// Most samples kept per runner. The oldest go first.
14+const MAX_SAMPLES: usize = 800;
15+
16+/// The samples of every runner, by runner id. Shared through `AppState`.
17+#[derive(Debug, Default)]
18+pub struct RunnerMetrics {
19+ runners: Mutex<HashMap<String, VecDeque<RunnerSample>>>,
20+}
21+
22+impl 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+}
crates/forge-web/src/pages/admin_runners.rsmodified+507 -7
@@ -7,8 +7,11 @@
7 //! runner are audited; the token itself is never written to the audit log.7 //! runner are audited; the token itself is never written to the audit log.
8 8
9 use forge_ci::build::{self, Freshness};9 use forge_ci::build::{self, Freshness};
10+use forge_ci::proto::RunnerSample;
10 use forge_core::AuditAction;11 use forge_core::AuditAction;
11-use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, RestartMode, runner_field};12+use forge_core::ci::{
13+ CiRunner, FieldKind, JobState, RUNNER_FIELDS, RestartMode, RunnerJob, runner_field,
14+};
12 use forge_core::store::health::runner_is_online;15 use forge_core::store::health::runner_is_online;
13 use serde::Deserialize;16 use serde::Deserialize;
14 use time::OffsetDateTime;17 use time::OffsetDateTime;
@@ -23,12 +26,13 @@ use topcoat::router::{page, path_param, route};
23 use topcoat::view::{View, component, view};26 use topcoat::view::{View, component, view};
24 27
25 use crate::audit::{self, Actor, Target};28 use crate::audit::{self, Actor, Target};
29+use crate::ci::metrics_chart::{self, Bucket};
26 use crate::ci::runner_log::Line;30 use crate::ci::runner_log::Line;
27 use crate::auth::check_csrf;31 use crate::auth::check_csrf;
28 use crate::i18n::admin::{self as g, K};32 use crate::i18n::admin::{self as g, K};
29 use crate::i18n::{self, Key, Lang};33 use crate::i18n::{self, Key, Lang};
30 use crate::pages::admin_users::admin_only;34 use crate::pages::admin_users::admin_only;
31-use crate::pages::ci_runs::events_response;35+use crate::pages::ci_runs::{age_text, duration_text, events_response, run_href, state_text};
32 use crate::pages::repo_mirrors::stamp_in_tz;36 use crate::pages::repo_mirrors::stamp_in_tz;
33 use crate::state::AppState;37 use crate::state::AppState;
34 use crate::views::{empty_state, enc, now_unix, relative_time, shell};38 use crate::views::{empty_state, enc, now_unix, relative_time, shell};
@@ -790,12 +794,15 @@ fn sel(on: bool) -> Option<&'static str> {
790 on.then_some("selected")794 on.then_some("selected")
791 }795 }
792 796
793-/// The detail page tabs: slug and the config keys on it. `identity` and `logs` are read-only.797+/// The detail page tabs: slug and the config keys on it. `jobs`, `metrics`, `identity` and `logs` are
794-const TABS: [(&str, &[&str]); 6] = [798+/// read-only.
799+const TABS: [(&str, &[&str]); 8] = [
795 (800 (
796 "general",801 "general",
797 &["concurrency", "labels", "executor", "auto_update"],802 &["concurrency", "labels", "executor", "auto_update"],
798 ),803 ),
804+ ("jobs", &[]),
805+ ("metrics", &[]),
799 (806 (
800 "limits",807 "limits",
801 &[808 &[
@@ -828,6 +835,8 @@ fn tab_label(lang: Lang, slug: &str) -> &'static str {
828 "storage" => s(lang, "Storage", "Depolama"),835 "storage" => s(lang, "Storage", "Depolama"),
829 "sandbox" => s(lang, "Sandbox", "Kum havuzu"),836 "sandbox" => s(lang, "Sandbox", "Kum havuzu"),
830 "logs" => s(lang, "Logs", "Günlük"),837 "logs" => s(lang, "Logs", "Günlük"),
838+ "jobs" => s(lang, "Jobs", "İşler"),
839+ "metrics" => s(lang, "Metrics", "Ölçümler"),
831 _ => s(lang, "Identity", "Kimlik"),840 _ => s(lang, "Identity", "Kimlik"),
832 }841 }
833 }842 }
@@ -1162,6 +1171,367 @@ fn or_dash(text: String) -> String {
1162 }1171 }
1163 }1172 }
1164 1173
1174+/// How many finished jobs the jobs tab lists, newest first.
1175+const RECENT_JOBS: usize = 20;
1176+
1177+/// One job row of the jobs tab, already formatted.
1178+struct RunnerJobRow {
1179+ name: String,
1180+ /// `owner/name` of the job's repo.
1181+ repo: String,
1182+ run_href: String,
1183+ /// `#` and the run's number.
1184+ run_text: String,
1185+ state_text: String,
1186+ /// `ci-state ci-<state>`, the class the runs list colours the state with.
1187+ state_class: String,
1188+ /// The run time so far for a running job, the whole run time for a finished one. `-` when unknown.
1189+ duration: String,
1190+ /// The time from queued to started. `-` when it never started.
1191+ waited: String,
1192+ /// The finish stamp, for the `<time>` element. Empty when it has not finished.
1193+ finished_at: String,
1194+ /// "3 minutes ago". `-` when it has not finished.
1195+ finished_ago: String,
1196+}
1197+
1198+fn runner_job_row(lang: Lang, job: &RunnerJob) -> RunnerJobRow {
1199+ let j = &job.job;
1200+ let repo = format!("{}/{}", job.owner, job.repo);
1201+ let finished_at = j.finished_at.clone().unwrap_or_default();
1202+ RunnerJobRow {
1203+ name: j.name.clone(),
1204+ run_href: run_href(&repo, job.run_number),
1205+ repo,
1206+ run_text: format!("#{}", job.run_number),
1207+ state_text: state_text(lang, j.state.as_str()),
1208+ state_class: format!("ci-state ci-{}", j.state.as_str()),
1209+ duration: or_dash(duration_text(
1210+ lang,
1211+ j.started_at.as_deref(),
1212+ j.finished_at.as_deref(),
1213+ )),
1214+ waited: or_dash(duration_text(
1215+ lang,
1216+ j.queued_at.as_deref(),
1217+ j.started_at.as_deref(),
1218+ )),
1219+ finished_ago: if finished_at.is_empty() {
1220+ "-".to_owned()
1221+ } else {
1222+ age_text(lang, &finished_at)
1223+ },
1224+ finished_at,
1225+ }
1226+}
1227+
1228+/// The runner's jobs for its jobs tab: the running ones, then the newest finished ones.
1229+async fn runner_job_rows(
1230+ state: &AppState,
1231+ lang: Lang,
1232+ runner_id: &str,
1233+) -> forge_core::Result<(Vec<RunnerJobRow>, Vec<RunnerJobRow>)> {
1234+ let jobs = state.store.runner_jobs(runner_id, RECENT_JOBS).await?;
1235+ let (running, finished): (Vec<&RunnerJob>, Vec<&RunnerJob>) = jobs
1236+ .iter()
1237+ .partition(|job| job.job.state == JobState::Running);
1238+ let to_row = |job: &RunnerJob| runner_job_row(lang, job);
1239+ Ok((
1240+ running.into_iter().map(to_row).collect(),
1241+ finished.into_iter().map(to_row).collect(),
1242+ ))
1243+}
1244+
1245+/// The metrics tab: three graphs over the last hour and the table of their buckets.
1246+#[derive(Default)]
1247+struct MetricsTab {
1248+ /// True when no sample falls in the last hour.
1249+ empty: bool,
1250+ charts: Vec<MxChart>,
1251+ rows: Vec<MxRow>,
1252+}
1253+
1254+/// One graph with its caption, legend and hover targets, all as the strings the markup needs.
1255+struct MxChart {
1256+ aria: &'static str,
1257+ caption: String,
1258+ /// The swatch class and the text of each legend entry. Empty when the chart has one series.
1259+ legend: Vec<(&'static str, &'static str)>,
1260+ grids: Vec<String>,
1261+ /// The y label position and text of each tick.
1262+ ticks: Vec<(String, String)>,
1263+ /// The x position and width of each band marking running jobs.
1264+ bands: Vec<(String, String)>,
1265+ paths: Vec<MxPath>,
1266+ hits: Vec<MxHit>,
1267+ x0: String,
1268+ mid: String,
1269+ x1: String,
1270+ y0: String,
1271+ y1: String,
1272+ tick_x: String,
1273+ band_h: String,
1274+ /// The SVG viewBox, `0 0 W H`.
1275+ view_box: String,
1276+}
1277+
1278+struct MxPath {
1279+ d: String,
1280+ class: &'static str,
1281+}
1282+
1283+/// The hover band of one bucket, its crosshair and its tooltip.
1284+struct MxHit {
1285+ x: String,
1286+ w: String,
1287+ cx: String,
1288+ /// The `<title>` text: the time and the values, for a screen reader and a plain browser tip.
1289+ title: String,
1290+ tip_x: String,
1291+ tip_y: String,
1292+ tip_w: String,
1293+ tip_h: String,
1294+ lines: Vec<MxText>,
1295+}
1296+
1297+struct MxText {
1298+ x: String,
1299+ y: String,
1300+ text: String,
1301+}
1302+
1303+/// One row of the table under the graphs.
1304+struct MxRow {
1305+ time: String,
1306+ cpu: String,
1307+ mem: String,
1308+ rx: String,
1309+ tx: String,
1310+}
1311+
1312+/// The chart's value text is taken from the view's `fn(f64) -> String` in `mx_chart`.
1313+fn n(value: f64) -> String {
1314+ format!("{value:.1}")
1315+}
1316+
1317+fn cpu_of(b: &Bucket) -> f64 {
1318+ b.cpu
1319+}
1320+
1321+fn mem_of(b: &Bucket) -> f64 {
1322+ b.mem_used
1323+}
1324+
1325+fn rx_of(b: &Bucket) -> f64 {
1326+ b.rx
1327+}
1328+
1329+fn tx_of(b: &Bucket) -> f64 {
1330+ b.tx
1331+}
1332+
1333+/// A rate in bytes per second as `80 KiB/s`, one decimal below ten units.
1334+fn rate_text(bytes: f64) -> String {
1335+ const KIB: f64 = 1024.0;
1336+ const MIB: f64 = KIB * 1024.0;
1337+ const GIB: f64 = MIB * 1024.0;
1338+ let (value, unit) = if bytes >= GIB {
1339+ (bytes / GIB, "GiB")
1340+ } else if bytes >= MIB {
1341+ (bytes / MIB, "MiB")
1342+ } else if bytes >= KIB {
1343+ (bytes / KIB, "KiB")
1344+ } else {
1345+ return format!("{bytes:.0} B/s");
1346+ };
1347+ if value >= 10.0 {
1348+ format!("{value:.0} {unit}/s")
1349+ } else {
1350+ format!("{value:.1} {unit}/s")
1351+ }
1352+}
1353+
1354+/// `HH:MM` of the UTC time of day of a Unix time in milliseconds.
1355+fn clock_hm(at_ms: i64) -> String {
1356+ let day = (at_ms / 1000).rem_euclid(86_400);
1357+ format!("{:02}:{:02}", day / 3600, day % 3600 / 60)
1358+}
1359+
1360+/// The memory caption: `Memory 5.1 GiB of 7.6 GiB`.
1361+fn memory_text(lang: Lang, used: f64, total: f64) -> String {
1362+ let label = s(lang, "Memory", "Bellek");
1363+ let sep = s(lang, "of", "/");
1364+ format!(
1365+ "{label} {} {sep} {}",
1366+ bytes_text(used as u64),
1367+ bytes_text(total as u64)
1368+ )
1369+}
1370+
1371+/// Builds one chart. `series` gives each line's value and class; `tip` gives a bucket's tooltip
1372+/// lines, and `tick` the text of an axis value.
1373+#[allow(clippy::too_many_arguments)]
1374+fn mx_chart(
1375+ points: &[Option<Bucket>],
1376+ max: f64,
1377+ series: &[metrics_chart::Series],
1378+ band: bool,
1379+ tick: &dyn Fn(f64) -> String,
1380+ tip: &dyn Fn(&Bucket) -> Vec<String>,
1381+ caption: String,
1382+ legend: Vec<(&'static str, &'static str)>,
1383+ aria: &'static str,
1384+) -> MxChart {
1385+ let svg = metrics_chart::svg(points, max, series, band);
1386+ let hits = svg
1387+ .hits
1388+ .iter()
1389+ .map(|hit| {
1390+ let time = format!("{} UTC", clock_hm(hit.bucket.at_ms));
1391+ let mut texts = vec![time.clone()];
1392+ texts.extend(tip(&hit.bucket));
1393+ let title = texts.join(", ");
1394+ let lines = texts
1395+ .into_iter()
1396+ .take(3)
1397+ .enumerate()
1398+ .map(|(i, text)| MxText {
1399+ x: n(hit.tip_x + 6.0),
1400+ y: n(hit.tip_y + 13.0 + 12.0 * i as f64),
1401+ text,
1402+ })
1403+ .collect();
1404+ MxHit {
1405+ x: n(hit.x),
1406+ w: n(hit.w),
1407+ cx: n(hit.cx),
1408+ title,
1409+ tip_x: n(hit.tip_x),
1410+ tip_y: n(hit.tip_y),
1411+ tip_w: n(hit.tip_w),
1412+ tip_h: n(hit.tip_h),
1413+ lines,
1414+ }
1415+ })
1416+ .collect();
1417+ MxChart {
1418+ aria,
1419+ caption,
1420+ legend,
1421+ grids: svg.grids.iter().map(|y| n(*y)).collect(),
1422+ ticks: svg
1423+ .ticks
1424+ .iter()
1425+ .map(|(y, v)| (n(*y), tick(*v)))
1426+ .collect(),
1427+ bands: svg
1428+ .bands
1429+ .iter()
1430+ .map(|(x, w)| (n(*x), n(*w)))
1431+ .collect(),
1432+ paths: svg
1433+ .paths
1434+ .into_iter()
1435+ .map(|p| MxPath {
1436+ d: p.d,
1437+ class: p.class,
1438+ })
1439+ .collect(),
1440+ hits,
1441+ x0: n(metrics_chart::X0),
1442+ mid: n((metrics_chart::X0 + metrics_chart::X1) / 2.0),
1443+ x1: n(metrics_chart::X1),
1444+ y0: n(metrics_chart::Y0),
1445+ y1: n(metrics_chart::Y1),
1446+ tick_x: n(metrics_chart::X0 - 4.0),
1447+ band_h: n(metrics_chart::Y1 - metrics_chart::Y0),
1448+ view_box: format!("0 0 {} {}", metrics_chart::VIEW_W, metrics_chart::VIEW_H),
1449+ }
1450+}
1451+
1452+/// The three graphs of a runner's samples as of `now_ms`, with the table of their buckets.
1453+fn metrics_tab(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsTab {
1454+ let points = metrics_chart::chart_points(samples, now_ms);
1455+ let latest = points.iter().rev().flatten().next().copied();
1456+ let empty = latest.is_none();
1457+ let mem_total = points
1458+ .iter()
1459+ .flatten()
1460+ .map(|b| b.mem_total)
1461+ .fold(0.0_f64, f64::max);
1462+ let net_top = metrics_chart::net_max(&points);
1463+ let cpu_caption = match latest {
1464+ Some(b) => format!("CPU {:.0}%", b.cpu),
1465+ None => "CPU -".to_owned(),
1466+ };
1467+ let mem_caption = match latest {
1468+ Some(b) => memory_text(lang, b.mem_used, b.mem_total),
1469+ None => format!("{} -", s(lang, "Memory", "Bellek")),
1470+ };
1471+ let net_caption = match latest {
1472+ Some(b) => format!("↓ {} ↑ {}", rate_text(b.rx), rate_text(b.tx)),
1473+ None => "↓ - ↑ -".to_owned(),
1474+ };
1475+ let running_label = s(lang, "Running jobs", "Çalışan iş");
1476+ let cpu = mx_chart(
1477+ &points,
1478+ 100.0,
1479+ &[(cpu_of, "mx-line")],
1480+ true,
1481+ &|v| format!("{v:.0}%"),
1482+ &|b| {
1483+ vec![
1484+ format!("CPU {:.0}%", b.cpu),
1485+ format!("{running_label} {}", b.running),
1486+ ]
1487+ },
1488+ cpu_caption,
1489+ Vec::new(),
1490+ s(lang, "CPU over the last hour", "CPU, son bir saat"),
1491+ );
1492+ let mem = mx_chart(
1493+ &points,
1494+ mem_total,
1495+ &[(mem_of, "mx-line")],
1496+ false,
1497+ &|v| bytes_text(v as u64),
1498+ &|b| vec![memory_text(lang, b.mem_used, b.mem_total)],
1499+ mem_caption,
1500+ Vec::new(),
1501+ s(lang, "Memory over the last hour", "Bellek, son bir saat"),
1502+ );
1503+ let net = mx_chart(
1504+ &points,
1505+ net_top,
1506+ &[(rx_of, "mx-line"), (tx_of, "mx-line mx-line-sent")],
1507+ false,
1508+ &rate_text,
1509+ &|b| vec![format!("↓ {}", rate_text(b.rx)), format!("↑ {}", rate_text(b.tx))],
1510+ net_caption,
1511+ vec![
1512+ ("mx-key", s(lang, "Received", "Alınan")),
1513+ ("mx-key mx-key-sent", s(lang, "Sent", "Gönderilen")),
1514+ ],
1515+ s(lang, "Network over the last hour", "Ağ, son bir saat"),
1516+ );
1517+ let rows = points
1518+ .iter()
1519+ .flatten()
1520+ .map(|b| MxRow {
1521+ time: clock_hm(b.at_ms),
1522+ cpu: format!("{:.0}%", b.cpu),
1523+ mem: bytes_text(b.mem_used as u64),
1524+ rx: rate_text(b.rx),
1525+ tx: rate_text(b.tx),
1526+ })
1527+ .collect();
1528+ MetricsTab {
1529+ empty,
1530+ charts: vec![cpu, mem, net],
1531+ rows,
1532+ }
1533+}
1534+
1165 fn tab_class(on: bool) -> &'static str {1535 fn tab_class(on: bool) -> &'static str {
1166 if on {1536 if on {
1167 "subnav-link current"1537 "subnav-link current"
@@ -1180,6 +1550,9 @@ async fn runner_detail_view(
1180 notice: Option<(&'static str, bool)>,1550 notice: Option<(&'static str, bool)>,
1181 tab: &'static str,1551 tab: &'static str,
1182 log: Vec<LogRow>,1552 log: Vec<LogRow>,
1553+ running_jobs: Vec<RunnerJobRow>,
1554+ recent_jobs: Vec<RunnerJobRow>,
1555+ metrics: MetricsTab,
1183 ) -> Result<impl View> {1556 ) -> Result<impl View> {
1184 let version = or_dash(runner.reported.version.clone().unwrap_or_default());1557 let version = or_dash(runner.reported.version.clone().unwrap_or_default());
1185 let cpus = or_dash(1558 let cpus = or_dash(
@@ -1212,7 +1585,8 @@ async fn runner_detail_view(
1212 };1585 };
1213 let shown = detail_fields(lang, tab, &fields);1586 let shown = detail_fields(lang, tab, &fields);
1214 let identity = identity_rows(lang, &fields);1587 let identity = identity_rows(lang, &fields);
1215- let editing = !matches!(tab, "identity" | "logs");1588+ let editing = !matches!(tab, "identity" | "logs" | "jobs" | "metrics");
1589+ let jobs_href = format!("{}?tab=jobs", row.detail_href);
1216 let save_action = format!("{}/settings", row.detail_href);1590 let save_action = format!("{}/settings", row.detail_href);
1217 let reset_action = row.config_action.clone();1591 let reset_action = row.config_action.clone();
1218 Ok(view! {1592 Ok(view! {
@@ -1239,7 +1613,7 @@ async fn runner_detail_view(
1239 }1613 }
1240 <section class="card">1614 <section class="card">
1241 <div class="srv-grid srv-stats">1615 <div class="srv-grid srv-stats">
1242- <div class="srv-field"><span class="srv-label">(s(lang, "Running jobs", "Çalışan işler"))</span><strong>(in_use.as_str())</strong></div>1616+ <div class="srv-field"><span class="srv-label">(s(lang, "Running jobs", "Çalışan işler"))</span><strong><a href=(jobs_href.as_str())>(in_use.as_str())</a></strong></div>
1243 <div class="srv-field"><span class="srv-label">(g::t(lang, K::LastSeen))</span><strong title=(row.last_seen_full.as_str())><time data-rel="true" datetime=(row.last_seen_at.as_str())>(row.last_seen.as_str())</time></strong></div>1617 <div class="srv-field"><span class="srv-label">(g::t(lang, K::LastSeen))</span><strong title=(row.last_seen_full.as_str())><time data-rel="true" datetime=(row.last_seen_at.as_str())>(row.last_seen.as_str())</time></strong></div>
1244 <div class="srv-field"><span class="srv-label">(s(lang, "Build", "Derleme"))</span><strong class="runner-build-stat" title=(row.build.as_str())>(if row.build_short.is_empty() { "-" } else { row.build_short.as_str() })<span class=(format!("ci-state {}", row.build_class))>(row.build_label)</span></strong></div>1618 <div class="srv-field"><span class="srv-label">(s(lang, "Build", "Derleme"))</span><strong class="runner-build-stat" title=(row.build.as_str())>(if row.build_short.is_empty() { "-" } else { row.build_short.as_str() })<span class=(format!("ci-state {}", row.build_class))>(row.build_label)</span></strong></div>
1245 <div class="srv-field"><span class="srv-label">(s(lang, "Runner version", "Çalıştırıcı sürümü"))</span><strong>(version.as_str())</strong></div>1619 <div class="srv-field"><span class="srv-label">(s(lang, "Runner version", "Çalıştırıcı sürümü"))</span><strong>(version.as_str())</strong></div>
@@ -1311,6 +1685,121 @@ async fn runner_detail_view(
1311 }1685 }
1312 </pre>1686 </pre>
1313 }1687 }
1688+ } else if tab == "metrics" {
1689+ if metrics.empty {
1690+ <p class="muted small">(s(lang, "No metrics yet. A runner sends them from this version on; an older one sends nothing.", "Henüz ölçüm yok. Ölçümleri bu sürümden itibaren çalıştırıcı gönderir; eski sürüm hiçbir şey göndermez."))</p>
1691+ } else {
1692+ <div class="mx-stack">
1693+ for c in metrics.charts.iter() {
1694+ <div class="mx-row">
1695+ <div class="mx-head">
1696+ <p class="mx-caption">(c.caption.as_str())</p>
1697+ if !c.legend.is_empty() {
1698+ <ul class="mx-legend">
1699+ for (key, text) in c.legend.iter() {
1700+ <li><span class=(*key) aria-hidden="true"></span>(*text)</li>
1701+ }
1702+ </ul>
1703+ }
1704+ </div>
1705+ <svg class="mx-svg" viewBox=(c.view_box.as_str()) role="img" aria-label=(c.aria)>
1706+ for y in c.grids.iter() {
1707+ <line class="mx-grid" x1=(c.x0.as_str()) x2=(c.x1.as_str()) y1=(y.as_str()) y2=(y.as_str())/>
1708+ }
1709+ for (x, w) in c.bands.iter() {
1710+ <rect class="mx-band" x=(x.as_str()) y=(c.y0.as_str()) width=(w.as_str()) height=(c.band_h.as_str())/>
1711+ }
1712+ for (y, text) in c.ticks.iter() {
1713+ <text class="mx-axis" x=(c.tick_x.as_str()) y=(y.as_str()) text-anchor="end" dominant-baseline="middle">(text.as_str())</text>
1714+ }
1715+ for p in c.paths.iter() {
1716+ <path class=(p.class) d=(p.d.as_str())/>
1717+ }
1718+ <text class="mx-axis" x=(c.x0.as_str()) y="106">(s(lang, "-60 min", "-60 dk"))</text>
1719+ <text class="mx-axis" x=(c.mid.as_str()) y="106" text-anchor="middle">(s(lang, "-30 min", "-30 dk"))</text>
1720+ <text class="mx-axis" x=(c.x1.as_str()) y="106" text-anchor="end">(s(lang, "now", "şimdi"))</text>
1721+ for hit in c.hits.iter() {
1722+ <g class="mx-hit">
1723+ <title>(hit.title.as_str())</title>
1724+ <rect class="mx-hit-area" x=(hit.x.as_str()) y=(c.y0.as_str()) width=(hit.w.as_str()) height=(c.band_h.as_str())/>
1725+ <line class="mx-cross" x1=(hit.cx.as_str()) x2=(hit.cx.as_str()) y1=(c.y0.as_str()) y2=(c.y1.as_str())/>
1726+ <g class="mx-tip">
1727+ <rect x=(hit.tip_x.as_str()) y=(hit.tip_y.as_str()) width=(hit.tip_w.as_str()) height=(hit.tip_h.as_str()) rx="4"/>
1728+ for line in hit.lines.iter() {
1729+ <text x=(line.x.as_str()) y=(line.y.as_str())>(line.text.as_str())</text>
1730+ }
1731+ </g>
1732+ </g>
1733+ }
1734+ </svg>
1735+ </div>
1736+ }
1737+ </div>
1738+ <details class="mx-table">
1739+ <summary>(s(lang, "Show as table", "Tablo olarak göster"))</summary>
1740+ <div class="table-wrap mx-table-scroll">
1741+ <table class="table">
1742+ <thead><tr><th>(s(lang, "Time (UTC)", "Saat (UTC)"))</th><th>(s(lang, "CPU", "CPU"))</th><th>(s(lang, "Memory", "Bellek"))</th><th>(s(lang, "Received", "Alınan"))</th><th>(s(lang, "Sent", "Gönderilen"))</th></tr></thead>
1743+ <tbody>
1744+ for row in metrics.rows.iter() {
1745+ <tr>
1746+ <td class="nowrap">(row.time.as_str())</td>
1747+ <td class="nowrap">(row.cpu.as_str())</td>
1748+ <td class="nowrap">(row.mem.as_str())</td>
1749+ <td class="nowrap">(row.rx.as_str())</td>
1750+ <td class="nowrap">(row.tx.as_str())</td>
1751+ </tr>
1752+ }
1753+ </tbody>
1754+ </table>
1755+ </div>
1756+ </details>
1757+ }
1758+ } else if tab == "jobs" {
1759+ <h2>(s(lang, "Running now", "Şu an çalışan"))</h2>
1760+ if running_jobs.is_empty() {
1761+ <p class="muted small">(s(lang, "Not running any job.", "Hiçbir iş çalıştırmıyor."))</p>
1762+ } else {
1763+ <div class="table-wrap">
1764+ <table class="table queue-table">
1765+ <thead><tr><th>(s(lang, "Job", "İş"))</th><th>(s(lang, "Repo", "Depo"))</th><th>(s(lang, "Run", "Çalıştırma"))</th><th>(s(lang, "Running for", "Çalışma süresi"))</th><th>(s(lang, "Waited", "Bekleme"))</th></tr></thead>
1766+ <tbody>
1767+ for job in running_jobs.iter() {
1768+ <tr>
1769+ <td>(job.name.as_str())</td>
1770+ <td class="nowrap">(job.repo.as_str())</td>
1771+ <td class="nowrap"><a href=(job.run_href.as_str())>(job.run_text.as_str())</a></td>
1772+ <td class="nowrap">(job.duration.as_str())</td>
1773+ <td class="nowrap">(job.waited.as_str())</td>
1774+ </tr>
1775+ }
1776+ </tbody>
1777+ </table>
1778+ </div>
1779+ }
1780+ <h2>(s(lang, "Recent", "Son"))</h2>
1781+ if recent_jobs.is_empty() {
1782+ <p class="muted small">(s(lang, "No finished jobs yet.", "Henüz biten iş yok."))</p>
1783+ } else {
1784+ <div class="table-wrap">
1785+ <table class="table queue-table">
1786+ <thead><tr><th>(s(lang, "Job", "İş"))</th><th>(s(lang, "Repo", "Depo"))</th><th>(s(lang, "Run", "Çalıştırma"))</th><th>(s(lang, "State", "Durum"))</th><th>(s(lang, "Took", "Süre"))</th><th>(s(lang, "Waited", "Bekleme"))</th><th>(s(lang, "Finished", "Bitiş"))</th></tr></thead>
1787+ <tbody>
1788+ for job in recent_jobs.iter() {
1789+ <tr>
1790+ <td>(job.name.as_str())</td>
1791+ <td class="nowrap">(job.repo.as_str())</td>
1792+ <td class="nowrap"><a href=(job.run_href.as_str())>(job.run_text.as_str())</a></td>
1793+ <td><span class=(job.state_class.as_str())>(job.state_text.as_str())</span></td>
1794+ <td class="nowrap">(job.duration.as_str())</td>
1795+ <td class="nowrap">(job.waited.as_str())</td>
1796+ <td class="nowrap"><time data-rel="true" datetime=(job.finished_at.as_str())>(job.finished_ago.as_str())</time></td>
1797+ </tr>
1798+ }
1799+ </tbody>
1800+ </table>
1801+ </div>
1802+ }
1314 } else {1803 } else {
1315 <p class="muted small">(s(lang, "Set when the runner registered. These cannot be changed from the forge.", "Çalıştırıcı kaydolurken belirlenir. Forge üzerinden değiştirilemez."))</p>1804 <p class="muted small">(s(lang, "Set when the runner registered. These cannot be changed from the forge.", "Çalıştırıcı kaydolurken belirlenir. Forge üzerinden değiştirilemez."))</p>
1316 <div class="srv-grid">1805 <div class="srv-grid">
@@ -1350,9 +1839,20 @@ async fn runner_detail_page(cx: &Cx) -> Result<impl View> {
1350 } else {1839 } else {
1351 Vec::new()1840 Vec::new()
1352 };1841 };
1842+ let (running_jobs, recent_jobs) = if tab == "jobs" {
1843+ runner_job_rows(state, lang, &runner.id).await?
1844+ } else {
1845+ (Vec::new(), Vec::new())
1846+ };
1847+ let metrics = if tab == "metrics" {
1848+ let samples = state.runner_metrics.samples(&runner.id);
1849+ metrics_tab(lang, &samples, now_unix().saturating_mul(1000))
1850+ } else {
1851+ MetricsTab::default()
1852+ };
1353 let title = runner.name.clone();1853 let title = runner.name.clone();
1354 Ok(view! {1854 Ok(view! {
1355- shell(title: title.as_str(), viewer: Some(&viewer), runner_detail_view(lang: lang, csrf: csrf, runner: runner.clone(), row: row, fields: fields, notice: notice, tab: tab, log: log))1855+ shell(title: title.as_str(), viewer: Some(&viewer), runner_detail_view(lang: lang, csrf: csrf, runner: runner.clone(), row: row, fields: fields, notice: notice, tab: tab, log: log, running_jobs: running_jobs, recent_jobs: recent_jobs, metrics: metrics))
1356 })1856 })
1357 }1857 }
1358 1858
crates/forge-web/src/pages/settings_security.rsmodified+1 -0
@@ -1105,6 +1105,7 @@ mod tests {
1105 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),1105 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
1106 ci_live: Arc::new(crate::ci::CiLive::default()),1106 ci_live: Arc::new(crate::ci::CiLive::default()),
1107 runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()),1107 runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()),
1108+ runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()),
1108 live: Arc::new(crate::live::LiveHub::default()),1109 live: Arc::new(crate::live::LiveHub::default()),
1109 push_live: Arc::new(crate::web_push::PushLive::default()),1110 push_live: Arc::new(crate::web_push::PushLive::default()),
1110 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),1111 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),
crates/forge-web/src/state.rsmodified+3 -0
@@ -51,6 +51,9 @@ pub struct AppState {
51 pub ci_live: Arc<crate::ci::CiLive>,51 pub ci_live: Arc<crate::ci::CiLive>,
52 /// The log each CI runner sent, kept in memory for its admin page. See `ci::runner_log`.52 /// The log each CI runner sent, kept in memory for its admin page. See `ci::runner_log`.
53 pub runner_logs: Arc<crate::ci::runner_log::RunnerLogs>,53 pub runner_logs: Arc<crate::ci::runner_log::RunnerLogs>,
54+ /// The host CPU, memory and network samples of each CI runner, for the graphs on its page. See
55+ /// `ci::runner_metrics`.
56+ pub runner_metrics: Arc<crate::ci::runner_metrics::RunnerMetrics>,
54 /// Change signals of live pages, keyed by topic. See `live`.57 /// Change signals of live pages, keyed by topic. See `live`.
55 pub live: Arc<crate::live::LiveHub>,58 pub live: Arc<crate::live::LiveHub>,
56 /// Device changes per user. The settings pages showing a user's push devices listen to it.59 /// Device changes per user. The settings pages showing a user's push devices listen to it.
crates/forge-web/src/test_support.rsmodified+1 -0
@@ -94,6 +94,7 @@ pub async fn test_state(dir: &Path) -> AppState {
94 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),94 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
95 ci_live: Arc::new(crate::ci::CiLive::default()),95 ci_live: Arc::new(crate::ci::CiLive::default()),
96 runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()),96 runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()),
97+ runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()),
97 live: Arc::new(crate::live::LiveHub::default()),98 live: Arc::new(crate::live::LiveHub::default()),
98 push_live: Arc::new(crate::web_push::PushLive::default()),99 push_live: Arc::new(crate::web_push::PushLive::default()),
99 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),100 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),
style/_admin_rows.scssmodified+140 -0
@@ -121,3 +121,143 @@
121 .ci-log.runner-log {121 .ci-log.runner-log {
122 padding: 8px 12px;122 padding: 8px 12px;
123 }123 }
124+
125+// The metrics tab: three small graphs, one under another, each with its caption on the left. Every
126+// graph is its own SVG with one y axis; colours come from tokens only. A line follows the accent, a
127+// sent line is dashed in the secondary text colour so it is told apart without colour.
128+.mx-stack {
129+ display: grid;
130+ gap: 10px;
131+}
132+
133+.mx-row {
134+ display: grid;
135+ grid-template-columns: 200px minmax(0, 1fr);
136+ align-items: center;
137+ gap: 4px 16px;
138+}
139+
140+.mx-caption {
141+ margin: 0;
142+ color: var(--text);
143+ font-size: 0.875rem;
144+ font-weight: 600;
145+ font-variant-numeric: tabular-nums;
146+ white-space: nowrap;
147+}
148+
149+.mx-legend {
150+ display: flex;
151+ flex-wrap: wrap;
152+ gap: 4px 12px;
153+ margin: 4px 0 0;
154+ padding: 0;
155+ list-style: none;
156+ color: var(--text-2);
157+ font-size: 0.75rem;
158+}
159+
160+// A legend swatch: a short line in the series' style. It carries the identity, the text does not.
161+.mx-key {
162+ display: inline-block;
163+ width: 16px;
164+ margin-right: 6px;
165+ border-top: 2px solid var(--accent);
166+ vertical-align: middle;
167+}
168+
169+.mx-key-sent {
170+ border-top-style: dashed;
171+ border-top-color: var(--text-2);
172+}
173+
174+.mx-svg {
175+ display: block;
176+ width: 100%;
177+ height: auto;
178+ overflow: visible;
179+}
180+
181+.mx-grid {
182+ stroke: var(--border);
183+ stroke-width: 1;
184+ opacity: 0.6;
185+ vector-effect: non-scaling-stroke;
186+}
187+
188+.mx-band {
189+ fill: var(--accent-soft);
190+}
191+
192+.mx-axis {
193+ fill: var(--muted);
194+ font-size: 9px;
195+ font-variant-numeric: tabular-nums;
196+}
197+
198+.mx-line {
199+ fill: none;
200+ stroke: var(--accent);
201+ stroke-width: 2;
202+ stroke-linejoin: round;
203+ stroke-linecap: round;
204+ vector-effect: non-scaling-stroke;
205+}
206+
207+.mx-line-sent {
208+ stroke: var(--text-2);
209+ stroke-dasharray: 4 3;
210+}
211+
212+// The hover band covers the whole plot height of one bucket and is see-through.
213+.mx-hit-area {
214+ fill: transparent;
215+}
216+
217+.mx-cross {
218+ stroke: var(--muted);
219+ stroke-width: 1;
220+ opacity: 0;
221+ pointer-events: none;
222+ vector-effect: non-scaling-stroke;
223+}
224+
225+.mx-tip {
226+ opacity: 0;
227+ pointer-events: none;
228+
229+ rect {
230+ fill: var(--surface);
231+ stroke: var(--border-strong);
232+ stroke-width: 1;
233+ }
234+
235+ text {
236+ fill: var(--text);
237+ font-size: 9px;
238+ font-variant-numeric: tabular-nums;
239+ }
240+}
241+
242+.mx-hit:hover .mx-tip,
243+.mx-hit:hover .mx-cross {
244+ opacity: 1;
245+}
246+
247+.mx-table summary {
248+ margin-top: 6px;
249+ color: var(--text-2);
250+ font-size: 0.8125rem;
251+ cursor: pointer;
252+}
253+
254+.mx-table-scroll {
255+ max-height: 240px;
256+ overflow: auto;
257+}
258+
259+@media (max-width: 600px) {
260+ .mx-row {
261+ grid-template-columns: minmax(0, 1fr);
262+ }
263+}