From 67c35730fe30eb87e83c7fc83cda2fac52842599 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 29 Oct 2026 23:05:12 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(ci):=20a=20runner's=20page=20h?= =?UTF-8?q?as=20a=20Logs=20tab=20with=20the=20runner's=20own=20log,=20so?= =?UTF-8?q?=20a=20long=20queue=20can=20be=20explained:=20the=20runner=20ke?= =?UTF-8?q?eps=20its=20last=202000=20info=20and=20warn=20lines=20and=20sen?= =?UTF-8?q?ds=20them=20to=20the=20forge=20every=202=20s=20(resending=20wha?= =?UTF-8?q?t=20a=20restarted=20forge=20lost),=20logs=20once=20per=20change?= =?UTF-8?q?=20why=20it=20is=20not=20claiming=20(all=20slots=20busy,=20a=20?= =?UTF-8?q?pending=20restart=20or=20update,=20memory=20pressure),=20and=20?= =?UTF-8?q?the=20forge=20adds=20a=20note=20when=20a=20claim=20ends=20with?= =?UTF-8?q?=20nothing=20while=20jobs=20are=20queued:=20how=20many=20need?= =?UTF-8?q?=20labels=20the=20runner=20lacks,=20how=20many=20wait=20for=20m?= =?UTF-8?q?emory=20and=20the=20smallest=20need=20against=20the=20free=20me?= =?UTF-8?q?mory,=20and=20when=20a=20job=20that=20waited=20over=205=20minut?= =?UTF-8?q?es=20holds=20smaller=20ones=20back=20until=20it=20fits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-ci/src/proto.rs | 32 ++ crates/forge-core/src/ci.rs | 21 ++ crates/forge-core/src/store/ci.rs | 82 ++++- crates/forge-runner/src/cli.rs | 19 +- crates/forge-runner/src/client.rs | 34 ++- crates/forge-runner/src/lib.rs | 1 + crates/forge-runner/src/limiter.rs | 5 + crates/forge-runner/src/pressure.rs | 5 + crates/forge-runner/src/runner.rs | 47 +++ crates/forge-runner/src/selflog.rs | 289 ++++++++++++++++++ crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/ci/api.rs | 128 +++++++- crates/forge-web/src/ci/mod.rs | 1 + crates/forge-web/src/ci/runner_log.rs | 234 ++++++++++++++ crates/forge-web/src/pages/admin_runners.rs | 71 ++++- .../forge-web/src/pages/settings_security.rs | 1 + crates/forge-web/src/state.rs | 2 + crates/forge-web/src/test_support.rs | 1 + style/_admin_rows.scss | 29 ++ 19 files changed, 984 insertions(+), 19 deletions(-) create mode 100644 crates/forge-runner/src/selflog.rs create mode 100644 crates/forge-web/src/ci/runner_log.rs diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index 3447aa5..3353a41 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -98,6 +98,38 @@ pub struct RequeueRequest { pub reason: String, } +/// The capability of a runner that ships its own log with [`RunnerLogBatch`]. +pub const CAP_RUNNER_LOG: &str = "runner_log"; + +/// `POST /api/v1/ci/runners/log`: lines of the runner's own log (not a job's), so an admin can see +/// on the runner's page what it was doing, for example why it claimed nothing. Lines are numbered +/// from 0 per process start (`boot_id`); `first_seq` is the number of the first line in `lines`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RunnerLogBatch { + pub boot_id: String, + pub first_seq: u64, + pub lines: Vec, +} + +/// One line of a runner's own log. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RunnerLogLine { + /// Unix time in milliseconds. + pub at_ms: i64, + /// `error`, `warn`, `info`, `debug` or `trace`. + pub level: String, + /// The formatted message with its fields, without timestamp or level. + pub text: String, +} + +/// The answer to a [`RunnerLogBatch`]: the number of the next line the forge wants for this boot +/// id. A forge that restarted (or never saw this boot id) answers 0 and the runner resends what it +/// still holds; lines it no longer holds are skipped. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RunnerLogAck { + pub next_seq: u64, +} + /// 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/src/ci.rs b/crates/forge-core/src/ci.rs index 0028c13..43d0452 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -478,6 +478,27 @@ pub fn pick_by_memory( None } +/// Why the queued jobs were not handed to one runner's claim. Counts only: nothing is claimed. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct QueueSkips { + /// Queued jobs in all. + pub queued: usize, + /// Queued jobs whose `runs_on` names a label the runner lacks. + pub lacking_labels: usize, + /// The labels those jobs name that the runner lacks. Sorted, without repeats. + pub missing_labels: Vec, + /// Jobs the runner has the labels for but not the free memory. Only counted when the runner + /// offered its memory. + pub too_big: usize, + /// The smallest reservation among the `too_big` jobs, in bytes. + pub smallest_need: Option, + /// Jobs that fit but wait behind an older one that has starved (see [`pick_by_memory`]): the + /// runner takes nothing until that one fits. + pub held_behind: usize, + /// What the starved job reserves, in bytes, when one holds the queue. + pub starved_need: Option, +} + fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool { forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n)) } diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 1e140d1..dd10dfe 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -4,7 +4,7 @@ //! writer. Multi-step changes (create, claim, finish, cancel, reap, purge) run in one transaction. //! The `needs` and `runs_on` arrays are read out of the JobSpec JSON in `spec_json`. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::time::Duration; use turso::{Connection, Row, Value}; @@ -15,7 +15,7 @@ use super::{ }; use crate::ci::{ CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY, - MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, RestartMode, RunState, RunnerReport, + MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerReport, RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field, }; use crate::error::{Error, Result}; @@ -218,6 +218,25 @@ fn runs_on_covered(spec: &str, labels: &[String]) -> bool { } } +/// The `runs_on` labels of the spec that `labels` lack. Nothing for a malformed spec. +fn runs_on_missing(spec: &str, labels: &[String]) -> Vec { + let Ok(value) = serde_json::from_str::(spec) else { + return Vec::new(); + }; + value + .get("runs_on") + .and_then(|v| v.as_array()) + .map(|items| { + items + .iter() + .filter_map(|item| item.as_str()) + .filter(|want| !labels.iter().any(|have| have == want)) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default() +} + /// Secret names follow the JobSpec rule: `^[A-Z_][A-Z0-9_]{0,63}$`. fn validate_secret_name(name: &str) -> Result<()> { let first_ok = name @@ -1096,6 +1115,65 @@ impl Store { Ok(claimed.map(|(job, run)| (job, run, token))) } + /// Counts the queued jobs that `runner` with `offer` cannot take, and why. Read only: it + /// claims nothing, so it is safe to call for a note on a claim that got no job. + pub async fn queue_skips( + &self, + runner: &CiRunner, + offer: Option, + ) -> Result { + let queued: Vec<(String, Option)> = { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT spec, queued_at FROM ci_jobs WHERE state = 'queued' ORDER BY queued_at, id", + (), + |row| Ok((col_text(row, 0)?, col_opt_text(row, 1)?)), + ) + .await? + }; + let now = stamp_to_unix(&now_stamp()).unwrap_or(0); + let mut skips = QueueSkips { + queued: queued.len(), + ..QueueSkips::default() + }; + let mut missing = BTreeSet::new(); + // The same walk as `pick_by_memory`, oldest first, counting instead of picking. + for (spec, queued_at) in &queued { + if !runs_on_covered(spec, &runner.labels) { + skips.lacking_labels += 1; + missing.extend(runs_on_missing(spec, &runner.labels)); + continue; + } + let Some(offer) = offer else { + continue; + }; + let declared = declared_memory(spec); + if skips.starved_need.is_some() { + if offer.fits(declared) { + skips.held_behind += 1; + } else { + skips.too_big += 1; + } + continue; + } + if !offer.fits(declared) { + let need = offer.reservation(declared); + skips.too_big += 1; + skips.smallest_need = Some(skips.smallest_need.map_or(need, |n| n.min(need))); + let waited = queued_at + .as_deref() + .and_then(stamp_to_unix) + .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)); + if waited >= STARVE_AFTER_SECS { + skips.starved_need = Some(need); + } + } + } + skips.missing_labels = missing.into_iter().collect(); + Ok(skips) + } + /// The job, only while it is running and the token matches its stored hash. pub async fn job_by_token(&self, job_id: &str, token_plain: &str) -> Result> { let conn = self.read_conn().await; diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index 816c966..2429470 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -12,7 +12,9 @@ use std::time::Duration; use clap::{CommandFactory, Parser, Subcommand}; use forge_ci::proto::RegisterRequest; use tokio_util::sync::CancellationToken; -use tracing_subscriber::EnvFilter; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; +use tracing_subscriber::{EnvFilter, Layer as _}; use crate::cache::CacheStore; use crate::client::ForgeClient; @@ -22,6 +24,7 @@ use crate::oci::ImageStore; use crate::pressure::Pressure; use crate::runner::{RunEnd, RunOptions, Runner}; use crate::sandbox::idmap::IdMap; +use crate::selflog; use crate::update; /// How often unused images are garbage collected, after the one at startup. @@ -106,11 +109,17 @@ where } }; // Another subscriber may already be installed, for example by forge-web. Keep that one. - let _ = tracing_subscriber::fmt() - .with_env_filter( - EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")), + // The env filter applies to the terminal output only. The runner's own log that is shipped to + // the forge is always INFO and above, whatever the env filter says, see `selflog`. + let _ = tracing_subscriber::registry() + .with( + tracing_subscriber::fmt::layer() + .with_writer(std::io::stderr) + .with_filter( + EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")), + ), ) - .with_writer(std::io::stderr) + .with(selflog::layer()) .try_init(); let argv = std::iter::once(OsString::from(bin_name)).chain(args); let cli = match Cli::command() diff --git a/crates/forge-runner/src/client.rs b/crates/forge-runner/src/client.rs index 8877082..643d067 100644 --- a/crates/forge-runner/src/client.rs +++ b/crates/forge-runner/src/client.rs @@ -7,10 +7,10 @@ use std::path::Path; use std::time::Duration; use forge_ci::proto::{ - BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, - HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER, - RegisterRequest, RegisterResponse, RequeueRequest, RestartMode, RunnerConfigOverrides, - RunnerConfigReport, + 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, }; use reqwest::StatusCode; use reqwest::header::{CONTENT_LENGTH, HeaderMap}; @@ -33,6 +33,8 @@ const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256"; /// `GET`: the forge's binary, for a runner that is updating itself. 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"; /// Errors from talking to the forge. #[derive(Debug, thiserror::Error)] @@ -146,7 +148,11 @@ impl ForgeClient { memory_bytes: host.memory_bytes, build: Some(forge_ci::build::display()), boot_id: Some(crate::restart::boot_id().to_owned()), - capabilities: vec![CAP_RESTART.to_owned(), CAP_REQUEUE.to_owned()], + capabilities: vec![ + CAP_RESTART.to_owned(), + CAP_REQUEUE.to_owned(), + CAP_RUNNER_LOG.to_owned(), + ], free_memory_bytes: memory.map(|m| m.free), memory_budget_bytes: memory.map(|m| m.budget), reserve_memory_bytes: memory.map(|m| m.reserve), @@ -219,6 +225,24 @@ impl ForgeClient { json_or_error(resp).await } + /// `POST /api/v1/ci/runners/log`: ships a batch of the runner's own log. Returns the forge's + /// ack, the number of the next line it wants. + pub async fn post_runner_log( + &self, + runner_secret: &str, + batch: &RunnerLogBatch, + ) -> Result { + let resp = self + .http + .post(self.url(RUNNER_LOG_PATH)) + .bearer_auth(runner_secret) + .json(batch) + .timeout(REQUEST_TIMEOUT) + .send() + .await?; + json_or_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 e2bd41d..ced40d0 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -21,5 +21,6 @@ pub mod pressure; pub mod restart; pub mod runner; pub mod sandbox; +pub mod selflog; pub mod update; pub mod workspace; diff --git a/crates/forge-runner/src/limiter.rs b/crates/forge-runner/src/limiter.rs index ae0a030..93ba3fe 100644 --- a/crates/forge-runner/src/limiter.rs +++ b/crates/forge-runner/src/limiter.rs @@ -61,6 +61,11 @@ impl Limiter { self.lock().current } + /// Job slots free right now. Zero means every slot is taken by a running job. + pub fn free_slots(&self) -> usize { + self.semaphore.available_permits() + } + fn lock(&self) -> std::sync::MutexGuard<'_, State> { self.state.lock().unwrap_or_else(PoisonError::into_inner) } diff --git a/crates/forge-runner/src/pressure.rs b/crates/forge-runner/src/pressure.rs index 4338611..bcea73b 100644 --- a/crates/forge-runner/src/pressure.rs +++ b/crates/forge-runner/src/pressure.rs @@ -376,6 +376,11 @@ impl Pressure { Some(max.saturating_sub(box_usage(&self.dir)?)) } + /// The admission gate as it is now: how many jobs are parked and whether the box is hot. + pub fn gate(&self) -> Gate { + self.lock().gate + } + /// Resolves once the runner may claim: no job is parked and the box is not under pressure. /// Woken by the controller, never by a timer. pub async fn wait_open(&self) { diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index eadea55..c98bced 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -23,6 +23,7 @@ use crate::memory::MemoryGate; use crate::oom::OomSink; use crate::pressure::Pressure; use crate::restart::{self, RestartState, Step}; +use crate::selflog; use crate::update::{self, Installed, UpdateState}; use crate::workspace; @@ -32,6 +33,8 @@ const LOG_CHANNEL: usize = 64; const FINISH_ATTEMPTS: u32 = 5; /// Largest single artifact the runner will upload. The forge enforces its own total cap. const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024; +/// How long a stopping runner waits for its last log lines to reach the forge. +const LOG_FLUSH: Duration = Duration::from_secs(5); /// Timing knobs. Production uses the defaults. Tests shorten them. #[derive(Clone, Copy, Debug)] @@ -158,6 +161,15 @@ impl Runner { ); // Parent of every job's token, so a `now` restart can cancel them all at once. let jobs_cancel = shutdown.child_token(); + // Ships the runner's own log to the forge until the loop has ended. See `selflog`. + let ship_stop = CancellationToken::new(); + let shipper = tokio::spawn(selflog::ship( + self.client.clone(), + self.config.runner_secret.clone(), + ship_stop.clone(), + )); + // The reason the claim loop last logged for not claiming, see `not_claiming`. + let mut blocked: Option = None; let end = loop { match restart::decide( self.restart.pending(), @@ -176,6 +188,10 @@ impl Runner { continue; } Step::WaitForJobs => { + not_claiming( + &mut blocked, + "a restart is pending, waiting for the running jobs".to_owned(), + ); tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, Some(joined) = jobs.join_next() => { @@ -193,6 +209,10 @@ impl Runner { { if !jobs.is_empty() { // Claiming is paused until the running jobs finish. + not_claiming( + &mut blocked, + "a new binary is pending, waiting for the running jobs".to_owned(), + ); tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, Some(joined) = jobs.join_next() => { @@ -225,12 +245,27 @@ impl Runner { if let Some(pressure) = &self.pressure { // A parked job or a box under pressure means no new job. The controller wakes // this when that changes. + let gate = pressure.gate(); + if !gate.open() { + let hot = if gate.hot { ", box under pressure" } else { "" }; + not_claiming( + &mut blocked, + format!("memory pressure, {} job(s) parked{hot}", gate.frozen), + ); + } tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, () = self.restart.changed() => continue, () = pressure.wait_open() => {} } } + // Every slot taken: the loop waits below for a job to finish. A free slot ends the block. + if self.limiter.free_slots() == 0 { + let limit = self.limiter.current(); + not_claiming(&mut blocked, format!("{limit} of {limit} jobs running")); + } else { + blocked = None; + } let permit = tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, () = self.restart.changed() => continue, @@ -323,6 +358,9 @@ impl Runner { } } tracing::info!("runner stopped"); + // 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; end } @@ -597,6 +635,15 @@ impl Runner { } } +/// Logs why the claim loop is not claiming, at info level, but only when the reason differs from +/// the one logged last. `last` is cleared once the loop passes the checks and has a free slot. +fn not_claiming(last: &mut Option, reason: String) { + if last.as_deref() != Some(reason.as_str()) { + tracing::info!("not claiming: {reason}"); + *last = Some(reason); + } +} + async fn send_line(tx: &mpsc::Sender>, line: String) { let mut bytes = line.into_bytes(); bytes.push(b'\n'); diff --git a/crates/forge-runner/src/selflog.rs b/crates/forge-runner/src/selflog.rs new file mode 100644 index 0000000..b52d18a --- /dev/null +++ b/crates/forge-runner/src/selflog.rs @@ -0,0 +1,289 @@ +//! The runner's own log, shipped to the forge. A tracing layer formats every INFO (or more severe) +//! event into a bounded in-memory ring. [`ship`] posts the lines the forge has not seen yet, so the +//! runner's page on the forge shows what it was doing, for example why a job waited in the queue. +//! Job logs are not part of this. They have their own path, see [`crate::logs`]. + +use std::collections::VecDeque; +use std::fmt::{Debug, Write as _}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use forge_ci::proto::{RunnerLogBatch, RunnerLogLine}; +use reqwest::StatusCode; +use tokio_util::sync::CancellationToken; +use tracing::field::{Field, Visit}; +use tracing::{Event, Level, Subscriber}; +use tracing_subscriber::Layer; +use tracing_subscriber::layer::Context; + +use crate::client::{ClientError, ForgeClient}; + +/// Most lines the ring holds. The oldest are dropped first. +pub const CAPACITY: usize = 2000; +/// Longest text kept for one line, in bytes. Longer text is cut on a character boundary. +pub const MAX_TEXT: usize = 4096; +/// Most lines in one batch. +pub const BATCH: usize = 500; +/// Time between two shipping attempts. +const EVERY: Duration = Duration::from_secs(2); +/// Event targets that are noise. Shipping uses HTTP, so these would feed back into the ring. +const SKIP_TARGETS: [&str; 4] = ["reqwest", "hyper", "h2", "rustls"]; + +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() +} + +/// The layer that fills the ring. Add it to the subscriber with `.with(selflog::layer())`. +pub fn layer() -> SelfLog { + SelfLog { ring: ring() } +} + +/// A bounded buffer of log lines. Each line gets the next sequence number, counting from 0 for +/// the process. Lines are shipped by sequence number, so a line keeps its number after older +/// ones are dropped. +pub struct Ring { + capacity: usize, + state: Mutex, +} + +#[derive(Default)] +struct State { + lines: VecDeque, + /// The number the next line gets. Also how many lines were ever pushed. + next: u64, +} + +impl Ring { + /// An empty ring that holds at most `capacity` lines. + pub fn new(capacity: usize) -> Self { + Self { + capacity, + state: Mutex::new(State::default()), + } + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Adds a line, dropping the oldest one when the ring is full. + pub fn push(&self, line: RunnerLogLine) { + let mut state = self.lock(); + if state.lines.len() >= self.capacity { + state.lines.pop_front(); + } + state.lines.push_back(line); + state.next += 1; + } + + /// The number the next line will get. + pub fn end(&self) -> u64 { + self.lock().next + } + + /// Up to `max` lines from number `from` on. Lines already dropped are skipped, so the first + /// returned number is `from` or later. The number is returned with the lines. + pub fn batch(&self, from: u64, max: usize) -> (u64, Vec) { + let state = self.lock(); + let oldest = state.next - state.lines.len() as u64; + let first = from.max(oldest); + if first >= state.next { + return (first, Vec::new()); + } + let skip = (first - oldest) as usize; + let lines = state.lines.iter().skip(skip).take(max).cloned().collect(); + (first, lines) + } +} + +/// The tracing layer that puts INFO (and more severe) events into the ring. +pub struct SelfLog { + ring: Arc, +} + +impl Layer for SelfLog { + fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) { + let meta = event.metadata(); + if *meta.level() > Level::INFO { + return; + } + if SKIP_TARGETS + .iter() + .any(|prefix| meta.target().starts_with(prefix)) + { + return; + } + let mut text = Text::default(); + event.record(&mut text); + self.ring.push(RunnerLogLine { + at_ms: now_ms(), + level: level_name(*meta.level()).to_owned(), + text: truncate(text.finish()), + }); + } +} + +/// Collects an event's message and fields into one line, in the same shape the fmt layer uses: +/// the message, then `key=value` for each field. +#[derive(Default)] +struct Text { + message: String, + fields: String, +} + +impl Text { + fn finish(self) -> String { + match (self.message.is_empty(), self.fields.is_empty()) { + (_, true) => self.message, + (true, false) => self.fields.trim_start().to_owned(), + (false, false) => format!("{}{}", self.message, self.fields), + } + } +} + +impl Visit for Text { + fn record_str(&mut self, field: &Field, value: &str) { + if field.name() == "message" { + self.message.push_str(value); + } else { + let _ = write!(self.fields, " {}={value}", field.name()); + } + } + + fn record_debug(&mut self, field: &Field, value: &dyn Debug) { + if field.name() == "message" { + let _ = write!(self.message, "{value:?}"); + } else { + let _ = write!(self.fields, " {}={value:?}", field.name()); + } + } +} + +fn level_name(level: Level) -> &'static str { + match level { + Level::ERROR => "error", + Level::WARN => "warn", + Level::INFO => "info", + Level::DEBUG => "debug", + _ => "trace", + } +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)) +} + +/// Cuts `text` to at most [`MAX_TEXT`] bytes, on a character boundary. +fn truncate(mut text: String) -> String { + if text.len() > MAX_TEXT { + let mut end = MAX_TEXT; + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + } + text +} + +/// Posts the lines the forge has not seen yet, every two seconds, under the boot id of this +/// process. Failures are logged at debug level and retried on the next tick. When `stop` is +/// cancelled, the lines still held are sent before returning, so the caller may bound this with a +/// timeout. An older forge without the endpoint answers 404, and then shipping stops for good. +pub async fn ship(client: ForgeClient, runner_secret: String, stop: CancellationToken) { + let ring = ring(); + let boot_id = crate::restart::boot_id(); + let mut next_seq = 0_u64; + let mut ticker = tokio::time::interval(EVERY); + loop { + let stopping = tokio::select! { + _ = ticker.tick() => false, + () = stop.cancelled() => true, + }; + loop { + let (first_seq, lines) = ring.batch(next_seq, BATCH); + if lines.is_empty() { + break; + } + let batch = RunnerLogBatch { + boot_id: boot_id.to_owned(), + first_seq, + lines, + }; + match client.post_runner_log(&runner_secret, &batch).await { + Ok(ack) => { + let moved = ack.next_seq != next_seq; + next_seq = ack.next_seq; + // A final flush sends batch after batch, but only while the forge moves on. + if !stopping || !moved { + break; + } + } + Err(ClientError::Status { + status: StatusCode::NOT_FOUND, + .. + }) => return, + Err(e) => { + tracing::debug!(error = %e, "cannot ship the runner log, retrying"); + break; + } + } + } + if stopping { + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn line(text: &str) -> RunnerLogLine { + RunnerLogLine { + at_ms: 0, + level: "info".into(), + text: text.into(), + } + } + + #[test] + fn ring_drops_the_oldest_lines() { + let ring = Ring::new(3); + for i in 0..5 { + ring.push(line(&i.to_string())); + } + assert_eq!(ring.end(), 5); + let (first, lines) = ring.batch(0, 10); + assert_eq!(first, 2); + let texts: Vec<_> = lines.iter().map(|l| l.text.as_str()).collect(); + assert_eq!(texts, ["2", "3", "4"]); + } + + #[test] + fn sequence_numbers_follow_the_request() { + let ring = Ring::new(10); + for i in 0..4 { + ring.push(line(&i.to_string())); + } + let (first, lines) = ring.batch(1, 2); + assert_eq!(first, 1); + assert_eq!(lines.len(), 2); + assert_eq!(lines[0].text, "1"); + // Nothing at or after the end. + assert!(ring.batch(4, 10).1.is_empty()); + } + + #[test] + fn long_text_is_cut_on_a_char_boundary() { + let text = "é".repeat(MAX_TEXT); + let cut = truncate(text); + assert!(cut.len() <= MAX_TEXT); + assert!(cut.ends_with('é')); + } +} diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 62dbaf9..8e2a789 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -135,6 +135,7 @@ pub async fn serve( mail_waker: Arc::new(Notify::new()), 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()), 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 2516eb6..173e8b5 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -12,10 +12,12 @@ 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, + RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, }; use forge_core::Error as CoreError; -use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, MemoryOffer, RunState, RunnerReport}; +use forge_core::ci::{ + CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RunState, RunnerReport, +}; use futures_util::StreamExt; use http::header::HeaderValue; use serde_json::json; @@ -27,6 +29,7 @@ use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route}; use crate::api::{self, Refusal}; use crate::ci::{artifact_key, log_path}; +use crate::pages::admin_runners::bytes_text; use crate::pages::repo::https_clone_url; use crate::self_update; use crate::state::AppState; @@ -42,6 +45,8 @@ const LOG_SIZE_HEADER: &str = "x-forge-log-size"; const MAX_LOG_CHUNK: usize = 1024 * 1024; /// Largest JSON body on the runner routes, in bytes. 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; /// 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. @@ -312,6 +317,40 @@ async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Respons } } +/// `POST /api/v1/ci/runners/log`: a batch of the runner's own log lines. Answers the next line +/// number the forge wants for this boot id, so the runner resends what was lost. +#[route(POST "/api/v1/ci/runners/log")] +async fn runner_log(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_LOG_BATCH).await { + Ok(bytes) => bytes, + Err(res) => return Ok(*res), + }; + let batch: RunnerLogBatch = 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.boot_id.is_empty() || batch.boot_id.len() > 64 { + return Ok(api::error( + StatusCode::UNPROCESSABLE_ENTITY, + "the boot id is missing or too long", + )); + } + let next_seq = state.runner_logs.ingest(&runner.id, &batch); + state.ci_live.bump_runners(); + let ack = serde_json::to_value(RunnerLogAck { next_seq }).unwrap_or_default(); + Ok(api::json(StatusCode::OK, &ack)) +} + /// `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")] @@ -379,6 +418,7 @@ async fn claim_work( // A runner that is to restart gets no new job. It is answered at once, so it sees the // request without waiting out the long poll. if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) { + note_restart_pending(state, runner).await; return Ok(empty(StatusCode::NO_CONTENT)); } match try_claim(state, runner, offer).await { @@ -390,11 +430,88 @@ async fn claim_work( .await .is_err() { + note_idle(state, runner, offer).await; return Ok(empty(StatusCode::NO_CONTENT)); } } } +/// Writes to the runner's log that a restart is holding back the queued jobs. Writes nothing when +/// no job is queued, so an idle runner does not fill its log. +async fn note_restart_pending(state: &AppState, runner: &CiRunner) { + let Ok(skips) = state.store.queue_skips(runner, None).await else { + return; + }; + if skips.queued > 0 { + note_runner( + state, + &runner.id, + "a restart is pending, not handing out jobs", + ); + } +} + +/// Writes to the runner's log why a long poll ended with no job while work is queued. Writes +/// nothing when no job is queued. +async fn note_idle(state: &AppState, runner: &CiRunner, offer: Option) { + let skips = match state.store.queue_skips(runner, offer).await { + Ok(skips) => skips, + Err(e) => { + tracing::warn!(error = %e, "ci: counting the queued jobs failed"); + return; + } + }; + if let Some(text) = idle_text(&skips, offer.map(|o| o.free)) { + note_runner(state, &runner.id, &text); + } +} + +/// Stores a forge note in the runner's log and wakes the admin pages when it was written. +fn note_runner(state: &AppState, runner_id: &str, text: &str) { + if state.runner_logs.note(runner_id, text) { + state.ci_live.bump_runners(); + } +} + +/// The reason a runner got no job, from the queued jobs it could not take. `None` when no job is +/// queued. `free` is the memory the runner offered, when it offered any. +fn idle_text(skips: &QueueSkips, free: Option) -> Option { + if skips.queued == 0 { + return None; + } + let mut parts = vec![format!( + "{} queued {}", + skips.queued, + if skips.queued == 1 { "job" } else { "jobs" } + )]; + if skips.lacking_labels > 0 { + parts.push(format!( + "{} need labels this runner lacks ({})", + skips.lacking_labels, + skips.missing_labels.join(", ") + )); + } + if let (true, Some(need), Some(free)) = (skips.too_big > 0, skips.smallest_need, free) { + parts.push(format!( + "{} waiting for memory: smallest needs {}, {} free", + skips.too_big, + bytes_text(need), + bytes_text(free) + )); + } + if let (Some(need), Some(free)) = (skips.starved_need, free) { + parts.push(format!( + "{} held back: a job queued over {} min ago needs {}, {} free, so no smaller job \ + starts until running jobs finish and it fits", + skips.held_behind, + forge_core::ci::STARVE_AFTER_SECS / 60, + bytes_text(need), + bytes_text(free) + )); + } + Some(parts.join("; ")) +} + /// The running binary, for a runner that updates itself. 404 unless self-update is enabled. #[route(GET "/api/v1/ci/runners/binary")] async fn runner_binary(cx: &Cx) -> topcoat::Result { @@ -448,6 +565,13 @@ async fn try_claim( state.ci_live.bump_run(&run.id); state.ci_live.bump_repo(&run.repo_id); state.ci_live.bump_runners(); + // The next refusal is written again, and this job is written now. + state.runner_logs.clear_note(&runner.id); + note_runner( + state, + &runner.id, + &format!("took job {} of run #{}", job.name, run.number), + ); let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?; let repo = state .store diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web/src/ci/mod.rs index f9a7fe2..80f1167 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web/src/ci/mod.rs @@ -14,6 +14,7 @@ pub mod api; pub mod live; pub mod reaper; pub mod release; +pub mod runner_log; 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 new file mode 100644 index 0000000..26fc9bd --- /dev/null +++ b/crates/forge-web/src/ci/runner_log.rs @@ -0,0 +1,234 @@ +//! The runner's own log, kept in memory so an admin can read it on the runner's page. A runner +//! ships its lines in batches (`POST /api/v1/ci/runners/log`) and the forge keeps the newest +//! `MAX_LINES` per runner. Lines are not stored in the database: a restart of the forge drops them, +//! and the runner resends what it still holds on its next batch. +//! +//! The forge also writes its own lines (`from_forge`): why a claim got no job, and which job it +//! took. A reason that repeats is written once, see `note`. + +use std::collections::{HashMap, VecDeque}; +use std::sync::{Mutex, MutexGuard}; + +use forge_ci::proto::RunnerLogBatch; + +/// Most lines kept per runner. The oldest go first. +const MAX_LINES: usize = 2000; +/// Most lines taken from one batch. The rest are left for the runner to resend. +const MAX_BATCH_LINES: usize = 1000; +/// Longest text kept per line, in bytes. Longer text is cut on a character boundary. +const MAX_TEXT_BYTES: usize = 4096; +/// Longest boot id kept, in bytes. +const MAX_BOOT_ID_BYTES: usize = 64; +/// The levels a runner may send. Any other level is stored as `info`. +const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"]; + +/// One line of a runner's log, as the admin page shows it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Line { + /// Unix time in milliseconds. + pub at_ms: i64, + pub level: String, + pub text: String, + /// True for a line the forge wrote, false for a line the runner sent. + pub from_forge: bool, +} + +/// What the forge holds for one runner. +#[derive(Debug, Default)] +struct PerRunner { + /// The boot id of the runner process the lines come from. Empty before the first batch. + boot_id: String, + /// The number of the next line the forge wants from the runner for `boot_id`. + next_seq: u64, + lines: VecDeque, + /// The last forge note written, so a reason that repeats is not written again. + last_note: Option, +} + +/// The lines of every runner, by runner id. Shared through `AppState`. +#[derive(Debug, Default)] +pub struct RunnerLogs { + runners: Mutex>, +} + +impl RunnerLogs { + /// Takes a batch from a runner and returns the next line number the forge wants. A new boot id + /// starts a fresh numbering, and the lines already in `lines` are kept. Lines before the + /// wanted number are skipped, so a resent batch adds only what is new. + pub fn ingest(&self, runner_id: &str, batch: &RunnerLogBatch) -> u64 { + if batch.boot_id.is_empty() || batch.boot_id.len() > MAX_BOOT_ID_BYTES { + return self.next_seq(runner_id); + } + let mut runners = self.lock(); + let entry = runners.entry(runner_id.to_owned()).or_default(); + if entry.boot_id != batch.boot_id { + entry.boot_id = batch.boot_id.clone(); + entry.next_seq = 0; + let short: String = batch.boot_id.chars().take(8).collect(); + push(entry, forge_line(format!("runner started (boot {short})"))); + } + if batch.first_seq > entry.next_seq { + let missing = batch.first_seq - entry.next_seq; + push(entry, forge_line(format!("{missing} lines missing"))); + } + for (i, line) in batch.lines.iter().take(MAX_BATCH_LINES).enumerate() { + let seq = batch.first_seq + i as u64; + if seq < entry.next_seq { + continue; + } + push( + entry, + Line { + at_ms: line.at_ms, + level: level_of(&line.level), + text: cut(&line.text, MAX_TEXT_BYTES), + from_forge: false, + }, + ); + } + let taken = batch.lines.len().min(MAX_BATCH_LINES) as u64; + entry.next_seq = entry.next_seq.max(batch.first_seq + taken); + entry.next_seq + } + + /// Writes a forge line saying why the runner got no job. Writes nothing when `text` is the + /// last note for this runner. Returns true when a line was written. + pub fn note(&self, runner_id: &str, text: &str) -> bool { + let mut runners = self.lock(); + let entry = runners.entry(runner_id.to_owned()).or_default(); + if entry.last_note.as_deref() == Some(text) { + return false; + } + entry.last_note = Some(text.to_owned()); + push(entry, forge_line(text.to_owned())); + true + } + + /// Forgets the last note, so the next refusal of this runner is written again. Called when a + /// job is handed out. + pub fn clear_note(&self, runner_id: &str) { + if let Some(entry) = self.lock().get_mut(runner_id) { + entry.last_note = None; + } + } + + /// The lines of a runner, oldest first. Empty for a runner that never sent a line. + pub fn lines(&self, runner_id: &str) -> Vec { + self.lock() + .get(runner_id) + .map(|entry| entry.lines.iter().cloned().collect()) + .unwrap_or_default() + } + + fn next_seq(&self, runner_id: &str) -> u64 { + self.lock().get(runner_id).map_or(0, |entry| entry.next_seq) + } + + 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()) + } +} + +/// Adds a line and drops the oldest lines beyond `MAX_LINES`. +fn push(entry: &mut PerRunner, line: Line) { + entry.lines.push_back(line); + while entry.lines.len() > MAX_LINES { + entry.lines.pop_front(); + } +} + +/// A line the forge wrote now, at level `info`. +fn forge_line(text: String) -> Line { + let at_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)); + Line { + at_ms, + level: "info".to_owned(), + text, + from_forge: true, + } +} + +/// The level as sent, or `info` for a level the forge does not know. +fn level_of(level: &str) -> String { + if LEVELS.contains(&level) { + level.to_owned() + } else { + "info".to_owned() + } +} + +/// `text` cut to at most `max` bytes, on a character boundary. +fn cut(text: &str, max: usize) -> String { + if text.len() <= max { + return text.to_owned(); + } + let mut end = max; + while !text.is_char_boundary(end) { + end -= 1; + } + text[..end].to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + use forge_ci::proto::RunnerLogLine; + + fn batch(boot: &str, first_seq: u64, texts: &[&str]) -> RunnerLogBatch { + RunnerLogBatch { + boot_id: boot.to_owned(), + first_seq, + lines: texts + .iter() + .map(|t| RunnerLogLine { + at_ms: 1, + level: "info".to_owned(), + text: (*t).to_owned(), + }) + .collect(), + } + } + + /// A resent batch adds only the lines the forge has not seen, and a gap is marked. + #[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); + // Resend of 0..=2: only "c" is new. + assert_eq!( + logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b", "c"])), + 3 + ); + // Lines 3 and 4 were lost before the forge saw them: a marker, then the batch. + assert_eq!(logs.ingest("r1", &batch("bootaaaaaaaaaa", 5, &["f"])), 6); + + let texts: Vec = logs.lines("r1").into_iter().map(|l| l.text).collect(); + assert_eq!( + texts, + [ + "runner started (boot bootaaaa)", + "a", + "b", + "c", + "2 lines missing", + "f" + ] + ); + } + + /// A reason is written once while it repeats, and again after the runner gets a job. + #[test] + fn note_is_written_once_until_cleared() { + let logs = RunnerLogs::default(); + assert!(logs.note("r1", "a restart is pending")); + assert!(!logs.note("r1", "a restart is pending")); + logs.clear_note("r1"); + assert!(logs.note("r1", "a restart is pending")); + let lines = logs.lines("r1"); + assert_eq!(lines.len(), 2); + assert!(lines.iter().all(|l| l.from_forge)); + } +} diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index d6a03fe..eff7505 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -23,6 +23,7 @@ use topcoat::router::{page, path_param, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; +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}; @@ -789,8 +790,8 @@ fn sel(on: bool) -> Option<&'static str> { on.then_some("selected") } -/// The detail page tabs: slug and the config keys on it. `identity` is the read-only block. -const TABS: [(&str, &[&str]); 5] = [ +/// The detail page tabs: slug and the config keys on it. `identity` and `logs` are read-only. +const TABS: [(&str, &[&str]); 6] = [ ( "general", &["concurrency", "labels", "executor", "auto_update"], @@ -817,6 +818,7 @@ const TABS: [(&str, &[&str]); 5] = [ ), ("sandbox", &["sandbox.userns"]), ("identity", &[]), + ("logs", &[]), ]; fn tab_label(lang: Lang, slug: &str) -> &'static str { @@ -825,6 +827,7 @@ fn tab_label(lang: Lang, slug: &str) -> &'static str { "limits" => s(lang, "Limits", "Sınırlar"), "storage" => s(lang, "Storage", "Depolama"), "sandbox" => s(lang, "Sandbox", "Kum havuzu"), + "logs" => s(lang, "Logs", "Günlük"), _ => s(lang, "Identity", "Kimlik"), } } @@ -1086,6 +1089,47 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec .collect() } +/// Most log lines the logs tab shows: the newest. +const LOG_SHOWN: usize = 500; + +/// One line of the logs tab, ready to render. +struct LogRow { + /// UTC time of day, `HH:MM:SS`. + time: String, + level: String, + text: String, + /// `forge` for a line the forge wrote, empty for one the runner sent. + chip: &'static str, + /// The line's classes. Warn and error lines get a class of their own. + class: &'static str, +} + +/// The newest `LOG_SHOWN` lines, newest first so the tab opens on what the runner did last. +fn log_rows_of(lines: &[Line]) -> Vec { + let start = lines.len().saturating_sub(LOG_SHOWN); + lines[start..] + .iter() + .rev() + .map(|line| LogRow { + time: clock_text(line.at_ms), + level: line.level.clone(), + text: line.text.clone(), + chip: if line.from_forge { "forge" } else { "" }, + class: match line.level.as_str() { + "error" => "runner-log-line is-error", + "warn" => "runner-log-line is-warn", + _ => "runner-log-line", + }, + }) + .collect() +} + +/// The UTC time of day of a Unix time in milliseconds, as `HH:MM:SS`. +fn clock_text(at_ms: i64) -> String { + let day = (at_ms / 1000).rem_euclid(86_400); + format!("{:02}:{:02}:{:02}", day / 3600, day % 3600 / 60, day % 60) +} + /// The read-only identity entries: label and value. The secret is never shown. fn identity_rows(lang: Lang, fields: &[FieldRow]) -> Vec<(&'static str, String)> { fields @@ -1104,7 +1148,8 @@ fn identity_rows(lang: Lang, fields: &[FieldRow]) -> Vec<(&'static str, String)> .collect() } -fn bytes_text(bytes: u64) -> String { +/// A byte count in GiB with one decimal, such as `3.7 GiB`. +pub(crate) fn bytes_text(bytes: u64) -> String { let gib = bytes as f64 / (1u64 << 30) as f64; format!("{gib:.1} GiB") } @@ -1134,6 +1179,7 @@ async fn runner_detail_view( fields: Vec, notice: Option<(&'static str, bool)>, tab: &'static str, + log: Vec, ) -> Result { let version = or_dash(runner.reported.version.clone().unwrap_or_default()); let cpus = or_dash( @@ -1166,7 +1212,7 @@ async fn runner_detail_view( }; let shown = detail_fields(lang, tab, &fields); let identity = identity_rows(lang, &fields); - let editing = tab != "identity"; + let editing = !matches!(tab, "identity" | "logs"); let save_action = format!("{}/settings", row.detail_href); let reset_action = row.config_action.clone(); Ok(view! { @@ -1255,6 +1301,16 @@ async fn runner_detail_view( + } else if tab == "logs" { + if log.is_empty() { +

(s(lang, "No log lines yet. Only a runner from the version that sends its log does so; an older runner sends nothing.", "Henüz günlük satırı yok. Günlüğünü yalnızca bunu destekleyen sürüm gönderir; eski sürüm hiçbir şey göndermez."))

+ } else { +
+                        for row in log.iter() {
+                            (row.time.as_str())" "(row.level.as_str())" "(row.chip)" "(row.text.as_str())"\n"
+                        }
+                    
+ } } else {

(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."))

@@ -1289,9 +1345,14 @@ async fn runner_detail_page(cx: &Cx) -> Result { let csrf = viewer.1.csrf_token.clone(); let notice = notice_from_query(cx, lang); let tab = tab_from_query(cx); + let log = if tab == "logs" { + log_rows_of(&state.runner_logs.lines(&runner.id)) + } else { + Vec::new() + }; let title = runner.name.clone(); Ok(view! { - 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)) + 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)) }) } diff --git a/crates/forge-web/src/pages/settings_security.rs b/crates/forge-web/src/pages/settings_security.rs index 94c8f94..d3b0a7f 100644 --- a/crates/forge-web/src/pages/settings_security.rs +++ b/crates/forge-web/src/pages/settings_security.rs @@ -1104,6 +1104,7 @@ mod tests { mail_waker: Arc::new(tokio::sync::Notify::new()), 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()), 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/state.rs b/crates/forge-web/src/state.rs index 9b372cc..872b176 100644 --- a/crates/forge-web/src/state.rs +++ b/crates/forge-web/src/state.rs @@ -49,6 +49,8 @@ pub struct AppState { pub notify_hub: Arc, /// Change counters of CI jobs and runs. Log followers and run pages wait on them. pub ci_live: Arc, + /// The log each CI runner sent, kept in memory for its admin page. See `ci::runner_log`. + pub runner_logs: Arc, /// Change signals of live pages, keyed by topic. See `live`. pub live: Arc, /// Device changes per user. The settings pages showing a user's push devices listen to it. diff --git a/crates/forge-web/src/test_support.rs b/crates/forge-web/src/test_support.rs index e8dd44c..a8d658d 100644 --- a/crates/forge-web/src/test_support.rs +++ b/crates/forge-web/src/test_support.rs @@ -93,6 +93,7 @@ pub async fn test_state(dir: &Path) -> AppState { mail_waker: Arc::new(Notify::new()), 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()), 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/style/_admin_rows.scss b/style/_admin_rows.scss index 5d10a1f..9fb7140 100644 --- a/style/_admin_rows.scss +++ b/style/_admin_rows.scss @@ -92,3 +92,32 @@ width: 52px; } } + +// The runner's own log on its admin page (the logs tab), newest line first. Lines stay inline: +// the pre breaks them with its own newlines. +.runner-log-line { + &.is-warn { + color: var(--warn); + } + + &.is-error { + color: var(--danger); + } +} + +.runner-log-time, +.runner-log-level { + color: var(--muted); +} + +.runner-log-chip:not(:empty) { + padding: 0 6px; + border-radius: var(--radius-sm); + background: var(--accent-soft); + color: var(--accent-ink); +} + +// Job logs pad each numbered line; the runner log has no numbers, so the box pads instead. +.ci-log.runner-log { + padding: 8px 12px; +}