forge
Explore
Log in

Don't you dare go Hollow

A runner's page has a Logs tab with the runner's own log, so a long queue can be explained: the runner keeps its last 2000 info and warn lines and sends them to the forge every 2 s (resending what a restarted forge lost), logs once per change why it is not claiming (all slots busy, a pending restart or update, memory pressure), and the forge adds a note when a claim ends with nothing while jobs are queued: how many need labels the runner lacks, how many wait for memory and the smallest need against the free memory, and when a job that waited over 5 minutes holds smaller ones back until it fits

Browse files at this commit

67c35730fe30eb87e83c7fc83cda2fac52842599Ahmet Kaan GümüşParent: adf7464
  • feat
    • a runner's page has a Logs tab with the runner's own log, so a long queue can be explained: the runner keeps its last 2000 info and warn lines and sends them to the forge every 2 s (resending what a restarted forge lost), logs once per change why it is not claiming (all slots busy, a pending restart or update, memory pressure), and the forge adds a note when a claim ends with nothing while jobs are queued: how many need labels the runner lacks, how many wait for memory and the smallest need against the free memory, and when a job that waited over 5 minutes holds smaller ones back until it fits
Show full message
✨ feat(ci): a runner's page has a Logs tab with the runner's own log, so a long queue can be explained: the runner keeps its last 2000 info and warn lines and sends them to the forge every 2 s (resending what a restarted forge lost), logs once per change why it is not claiming (all slots busy, a pending restart or update, memory pressure), and the forge adds a note when a claim ends with nothing while jobs are queued: how many need labels the runner lacks, how many wait for memory and the smallest need against the free memory, and when a job that waited over 5 minutes holds smaller ones back until it fits
crates/forge-ci/src/proto.rsmodified+32 -0
@@ -98,6 +98,38 @@ pub struct RequeueRequest {
98 pub reason: String,98 pub reason: String,
99 }99 }
100 100
101+/// The capability of a runner that ships its own log with [`RunnerLogBatch`].
102+pub const CAP_RUNNER_LOG: &str = "runner_log";
103+
104+/// `POST /api/v1/ci/runners/log`: lines of the runner's own log (not a job's), so an admin can see
105+/// on the runner's page what it was doing, for example why it claimed nothing. Lines are numbered
106+/// from 0 per process start (`boot_id`); `first_seq` is the number of the first line in `lines`.
107+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
108+pub struct RunnerLogBatch {
109+ pub boot_id: String,
110+ pub first_seq: u64,
111+ pub lines: Vec<RunnerLogLine>,
112+}
113+
114+/// One line of a runner's own log.
115+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
116+pub struct RunnerLogLine {
117+ /// Unix time in milliseconds.
118+ pub at_ms: i64,
119+ /// `error`, `warn`, `info`, `debug` or `trace`.
120+ pub level: String,
121+ /// The formatted message with its fields, without timestamp or level.
122+ pub text: String,
123+}
124+
125+/// The answer to a [`RunnerLogBatch`]: the number of the next line the forge wants for this boot
126+/// id. A forge that restarted (or never saw this boot id) answers 0 and the runner resends what it
127+/// still holds; lines it no longer holds are skipped.
128+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
129+pub struct RunnerLogAck {
130+ pub next_seq: u64,
131+}
132+
101 /// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish133 /// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish
102 /// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops134 /// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops
103 /// claiming, restarts the way a self-update does (exit 75), and the forge clears135 /// claiming, restarts the way a self-update does (exit 75), and the forge clears
crates/forge-core/src/ci.rsmodified+21 -0
@@ -478,6 +478,27 @@ pub fn pick_by_memory(
478 None478 None
479 }479 }
480 480
481+/// Why the queued jobs were not handed to one runner's claim. Counts only: nothing is claimed.
482+#[derive(Debug, Clone, Default, PartialEq, Eq)]
483+pub struct QueueSkips {
484+ /// Queued jobs in all.
485+ pub queued: usize,
486+ /// Queued jobs whose `runs_on` names a label the runner lacks.
487+ pub lacking_labels: usize,
488+ /// The labels those jobs name that the runner lacks. Sorted, without repeats.
489+ pub missing_labels: Vec<String>,
490+ /// Jobs the runner has the labels for but not the free memory. Only counted when the runner
491+ /// offered its memory.
492+ pub too_big: usize,
493+ /// The smallest reservation among the `too_big` jobs, in bytes.
494+ pub smallest_need: Option<u64>,
495+ /// Jobs that fit but wait behind an older one that has starved (see [`pick_by_memory`]): the
496+ /// runner takes nothing until that one fits.
497+ pub held_behind: usize,
498+ /// What the starved job reserves, in bytes, when one holds the queue.
499+ pub starved_need: Option<u64>,
500+}
501+
481 fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool {502 fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool {
482 forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n))503 forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n))
483 }504 }
crates/forge-core/src/store/ci.rsmodified+80 -2
@@ -4,7 +4,7 @@
4 //! writer. Multi-step changes (create, claim, finish, cancel, reap, purge) run in one transaction.4 //! writer. Multi-step changes (create, claim, finish, cancel, reap, purge) run in one transaction.
5 //! The `needs` and `runs_on` arrays are read out of the JobSpec JSON in `spec_json`.5 //! The `needs` and `runs_on` arrays are read out of the JobSpec JSON in `spec_json`.
6 6
7-use std::collections::BTreeMap;7+use std::collections::{BTreeMap, BTreeSet};
8 use std::time::Duration;8 use std::time::Duration;
9 9
10 use turso::{Connection, Row, Value};10 use turso::{Connection, Row, Value};
@@ -15,7 +15,7 @@ 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, RestartMode, RunState, RunnerReport,18+ MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerReport,
19 RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field,19 RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field,
20 };20 };
21 use crate::error::{Error, Result};21 use crate::error::{Error, Result};
@@ -218,6 +218,25 @@ fn runs_on_covered(spec: &str, labels: &[String]) -> bool {
218 }218 }
219 }219 }
220 220
221+/// The `runs_on` labels of the spec that `labels` lack. Nothing for a malformed spec.
222+fn runs_on_missing(spec: &str, labels: &[String]) -> Vec<String> {
223+ let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else {
224+ return Vec::new();
225+ };
226+ value
227+ .get("runs_on")
228+ .and_then(|v| v.as_array())
229+ .map(|items| {
230+ items
231+ .iter()
232+ .filter_map(|item| item.as_str())
233+ .filter(|want| !labels.iter().any(|have| have == want))
234+ .map(str::to_owned)
235+ .collect()
236+ })
237+ .unwrap_or_default()
238+}
239+
221 /// Secret names follow the JobSpec rule: `^[A-Z_][A-Z0-9_]{0,63}$`.240 /// Secret names follow the JobSpec rule: `^[A-Z_][A-Z0-9_]{0,63}$`.
222 fn validate_secret_name(name: &str) -> Result<()> {241 fn validate_secret_name(name: &str) -> Result<()> {
223 let first_ok = name242 let first_ok = name
@@ -1096,6 +1115,65 @@ impl Store {
1096 Ok(claimed.map(|(job, run)| (job, run, token)))1115 Ok(claimed.map(|(job, run)| (job, run, token)))
1097 }1116 }
1098 1117
1118+ /// Counts the queued jobs that `runner` with `offer` cannot take, and why. Read only: it
1119+ /// claims nothing, so it is safe to call for a note on a claim that got no job.
1120+ pub async fn queue_skips(
1121+ &self,
1122+ runner: &CiRunner,
1123+ offer: Option<MemoryOffer>,
1124+ ) -> Result<QueueSkips> {
1125+ let queued: Vec<(String, Option<String>)> = {
1126+ let conn = self.read_conn().await;
1127+ fetch_all(
1128+ &conn,
1129+ "SELECT spec, queued_at FROM ci_jobs WHERE state = 'queued' ORDER BY queued_at, id",
1130+ (),
1131+ |row| Ok((col_text(row, 0)?, col_opt_text(row, 1)?)),
1132+ )
1133+ .await?
1134+ };
1135+ let now = stamp_to_unix(&now_stamp()).unwrap_or(0);
1136+ let mut skips = QueueSkips {
1137+ queued: queued.len(),
1138+ ..QueueSkips::default()
1139+ };
1140+ let mut missing = BTreeSet::new();
1141+ // The same walk as `pick_by_memory`, oldest first, counting instead of picking.
1142+ for (spec, queued_at) in &queued {
1143+ if !runs_on_covered(spec, &runner.labels) {
1144+ skips.lacking_labels += 1;
1145+ missing.extend(runs_on_missing(spec, &runner.labels));
1146+ continue;
1147+ }
1148+ let Some(offer) = offer else {
1149+ continue;
1150+ };
1151+ let declared = declared_memory(spec);
1152+ if skips.starved_need.is_some() {
1153+ if offer.fits(declared) {
1154+ skips.held_behind += 1;
1155+ } else {
1156+ skips.too_big += 1;
1157+ }
1158+ continue;
1159+ }
1160+ if !offer.fits(declared) {
1161+ let need = offer.reservation(declared);
1162+ skips.too_big += 1;
1163+ skips.smallest_need = Some(skips.smallest_need.map_or(need, |n| n.min(need)));
1164+ let waited = queued_at
1165+ .as_deref()
1166+ .and_then(stamp_to_unix)
1167+ .map_or(0, |at| u64::try_from(now - at).unwrap_or(0));
1168+ if waited >= STARVE_AFTER_SECS {
1169+ skips.starved_need = Some(need);
1170+ }
1171+ }
1172+ }
1173+ skips.missing_labels = missing.into_iter().collect();
1174+ Ok(skips)
1175+ }
1176+
1099 /// The job, only while it is running and the token matches its stored hash.1177 /// The job, only while it is running and the token matches its stored hash.
1100 pub async fn job_by_token(&self, job_id: &str, token_plain: &str) -> Result<Option<CiJob>> {1178 pub async fn job_by_token(&self, job_id: &str, token_plain: &str) -> Result<Option<CiJob>> {
1101 let conn = self.read_conn().await;1179 let conn = self.read_conn().await;
crates/forge-runner/src/cli.rsmodified+14 -5
@@ -12,7 +12,9 @@ use std::time::Duration;
12 use clap::{CommandFactory, Parser, Subcommand};12 use clap::{CommandFactory, Parser, Subcommand};
13 use forge_ci::proto::RegisterRequest;13 use forge_ci::proto::RegisterRequest;
14 use tokio_util::sync::CancellationToken;14 use tokio_util::sync::CancellationToken;
15-use tracing_subscriber::EnvFilter;15+use tracing_subscriber::layer::SubscriberExt;
16+use tracing_subscriber::util::SubscriberInitExt;
17+use tracing_subscriber::{EnvFilter, Layer as _};
16 18
17 use crate::cache::CacheStore;19 use crate::cache::CacheStore;
18 use crate::client::ForgeClient;20 use crate::client::ForgeClient;
@@ -22,6 +24,7 @@ use crate::oci::ImageStore;
22 use crate::pressure::Pressure;24 use crate::pressure::Pressure;
23 use crate::runner::{RunEnd, RunOptions, Runner};25 use crate::runner::{RunEnd, RunOptions, Runner};
24 use crate::sandbox::idmap::IdMap;26 use crate::sandbox::idmap::IdMap;
27+use crate::selflog;
25 use crate::update;28 use crate::update;
26 29
27 /// How often unused images are garbage collected, after the one at startup.30 /// How often unused images are garbage collected, after the one at startup.
@@ -106,11 +109,17 @@ where
106 }109 }
107 };110 };
108 // Another subscriber may already be installed, for example by forge-web. Keep that one.111 // Another subscriber may already be installed, for example by forge-web. Keep that one.
109- let _ = tracing_subscriber::fmt()112+ // The env filter applies to the terminal output only. The runner's own log that is shipped to
110- .with_env_filter(113+ // the forge is always INFO and above, whatever the env filter says, see `selflog`.
111- EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),114+ let _ = tracing_subscriber::registry()
115+ .with(
116+ tracing_subscriber::fmt::layer()
117+ .with_writer(std::io::stderr)
118+ .with_filter(
119+ EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
120+ ),
112 )121 )
113- .with_writer(std::io::stderr)122+ .with(selflog::layer())
114 .try_init();123 .try_init();
115 let argv = std::iter::once(OsString::from(bin_name)).chain(args);124 let argv = std::iter::once(OsString::from(bin_name)).chain(args);
116 let cli = match Cli::command()125 let cli = match Cli::command()
crates/forge-runner/src/client.rsmodified+29 -5
@@ -7,10 +7,10 @@ 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, CONCURRENCY_HEADER, ClaimRequest, FinishRequest,10+ BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CAP_RUNNER_LOG, CONCURRENCY_HEADER, ClaimRequest,
11- HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER,11+ FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER,
12- RegisterRequest, RegisterResponse, RequeueRequest, RestartMode, RunnerConfigOverrides,12+ RESTART_HEADER, RegisterRequest, RegisterResponse, RequeueRequest, RestartMode,
13- RunnerConfigReport,13+ RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch,
14 };14 };
15 use reqwest::StatusCode;15 use reqwest::StatusCode;
16 use reqwest::header::{CONTENT_LENGTH, HeaderMap};16 use reqwest::header::{CONTENT_LENGTH, HeaderMap};
@@ -33,6 +33,8 @@ const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256";
33 /// `GET`: the forge's binary, for a runner that is updating itself.33 /// `GET`: the forge's binary, for a runner that is updating itself.
34 const BINARY_PATH: &str = "/api/v1/ci/runners/binary";34 const BINARY_PATH: &str = "/api/v1/ci/runners/binary";
35 const CONFIG_PATH: &str = "/api/v1/ci/runners/config";35 const CONFIG_PATH: &str = "/api/v1/ci/runners/config";
36+/// `POST`: lines of the runner's own log, see [`crate::selflog`].
37+const RUNNER_LOG_PATH: &str = "/api/v1/ci/runners/log";
36 38
37 /// Errors from talking to the forge.39 /// Errors from talking to the forge.
38 #[derive(Debug, thiserror::Error)]40 #[derive(Debug, thiserror::Error)]
@@ -146,7 +148,11 @@ impl ForgeClient {
146 memory_bytes: host.memory_bytes,148 memory_bytes: host.memory_bytes,
147 build: Some(forge_ci::build::display()),149 build: Some(forge_ci::build::display()),
148 boot_id: Some(crate::restart::boot_id().to_owned()),150 boot_id: Some(crate::restart::boot_id().to_owned()),
149- capabilities: vec![CAP_RESTART.to_owned(), CAP_REQUEUE.to_owned()],151+ capabilities: vec![
152+ CAP_RESTART.to_owned(),
153+ CAP_REQUEUE.to_owned(),
154+ CAP_RUNNER_LOG.to_owned(),
155+ ],
150 free_memory_bytes: memory.map(|m| m.free),156 free_memory_bytes: memory.map(|m| m.free),
151 memory_budget_bytes: memory.map(|m| m.budget),157 memory_budget_bytes: memory.map(|m| m.budget),
152 reserve_memory_bytes: memory.map(|m| m.reserve),158 reserve_memory_bytes: memory.map(|m| m.reserve),
@@ -219,6 +225,24 @@ impl ForgeClient {
219 json_or_error(resp).await225 json_or_error(resp).await
220 }226 }
221 227
228+ /// `POST /api/v1/ci/runners/log`: ships a batch of the runner's own log. Returns the forge's
229+ /// ack, the number of the next line it wants.
230+ pub async fn post_runner_log(
231+ &self,
232+ runner_secret: &str,
233+ batch: &RunnerLogBatch,
234+ ) -> Result<RunnerLogAck, ClientError> {
235+ let resp = self
236+ .http
237+ .post(self.url(RUNNER_LOG_PATH))
238+ .bearer_auth(runner_secret)
239+ .json(batch)
240+ .timeout(REQUEST_TIMEOUT)
241+ .send()
242+ .await?;
243+ json_or_error(resp).await
244+ }
245+
222 /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the246 /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the
223 /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised247 /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised
224 /// value and syncs the file.248 /// value and syncs the file.
crates/forge-runner/src/lib.rsmodified+1 -0
@@ -21,5 +21,6 @@ pub mod pressure;
21 pub mod restart;21 pub mod restart;
22 pub mod runner;22 pub mod runner;
23 pub mod sandbox;23 pub mod sandbox;
24+pub mod selflog;
24 pub mod update;25 pub mod update;
25 pub mod workspace;26 pub mod workspace;
crates/forge-runner/src/limiter.rsmodified+5 -0
@@ -61,6 +61,11 @@ impl Limiter {
61 self.lock().current61 self.lock().current
62 }62 }
63 63
64+ /// Job slots free right now. Zero means every slot is taken by a running job.
65+ pub fn free_slots(&self) -> usize {
66+ self.semaphore.available_permits()
67+ }
68+
64 fn lock(&self) -> std::sync::MutexGuard<'_, State> {69 fn lock(&self) -> std::sync::MutexGuard<'_, State> {
65 self.state.lock().unwrap_or_else(PoisonError::into_inner)70 self.state.lock().unwrap_or_else(PoisonError::into_inner)
66 }71 }
crates/forge-runner/src/pressure.rsmodified+5 -0
@@ -376,6 +376,11 @@ impl Pressure {
376 Some(max.saturating_sub(box_usage(&self.dir)?))376 Some(max.saturating_sub(box_usage(&self.dir)?))
377 }377 }
378 378
379+ /// The admission gate as it is now: how many jobs are parked and whether the box is hot.
380+ pub fn gate(&self) -> Gate {
381+ self.lock().gate
382+ }
383+
379 /// Resolves once the runner may claim: no job is parked and the box is not under pressure.384 /// Resolves once the runner may claim: no job is parked and the box is not under pressure.
380 /// Woken by the controller, never by a timer.385 /// Woken by the controller, never by a timer.
381 pub async fn wait_open(&self) {386 pub async fn wait_open(&self) {
crates/forge-runner/src/runner.rsmodified+47 -0
@@ -23,6 +23,7 @@ use crate::memory::MemoryGate;
23 use crate::oom::OomSink;23 use crate::oom::OomSink;
24 use crate::pressure::Pressure;24 use crate::pressure::Pressure;
25 use crate::restart::{self, RestartState, Step};25 use crate::restart::{self, RestartState, Step};
26+use crate::selflog;
26 use crate::update::{self, Installed, UpdateState};27 use crate::update::{self, Installed, UpdateState};
27 use crate::workspace;28 use crate::workspace;
28 29
@@ -32,6 +33,8 @@ const LOG_CHANNEL: usize = 64;
32 const FINISH_ATTEMPTS: u32 = 5;33 const FINISH_ATTEMPTS: u32 = 5;
33 /// Largest single artifact the runner will upload. The forge enforces its own total cap.34 /// Largest single artifact the runner will upload. The forge enforces its own total cap.
34 const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024;35 const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024;
36+/// How long a stopping runner waits for its last log lines to reach the forge.
37+const LOG_FLUSH: Duration = Duration::from_secs(5);
35 38
36 /// Timing knobs. Production uses the defaults. Tests shorten them.39 /// Timing knobs. Production uses the defaults. Tests shorten them.
37 #[derive(Clone, Copy, Debug)]40 #[derive(Clone, Copy, Debug)]
@@ -158,6 +161,15 @@ impl Runner {
158 );161 );
159 // Parent of every job's token, so a `now` restart can cancel them all at once.162 // Parent of every job's token, so a `now` restart can cancel them all at once.
160 let jobs_cancel = shutdown.child_token();163 let jobs_cancel = shutdown.child_token();
164+ // Ships the runner's own log to the forge until the loop has ended. See `selflog`.
165+ let ship_stop = CancellationToken::new();
166+ let shipper = tokio::spawn(selflog::ship(
167+ self.client.clone(),
168+ self.config.runner_secret.clone(),
169+ ship_stop.clone(),
170+ ));
171+ // The reason the claim loop last logged for not claiming, see `not_claiming`.
172+ let mut blocked: Option<String> = None;
161 let end = loop {173 let end = loop {
162 match restart::decide(174 match restart::decide(
163 self.restart.pending(),175 self.restart.pending(),
@@ -176,6 +188,10 @@ impl Runner {
176 continue;188 continue;
177 }189 }
178 Step::WaitForJobs => {190 Step::WaitForJobs => {
191+ not_claiming(
192+ &mut blocked,
193+ "a restart is pending, waiting for the running jobs".to_owned(),
194+ );
179 tokio::select! {195 tokio::select! {
180 _ = shutdown.cancelled() => break RunEnd::Stopped,196 _ = shutdown.cancelled() => break RunEnd::Stopped,
181 Some(joined) = jobs.join_next() => {197 Some(joined) = jobs.join_next() => {
@@ -193,6 +209,10 @@ impl Runner {
193 {209 {
194 if !jobs.is_empty() {210 if !jobs.is_empty() {
195 // Claiming is paused until the running jobs finish.211 // Claiming is paused until the running jobs finish.
212+ not_claiming(
213+ &mut blocked,
214+ "a new binary is pending, waiting for the running jobs".to_owned(),
215+ );
196 tokio::select! {216 tokio::select! {
197 _ = shutdown.cancelled() => break RunEnd::Stopped,217 _ = shutdown.cancelled() => break RunEnd::Stopped,
198 Some(joined) = jobs.join_next() => {218 Some(joined) = jobs.join_next() => {
@@ -225,12 +245,27 @@ impl Runner {
225 if let Some(pressure) = &self.pressure {245 if let Some(pressure) = &self.pressure {
226 // A parked job or a box under pressure means no new job. The controller wakes246 // A parked job or a box under pressure means no new job. The controller wakes
227 // this when that changes.247 // this when that changes.
248+ let gate = pressure.gate();
249+ if !gate.open() {
250+ let hot = if gate.hot { ", box under pressure" } else { "" };
251+ not_claiming(
252+ &mut blocked,
253+ format!("memory pressure, {} job(s) parked{hot}", gate.frozen),
254+ );
255+ }
228 tokio::select! {256 tokio::select! {
229 _ = shutdown.cancelled() => break RunEnd::Stopped,257 _ = shutdown.cancelled() => break RunEnd::Stopped,
230 () = self.restart.changed() => continue,258 () = self.restart.changed() => continue,
231 () = pressure.wait_open() => {}259 () = pressure.wait_open() => {}
232 }260 }
233 }261 }
262+ // Every slot taken: the loop waits below for a job to finish. A free slot ends the block.
263+ if self.limiter.free_slots() == 0 {
264+ let limit = self.limiter.current();
265+ not_claiming(&mut blocked, format!("{limit} of {limit} jobs running"));
266+ } else {
267+ blocked = None;
268+ }
234 let permit = tokio::select! {269 let permit = tokio::select! {
235 _ = shutdown.cancelled() => break RunEnd::Stopped,270 _ = shutdown.cancelled() => break RunEnd::Stopped,
236 () = self.restart.changed() => continue,271 () = self.restart.changed() => continue,
@@ -323,6 +358,9 @@ impl Runner {
323 }358 }
324 }359 }
325 tracing::info!("runner stopped");360 tracing::info!("runner stopped");
361+ // The last lines go out too, but a dead forge must not hold up the exit.
362+ ship_stop.cancel();
363+ let _ = tokio::time::timeout(LOG_FLUSH, shipper).await;
326 end364 end
327 }365 }
328 366
@@ -597,6 +635,15 @@ impl Runner {
597 }635 }
598 }636 }
599 637
638+/// Logs why the claim loop is not claiming, at info level, but only when the reason differs from
639+/// the one logged last. `last` is cleared once the loop passes the checks and has a free slot.
640+fn not_claiming(last: &mut Option<String>, reason: String) {
641+ if last.as_deref() != Some(reason.as_str()) {
642+ tracing::info!("not claiming: {reason}");
643+ *last = Some(reason);
644+ }
645+}
646+
600 async fn send_line(tx: &mpsc::Sender<Vec<u8>>, line: String) {647 async fn send_line(tx: &mpsc::Sender<Vec<u8>>, line: String) {
601 let mut bytes = line.into_bytes();648 let mut bytes = line.into_bytes();
602 bytes.push(b'\n');649 bytes.push(b'\n');
crates/forge-runner/src/selflog.rsadded+289 -0
@@ -0,0 +1,289 @@
1+//! The runner's own log, shipped to the forge. A tracing layer formats every INFO (or more severe)
2+//! event into a bounded in-memory ring. [`ship`] posts the lines the forge has not seen yet, so the
3+//! runner's page on the forge shows what it was doing, for example why a job waited in the queue.
4+//! Job logs are not part of this. They have their own path, see [`crate::logs`].
5+
6+use std::collections::VecDeque;
7+use std::fmt::{Debug, Write as _};
8+use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
9+use std::time::{Duration, SystemTime, UNIX_EPOCH};
10+
11+use forge_ci::proto::{RunnerLogBatch, RunnerLogLine};
12+use reqwest::StatusCode;
13+use tokio_util::sync::CancellationToken;
14+use tracing::field::{Field, Visit};
15+use tracing::{Event, Level, Subscriber};
16+use tracing_subscriber::Layer;
17+use tracing_subscriber::layer::Context;
18+
19+use crate::client::{ClientError, ForgeClient};
20+
21+/// Most lines the ring holds. The oldest are dropped first.
22+pub const CAPACITY: usize = 2000;
23+/// Longest text kept for one line, in bytes. Longer text is cut on a character boundary.
24+pub const MAX_TEXT: usize = 4096;
25+/// Most lines in one batch.
26+pub const BATCH: usize = 500;
27+/// Time between two shipping attempts.
28+const EVERY: Duration = Duration::from_secs(2);
29+/// Event targets that are noise. Shipping uses HTTP, so these would feed back into the ring.
30+const SKIP_TARGETS: [&str; 4] = ["reqwest", "hyper", "h2", "rustls"];
31+
32+static RING: OnceLock<Arc<Ring>> = OnceLock::new();
33+
34+/// The ring shared by the layer and the shipper.
35+pub fn ring() -> Arc<Ring> {
36+ RING.get_or_init(|| Arc::new(Ring::new(CAPACITY)))
37+ .clone()
38+}
39+
40+/// The layer that fills the ring. Add it to the subscriber with `.with(selflog::layer())`.
41+pub fn layer() -> SelfLog {
42+ SelfLog { ring: ring() }
43+}
44+
45+/// A bounded buffer of log lines. Each line gets the next sequence number, counting from 0 for
46+/// the process. Lines are shipped by sequence number, so a line keeps its number after older
47+/// ones are dropped.
48+pub struct Ring {
49+ capacity: usize,
50+ state: Mutex<State>,
51+}
52+
53+#[derive(Default)]
54+struct State {
55+ lines: VecDeque<RunnerLogLine>,
56+ /// The number the next line gets. Also how many lines were ever pushed.
57+ next: u64,
58+}
59+
60+impl Ring {
61+ /// An empty ring that holds at most `capacity` lines.
62+ pub fn new(capacity: usize) -> Self {
63+ Self {
64+ capacity,
65+ state: Mutex::new(State::default()),
66+ }
67+ }
68+
69+ fn lock(&self) -> MutexGuard<'_, State> {
70+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
71+ }
72+
73+ /// Adds a line, dropping the oldest one when the ring is full.
74+ pub fn push(&self, line: RunnerLogLine) {
75+ let mut state = self.lock();
76+ if state.lines.len() >= self.capacity {
77+ state.lines.pop_front();
78+ }
79+ state.lines.push_back(line);
80+ state.next += 1;
81+ }
82+
83+ /// The number the next line will get.
84+ pub fn end(&self) -> u64 {
85+ self.lock().next
86+ }
87+
88+ /// Up to `max` lines from number `from` on. Lines already dropped are skipped, so the first
89+ /// returned number is `from` or later. The number is returned with the lines.
90+ pub fn batch(&self, from: u64, max: usize) -> (u64, Vec<RunnerLogLine>) {
91+ let state = self.lock();
92+ let oldest = state.next - state.lines.len() as u64;
93+ let first = from.max(oldest);
94+ if first >= state.next {
95+ return (first, Vec::new());
96+ }
97+ let skip = (first - oldest) as usize;
98+ let lines = state.lines.iter().skip(skip).take(max).cloned().collect();
99+ (first, lines)
100+ }
101+}
102+
103+/// The tracing layer that puts INFO (and more severe) events into the ring.
104+pub struct SelfLog {
105+ ring: Arc<Ring>,
106+}
107+
108+impl<S: Subscriber> Layer<S> for SelfLog {
109+ fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
110+ let meta = event.metadata();
111+ if *meta.level() > Level::INFO {
112+ return;
113+ }
114+ if SKIP_TARGETS
115+ .iter()
116+ .any(|prefix| meta.target().starts_with(prefix))
117+ {
118+ return;
119+ }
120+ let mut text = Text::default();
121+ event.record(&mut text);
122+ self.ring.push(RunnerLogLine {
123+ at_ms: now_ms(),
124+ level: level_name(*meta.level()).to_owned(),
125+ text: truncate(text.finish()),
126+ });
127+ }
128+}
129+
130+/// Collects an event's message and fields into one line, in the same shape the fmt layer uses:
131+/// the message, then `key=value` for each field.
132+#[derive(Default)]
133+struct Text {
134+ message: String,
135+ fields: String,
136+}
137+
138+impl Text {
139+ fn finish(self) -> String {
140+ match (self.message.is_empty(), self.fields.is_empty()) {
141+ (_, true) => self.message,
142+ (true, false) => self.fields.trim_start().to_owned(),
143+ (false, false) => format!("{}{}", self.message, self.fields),
144+ }
145+ }
146+}
147+
148+impl Visit for Text {
149+ fn record_str(&mut self, field: &Field, value: &str) {
150+ if field.name() == "message" {
151+ self.message.push_str(value);
152+ } else {
153+ let _ = write!(self.fields, " {}={value}", field.name());
154+ }
155+ }
156+
157+ fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
158+ if field.name() == "message" {
159+ let _ = write!(self.message, "{value:?}");
160+ } else {
161+ let _ = write!(self.fields, " {}={value:?}", field.name());
162+ }
163+ }
164+}
165+
166+fn level_name(level: Level) -> &'static str {
167+ match level {
168+ Level::ERROR => "error",
169+ Level::WARN => "warn",
170+ Level::INFO => "info",
171+ Level::DEBUG => "debug",
172+ _ => "trace",
173+ }
174+}
175+
176+fn now_ms() -> i64 {
177+ SystemTime::now()
178+ .duration_since(UNIX_EPOCH)
179+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
180+}
181+
182+/// Cuts `text` to at most [`MAX_TEXT`] bytes, on a character boundary.
183+fn truncate(mut text: String) -> String {
184+ if text.len() > MAX_TEXT {
185+ let mut end = MAX_TEXT;
186+ while !text.is_char_boundary(end) {
187+ end -= 1;
188+ }
189+ text.truncate(end);
190+ }
191+ text
192+}
193+
194+/// Posts the lines the forge has not seen yet, every two seconds, under the boot id of this
195+/// process. Failures are logged at debug level and retried on the next tick. When `stop` is
196+/// cancelled, the lines still held are sent before returning, so the caller may bound this with a
197+/// timeout. An older forge without the endpoint answers 404, and then shipping stops for good.
198+pub async fn ship(client: ForgeClient, runner_secret: String, stop: CancellationToken) {
199+ let ring = ring();
200+ let boot_id = crate::restart::boot_id();
201+ let mut next_seq = 0_u64;
202+ let mut ticker = tokio::time::interval(EVERY);
203+ loop {
204+ let stopping = tokio::select! {
205+ _ = ticker.tick() => false,
206+ () = stop.cancelled() => true,
207+ };
208+ loop {
209+ let (first_seq, lines) = ring.batch(next_seq, BATCH);
210+ if lines.is_empty() {
211+ break;
212+ }
213+ let batch = RunnerLogBatch {
214+ boot_id: boot_id.to_owned(),
215+ first_seq,
216+ lines,
217+ };
218+ match client.post_runner_log(&runner_secret, &batch).await {
219+ Ok(ack) => {
220+ let moved = ack.next_seq != next_seq;
221+ next_seq = ack.next_seq;
222+ // A final flush sends batch after batch, but only while the forge moves on.
223+ if !stopping || !moved {
224+ break;
225+ }
226+ }
227+ Err(ClientError::Status {
228+ status: StatusCode::NOT_FOUND,
229+ ..
230+ }) => return,
231+ Err(e) => {
232+ tracing::debug!(error = %e, "cannot ship the runner log, retrying");
233+ break;
234+ }
235+ }
236+ }
237+ if stopping {
238+ return;
239+ }
240+ }
241+}
242+
243+#[cfg(test)]
244+mod tests {
245+ use super::*;
246+
247+ fn line(text: &str) -> RunnerLogLine {
248+ RunnerLogLine {
249+ at_ms: 0,
250+ level: "info".into(),
251+ text: text.into(),
252+ }
253+ }
254+
255+ #[test]
256+ fn ring_drops_the_oldest_lines() {
257+ let ring = Ring::new(3);
258+ for i in 0..5 {
259+ ring.push(line(&i.to_string()));
260+ }
261+ assert_eq!(ring.end(), 5);
262+ let (first, lines) = ring.batch(0, 10);
263+ assert_eq!(first, 2);
264+ let texts: Vec<_> = lines.iter().map(|l| l.text.as_str()).collect();
265+ assert_eq!(texts, ["2", "3", "4"]);
266+ }
267+
268+ #[test]
269+ fn sequence_numbers_follow_the_request() {
270+ let ring = Ring::new(10);
271+ for i in 0..4 {
272+ ring.push(line(&i.to_string()));
273+ }
274+ let (first, lines) = ring.batch(1, 2);
275+ assert_eq!(first, 1);
276+ assert_eq!(lines.len(), 2);
277+ assert_eq!(lines[0].text, "1");
278+ // Nothing at or after the end.
279+ assert!(ring.batch(4, 10).1.is_empty());
280+ }
281+
282+ #[test]
283+ fn long_text_is_cut_on_a_char_boundary() {
284+ let text = "é".repeat(MAX_TEXT);
285+ let cut = truncate(text);
286+ assert!(cut.len() <= MAX_TEXT);
287+ assert!(cut.ends_with('é'));
288+ }
289+}
crates/forge-web/src/boot.rsmodified+1 -0
@@ -135,6 +135,7 @@ pub async fn serve(
135 mail_waker: Arc::new(Notify::new()),135 mail_waker: Arc::new(Notify::new()),
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 live: Arc::new(crate::live::LiveHub::default()),139 live: Arc::new(crate::live::LiveHub::default()),
139 push_live: Arc::new(crate::web_push::PushLive::default()),140 push_live: Arc::new(crate::web_push::PushLive::default()),
140 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),141 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),
crates/forge-web/src/ci/api.rsmodified+126 -2
@@ -12,10 +12,12 @@ 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,15+ RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch,
16 };16 };
17 use forge_core::Error as CoreError;17 use forge_core::Error as CoreError;
18-use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, MemoryOffer, RunState, RunnerReport};18+use forge_core::ci::{
19+ CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RunState, RunnerReport,
20+};
19 use futures_util::StreamExt;21 use futures_util::StreamExt;
20 use http::header::HeaderValue;22 use http::header::HeaderValue;
21 use serde_json::json;23 use serde_json::json;
@@ -27,6 +29,7 @@ use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route};
27 29
28 use crate::api::{self, Refusal};30 use crate::api::{self, Refusal};
29 use crate::ci::{artifact_key, log_path};31 use crate::ci::{artifact_key, log_path};
32+use crate::pages::admin_runners::bytes_text;
30 use crate::pages::repo::https_clone_url;33 use crate::pages::repo::https_clone_url;
31 use crate::self_update;34 use crate::self_update;
32 use crate::state::AppState;35 use crate::state::AppState;
@@ -42,6 +45,8 @@ const LOG_SIZE_HEADER: &str = "x-forge-log-size";
42 const MAX_LOG_CHUNK: usize = 1024 * 1024;45 const MAX_LOG_CHUNK: usize = 1024 * 1024;
43 /// Largest JSON body on the runner routes, in bytes.46 /// Largest JSON body on the runner routes, in bytes.
44 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.
49+const MAX_LOG_BATCH: usize = 1024 * 1024;
45 /// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say.50 /// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say.
46 const DEFAULT_RESERVE: u64 = 1 << 30;51 const DEFAULT_RESERVE: u64 = 1 << 30;
47 /// Longest runner name or label, in bytes.52 /// Longest runner name or label, in bytes.
@@ -312,6 +317,40 @@ async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Respons
312 }317 }
313 }318 }
314 319
320+/// `POST /api/v1/ci/runners/log`: a batch of the runner's own log lines. Answers the next line
321+/// number the forge wants for this boot id, so the runner resends what was lost.
322+#[route(POST "/api/v1/ci/runners/log")]
323+async fn runner_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
324+ let state = app_context::<AppState>(cx);
325+ let runner = match runner_from(state, headers(cx)).await {
326+ Ok(runner) => runner,
327+ Err(res) => return Ok(*res),
328+ };
329+ let bytes = match api::read_body(body, MAX_LOG_BATCH).await {
330+ Ok(bytes) => bytes,
331+ Err(res) => return Ok(*res),
332+ };
333+ let batch: RunnerLogBatch = match serde_json::from_slice(&bytes) {
334+ Ok(batch) => batch,
335+ Err(e) => {
336+ return Ok(api::error(
337+ StatusCode::BAD_REQUEST,
338+ &format!("invalid JSON body: {e}"),
339+ ));
340+ }
341+ };
342+ if batch.boot_id.is_empty() || batch.boot_id.len() > 64 {
343+ return Ok(api::error(
344+ StatusCode::UNPROCESSABLE_ENTITY,
345+ "the boot id is missing or too long",
346+ ));
347+ }
348+ let next_seq = state.runner_logs.ingest(&runner.id, &batch);
349+ state.ci_live.bump_runners();
350+ let ack = serde_json::to_value(RunnerLogAck { next_seq }).unwrap_or_default();
351+ Ok(api::json(StatusCode::OK, &ack))
352+}
353+
315 /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it354 /// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it
316 /// starts, applies them to its in-memory config, then reports its effective config here.355 /// starts, applies them to its in-memory config, then reports its effective config here.
317 #[route(GET "/api/v1/ci/runners/config")]356 #[route(GET "/api/v1/ci/runners/config")]
@@ -379,6 +418,7 @@ async fn claim_work(
379 // A runner that is to restart gets no new job. It is answered at once, so it sees the418 // A runner that is to restart gets no new job. It is answered at once, so it sees the
380 // request without waiting out the long poll.419 // request without waiting out the long poll.
381 if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) {420 if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) {
421+ note_restart_pending(state, runner).await;
382 return Ok(empty(StatusCode::NO_CONTENT));422 return Ok(empty(StatusCode::NO_CONTENT));
383 }423 }
384 match try_claim(state, runner, offer).await {424 match try_claim(state, runner, offer).await {
@@ -390,11 +430,88 @@ async fn claim_work(
390 .await430 .await
391 .is_err()431 .is_err()
392 {432 {
433+ note_idle(state, runner, offer).await;
393 return Ok(empty(StatusCode::NO_CONTENT));434 return Ok(empty(StatusCode::NO_CONTENT));
394 }435 }
395 }436 }
396 }437 }
397 438
439+/// Writes to the runner's log that a restart is holding back the queued jobs. Writes nothing when
440+/// no job is queued, so an idle runner does not fill its log.
441+async fn note_restart_pending(state: &AppState, runner: &CiRunner) {
442+ let Ok(skips) = state.store.queue_skips(runner, None).await else {
443+ return;
444+ };
445+ if skips.queued > 0 {
446+ note_runner(
447+ state,
448+ &runner.id,
449+ "a restart is pending, not handing out jobs",
450+ );
451+ }
452+}
453+
454+/// Writes to the runner's log why a long poll ended with no job while work is queued. Writes
455+/// nothing when no job is queued.
456+async fn note_idle(state: &AppState, runner: &CiRunner, offer: Option<MemoryOffer>) {
457+ let skips = match state.store.queue_skips(runner, offer).await {
458+ Ok(skips) => skips,
459+ Err(e) => {
460+ tracing::warn!(error = %e, "ci: counting the queued jobs failed");
461+ return;
462+ }
463+ };
464+ if let Some(text) = idle_text(&skips, offer.map(|o| o.free)) {
465+ note_runner(state, &runner.id, &text);
466+ }
467+}
468+
469+/// Stores a forge note in the runner's log and wakes the admin pages when it was written.
470+fn note_runner(state: &AppState, runner_id: &str, text: &str) {
471+ if state.runner_logs.note(runner_id, text) {
472+ state.ci_live.bump_runners();
473+ }
474+}
475+
476+/// The reason a runner got no job, from the queued jobs it could not take. `None` when no job is
477+/// queued. `free` is the memory the runner offered, when it offered any.
478+fn idle_text(skips: &QueueSkips, free: Option<u64>) -> Option<String> {
479+ if skips.queued == 0 {
480+ return None;
481+ }
482+ let mut parts = vec![format!(
483+ "{} queued {}",
484+ skips.queued,
485+ if skips.queued == 1 { "job" } else { "jobs" }
486+ )];
487+ if skips.lacking_labels > 0 {
488+ parts.push(format!(
489+ "{} need labels this runner lacks ({})",
490+ skips.lacking_labels,
491+ skips.missing_labels.join(", ")
492+ ));
493+ }
494+ if let (true, Some(need), Some(free)) = (skips.too_big > 0, skips.smallest_need, free) {
495+ parts.push(format!(
496+ "{} waiting for memory: smallest needs {}, {} free",
497+ skips.too_big,
498+ bytes_text(need),
499+ bytes_text(free)
500+ ));
501+ }
502+ if let (Some(need), Some(free)) = (skips.starved_need, free) {
503+ parts.push(format!(
504+ "{} held back: a job queued over {} min ago needs {}, {} free, so no smaller job \
505+ starts until running jobs finish and it fits",
506+ skips.held_behind,
507+ forge_core::ci::STARVE_AFTER_SECS / 60,
508+ bytes_text(need),
509+ bytes_text(free)
510+ ));
511+ }
512+ Some(parts.join("; "))
513+}
514+
398 /// The running binary, for a runner that updates itself. 404 unless self-update is enabled.515 /// The running binary, for a runner that updates itself. 404 unless self-update is enabled.
399 #[route(GET "/api/v1/ci/runners/binary")]516 #[route(GET "/api/v1/ci/runners/binary")]
400 async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> {517 async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> {
@@ -448,6 +565,13 @@ async fn try_claim(
448 state.ci_live.bump_run(&run.id);565 state.ci_live.bump_run(&run.id);
449 state.ci_live.bump_repo(&run.repo_id);566 state.ci_live.bump_repo(&run.repo_id);
450 state.ci_live.bump_runners();567 state.ci_live.bump_runners();
568+ // The next refusal is written again, and this job is written now.
569+ state.runner_logs.clear_note(&runner.id);
570+ note_runner(
571+ state,
572+ &runner.id,
573+ &format!("took job {} of run #{}", job.name, run.number),
574+ );
451 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;575 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
452 let repo = state576 let repo = state
453 .store577 .store
crates/forge-web/src/ci/mod.rsmodified+1 -0
@@ -14,6 +14,7 @@ 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 runner_log;
17 pub mod schedule;18 pub mod schedule;
18 pub mod scheduled;19 pub mod scheduled;
19 20
crates/forge-web/src/ci/runner_log.rsadded+234 -0
@@ -0,0 +1,234 @@
1+//! The runner's own log, kept in memory so an admin can read it on the runner's page. A runner
2+//! ships its lines in batches (`POST /api/v1/ci/runners/log`) and the forge keeps the newest
3+//! `MAX_LINES` per runner. Lines are not stored in the database: a restart of the forge drops them,
4+//! and the runner resends what it still holds on its next batch.
5+//!
6+//! The forge also writes its own lines (`from_forge`): why a claim got no job, and which job it
7+//! took. A reason that repeats is written once, see `note`.
8+
9+use std::collections::{HashMap, VecDeque};
10+use std::sync::{Mutex, MutexGuard};
11+
12+use forge_ci::proto::RunnerLogBatch;
13+
14+/// Most lines kept per runner. The oldest go first.
15+const MAX_LINES: usize = 2000;
16+/// Most lines taken from one batch. The rest are left for the runner to resend.
17+const MAX_BATCH_LINES: usize = 1000;
18+/// Longest text kept per line, in bytes. Longer text is cut on a character boundary.
19+const MAX_TEXT_BYTES: usize = 4096;
20+/// Longest boot id kept, in bytes.
21+const MAX_BOOT_ID_BYTES: usize = 64;
22+/// The levels a runner may send. Any other level is stored as `info`.
23+const LEVELS: [&str; 5] = ["error", "warn", "info", "debug", "trace"];
24+
25+/// One line of a runner's log, as the admin page shows it.
26+#[derive(Clone, Debug, PartialEq, Eq)]
27+pub struct Line {
28+ /// Unix time in milliseconds.
29+ pub at_ms: i64,
30+ pub level: String,
31+ pub text: String,
32+ /// True for a line the forge wrote, false for a line the runner sent.
33+ pub from_forge: bool,
34+}
35+
36+/// What the forge holds for one runner.
37+#[derive(Debug, Default)]
38+struct PerRunner {
39+ /// The boot id of the runner process the lines come from. Empty before the first batch.
40+ boot_id: String,
41+ /// The number of the next line the forge wants from the runner for `boot_id`.
42+ next_seq: u64,
43+ lines: VecDeque<Line>,
44+ /// The last forge note written, so a reason that repeats is not written again.
45+ last_note: Option<String>,
46+}
47+
48+/// The lines of every runner, by runner id. Shared through `AppState`.
49+#[derive(Debug, Default)]
50+pub struct RunnerLogs {
51+ runners: Mutex<HashMap<String, PerRunner>>,
52+}
53+
54+impl RunnerLogs {
55+ /// Takes a batch from a runner and returns the next line number the forge wants. A new boot id
56+ /// starts a fresh numbering, and the lines already in `lines` are kept. Lines before the
57+ /// wanted number are skipped, so a resent batch adds only what is new.
58+ pub fn ingest(&self, runner_id: &str, batch: &RunnerLogBatch) -> u64 {
59+ if batch.boot_id.is_empty() || batch.boot_id.len() > MAX_BOOT_ID_BYTES {
60+ return self.next_seq(runner_id);
61+ }
62+ let mut runners = self.lock();
63+ let entry = runners.entry(runner_id.to_owned()).or_default();
64+ if entry.boot_id != batch.boot_id {
65+ entry.boot_id = batch.boot_id.clone();
66+ entry.next_seq = 0;
67+ let short: String = batch.boot_id.chars().take(8).collect();
68+ push(entry, forge_line(format!("runner started (boot {short})")));
69+ }
70+ if batch.first_seq > entry.next_seq {
71+ let missing = batch.first_seq - entry.next_seq;
72+ push(entry, forge_line(format!("{missing} lines missing")));
73+ }
74+ for (i, line) in batch.lines.iter().take(MAX_BATCH_LINES).enumerate() {
75+ let seq = batch.first_seq + i as u64;
76+ if seq < entry.next_seq {
77+ continue;
78+ }
79+ push(
80+ entry,
81+ Line {
82+ at_ms: line.at_ms,
83+ level: level_of(&line.level),
84+ text: cut(&line.text, MAX_TEXT_BYTES),
85+ from_forge: false,
86+ },
87+ );
88+ }
89+ let taken = batch.lines.len().min(MAX_BATCH_LINES) as u64;
90+ entry.next_seq = entry.next_seq.max(batch.first_seq + taken);
91+ entry.next_seq
92+ }
93+
94+ /// Writes a forge line saying why the runner got no job. Writes nothing when `text` is the
95+ /// last note for this runner. Returns true when a line was written.
96+ pub fn note(&self, runner_id: &str, text: &str) -> bool {
97+ let mut runners = self.lock();
98+ let entry = runners.entry(runner_id.to_owned()).or_default();
99+ if entry.last_note.as_deref() == Some(text) {
100+ return false;
101+ }
102+ entry.last_note = Some(text.to_owned());
103+ push(entry, forge_line(text.to_owned()));
104+ true
105+ }
106+
107+ /// Forgets the last note, so the next refusal of this runner is written again. Called when a
108+ /// job is handed out.
109+ pub fn clear_note(&self, runner_id: &str) {
110+ if let Some(entry) = self.lock().get_mut(runner_id) {
111+ entry.last_note = None;
112+ }
113+ }
114+
115+ /// The lines of a runner, oldest first. Empty for a runner that never sent a line.
116+ pub fn lines(&self, runner_id: &str) -> Vec<Line> {
117+ self.lock()
118+ .get(runner_id)
119+ .map(|entry| entry.lines.iter().cloned().collect())
120+ .unwrap_or_default()
121+ }
122+
123+ fn next_seq(&self, runner_id: &str) -> u64 {
124+ self.lock().get(runner_id).map_or(0, |entry| entry.next_seq)
125+ }
126+
127+ fn lock(&self) -> MutexGuard<'_, HashMap<String, PerRunner>> {
128+ // A panic while the lock was held leaves the map usable, so a poisoned lock is taken as is.
129+ self.runners.lock().unwrap_or_else(|e| e.into_inner())
130+ }
131+}
132+
133+/// Adds a line and drops the oldest lines beyond `MAX_LINES`.
134+fn push(entry: &mut PerRunner, line: Line) {
135+ entry.lines.push_back(line);
136+ while entry.lines.len() > MAX_LINES {
137+ entry.lines.pop_front();
138+ }
139+}
140+
141+/// A line the forge wrote now, at level `info`.
142+fn forge_line(text: String) -> Line {
143+ let at_ms = std::time::SystemTime::now()
144+ .duration_since(std::time::UNIX_EPOCH)
145+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));
146+ Line {
147+ at_ms,
148+ level: "info".to_owned(),
149+ text,
150+ from_forge: true,
151+ }
152+}
153+
154+/// The level as sent, or `info` for a level the forge does not know.
155+fn level_of(level: &str) -> String {
156+ if LEVELS.contains(&level) {
157+ level.to_owned()
158+ } else {
159+ "info".to_owned()
160+ }
161+}
162+
163+/// `text` cut to at most `max` bytes, on a character boundary.
164+fn cut(text: &str, max: usize) -> String {
165+ if text.len() <= max {
166+ return text.to_owned();
167+ }
168+ let mut end = max;
169+ while !text.is_char_boundary(end) {
170+ end -= 1;
171+ }
172+ text[..end].to_owned()
173+}
174+
175+#[cfg(test)]
176+mod tests {
177+ use super::*;
178+ use forge_ci::proto::RunnerLogLine;
179+
180+ fn batch(boot: &str, first_seq: u64, texts: &[&str]) -> RunnerLogBatch {
181+ RunnerLogBatch {
182+ boot_id: boot.to_owned(),
183+ first_seq,
184+ lines: texts
185+ .iter()
186+ .map(|t| RunnerLogLine {
187+ at_ms: 1,
188+ level: "info".to_owned(),
189+ text: (*t).to_owned(),
190+ })
191+ .collect(),
192+ }
193+ }
194+
195+ /// A resent batch adds only the lines the forge has not seen, and a gap is marked.
196+ #[test]
197+ fn ingest_skips_what_is_known_and_marks_gaps() {
198+ let logs = RunnerLogs::default();
199+ assert_eq!(logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b"])), 2);
200+ // Resend of 0..=2: only "c" is new.
201+ assert_eq!(
202+ logs.ingest("r1", &batch("bootaaaaaaaaaa", 0, &["a", "b", "c"])),
203+ 3
204+ );
205+ // Lines 3 and 4 were lost before the forge saw them: a marker, then the batch.
206+ assert_eq!(logs.ingest("r1", &batch("bootaaaaaaaaaa", 5, &["f"])), 6);
207+
208+ let texts: Vec<String> = logs.lines("r1").into_iter().map(|l| l.text).collect();
209+ assert_eq!(
210+ texts,
211+ [
212+ "runner started (boot bootaaaa)",
213+ "a",
214+ "b",
215+ "c",
216+ "2 lines missing",
217+ "f"
218+ ]
219+ );
220+ }
221+
222+ /// A reason is written once while it repeats, and again after the runner gets a job.
223+ #[test]
224+ fn note_is_written_once_until_cleared() {
225+ let logs = RunnerLogs::default();
226+ assert!(logs.note("r1", "a restart is pending"));
227+ assert!(!logs.note("r1", "a restart is pending"));
228+ logs.clear_note("r1");
229+ assert!(logs.note("r1", "a restart is pending"));
230+ let lines = logs.lines("r1");
231+ assert_eq!(lines.len(), 2);
232+ assert!(lines.iter().all(|l| l.from_forge));
233+ }
234+}
crates/forge-web/src/pages/admin_runners.rsmodified+66 -5
@@ -23,6 +23,7 @@ use topcoat::router::{page, path_param, route};
23 use topcoat::view::{View, component, view};23 use topcoat::view::{View, component, view};
24 24
25 use crate::audit::{self, Actor, Target};25 use crate::audit::{self, Actor, Target};
26+use crate::ci::runner_log::Line;
26 use crate::auth::check_csrf;27 use crate::auth::check_csrf;
27 use crate::i18n::admin::{self as g, K};28 use crate::i18n::admin::{self as g, K};
28 use crate::i18n::{self, Key, Lang};29 use crate::i18n::{self, Key, Lang};
@@ -789,8 +790,8 @@ fn sel(on: bool) -> Option<&'static str> {
789 on.then_some("selected")790 on.then_some("selected")
790 }791 }
791 792
792-/// The detail page tabs: slug and the config keys on it. `identity` is the read-only block.793+/// The detail page tabs: slug and the config keys on it. `identity` and `logs` are read-only.
793-const TABS: [(&str, &[&str]); 5] = [794+const TABS: [(&str, &[&str]); 6] = [
794 (795 (
795 "general",796 "general",
796 &["concurrency", "labels", "executor", "auto_update"],797 &["concurrency", "labels", "executor", "auto_update"],
@@ -817,6 +818,7 @@ const TABS: [(&str, &[&str]); 5] = [
817 ),818 ),
818 ("sandbox", &["sandbox.userns"]),819 ("sandbox", &["sandbox.userns"]),
819 ("identity", &[]),820 ("identity", &[]),
821+ ("logs", &[]),
820 ];822 ];
821 823
822 fn tab_label(lang: Lang, slug: &str) -> &'static str {824 fn tab_label(lang: Lang, slug: &str) -> &'static str {
@@ -825,6 +827,7 @@ fn tab_label(lang: Lang, slug: &str) -> &'static str {
825 "limits" => s(lang, "Limits", "Sınırlar"),827 "limits" => s(lang, "Limits", "Sınırlar"),
826 "storage" => s(lang, "Storage", "Depolama"),828 "storage" => s(lang, "Storage", "Depolama"),
827 "sandbox" => s(lang, "Sandbox", "Kum havuzu"),829 "sandbox" => s(lang, "Sandbox", "Kum havuzu"),
830+ "logs" => s(lang, "Logs", "Günlük"),
828 _ => s(lang, "Identity", "Kimlik"),831 _ => s(lang, "Identity", "Kimlik"),
829 }832 }
830 }833 }
@@ -1086,6 +1089,47 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField>
1086 .collect()1089 .collect()
1087 }1090 }
1088 1091
1092+/// Most log lines the logs tab shows: the newest.
1093+const LOG_SHOWN: usize = 500;
1094+
1095+/// One line of the logs tab, ready to render.
1096+struct LogRow {
1097+ /// UTC time of day, `HH:MM:SS`.
1098+ time: String,
1099+ level: String,
1100+ text: String,
1101+ /// `forge` for a line the forge wrote, empty for one the runner sent.
1102+ chip: &'static str,
1103+ /// The line's classes. Warn and error lines get a class of their own.
1104+ class: &'static str,
1105+}
1106+
1107+/// The newest `LOG_SHOWN` lines, newest first so the tab opens on what the runner did last.
1108+fn log_rows_of(lines: &[Line]) -> Vec<LogRow> {
1109+ let start = lines.len().saturating_sub(LOG_SHOWN);
1110+ lines[start..]
1111+ .iter()
1112+ .rev()
1113+ .map(|line| LogRow {
1114+ time: clock_text(line.at_ms),
1115+ level: line.level.clone(),
1116+ text: line.text.clone(),
1117+ chip: if line.from_forge { "forge" } else { "" },
1118+ class: match line.level.as_str() {
1119+ "error" => "runner-log-line is-error",
1120+ "warn" => "runner-log-line is-warn",
1121+ _ => "runner-log-line",
1122+ },
1123+ })
1124+ .collect()
1125+}
1126+
1127+/// The UTC time of day of a Unix time in milliseconds, as `HH:MM:SS`.
1128+fn clock_text(at_ms: i64) -> String {
1129+ let day = (at_ms / 1000).rem_euclid(86_400);
1130+ format!("{:02}:{:02}:{:02}", day / 3600, day % 3600 / 60, day % 60)
1131+}
1132+
1089 /// The read-only identity entries: label and value. The secret is never shown.1133 /// The read-only identity entries: label and value. The secret is never shown.
1090 fn identity_rows(lang: Lang, fields: &[FieldRow]) -> Vec<(&'static str, String)> {1134 fn identity_rows(lang: Lang, fields: &[FieldRow]) -> Vec<(&'static str, String)> {
1091 fields1135 fields
@@ -1104,7 +1148,8 @@ fn identity_rows(lang: Lang, fields: &[FieldRow]) -> Vec<(&'static str, String)>
1104 .collect()1148 .collect()
1105 }1149 }
1106 1150
1107-fn bytes_text(bytes: u64) -> String {1151+/// A byte count in GiB with one decimal, such as `3.7 GiB`.
1152+pub(crate) fn bytes_text(bytes: u64) -> String {
1108 let gib = bytes as f64 / (1u64 << 30) as f64;1153 let gib = bytes as f64 / (1u64 << 30) as f64;
1109 format!("{gib:.1} GiB")1154 format!("{gib:.1} GiB")
1110 }1155 }
@@ -1134,6 +1179,7 @@ async fn runner_detail_view(
1134 fields: Vec<FieldRow>,1179 fields: Vec<FieldRow>,
1135 notice: Option<(&'static str, bool)>,1180 notice: Option<(&'static str, bool)>,
1136 tab: &'static str,1181 tab: &'static str,
1182+ log: Vec<LogRow>,
1137 ) -> Result<impl View> {1183 ) -> Result<impl View> {
1138 let version = or_dash(runner.reported.version.clone().unwrap_or_default());1184 let version = or_dash(runner.reported.version.clone().unwrap_or_default());
1139 let cpus = or_dash(1185 let cpus = or_dash(
@@ -1166,7 +1212,7 @@ async fn runner_detail_view(
1166 };1212 };
1167 let shown = detail_fields(lang, tab, &fields);1213 let shown = detail_fields(lang, tab, &fields);
1168 let identity = identity_rows(lang, &fields);1214 let identity = identity_rows(lang, &fields);
1169- let editing = tab != "identity";1215+ let editing = !matches!(tab, "identity" | "logs");
1170 let save_action = format!("{}/settings", row.detail_href);1216 let save_action = format!("{}/settings", row.detail_href);
1171 let reset_action = row.config_action.clone();1217 let reset_action = row.config_action.clone();
1172 Ok(view! {1218 Ok(view! {
@@ -1255,6 +1301,16 @@ async fn runner_detail_view(
1255 <input type="hidden" name="tab" value=(tab)>1301 <input type="hidden" name="tab" value=(tab)>
1256 <input type="hidden" name="reset" value="1">1302 <input type="hidden" name="reset" value="1">
1257 </form>1303 </form>
1304+ } else if tab == "logs" {
1305+ if log.is_empty() {
1306+ <p class="muted small">(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."))</p>
1307+ } else {
1308+ <pre class="ci-log runner-log" role="log" aria-label=(s(lang, "Runner log", "Çalıştırıcı günlüğü"))>
1309+ for row in log.iter() {
1310+ <span class=(row.class)><span class="runner-log-time">(row.time.as_str())</span>" "<span class="runner-log-level">(row.level.as_str())</span>" "<span class="runner-log-chip">(row.chip)</span>" "(row.text.as_str())</span>"\n"
1311+ }
1312+ </pre>
1313+ }
1258 } else {1314 } else {
1259 <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>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>
1260 <div class="srv-grid">1316 <div class="srv-grid">
@@ -1289,9 +1345,14 @@ async fn runner_detail_page(cx: &Cx) -> Result<impl View> {
1289 let csrf = viewer.1.csrf_token.clone();1345 let csrf = viewer.1.csrf_token.clone();
1290 let notice = notice_from_query(cx, lang);1346 let notice = notice_from_query(cx, lang);
1291 let tab = tab_from_query(cx);1347 let tab = tab_from_query(cx);
1348+ let log = if tab == "logs" {
1349+ log_rows_of(&state.runner_logs.lines(&runner.id))
1350+ } else {
1351+ Vec::new()
1352+ };
1292 let title = runner.name.clone();1353 let title = runner.name.clone();
1293 Ok(view! {1354 Ok(view! {
1294- 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))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))
1295 })1356 })
1296 }1357 }
1297 1358
crates/forge-web/src/pages/settings_security.rsmodified+1 -0
@@ -1104,6 +1104,7 @@ mod tests {
1104 mail_waker: Arc::new(tokio::sync::Notify::new()),1104 mail_waker: Arc::new(tokio::sync::Notify::new()),
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 live: Arc::new(crate::live::LiveHub::default()),1108 live: Arc::new(crate::live::LiveHub::default()),
1108 push_live: Arc::new(crate::web_push::PushLive::default()),1109 push_live: Arc::new(crate::web_push::PushLive::default()),
1109 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),1110 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),
crates/forge-web/src/state.rsmodified+2 -0
@@ -49,6 +49,8 @@ pub struct AppState {
49 pub notify_hub: Arc<crate::notify_hub::NotifyHub>,49 pub notify_hub: Arc<crate::notify_hub::NotifyHub>,
50 /// Change counters of CI jobs and runs. Log followers and run pages wait on them.50 /// Change counters of CI jobs and runs. Log followers and run pages wait on them.
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`.
53+ pub runner_logs: Arc<crate::ci::runner_log::RunnerLogs>,
52 /// Change signals of live pages, keyed by topic. See `live`.54 /// Change signals of live pages, keyed by topic. See `live`.
53 pub live: Arc<crate::live::LiveHub>,55 pub live: Arc<crate::live::LiveHub>,
54 /// Device changes per user. The settings pages showing a user's push devices listen to it.56 /// 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
@@ -93,6 +93,7 @@ pub async fn test_state(dir: &Path) -> AppState {
93 mail_waker: Arc::new(Notify::new()),93 mail_waker: Arc::new(Notify::new()),
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 live: Arc::new(crate::live::LiveHub::default()),97 live: Arc::new(crate::live::LiveHub::default()),
97 push_live: Arc::new(crate::web_push::PushLive::default()),98 push_live: Arc::new(crate::web_push::PushLive::default()),
98 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),99 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),
style/_admin_rows.scssmodified+29 -0
@@ -92,3 +92,32 @@
92 width: 52px;92 width: 52px;
93 }93 }
94 }94 }
95+
96+// The runner's own log on its admin page (the logs tab), newest line first. Lines stay inline:
97+// the pre breaks them with its own newlines.
98+.runner-log-line {
99+ &.is-warn {
100+ color: var(--warn);
101+ }
102+
103+ &.is-error {
104+ color: var(--danger);
105+ }
106+}
107+
108+.runner-log-time,
109+.runner-log-level {
110+ color: var(--muted);
111+}
112+
113+.runner-log-chip:not(:empty) {
114+ padding: 0 6px;
115+ border-radius: var(--radius-sm);
116+ background: var(--accent-soft);
117+ color: var(--accent-ink);
118+}
119+
120+// Job logs pad each numbered line; the runner log has no numbers, so the box pads instead.
121+.ci-log.runner-log {
122+ padding: 8px 12px;
123+}