use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use forge_ci::mask::{MaskStream, Masker}; use forge_ci::proto::{FinishRequest, JobAssignment, Outcome}; use tokio::sync::mpsc; use tokio::task::{JoinHandle, JoinSet}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; use crate::artifacts; use crate::cache::CacheStore; use crate::client::{ClientError, ForgeClient}; use crate::config::RunnerConfig; use crate::executor::{ExecRequest, ExecResult, Executor}; use crate::limiter::Limiter; use crate::logs::{self, PumpConfig}; use crate::metrics; use crate::oom::OomSink; use crate::restart::{self, RestartState, Step}; use crate::selflog; use crate::update::{self, Installed, UpdateState}; use crate::workspace; const LOG_CHANNEL: usize = 64; const FORGE_PATIENCE: Duration = Duration::from_secs(10 * 60); const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024; const LOG_FLUSH: Duration = Duration::from_secs(5); #[derive(Clone, Copy, Debug)] pub struct RunOptions { pub heartbeat_every: Duration, pub claim_backoff: Duration, pub pump: PumpConfig, pub timeout_override: Option, } impl Default for RunOptions { fn default() -> Self { Self { heartbeat_every: Duration::from_secs(10), claim_backoff: Duration::from_secs(5), pump: PumpConfig::default(), timeout_override: None, } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RunEnd { Stopped, Updated, Restart, } #[derive(Clone)] pub struct Runner { client: ForgeClient, config: Arc, executor: Arc, options: RunOptions, cache: Option>, limiter: Arc, restart: Arc, } impl Runner { pub fn new( config: RunnerConfig, executor: Arc, options: RunOptions, ) -> Result { let client = ForgeClient::new(&config.url)?; let limiter = Limiter::new(config.concurrency); Ok(Self { client, config: Arc::new(config), executor, options, cache: None, limiter, restart: Arc::new(RestartState::default()), }) } pub fn with_cache(mut self, cache: CacheStore) -> Self { self.cache = Some(Arc::new(cache)); self } pub fn client(&self) -> &ForgeClient { &self.client } pub async fn run(&self, shutdown: CancellationToken) -> RunEnd { let mut jobs: JoinSet<()> = JoinSet::new(); let exe = if self.config.auto_update { match update::locate_self() { Ok(found) => Some(found), Err(e) => { tracing::warn!(error = %e, "auto update disabled, cannot read own binary"); None } } } else { None }; let mut updates = UpdateState::new( self.config.auto_update, exe.as_ref().map(|(_, sha)| sha.clone()), ); tracing::info!( name = %self.config.name, concurrency = self.limiter.current(), auto_update = updates.enabled(), "runner started" ); let jobs_cancel = shutdown.child_token(); let ship_stop = CancellationToken::new(); let shipper = tokio::spawn(selflog::ship( self.client.clone(), self.config.runner_secret.clone(), ship_stop.clone(), )); let limiter = self.limiter.clone(); let metrics_shipper = tokio::spawn(metrics::ship( self.client.clone(), self.config.runner_secret.clone(), self.config.work_dir.clone(), move || { let busy = limiter.current().saturating_sub(limiter.free_slots()); u32::try_from(busy).unwrap_or(u32::MAX) }, ship_stop.clone(), )); let mut blocked: Option = None; let end = loop { match restart::decide( self.restart.pending(), jobs.len(), self.restart.jobs_cancelled(), ) { Step::Proceed => {} Step::Restart => { tracing::info!("restart requested by the forge, restarting"); break RunEnd::Restart; } Step::CancelJobs => { tracing::info!("restart now requested, cancelling running jobs"); self.restart.mark_cancelled(); jobs_cancel.cancel(); 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() => log_joined(joined), () = self.restart.changed() => {} } continue; } } if let Some((exe_path, _)) = &exe && let Some(sha) = updates.pending().map(str::to_owned) { if !jobs.is_empty() { 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() => log_joined(joined), } continue; } match update::install(&self.client, &self.config.runner_secret, exe_path, &sha) .await { Ok(Installed::Replaced) => { tracing::info!(sha = %sha, "binary updated, restarting"); break RunEnd::Updated; } Ok(Installed::Listed) => { tracing::warn!(sha = %sha, "forge binary is on the bad list, not updating"); updates.give_up(&sha); } Err(e) => { tracing::warn!(sha = %sha, error = %e, "update failed, keeping this binary"); updates.give_up(&sha); } } continue; } 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, permit = self.limiter.acquire() => match permit { Ok(permit) => permit, Err(_) => break RunEnd::Stopped, }, }; let claimed = tokio::select! { _ = shutdown.cancelled() => { drop(permit); break RunEnd::Stopped; } r = self.client.claim_with( &self.config.runner_secret, &self.config.labels, Some(self.limiter.current()), ) => r, }; match claimed { Ok(reply) => { self.limiter.apply_logged(reply.concurrency); self.restart.observe(reply.restart); if updates.observe(reply.binary_sha256.as_deref()) && let Some(sha) = updates.pending() { tracing::info!(sha = %sha, "forge advertises a new binary, updating when idle"); } match reply.job { Some(job) => { tracing::info!( job_id = %job.job_id, job_name = %job.job_name, repo = %job.repo, "claimed job" ); let runner = self.clone(); let cancel = jobs_cancel.child_token(); jobs.spawn(async move { let _permit = permit; runner.process(job, cancel).await; }); } None => drop(permit), } } Err(e) => { drop(permit); tracing::warn!(error = %e, "claim failed, backing off"); tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, _ = tokio::time::sleep(self.options.claim_backoff) => {} } } } while let Some(joined) = jobs.try_join_next() { log_joined(joined); } }; while let Some(joined) = jobs.join_next().await { log_joined(joined); } tracing::info!("runner stopped"); ship_stop.cancel(); let _ = tokio::time::timeout(LOG_FLUSH, shipper).await; let _ = tokio::time::timeout(LOG_FLUSH, metrics_shipper).await; end } pub async fn process(&self, job: JobAssignment, shutdown: CancellationToken) -> Outcome { let mut secret_values: Vec = job.secrets.values().cloned().collect(); secret_values.push(job.job_token.clone()); let masker = Masker::new(secret_values); let (tx, rx) = mpsc::channel::>(LOG_CHANNEL); let pump = { let client = self.client.clone(); let job_id = job.job_id.clone(); let token = job.job_token.clone(); let cfg = self.options.pump; tokio::spawn(async move { logs::pump(&client, &job_id, &token, MaskStream::new(masker), rx, cfg).await }) }; send_line( &tx, format!( "forge-runner {}: job {} on runner {}, image {}, commit {}", forge_ci::build::display(), job.job_name, self.config.name, job.image, job.commit ), ) .await; let timeout = self .options .timeout_override .unwrap_or_else(|| Duration::from_secs(60 * u64::from(job.timeout_minutes))); let job_cancel = shutdown.child_token(); let timed_out = Arc::new(AtomicBool::new(false)); let heartbeat = self.spawn_heartbeat(&job, job_cancel.clone()); let timer = { let cancel = job_cancel.clone(); let flag = timed_out.clone(); tokio::spawn(async move { tokio::time::sleep(timeout).await; flag.store(true, Ordering::SeqCst); cancel.cancel(); }) }; let mut workspace_dir = None; let oom = OomSink::default(); let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await; let mut result = match prepared { Ok(dir) => { if let Some(cache) = &self.cache { for line in cache.restore(&job, &dir).await { send_line(&tx, line).await; } } let result = self .executor .run(ExecRequest { job: &job, workspace: &dir, logs: tx.clone(), cancel: job_cancel.clone(), oom: oom.clone(), }) .await; workspace_dir = Some(dir); result } Err(e) => ExecResult { outcome: Outcome::Error, exit_code: None, message: Some(format!("workspace: {e}")), }, }; let upload_error = match workspace_dir.as_deref() { Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => { self.upload_artifacts(&job, dir).await.err() } _ => None, }; if let Some(message) = upload_error { result = ExecResult { outcome: Outcome::Error, exit_code: result.exit_code, message: Some(message), }; } heartbeat.abort(); timer.abort(); if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled { result = ExecResult { outcome: Outcome::Failure, exit_code: None, message: Some(format!("timed out after {} minutes", job.timeout_minutes)), }; } if self.restart.jobs_cancelled() && shutdown.is_cancelled() && result.outcome == Outcome::Cancelled { result.message = Some("cancelled because an admin restarted the runner".to_owned()); } if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { for line in cache.save(&job, result.outcome, dir).await { send_line(&tx, line).await; } } if let Some(message) = &result.message { send_line(&tx, format!("runner: {message}")).await; } let oom_kills = oom.kills(); if let Some(kills) = oom_kills { send_line( &tx, format!( "runner: out of memory, the job ran out of the runner's memory and the \ out of memory killer stopped it ({kills} process(es))" ), ) .await; } drop(tx); match pump.await { Ok(Ok(bytes)) => tracing::debug!(job_id = %job.job_id, bytes, "logs shipped"), Ok(Err(e)) => tracing::warn!(job_id = %job.job_id, error = %e, "log shipping failed"), Err(e) => tracing::error!(job_id = %job.job_id, error = %e, "log task panicked"), } self.finish(&job, &result, oom_kills).await; if let Some(dir) = workspace_dir && let Err(e) = workspace::cleanup(&dir).await { tracing::warn!(job_id = %job.job_id, error = %e, "workspace cleanup failed"); } tracing::info!(job_id = %job.job_id, outcome = ?result.outcome, "job finished"); result.outcome } fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> { let client = self.client.clone(); let limiter = self.limiter.clone(); let restart = self.restart.clone(); let job_id = job.job_id.clone(); let token = job.job_token.clone(); let every = self.options.heartbeat_every; tokio::spawn(async move { let mut ticker = tokio::time::interval_at(Instant::now() + every, every); loop { ticker.tick().await; match client .heartbeat_with(&job_id, &token, Some(limiter.current())) .await { Ok(beat) if beat.cancel => { limiter.apply_logged(beat.concurrency); restart.observe(beat.restart); tracing::info!(job_id = %job_id, "forge requested cancel"); cancel.cancel(); return; } Ok(beat) => { limiter.apply_logged(beat.concurrency); restart.observe(beat.restart); } Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"), } } }) } async fn upload_artifacts( &self, job: &JobAssignment, dir: &std::path::Path, ) -> Result<(), String> { let found = artifacts::collect(dir, &job.artifacts, MAX_ARTIFACT_BYTES) .map_err(|e| format!("artifacts: {e}"))?; for artifact in &found { patiently(&job.job_id, "artifact upload", || { self.client .upload_artifact(&job.job_id, &job.job_token, &artifact.name, &artifact.path) }) .await .map_err(|e| format!("artifact {}: {e}", artifact.name))?; } tracing::info!(job_id = %job.job_id, count = found.len(), "artifacts uploaded"); Ok(()) } async fn finish(&self, job: &JobAssignment, result: &ExecResult, oom_kills: Option) { let req = FinishRequest { outcome: result.outcome, exit_code: result.exit_code, message: result.message.clone(), oom_killed: oom_kills.map(|_| true), oom_kills, }; let reported = patiently(&job.job_id, "finish", || { self.client.finish(&job.job_id, &job.job_token, &req) }) .await; if reported.is_ok() { return; } tracing::error!( job_id = %job.job_id, "could not report the job result; the forge will reap it after heartbeats stop" ); } } async fn patiently(job_id: &str, what: &str, mut op: F) -> Result<(), ClientError> where F: FnMut() -> Fut, Fut: std::future::Future>, { let started = Instant::now(); let mut attempt = 0u32; loop { attempt += 1; let Err(e) = op().await else { return Ok(()); }; tracing::warn!(job_id, attempt, error = %e, "{what} failed"); let away = match &e { ClientError::Http(_) => true, ClientError::Status { status, .. } => status.is_server_error(), _ => false, }; if !away || started.elapsed() >= FORGE_PATIENCE { return Err(e); } tokio::time::sleep(Duration::from_secs((2 * u64::from(attempt)).min(15))).await; } } fn not_claiming(last: &mut Option, reason: String) { if last.as_deref() != Some(reason.as_str()) { tracing::info!("not claiming: {reason}"); *last = Some(reason); } } fn log_joined(joined: Result<(), tokio::task::JoinError>) { if let Err(e) = joined { tracing::error!(error = %e, "job task panicked"); } } async fn send_line(tx: &mpsc::Sender>, line: String) { let mut bytes = line.into_bytes(); bytes.push(b'\n'); let _ = tx.send(bytes).await; }