From 42861fb5920826ad7717b60d817fb1dbfd265271 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 30 Oct 2026 00:31:01 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(ci):=20a=20runner's=20page=20a?= =?UTF-8?q?nswers=20what=20it=20is=20working=20on=20and=20how=20its=20host?= =?UTF-8?q?=20is=20doing:=20a=20Jobs=20tab=20lists=20the=20jobs=20it=20run?= =?UTF-8?q?s=20now=20and=20its=20last=2020=20finished=20ones,=20each=20wit?= =?UTF-8?q?h=20its=20run,=20how=20long=20it=20ran=20and=20how=20long=20it?= =?UTF-8?q?=20waited=20in=20the=20queue=20(the=20Running=20jobs=20stat=20l?= =?UTF-8?q?inks=20there,=20and=20ci=5Fjobs=20gets=20an=20index=20on=20runn?= =?UTF-8?q?er=5Fid,=20started=5Fat);=20a=20Metrics=20tab=20graphs=20the=20?= =?UTF-8?q?last=20hour=20of=20CPU=20(with=20the=20time=20jobs=20ran=20shad?= =?UTF-8?q?ed),=20memory=20against=20the=20total=20and=20network=20receive?= =?UTF-8?q?d=20and=20sent,=20from=20samples=20the=20runner=20takes=20from?= =?UTF-8?q?=20/proc=20every=205=20s=20and=20sends=20every=2010=20s;=20the?= =?UTF-8?q?=20graphs=20are=20server-drawn=20SVG=20in=20the=20accent=20colo?= =?UTF-8?q?ur=20with=20a=20hover=20readout=20per=2030=20s=20and=20a=20tabl?= =?UTF-8?q?e=20view,=20and=20the=20forge=20keeps=20the=20samples=20in=20me?= =?UTF-8?q?mory?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-ci/src/proto.rs | 27 + .../migrations/0068_ci_jobs_runner.sql | 4 + crates/forge-core/src/ci.rs | 14 + crates/forge-core/src/store/ci.rs | 52 +- crates/forge-core/src/store/migrate.rs | 1 + crates/forge-runner/src/client.rs | 33 +- crates/forge-runner/src/lib.rs | 1 + crates/forge-runner/src/metrics.rs | 230 ++++++++ crates/forge-runner/src/runner.rs | 13 + crates/forge-runner/src/selflog.rs | 5 +- crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/ci/api.rs | 39 +- crates/forge-web/src/ci/metrics_chart.rs | 290 ++++++++++ crates/forge-web/src/ci/mod.rs | 2 + crates/forge-web/src/ci/runner_log.rs | 5 +- crates/forge-web/src/ci/runner_metrics.rs | 69 +++ crates/forge-web/src/pages/admin_runners.rs | 514 +++++++++++++++++- .../forge-web/src/pages/settings_security.rs | 1 + crates/forge-web/src/state.rs | 3 + crates/forge-web/src/test_support.rs | 1 + style/_admin_rows.scss | 140 +++++ 21 files changed, 1427 insertions(+), 18 deletions(-) create mode 100644 crates/forge-core/migrations/0068_ci_jobs_runner.sql create mode 100644 crates/forge-runner/src/metrics.rs create mode 100644 crates/forge-web/src/ci/metrics_chart.rs create mode 100644 crates/forge-web/src/ci/runner_metrics.rs diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index 3353a41..3364a01 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -130,6 +130,33 @@ pub struct RunnerLogAck { pub next_seq: u64, } +/// The capability of a runner that sends [`RunnerMetricsBatch`]. +pub const CAP_RUNNER_METRICS: &str = "runner_metrics"; + +/// `POST /api/v1/ci/runners/metrics`: host usage samples, oldest first, for the graphs on the +/// runner's admin page. Answered with 204. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct RunnerMetricsBatch { + pub samples: Vec, +} + +/// One sample of the runner's host. Rates cover the time since the previous sample. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct RunnerSample { + /// Unix time in milliseconds. + pub at_ms: i64, + /// Busy share of all CPUs, 0 to 100. + pub cpu_percent: f32, + /// Memory in use (total minus available), in bytes. + pub mem_used_bytes: u64, + pub mem_total_bytes: u64, + /// Received and sent bytes per second over every interface but loopback. + pub net_rx_bytes_per_s: u64, + pub net_tx_bytes_per_s: u64, + /// Jobs running on the runner. + pub running_jobs: u32, +} + /// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish /// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops /// claiming, restarts the way a self-update does (exit 75), and the forge clears diff --git a/crates/forge-core/migrations/0068_ci_jobs_runner.sql b/crates/forge-core/migrations/0068_ci_jobs_runner.sql new file mode 100644 index 0000000..293235c --- /dev/null +++ b/crates/forge-core/migrations/0068_ci_jobs_runner.sql @@ -0,0 +1,4 @@ +-- A runner's admin page lists the jobs it ran, newest first (the Jobs tab). Applied by +-- store/migrate.rs. + +CREATE INDEX ci_jobs_runner ON ci_jobs(runner_id, started_at); diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 43d0452..409e927 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -557,6 +557,20 @@ pub struct CiJob { pub oom_kills: Option, } +/// A job of one runner, with the run and repo it belongs to, for the runner's admin page. The +/// run's page is `/{owner}/{repo}/ci/runs/{run_number}`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RunnerJob { + /// The job itself. + pub job: CiJob, + /// The number of the job's run, within its repo. + pub run_number: i64, + /// The username of the repo's owner. + pub owner: String, + /// The repo's name. + pub repo: String, +} + /// An artifact uploaded by a job. The file itself is stored outside the database. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiArtifact { diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index dd10dfe..43ff8da 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -15,8 +15,8 @@ use super::{ }; use crate::ci::{ CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY, - MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerReport, - RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field, + MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerJob, + RunnerReport, RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field, }; use crate::error::{Error, Result}; use crate::secret; @@ -33,6 +33,12 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \ reported_memory_budget, reported_memory_free, reported_memory_reserve"; +/// The job columns of `runner_jobs`, then the run's number and the repo's owner and name. +const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \ + j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \ + j.log_bytes, j.oom_kills, r.number, u.username, p.name"; +const RUNNER_JOB_FROM: &str = "FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id \ + JOIN repos p ON p.id = r.repo_id JOIN users u ON u.id = p.owner_id"; const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at"; /// Longest runner name, in bytes. @@ -155,6 +161,15 @@ fn map_job(row: &Row) -> Result { }) } +fn map_runner_job(row: &Row) -> Result { + Ok(RunnerJob { + job: map_job(row)?, + run_number: col_int(row, 15)?, + owner: col_text(row, 16)?, + repo: col_text(row, 17)?, + }) +} + fn map_artifact(row: &Row) -> Result { Ok(CiArtifact { id: col_text(row, 0)?, @@ -1663,6 +1678,39 @@ impl Store { jobs_of_run(&conn, run_id).await } + /// The jobs a runner holds or held: every running one, then its `recent` newest finished jobs + /// (by start time). Each carries its run's number and its repo's owner and name. + pub async fn runner_jobs(&self, runner_id: &str, recent: usize) -> Result> { + let conn = self.read_conn().await; + let mut jobs = fetch_all( + &conn, + &format!( + "SELECT {RUNNER_JOB_COLS} {RUNNER_JOB_FROM} \ + WHERE j.runner_id = ?1 AND j.state = 'running' ORDER BY j.started_at DESC" + ), + (runner_id.to_string(),), + map_runner_job, + ) + .await?; + let finished = fetch_all( + &conn, + &format!( + "SELECT {RUNNER_JOB_COLS} {RUNNER_JOB_FROM} \ + WHERE j.runner_id = ?1 \ + AND j.state IN ('success', 'failure', 'cancelled', 'error', 'skipped') \ + ORDER BY j.started_at DESC LIMIT ?2" + ), + ( + runner_id.to_string(), + i64::try_from(recent).unwrap_or(i64::MAX), + ), + map_runner_job, + ) + .await?; + jobs.extend(finished); + Ok(jobs) + } + pub async fn job_by_id(&self, id: &str) -> Result> { let conn = self.read_conn().await; load_job(&conn, id).await diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 1afdff8..c849a62 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -107,6 +107,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (65, include_str!("../../migrations/0065_hue_colours.sql")), (66, include_str!("../../migrations/0066_session_ip.sql")), (67, include_str!("../../migrations/0067_coauthored_commits.sql")), + (68, include_str!("../../migrations/0068_ci_jobs_runner.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-runner/src/client.rs b/crates/forge-runner/src/client.rs index 643d067..35001b8 100644 --- a/crates/forge-runner/src/client.rs +++ b/crates/forge-runner/src/client.rs @@ -7,10 +7,11 @@ use std::path::Path; use std::time::Duration; use forge_ci::proto::{ - BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CAP_RUNNER_LOG, CONCURRENCY_HEADER, ClaimRequest, - FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, - RESTART_HEADER, RegisterRequest, RegisterResponse, RequeueRequest, RestartMode, - RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, + BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CAP_RUNNER_LOG, CAP_RUNNER_METRICS, CONCURRENCY_HEADER, + ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, + RESERVE_MEMORY_HEADER, RESTART_HEADER, RegisterRequest, RegisterResponse, RequeueRequest, + RestartMode, RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, + RunnerMetricsBatch, }; use reqwest::StatusCode; use reqwest::header::{CONTENT_LENGTH, HeaderMap}; @@ -35,6 +36,8 @@ const BINARY_PATH: &str = "/api/v1/ci/runners/binary"; const CONFIG_PATH: &str = "/api/v1/ci/runners/config"; /// `POST`: lines of the runner's own log, see [`crate::selflog`]. const RUNNER_LOG_PATH: &str = "/api/v1/ci/runners/log"; +/// `POST`: host samples for the runner's graphs, see [`crate::metrics`]. +const RUNNER_METRICS_PATH: &str = "/api/v1/ci/runners/metrics"; /// Errors from talking to the forge. #[derive(Debug, thiserror::Error)] @@ -152,6 +155,7 @@ impl ForgeClient { CAP_RESTART.to_owned(), CAP_REQUEUE.to_owned(), CAP_RUNNER_LOG.to_owned(), + CAP_RUNNER_METRICS.to_owned(), ], free_memory_bytes: memory.map(|m| m.free), memory_budget_bytes: memory.map(|m| m.budget), @@ -243,6 +247,27 @@ impl ForgeClient { json_or_error(resp).await } + /// `POST /api/v1/ci/runners/metrics`: ships host samples. Answered with 204. + pub async fn post_runner_metrics( + &self, + runner_secret: &str, + batch: &RunnerMetricsBatch, + ) -> Result<(), ClientError> { + let resp = self + .http + .post(self.url(RUNNER_METRICS_PATH)) + .bearer_auth(runner_secret) + .json(batch) + .timeout(REQUEST_TIMEOUT) + .send() + .await?; + if resp.status().is_success() { + Ok(()) + } else { + Err(status_error(resp).await) + } + } + /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised /// value and syncs the file. diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index ced40d0..80af47a 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -14,6 +14,7 @@ pub mod disk; pub mod executor; pub mod limiter; pub mod logs; +pub mod metrics; pub mod memory; pub mod oci; pub mod oom; diff --git a/crates/forge-runner/src/metrics.rs b/crates/forge-runner/src/metrics.rs new file mode 100644 index 0000000..dac013e --- /dev/null +++ b/crates/forge-runner/src/metrics.rs @@ -0,0 +1,230 @@ +//! Host metrics for the graphs on the runner's admin page. Every [`EVERY`] the runner reads +//! `/proc` (CPU, memory, network) and turns the counters into a sample: CPU share and rates since +//! the previous reading. [`ship`] posts the buffered samples every [`FLUSH_EVERY`] ticks. On a +//! host without a readable `/proc` nothing is sampled and nothing is sent. + +use std::collections::VecDeque; +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; + +/// Time between two samples. +pub const EVERY: Duration = Duration::from_secs(5); +/// The buffer is posted on every this many ticks. +const FLUSH_EVERY: u64 = 2; +/// Most samples the buffer holds while the forge cannot be reached (an hour). The oldest go first. +pub const CAPACITY: usize = 360; + +/// Counters read from `/proc` at one moment. Busy and total are CPU jiffies, the others are +/// memory in bytes and network bytes since boot. +#[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, +} + +/// `(busy, total)` jiffies of the first `cpu ` line of `/proc/stat`. Idle includes iowait. +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)) +} + +/// `(MemTotal, MemAvailable)` of `/proc/meminfo`, in bytes. The file reports kibibytes. +pub fn parse_mem(text: &str) -> Option<(u64, u64)> { + let find = |key: &str| { + let line = text.lines().find(|l| l.starts_with(key))?; + let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; + kib.checked_mul(1024) + }; + Some((find("MemTotal:")?, find("MemAvailable:")?)) +} + +/// `(rx, tx)` bytes summed over the interfaces of `/proc/net/dev` except `lo`. The two header +/// lines have no colon and are skipped. +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)) +} + +/// Reads the three `/proc` files. `None` when any of them is missing or unreadable. +pub fn read_snapshot() -> 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 (mem_total, mem_available) = parse_mem(&mem)?; + let (rx, tx) = parse_net_dev(&net)?; + Some(Snapshot { + busy, + total, + mem_total, + mem_available, + rx, + tx, + }) +} + +/// Turns successive snapshots into samples. The first snapshot only sets the baseline. +#[derive(Default)] +pub struct Sampler { + prev: Option<(Instant, Snapshot)>, +} + +impl Sampler { + /// The sample for `snap`, taken at `now`, or `None` for the first reading. + 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) + }; + // Saturating `as` casts keep a negative or huge rate in range. + 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), + running_jobs, + }) + } +} + +/// Samples the host every [`EVERY`] and posts the buffer every [`FLUSH_EVERY`] ticks. `running` +/// gives the jobs on the runner now. A failed post keeps the buffer for the next one. An older +/// forge without the endpoint answers 404, and then sampling stops for good. When `stop` is +/// cancelled, the buffer gets one last post before returning. +pub async fn ship( + client: ForgeClient, + runner_secret: String, + 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() { + 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"; + // Total 1010, idle 840, so busy 170. + assert_eq!(parse_cpu(text), Some((170, 1010))); + } + + #[test] + fn mem_reads_total_and_available_in_bytes() { + let text = "MemTotal: 16000000 kB\nMemFree: 1000000 kB\nMemAvailable: 4000000 kB\n"; + assert_eq!(parse_mem(text), Some((16_000_000 * 1024, 4_000_000 * 1024))); + } + + #[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))); + } +} diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index c98bced..b6494d0 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -20,6 +20,7 @@ use crate::executor::{ExecRequest, ExecResult, Executor}; use crate::limiter::Limiter; use crate::logs::{self, PumpConfig}; use crate::memory::MemoryGate; +use crate::metrics; use crate::oom::OomSink; use crate::pressure::Pressure; use crate::restart::{self, RestartState, Step}; @@ -168,6 +169,17 @@ impl Runner { self.config.runner_secret.clone(), ship_stop.clone(), )); + // Host samples for the graphs, stopped with the same token. Jobs in use = slots taken. + let limiter = self.limiter.clone(); + let metrics_shipper = tokio::spawn(metrics::ship( + self.client.clone(), + self.config.runner_secret.clone(), + move || { + let busy = limiter.current().saturating_sub(limiter.free_slots()); + u32::try_from(busy).unwrap_or(u32::MAX) + }, + ship_stop.clone(), + )); // The reason the claim loop last logged for not claiming, see `not_claiming`. let mut blocked: Option = None; let end = loop { @@ -361,6 +373,7 @@ impl Runner { // The last lines go out too, but a dead forge must not hold up the exit. ship_stop.cancel(); let _ = tokio::time::timeout(LOG_FLUSH, shipper).await; + let _ = tokio::time::timeout(LOG_FLUSH, metrics_shipper).await; end } diff --git a/crates/forge-runner/src/selflog.rs b/crates/forge-runner/src/selflog.rs index b52d18a..fa0b9cc 100644 --- a/crates/forge-runner/src/selflog.rs +++ b/crates/forge-runner/src/selflog.rs @@ -33,8 +33,7 @@ static RING: OnceLock> = OnceLock::new(); /// The ring shared by the layer and the shipper. pub fn ring() -> Arc { - RING.get_or_init(|| Arc::new(Ring::new(CAPACITY))) - .clone() + RING.get_or_init(|| Arc::new(Ring::new(CAPACITY))).clone() } /// 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 { } } -fn now_ms() -> i64 { +pub(crate) fn now_ms() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)) diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 8e2a789..884f771 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -136,6 +136,7 @@ pub async fn serve( notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), ci_live: Arc::new(crate::ci::CiLive::default()), runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()), + runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()), live: Arc::new(crate::live::LiveHub::default()), push_live: Arc::new(crate::web_push::PushLive::default()), packages_live: Arc::new(crate::packages_live::PackagesLive::default()), diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 173e8b5..6c6777c 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -12,7 +12,7 @@ use forge_ci::proto::{ BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER, RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart, - RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, + RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch, }; use forge_core::Error as CoreError; use forge_core::ci::{ @@ -47,6 +47,10 @@ const MAX_LOG_CHUNK: usize = 1024 * 1024; const MAX_JSON_BODY: usize = 64 * 1024; /// Largest runner log batch, in bytes. A batch holds at most 1000 lines of up to 4 KiB each. const MAX_LOG_BATCH: usize = 1024 * 1024; +/// Largest metrics batch read: 400 samples of about 150 bytes each fit well inside it. +const MAX_METRICS_BATCH: usize = 256 * 1024; +/// Most samples one metrics batch may carry. +const MAX_METRICS_SAMPLES: usize = 400; /// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say. const DEFAULT_RESERVE: u64 = 1 << 30; /// Longest runner name or label, in bytes. @@ -351,6 +355,39 @@ async fn runner_log(cx: &Cx, body: Body) -> topcoat::Result { Ok(api::json(StatusCode::OK, &ack)) } +/// `POST /api/v1/ci/runners/metrics`: host usage samples of the runner, for the graphs on its admin +/// page. Answers 204 with no body. +#[route(POST "/api/v1/ci/runners/metrics")] +async fn runner_metrics(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + let runner = match runner_from(state, headers(cx)).await { + Ok(runner) => runner, + Err(res) => return Ok(*res), + }; + let bytes = match api::read_body(body, MAX_METRICS_BATCH).await { + Ok(bytes) => bytes, + Err(res) => return Ok(*res), + }; + let batch: RunnerMetricsBatch = match serde_json::from_slice(&bytes) { + Ok(batch) => batch, + Err(e) => { + return Ok(api::error( + StatusCode::BAD_REQUEST, + &format!("invalid JSON body: {e}"), + )); + } + }; + if batch.samples.len() > MAX_METRICS_SAMPLES { + return Ok(api::error( + StatusCode::UNPROCESSABLE_ENTITY, + "too many samples in one batch", + )); + } + state.runner_metrics.ingest(&runner.id, &batch); + state.ci_live.bump_runners(); + Ok(empty(StatusCode::NO_CONTENT)) +} + /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it /// starts, applies them to its in-memory config, then reports its effective config here. #[route(GET "/api/v1/ci/runners/config")] diff --git a/crates/forge-web/src/ci/metrics_chart.rs b/crates/forge-web/src/ci/metrics_chart.rs new file mode 100644 index 0000000..2cb15f9 --- /dev/null +++ b/crates/forge-web/src/ci/metrics_chart.rs @@ -0,0 +1,290 @@ +//! The geometry of the runner metrics graphs on the runner's admin page. Pure functions: samples go +//! in, plain numbers and SVG path data come out, and the view in `pages::admin_runners` writes the +//! markup. The plot covers the last hour in 30 s buckets (120 points). A bucket with no sample is +//! `None`, and a line breaks where two kept buckets are more than 30 s apart. + +use forge_ci::proto::RunnerSample; + +/// The width of the chart's viewBox. The SVG scales to its container with the aspect kept. +pub const VIEW_W: f64 = 700.0; +/// The height of the chart's viewBox. +pub const VIEW_H: f64 = 110.0; +/// Where the plot starts and ends on the x axis, and its top and bottom on the y axis. +pub const X0: f64 = 40.0; +pub const X1: f64 = 696.0; +pub const Y0: f64 = 6.0; +pub const Y1: f64 = 94.0; +/// The time one bucket covers, in milliseconds. +pub const BUCKET_MS: i64 = 30_000; +/// The number of buckets across the hour. +pub const BUCKETS: usize = 120; +/// The longest gap between two samples that a line bridges, in milliseconds. +const GAP_MS: i64 = 30_000; +/// The hover tooltip's size and its distance from the crosshair, in viewBox units. +const TIP_W: f64 = 128.0; +const TIP_H: f64 = 40.0; +const TIP_GAP: f64 = 8.0; + +/// The averages of the samples in one bucket. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Bucket { + /// Start of the bucket, Unix milliseconds. + pub at_ms: i64, + /// The first and last sample times in the bucket, used to break a line at a gap. + pub first_ms: i64, + pub last_ms: i64, + pub cpu: f64, + pub mem_used: f64, + pub mem_total: f64, + pub rx: f64, + pub tx: f64, + /// The most jobs running in any sample of the bucket. + pub running: u32, +} + +/// One line of the chart: its SVG path data and its CSS class. +#[derive(Clone, Debug, PartialEq)] +pub struct Path { + pub d: String, + pub class: &'static str, +} + +/// The hover target of one bucket: a band over the bucket, a crosshair at its centre, and a tooltip +/// box beside the crosshair. +#[derive(Clone, Debug, PartialEq)] +pub struct Hit { + pub x: f64, + pub w: f64, + pub cx: f64, + pub bucket: Bucket, + pub tip_x: f64, + pub tip_y: f64, + pub tip_w: f64, + pub tip_h: f64, +} + +/// One line of a chart: how to read its value from a bucket, and its CSS class. +pub type Series = (fn(&Bucket) -> f64, &'static str); + +/// Everything one chart draws, apart from its axis labels. +#[derive(Clone, Debug, PartialEq)] +pub struct Svg { + /// The y positions of the gridlines. + pub grids: Vec, + /// The y position and the value of each y label. + pub ticks: Vec<(f64, f64)>, + /// The x position and width of each band that marks running jobs. + pub bands: Vec<(f64, f64)>, + pub paths: Vec, + pub hits: Vec, +} + +/// Averages the samples of the last hour into `BUCKETS` buckets, oldest first. Samples before the +/// window or after `now_ms` are left out. +pub fn chart_points(samples: &[RunnerSample], now_ms: i64) -> Vec> { + let start = now_ms - BUCKET_MS * BUCKETS as i64; + let mut sums: Vec> = vec![None; BUCKETS]; + for s in samples { + if s.at_ms < start || s.at_ms > now_ms { + continue; + } + let index = (((s.at_ms - start) / BUCKET_MS) as usize).min(BUCKETS - 1); + let at_ms = start + index as i64 * BUCKET_MS; + let (bucket, count) = sums[index].get_or_insert(( + Bucket { + at_ms, + first_ms: s.at_ms, + last_ms: s.at_ms, + cpu: 0.0, + mem_used: 0.0, + mem_total: 0.0, + rx: 0.0, + tx: 0.0, + running: 0, + }, + 0.0, + )); + bucket.first_ms = bucket.first_ms.min(s.at_ms); + bucket.last_ms = bucket.last_ms.max(s.at_ms); + bucket.cpu += f64::from(s.cpu_percent); + bucket.mem_used += s.mem_used_bytes as f64; + bucket.mem_total = bucket.mem_total.max(s.mem_total_bytes as f64); + bucket.rx += s.net_rx_bytes_per_s as f64; + bucket.tx += s.net_tx_bytes_per_s as f64; + bucket.running = bucket.running.max(s.running_jobs); + *count += 1.0; + } + sums.into_iter() + .map(|slot| { + slot.map(|(mut bucket, count)| { + bucket.cpu /= count; + bucket.mem_used /= count; + bucket.rx /= count; + bucket.tx /= count; + bucket + }) + }) + .collect() +} + +/// The smallest "nice" number (1, 2, 2.5 or 5 times a power of ten) that is at least `value`. +/// Zero gives 1. +pub fn nice_max(value: u64) -> u64 { + if value <= 1 { + return 1; + } + let mut unit = 1u64; + while unit.saturating_mul(10) <= value { + unit *= 10; + } + [unit, unit * 2, unit * 5 / 2, unit * 5, unit * 10] + .into_iter() + .find(|candidate| *candidate >= value) + .unwrap_or(unit * 10) +} + +/// The largest value of a series over the buckets, as a whole number of bytes per second, at least +/// 1 KiB/s so a quiet network gets a readable scale. +pub fn net_max(points: &[Option]) -> f64 { + let peak = points + .iter() + .flatten() + .map(|b| b.rx.max(b.tx)) + .fold(0.0_f64, f64::max); + nice_max((peak.ceil() as u64).max(1024)) as f64 +} + +/// Builds the chart of `points`. `max` is the top of the y axis; `series` gives each line's value +/// and CSS class. `band` marks the buckets where jobs ran. +pub fn svg(points: &[Option], max: f64, series: &[Series], band: bool) -> Svg { + let max = if max > 0.0 { max } else { 1.0 }; + let bw = bucket_width(); + let bands = if band { + points + .iter() + .enumerate() + .filter(|(_, p)| p.is_some_and(|b| b.running > 0)) + .map(|(i, _)| (X0 + i as f64 * bw, bw)) + .collect() + } else { + Vec::new() + }; + let paths = series + .iter() + .map(|(value, class)| Path { + d: line_d(points, *value, max), + class, + }) + .collect(); + let hits = points + .iter() + .enumerate() + .filter_map(|(i, p)| { + let bucket = (*p)?; + let cx = X0 + (i as f64 + 0.5) * bw; + let tip_x = if cx > (X0 + X1) / 2.0 { + cx - TIP_GAP - TIP_W + } else { + cx + TIP_GAP + }; + Some(Hit { + x: X0 + i as f64 * bw, + w: bw, + cx, + bucket, + tip_x, + tip_y: Y0 + 2.0, + tip_w: TIP_W, + tip_h: TIP_H, + }) + }) + .collect(); + Svg { + grids: vec![y_of(max / 2.0, max), y_of(max, max)], + ticks: vec![ + (y_of(0.0, max), 0.0), + (y_of(max / 2.0, max), max / 2.0), + (y_of(max, max), max), + ], + bands, + paths, + hits, + } +} + +fn bucket_width() -> f64 { + (X1 - X0) / BUCKETS as f64 +} + +fn y_of(value: f64, max: f64) -> f64 { + Y1 - (value / max).clamp(0.0, 1.0) * (Y1 - Y0) +} + +/// The path of one series. A line is one `M` and `L` run; a bucket with no sample, or a gap of more +/// than `GAP_MS` between two samples, starts a new `M`. +fn line_d(points: &[Option], value: fn(&Bucket) -> f64, max: f64) -> String { + let bw = bucket_width(); + let mut d = String::new(); + let mut prev: Option = None; + for (i, point) in points.iter().enumerate() { + let Some(b) = point else { + prev = None; + continue; + }; + let joined = prev.is_some_and(|q| b.first_ms - q.last_ms <= GAP_MS); + let x = X0 + (i as f64 + 0.5) * bw; + let y = y_of(value(b), max); + d.push_str(if joined { " L" } else { " M" }); + d.push_str(&format!("{x:.1} {y:.1}")); + prev = Some(*b); + } + d.trim_start().to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample(at_ms: i64, cpu: f32) -> RunnerSample { + RunnerSample { + at_ms, + cpu_percent: cpu, + mem_used_bytes: 0, + mem_total_bytes: 0, + net_rx_bytes_per_s: 0, + net_tx_bytes_per_s: 0, + running_jobs: 0, + } + } + + /// Samples in one bucket are averaged, an empty bucket is `None`, and a gap of over 30 s starts a + /// new line segment. + #[test] + fn buckets_average_and_a_gap_breaks_the_line() { + let now = 7_200_000; + let start = now - BUCKET_MS * BUCKETS as i64; + let samples = [ + sample(start, 10.0), + sample(start + 5_000, 30.0), + // Bucket 1 is empty: the next sample comes 60 s after the last one above. + sample(start + 65_000, 50.0), + ]; + let points = chart_points(&samples, now); + assert_eq!(points[0].map(|b| b.cpu), Some(20.0)); + assert_eq!(points[1], None); + assert_eq!(points[2].map(|b| b.cpu), Some(50.0)); + let d = line_d(&points, |b| b.cpu, 100.0); + assert_eq!(d.matches('M').count(), 2, "{d}"); + assert_eq!(d.matches('L').count(), 0, "{d}"); + } + + #[test] + fn nice_max_rounds_up_to_one_two_two_and_a_half_or_five() { + assert_eq!(nice_max(0), 1); + assert_eq!(nice_max(10), 10); + assert_eq!(nice_max(11), 20); + assert_eq!(nice_max(1500), 2000); + assert_eq!(nice_max(2400), 2500); + assert_eq!(nice_max(3_145_728), 5_000_000); + } +} diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web/src/ci/mod.rs index 80f1167..a0c5c96 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web/src/ci/mod.rs @@ -14,7 +14,9 @@ pub mod api; pub mod live; pub mod reaper; pub mod release; +pub mod metrics_chart; pub mod runner_log; +pub mod runner_metrics; pub mod schedule; pub mod scheduled; diff --git a/crates/forge-web/src/ci/runner_log.rs b/crates/forge-web/src/ci/runner_log.rs index 26fc9bd..5fdf769 100644 --- a/crates/forge-web/src/ci/runner_log.rs +++ b/crates/forge-web/src/ci/runner_log.rs @@ -196,7 +196,10 @@ mod tests { #[test] fn ingest_skips_what_is_known_and_marks_gaps() { let logs = RunnerLogs::default(); - assert_eq!(logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b"])), 2); + assert_eq!( + logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b"])), + 2 + ); // Resend of 0..=2: only "c" is new. assert_eq!( logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b", "c"])), diff --git a/crates/forge-web/src/ci/runner_metrics.rs b/crates/forge-web/src/ci/runner_metrics.rs new file mode 100644 index 0000000..d400607 --- /dev/null +++ b/crates/forge-web/src/ci/runner_metrics.rs @@ -0,0 +1,69 @@ +//! The host usage of each CI runner (CPU, memory, network), kept in memory for the graphs on its +//! admin page. A runner ships its samples in batches (`POST /api/v1/ci/runners/metrics`); the forge +//! keeps the last hour per runner, at most `MAX_SAMPLES`. Samples are not stored in the database: +//! a restart of the forge drops them, and the runner keeps sending new ones. + +use std::collections::{HashMap, VecDeque}; +use std::sync::{Mutex, MutexGuard}; + +use forge_ci::proto::{RunnerMetricsBatch, RunnerSample}; + +/// How far back samples are kept, in milliseconds, counted from the newest sample. +pub const KEEP_MS: i64 = 3_600_000; +/// Most samples kept per runner. The oldest go first. +const MAX_SAMPLES: usize = 800; + +/// The samples of every runner, by runner id. Shared through `AppState`. +#[derive(Debug, Default)] +pub struct RunnerMetrics { + runners: Mutex>>, +} + +impl RunnerMetrics { + /// Takes a batch from a runner. Samples are taken in time order, and a sample whose time is not + /// after the newest one kept is ignored, so a resent sample is not stored twice. A CPU value is + /// clamped to 0 to 100, and a sample with a NaN CPU value is skipped. + pub fn ingest(&self, runner_id: &str, batch: &RunnerMetricsBatch) { + let mut sorted: Vec = batch + .samples + .iter() + .filter(|s| !s.cpu_percent.is_nan()) + .map(|s| RunnerSample { + cpu_percent: s.cpu_percent.clamp(0.0, 100.0), + ..*s + }) + .collect(); + sorted.sort_by_key(|s| s.at_ms); + + let mut runners = self.lock(); + let queue = runners.entry(runner_id.to_owned()).or_default(); + for sample in sorted { + let newest = queue.back().map_or(i64::MIN, |s| s.at_ms); + if sample.at_ms > newest { + queue.push_back(sample); + } + } + if let Some(newest) = queue.back().map(|s| s.at_ms) { + let oldest_kept = newest.saturating_sub(KEEP_MS); + while queue.front().is_some_and(|s| s.at_ms < oldest_kept) { + queue.pop_front(); + } + } + while queue.len() > MAX_SAMPLES { + queue.pop_front(); + } + } + + /// The samples of a runner, oldest first. Empty for a runner that never sent one. + pub fn samples(&self, runner_id: &str) -> Vec { + self.lock() + .get(runner_id) + .map(|queue| queue.iter().copied().collect()) + .unwrap_or_default() + } + + fn lock(&self) -> MutexGuard<'_, HashMap>> { + // A panic while the lock was held leaves the map usable, so a poisoned lock is taken as is. + self.runners.lock().unwrap_or_else(|e| e.into_inner()) + } +} diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index eff7505..6c6f8d3 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -7,8 +7,11 @@ //! runner are audited; the token itself is never written to the audit log. use forge_ci::build::{self, Freshness}; +use forge_ci::proto::RunnerSample; use forge_core::AuditAction; -use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, RestartMode, runner_field}; +use forge_core::ci::{ + CiRunner, FieldKind, JobState, RUNNER_FIELDS, RestartMode, RunnerJob, runner_field, +}; use forge_core::store::health::runner_is_online; use serde::Deserialize; use time::OffsetDateTime; @@ -23,12 +26,13 @@ use topcoat::router::{page, path_param, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; +use crate::ci::metrics_chart::{self, Bucket}; use crate::ci::runner_log::Line; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; use crate::pages::admin_users::admin_only; -use crate::pages::ci_runs::events_response; +use crate::pages::ci_runs::{age_text, duration_text, events_response, run_href, state_text}; use crate::pages::repo_mirrors::stamp_in_tz; use crate::state::AppState; use crate::views::{empty_state, enc, now_unix, relative_time, shell}; @@ -790,12 +794,15 @@ fn sel(on: bool) -> Option<&'static str> { on.then_some("selected") } -/// The detail page tabs: slug and the config keys on it. `identity` and `logs` are read-only. -const TABS: [(&str, &[&str]); 6] = [ +/// The detail page tabs: slug and the config keys on it. `jobs`, `metrics`, `identity` and `logs` are +/// read-only. +const TABS: [(&str, &[&str]); 8] = [ ( "general", &["concurrency", "labels", "executor", "auto_update"], ), + ("jobs", &[]), + ("metrics", &[]), ( "limits", &[ @@ -828,6 +835,8 @@ fn tab_label(lang: Lang, slug: &str) -> &'static str { "storage" => s(lang, "Storage", "Depolama"), "sandbox" => s(lang, "Sandbox", "Kum havuzu"), "logs" => s(lang, "Logs", "Günlük"), + "jobs" => s(lang, "Jobs", "İşler"), + "metrics" => s(lang, "Metrics", "Ölçümler"), _ => s(lang, "Identity", "Kimlik"), } } @@ -1162,6 +1171,367 @@ fn or_dash(text: String) -> String { } } +/// How many finished jobs the jobs tab lists, newest first. +const RECENT_JOBS: usize = 20; + +/// One job row of the jobs tab, already formatted. +struct RunnerJobRow { + name: String, + /// `owner/name` of the job's repo. + repo: String, + run_href: String, + /// `#` and the run's number. + run_text: String, + state_text: String, + /// `ci-state ci-`, the class the runs list colours the state with. + state_class: String, + /// The run time so far for a running job, the whole run time for a finished one. `-` when unknown. + duration: String, + /// The time from queued to started. `-` when it never started. + waited: String, + /// The finish stamp, for the `