forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli3 hours ago363 commits

runner.rs535 lines, 18.9 KiBHistoryRawDownload
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::Duration;
4
5use forge_ci::mask::{MaskStream, Masker};
6use forge_ci::proto::{FinishRequest, JobAssignment, Outcome};
7use tokio::sync::mpsc;
8use tokio::task::{JoinHandle, JoinSet};
9use tokio::time::Instant;
10use tokio_util::sync::CancellationToken;
11
12use crate::artifacts;
13use crate::cache::CacheStore;
14use crate::client::{ClientError, ForgeClient};
15use crate::config::RunnerConfig;
16use crate::executor::{ExecRequest, ExecResult, Executor};
17use crate::limiter::Limiter;
18use crate::logs::{self, PumpConfig};
19use crate::metrics;
20use crate::oom::OomSink;
21use crate::restart::{self, RestartState, Step};
22use crate::selflog;
23use crate::update::{self, Installed, UpdateState};
24use crate::workspace;
25
26const LOG_CHANNEL: usize = 64;
27const FORGE_PATIENCE: Duration = Duration::from_secs(10 * 60);
28const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024;
29const LOG_FLUSH: Duration = Duration::from_secs(5);
30
31#[derive(Clone, Copy, Debug)]
32pub struct RunOptions {
33 pub heartbeat_every: Duration,
34 pub claim_backoff: Duration,
35 pub pump: PumpConfig,
36 pub timeout_override: Option<Duration>,
37}
38
39impl Default for RunOptions {
40 fn default() -> Self {
41 Self {
42 heartbeat_every: Duration::from_secs(10),
43 claim_backoff: Duration::from_secs(5),
44 pump: PumpConfig::default(),
45 timeout_override: None,
46 }
47 }
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum RunEnd {
52 Stopped,
53 Updated,
54 Restart,
55}
56
57#[derive(Clone)]
58pub struct Runner {
59 client: ForgeClient,
60 config: Arc<RunnerConfig>,
61 executor: Arc<dyn Executor>,
62 options: RunOptions,
63 cache: Option<Arc<CacheStore>>,
64 limiter: Arc<Limiter>,
65 restart: Arc<RestartState>,
66}
67
68impl Runner {
69 pub fn new(
70 config: RunnerConfig,
71 executor: Arc<dyn Executor>,
72 options: RunOptions,
73 ) -> Result<Self, ClientError> {
74 let client = ForgeClient::new(&config.url)?;
75 let limiter = Limiter::new(config.concurrency);
76 Ok(Self {
77 client,
78 config: Arc::new(config),
79 executor,
80 options,
81 cache: None,
82 limiter,
83 restart: Arc::new(RestartState::default()),
84 })
85 }
86
87 pub fn with_cache(mut self, cache: CacheStore) -> Self {
88 self.cache = Some(Arc::new(cache));
89 self
90 }
91
92 pub fn client(&self) -> &ForgeClient {
93 &self.client
94 }
95
96 pub async fn run(&self, shutdown: CancellationToken) -> RunEnd {
97 let mut jobs: JoinSet<()> = JoinSet::new();
98 let exe = if self.config.auto_update {
99 match update::locate_self() {
100 Ok(found) => Some(found),
101 Err(e) => {
102 tracing::warn!(error = %e, "auto update disabled, cannot read own binary");
103 None
104 }
105 }
106 } else {
107 None
108 };
109 let mut updates = UpdateState::new(
110 self.config.auto_update,
111 exe.as_ref().map(|(_, sha)| sha.clone()),
112 );
113 tracing::info!(
114 name = %self.config.name,
115 concurrency = self.limiter.current(),
116 auto_update = updates.enabled(),
117 "runner started"
118 );
119 let jobs_cancel = shutdown.child_token();
120 let ship_stop = CancellationToken::new();
121 let shipper = tokio::spawn(selflog::ship(
122 self.client.clone(),
123 self.config.runner_secret.clone(),
124 ship_stop.clone(),
125 ));
126 let limiter = self.limiter.clone();
127 let metrics_shipper = tokio::spawn(metrics::ship(
128 self.client.clone(),
129 self.config.runner_secret.clone(),
130 self.config.work_dir.clone(),
131 move || {
132 let busy = limiter.current().saturating_sub(limiter.free_slots());
133 u32::try_from(busy).unwrap_or(u32::MAX)
134 },
135 ship_stop.clone(),
136 ));
137 let mut blocked: Option<String> = None;
138 let end = loop {
139 match restart::decide(
140 self.restart.pending(),
141 jobs.len(),
142 self.restart.jobs_cancelled(),
143 ) {
144 Step::Proceed => {}
145 Step::Restart => {
146 tracing::info!("restart requested by the forge, restarting");
147 break RunEnd::Restart;
148 }
149 Step::CancelJobs => {
150 tracing::info!("restart now requested, cancelling running jobs");
151 self.restart.mark_cancelled();
152 jobs_cancel.cancel();
153 continue;
154 }
155 Step::WaitForJobs => {
156 not_claiming(
157 &mut blocked,
158 "a restart is pending, waiting for the running jobs".to_owned(),
159 );
160 tokio::select! {
161 _ = shutdown.cancelled() => break RunEnd::Stopped,
162 Some(joined) = jobs.join_next() => log_joined(joined),
163 () = self.restart.changed() => {}
164 }
165 continue;
166 }
167 }
168 if let Some((exe_path, _)) = &exe
169 && let Some(sha) = updates.pending().map(str::to_owned)
170 {
171 if !jobs.is_empty() {
172 not_claiming(
173 &mut blocked,
174 "a new binary is pending, waiting for the running jobs".to_owned(),
175 );
176 tokio::select! {
177 _ = shutdown.cancelled() => break RunEnd::Stopped,
178 Some(joined) = jobs.join_next() => log_joined(joined),
179 }
180 continue;
181 }
182 match update::install(&self.client, &self.config.runner_secret, exe_path, &sha)
183 .await
184 {
185 Ok(Installed::Replaced) => {
186 tracing::info!(sha = %sha, "binary updated, restarting");
187 break RunEnd::Updated;
188 }
189 Ok(Installed::Listed) => {
190 tracing::warn!(sha = %sha, "forge binary is on the bad list, not updating");
191 updates.give_up(&sha);
192 }
193 Err(e) => {
194 tracing::warn!(sha = %sha, error = %e, "update failed, keeping this binary");
195 updates.give_up(&sha);
196 }
197 }
198 continue;
199 }
200
201 if self.limiter.free_slots() == 0 {
202 let limit = self.limiter.current();
203 not_claiming(&mut blocked, format!("{limit} of {limit} jobs running"));
204 } else {
205 blocked = None;
206 }
207 let permit = tokio::select! {
208 _ = shutdown.cancelled() => break RunEnd::Stopped,
209 () = self.restart.changed() => continue,
210 permit = self.limiter.acquire() => match permit {
211 Ok(permit) => permit,
212 Err(_) => break RunEnd::Stopped,
213 },
214 };
215 let claimed = tokio::select! {
216 _ = shutdown.cancelled() => {
217 drop(permit);
218 break RunEnd::Stopped;
219 }
220 r = self.client.claim_with(
221 &self.config.runner_secret,
222 &self.config.labels,
223 Some(self.limiter.current()),
224 ) => r,
225 };
226 match claimed {
227 Ok(reply) => {
228 self.limiter.apply_logged(reply.concurrency);
229 self.restart.observe(reply.restart);
230 if updates.observe(reply.binary_sha256.as_deref())
231 && let Some(sha) = updates.pending()
232 {
233 tracing::info!(sha = %sha, "forge advertises a new binary, updating when idle");
234 }
235 match reply.job {
236 Some(job) => {
237 tracing::info!(
238 job_id = %job.job_id,
239 job_name = %job.job_name,
240 repo = %job.repo,
241 "claimed job"
242 );
243 let runner = self.clone();
244 let cancel = jobs_cancel.child_token();
245 jobs.spawn(async move {
246 let _permit = permit;
247 runner.process(job, cancel).await;
248 });
249 }
250 None => drop(permit),
251 }
252 }
253 Err(e) => {
254 drop(permit);
255 tracing::warn!(error = %e, "claim failed, backing off");
256 tokio::select! {
257 _ = shutdown.cancelled() => break RunEnd::Stopped,
258 _ = tokio::time::sleep(self.options.claim_backoff) => {}
259 }
260 }
261 }
262 while let Some(joined) = jobs.try_join_next() {
263 log_joined(joined);
264 }
265 };
266 while let Some(joined) = jobs.join_next().await {
267 log_joined(joined);
268 }
269 tracing::info!("runner stopped");
270 ship_stop.cancel();
271 let _ = tokio::time::timeout(LOG_FLUSH, shipper).await;
272 let _ = tokio::time::timeout(LOG_FLUSH, metrics_shipper).await;
273 end
274 }
275
276 pub async fn process(&self, job: JobAssignment, shutdown: CancellationToken) -> Outcome {
277 let mut secret_values: Vec<String> = job.secrets.values().cloned().collect();
278 secret_values.push(job.job_token.clone());
279 let masker = Masker::new(secret_values);
280
281 let (tx, rx) = mpsc::channel::<Vec<u8>>(LOG_CHANNEL);
282 let pump = {
283 let client = self.client.clone();
284 let job_id = job.job_id.clone();
285 let token = job.job_token.clone();
286 let cfg = self.options.pump;
287 tokio::spawn(async move {
288 logs::pump(&client, &job_id, &token, MaskStream::new(masker), rx, cfg).await
289 })
290 };
291
292 send_line(
293 &tx,
294 format!(
295 "forge-runner {}: job {} on runner {}, image {}, commit {}",
296 forge_ci::build::display(),
297 job.job_name,
298 self.config.name,
299 job.image,
300 job.commit
301 ),
302 )
303 .await;
304
305 let timeout = self
306 .options
307 .timeout_override
308 .unwrap_or_else(|| Duration::from_secs(60 * u64::from(job.timeout_minutes)));
309 let job_cancel = shutdown.child_token();
310 let timed_out = Arc::new(AtomicBool::new(false));
311 let heartbeat = self.spawn_heartbeat(&job, job_cancel.clone());
312 let timer = {
313 let cancel = job_cancel.clone();
314 let flag = timed_out.clone();
315 tokio::spawn(async move {
316 tokio::time::sleep(timeout).await;
317 flag.store(true, Ordering::SeqCst);
318 cancel.cancel();
319 })
320 };
321
322 let mut workspace_dir = None;
323 let oom = OomSink::default();
324 let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await;
325 let mut result = match prepared {
326 Ok(dir) => {
327 if let Some(cache) = &self.cache {
328 for line in cache.restore(&job, &dir).await {
329 send_line(&tx, line).await;
330 }
331 }
332 let result = self
333 .executor
334 .run(ExecRequest {
335 job: &job,
336 workspace: &dir,
337 logs: tx.clone(),
338 cancel: job_cancel.clone(),
339 oom: oom.clone(),
340 })
341 .await;
342 workspace_dir = Some(dir);
343 result
344 }
345 Err(e) => ExecResult {
346 outcome: Outcome::Error,
347 exit_code: None,
348 message: Some(format!("workspace: {e}")),
349 },
350 };
351
352 let upload_error = match workspace_dir.as_deref() {
353 Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => {
354 self.upload_artifacts(&job, dir).await.err()
355 }
356 _ => None,
357 };
358 if let Some(message) = upload_error {
359 result = ExecResult {
360 outcome: Outcome::Error,
361 exit_code: result.exit_code,
362 message: Some(message),
363 };
364 }
365
366 heartbeat.abort();
367 timer.abort();
368 if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled {
369 result = ExecResult {
370 outcome: Outcome::Failure,
371 exit_code: None,
372 message: Some(format!("timed out after {} minutes", job.timeout_minutes)),
373 };
374 }
375
376 if self.restart.jobs_cancelled()
377 && shutdown.is_cancelled()
378 && result.outcome == Outcome::Cancelled
379 {
380 result.message = Some("cancelled because an admin restarted the runner".to_owned());
381 }
382
383 if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) {
384 for line in cache.save(&job, result.outcome, dir).await {
385 send_line(&tx, line).await;
386 }
387 }
388
389 if let Some(message) = &result.message {
390 send_line(&tx, format!("runner: {message}")).await;
391 }
392 let oom_kills = oom.kills();
393 if let Some(kills) = oom_kills {
394 send_line(
395 &tx,
396 format!(
397 "runner: out of memory, the job ran out of the runner's memory and the \
398 out of memory killer stopped it ({kills} process(es))"
399 ),
400 )
401 .await;
402 }
403 drop(tx);
404 match pump.await {
405 Ok(Ok(bytes)) => tracing::debug!(job_id = %job.job_id, bytes, "logs shipped"),
406 Ok(Err(e)) => tracing::warn!(job_id = %job.job_id, error = %e, "log shipping failed"),
407 Err(e) => tracing::error!(job_id = %job.job_id, error = %e, "log task panicked"),
408 }
409
410 self.finish(&job, &result, oom_kills).await;
411 if let Some(dir) = workspace_dir
412 && let Err(e) = workspace::cleanup(&dir).await
413 {
414 tracing::warn!(job_id = %job.job_id, error = %e, "workspace cleanup failed");
415 }
416 tracing::info!(job_id = %job.job_id, outcome = ?result.outcome, "job finished");
417 result.outcome
418 }
419
420 fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> {
421 let client = self.client.clone();
422 let limiter = self.limiter.clone();
423 let restart = self.restart.clone();
424 let job_id = job.job_id.clone();
425 let token = job.job_token.clone();
426 let every = self.options.heartbeat_every;
427 tokio::spawn(async move {
428 let mut ticker = tokio::time::interval_at(Instant::now() + every, every);
429 loop {
430 ticker.tick().await;
431 match client
432 .heartbeat_with(&job_id, &token, Some(limiter.current()))
433 .await
434 {
435 Ok(beat) if beat.cancel => {
436 limiter.apply_logged(beat.concurrency);
437 restart.observe(beat.restart);
438 tracing::info!(job_id = %job_id, "forge requested cancel");
439 cancel.cancel();
440 return;
441 }
442 Ok(beat) => {
443 limiter.apply_logged(beat.concurrency);
444 restart.observe(beat.restart);
445 }
446 Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"),
447 }
448 }
449 })
450 }
451
452 async fn upload_artifacts(
453 &self,
454 job: &JobAssignment,
455 dir: &std::path::Path,
456 ) -> Result<(), String> {
457 let found = artifacts::collect(dir, &job.artifacts, MAX_ARTIFACT_BYTES)
458 .map_err(|e| format!("artifacts: {e}"))?;
459 for artifact in &found {
460 patiently(&job.job_id, "artifact upload", || {
461 self.client
462 .upload_artifact(&job.job_id, &job.job_token, &artifact.name, &artifact.path)
463 })
464 .await
465 .map_err(|e| format!("artifact {}: {e}", artifact.name))?;
466 }
467 tracing::info!(job_id = %job.job_id, count = found.len(), "artifacts uploaded");
468 Ok(())
469 }
470
471 async fn finish(&self, job: &JobAssignment, result: &ExecResult, oom_kills: Option<u32>) {
472 let req = FinishRequest {
473 outcome: result.outcome,
474 exit_code: result.exit_code,
475 message: result.message.clone(),
476 oom_killed: oom_kills.map(|_| true),
477 oom_kills,
478 };
479 let reported = patiently(&job.job_id, "finish", || {
480 self.client.finish(&job.job_id, &job.job_token, &req)
481 })
482 .await;
483 if reported.is_ok() {
484 return;
485 }
486 tracing::error!(
487 job_id = %job.job_id,
488 "could not report the job result; the forge will reap it after heartbeats stop"
489 );
490 }
491}
492
493async fn patiently<F, Fut>(job_id: &str, what: &str, mut op: F) -> Result<(), ClientError>
494where
495 F: FnMut() -> Fut,
496 Fut: std::future::Future<Output = Result<(), ClientError>>,
497{
498 let started = Instant::now();
499 let mut attempt = 0u32;
500 loop {
501 attempt += 1;
502 let Err(e) = op().await else {
503 return Ok(());
504 };
505 tracing::warn!(job_id, attempt, error = %e, "{what} failed");
506 let away = match &e {
507 ClientError::Http(_) => true,
508 ClientError::Status { status, .. } => status.is_server_error(),
509 _ => false,
510 };
511 if !away || started.elapsed() >= FORGE_PATIENCE {
512 return Err(e);
513 }
514 tokio::time::sleep(Duration::from_secs((2 * u64::from(attempt)).min(15))).await;
515 }
516}
517
518fn not_claiming(last: &mut Option<String>, reason: String) {
519 if last.as_deref() != Some(reason.as_str()) {
520 tracing::info!("not claiming: {reason}");
521 *last = Some(reason);
522 }
523}
524
525fn log_joined(joined: Result<(), tokio::task::JoinError>) {
526 if let Err(e) = joined {
527 tracing::error!(error = %e, "job task panicked");
528 }
529}
530
531async fn send_line(tx: &mpsc::Sender<Vec<u8>>, line: String) {
532 let mut bytes = line.into_bytes();
533 bytes.push(b'\n');
534 let _ = tx.send(bytes).await;
535}