forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·10.5 MiB·b00f3f4·Tahinli·1 month ago·147 commits
| 1 | //! The runner loop: claim a job, run it, ship its logs and artifacts, and report the result. |
| 2 | |
| 3 | use std::sync::Arc; |
| 4 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use forge_ci::mask::{MaskStream, Masker}; |
| 8 | use forge_ci::proto::{FinishRequest, JobAssignment, Outcome}; |
| 9 | use tokio::sync::mpsc; |
| 10 | use tokio::task::{JoinHandle, JoinSet}; |
| 11 | use tokio::time::Instant; |
| 12 | use tokio_util::sync::CancellationToken; |
| 13 | |
| 14 | use crate::artifacts; |
| 15 | use crate::cache::CacheStore; |
| 16 | use crate::client::MemoryClaim; |
| 17 | use crate::client::{ClientError, ForgeClient}; |
| 18 | use crate::config::RunnerConfig; |
| 19 | use crate::executor::{ExecRequest, ExecResult, Executor}; |
| 20 | use crate::limiter::Limiter; |
| 21 | use crate::logs::{self, PumpConfig}; |
| 22 | use crate::memory::MemoryGate; |
| 23 | use crate::oom::OomSink; |
| 24 | use crate::pressure::Pressure; |
| 25 | use crate::restart::{self, RestartState, Step}; |
| 26 | use crate::update::{self, Installed, UpdateState}; |
| 27 | use crate::workspace; |
| 28 | |
| 29 | /// Log lines queued between the executor and the log shipper. |
| 30 | const LOG_CHANNEL: usize = 256; |
| 31 | /// How many times the runner tries to report a finished job. |
| 32 | const FINISH_ATTEMPTS: u32 = 5; |
| 33 | /// Largest single artifact the runner will upload. The forge enforces its own total cap. |
| 34 | const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024; |
| 35 | |
| 36 | /// Timing knobs. Production uses the defaults. Tests shorten them. |
| 37 | #[derive(Clone, Copy, Debug)] |
| 38 | pub struct RunOptions { |
| 39 | pub heartbeat_every: Duration, |
| 40 | pub claim_backoff: Duration, |
| 41 | pub pump: PumpConfig, |
| 42 | /// When set, replaces `timeout_minutes` from the job. |
| 43 | pub timeout_override: Option<Duration>, |
| 44 | } |
| 45 | |
| 46 | impl Default for RunOptions { |
| 47 | fn default() -> Self { |
| 48 | Self { |
| 49 | heartbeat_every: Duration::from_secs(10), |
| 50 | claim_backoff: Duration::from_secs(5), |
| 51 | pump: PumpConfig::default(), |
| 52 | timeout_override: None, |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /// How [`Runner::run`] ended. |
| 58 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 59 | pub enum RunEnd { |
| 60 | /// Shutdown was requested. |
| 61 | Stopped, |
| 62 | /// The binary was replaced. The caller exits with [`update::RESTART_EXIT_CODE`]. |
| 63 | Updated, |
| 64 | /// An admin asked for a restart and the jobs are done. The caller exits with |
| 65 | /// [`update::RESTART_EXIT_CODE`], like for an update. |
| 66 | Restart, |
| 67 | } |
| 68 | |
| 69 | /// A runner bound to one forge and one executor. |
| 70 | #[derive(Clone)] |
| 71 | pub struct Runner { |
| 72 | client: ForgeClient, |
| 73 | config: Arc<RunnerConfig>, |
| 74 | executor: Arc<dyn Executor>, |
| 75 | options: RunOptions, |
| 76 | /// The build cache, when it is on. See [`CacheStore`]. |
| 77 | cache: Option<Arc<CacheStore>>, |
| 78 | /// The live job limit. Starts at `runner.toml` and follows the forge's override. |
| 79 | limiter: Arc<Limiter>, |
| 80 | /// The memory budget and the running jobs' reservations, see [`crate::memory`]. |
| 81 | memory: Arc<MemoryGate>, |
| 82 | /// A restart an admin asked for, see [`restart`]. |
| 83 | restart: Arc<RestartState>, |
| 84 | /// The memory box and its controller, when the host allows it, see [`crate::pressure`]. |
| 85 | pressure: Option<Arc<Pressure>>, |
| 86 | } |
| 87 | |
| 88 | impl Runner { |
| 89 | pub fn new( |
| 90 | config: RunnerConfig, |
| 91 | executor: Arc<dyn Executor>, |
| 92 | options: RunOptions, |
| 93 | ) -> Result<Self, ClientError> { |
| 94 | let client = ForgeClient::new(&config.url)?; |
| 95 | let limiter = Limiter::new(config.concurrency); |
| 96 | let memory = MemoryGate::for_host(&config.limits); |
| 97 | Ok(Self { |
| 98 | client, |
| 99 | config: Arc::new(config), |
| 100 | executor, |
| 101 | options, |
| 102 | cache: None, |
| 103 | limiter, |
| 104 | memory, |
| 105 | restart: Arc::new(RestartState::default()), |
| 106 | pressure: None, |
| 107 | }) |
| 108 | } |
| 109 | |
| 110 | /// Turns on reactive memory control: jobs are paused under pressure, and no job is claimed |
| 111 | /// while one is parked. |
| 112 | pub fn with_pressure(mut self, pressure: Option<Arc<Pressure>>) -> Self { |
| 113 | self.pressure = pressure; |
| 114 | self |
| 115 | } |
| 116 | |
| 117 | /// Turns on the build cache for every job this runner runs. |
| 118 | pub fn with_cache(mut self, cache: CacheStore) -> Self { |
| 119 | self.cache = Some(Arc::new(cache)); |
| 120 | self |
| 121 | } |
| 122 | |
| 123 | pub fn client(&self) -> &ForgeClient { |
| 124 | &self.client |
| 125 | } |
| 126 | |
| 127 | /// Claims and runs jobs, up to `concurrency` at a time, until `shutdown` is cancelled. Jobs |
| 128 | /// still running at shutdown are cancelled and reported as cancelled. |
| 129 | /// |
| 130 | /// When the forge advertises a different binary and `auto_update` is on, no new jobs are |
| 131 | /// claimed. Once the running jobs finish, the binary is replaced and the loop returns |
| 132 | /// [`RunEnd::Updated`]. |
| 133 | pub async fn run(&self, shutdown: CancellationToken) -> RunEnd { |
| 134 | let mut jobs: JoinSet<()> = JoinSet::new(); |
| 135 | // Hashed once at startup. Without it, or with auto_update off, updates stay disabled. |
| 136 | let exe = if self.config.auto_update { |
| 137 | match update::locate_self() { |
| 138 | Ok(found) => Some(found), |
| 139 | Err(e) => { |
| 140 | tracing::warn!(error = %e, "auto update disabled, cannot read own binary"); |
| 141 | None |
| 142 | } |
| 143 | } |
| 144 | } else { |
| 145 | None |
| 146 | }; |
| 147 | let mut updates = UpdateState::new( |
| 148 | self.config.auto_update, |
| 149 | exe.as_ref().map(|(_, sha)| sha.clone()), |
| 150 | ); |
| 151 | tracing::info!( |
| 152 | name = %self.config.name, |
| 153 | concurrency = self.limiter.current(), |
| 154 | memory_budget = %forge_ci::size::format_size(self.memory.budget()), |
| 155 | reserve_memory = %forge_ci::size::format_size(self.memory.default_reserve()), |
| 156 | auto_update = updates.enabled(), |
| 157 | "runner started" |
| 158 | ); |
| 159 | // Parent of every job's token, so a `now` restart can cancel them all at once. |
| 160 | let jobs_cancel = shutdown.child_token(); |
| 161 | let end = loop { |
| 162 | match restart::decide( |
| 163 | self.restart.pending(), |
| 164 | jobs.len(), |
| 165 | self.restart.jobs_cancelled(), |
| 166 | ) { |
| 167 | Step::Proceed => {} |
| 168 | Step::Restart => { |
| 169 | tracing::info!("restart requested by the forge, restarting"); |
| 170 | break RunEnd::Restart; |
| 171 | } |
| 172 | Step::CancelJobs => { |
| 173 | tracing::info!("restart now requested, cancelling running jobs"); |
| 174 | self.restart.mark_cancelled(); |
| 175 | jobs_cancel.cancel(); |
| 176 | continue; |
| 177 | } |
| 178 | Step::WaitForJobs => { |
| 179 | tokio::select! { |
| 180 | _ = shutdown.cancelled() => break RunEnd::Stopped, |
| 181 | Some(joined) = jobs.join_next() => { |
| 182 | if let Err(e) = joined { |
| 183 | tracing::error!(error = %e, "job task panicked"); |
| 184 | } |
| 185 | } |
| 186 | () = self.restart.changed() => {} |
| 187 | } |
| 188 | continue; |
| 189 | } |
| 190 | } |
| 191 | if let Some((exe_path, _)) = &exe |
| 192 | && let Some(sha) = updates.pending().map(str::to_owned) |
| 193 | { |
| 194 | if !jobs.is_empty() { |
| 195 | // Claiming is paused until the running jobs finish. |
| 196 | tokio::select! { |
| 197 | _ = shutdown.cancelled() => break RunEnd::Stopped, |
| 198 | Some(joined) = jobs.join_next() => { |
| 199 | if let Err(e) = joined { |
| 200 | tracing::error!(error = %e, "job task panicked"); |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | continue; |
| 205 | } |
| 206 | match update::install(&self.client, &self.config.runner_secret, exe_path, &sha) |
| 207 | .await |
| 208 | { |
| 209 | Ok(Installed::Replaced) => { |
| 210 | tracing::info!(sha = %sha, "binary updated, restarting"); |
| 211 | break RunEnd::Updated; |
| 212 | } |
| 213 | Ok(Installed::Listed) => { |
| 214 | tracing::warn!(sha = %sha, "forge binary is on the bad list, not updating"); |
| 215 | updates.give_up(&sha); |
| 216 | } |
| 217 | Err(e) => { |
| 218 | tracing::warn!(sha = %sha, error = %e, "update failed, keeping this binary"); |
| 219 | updates.give_up(&sha); |
| 220 | } |
| 221 | } |
| 222 | continue; |
| 223 | } |
| 224 | |
| 225 | if let Some(pressure) = &self.pressure { |
| 226 | // A parked job or a box under pressure means no new job. The controller wakes |
| 227 | // this when that changes. |
| 228 | tokio::select! { |
| 229 | _ = shutdown.cancelled() => break RunEnd::Stopped, |
| 230 | () = self.restart.changed() => continue, |
| 231 | () = pressure.wait_open() => {} |
| 232 | } |
| 233 | } |
| 234 | let permit = tokio::select! { |
| 235 | _ = shutdown.cancelled() => break RunEnd::Stopped, |
| 236 | () = self.restart.changed() => continue, |
| 237 | permit = self.limiter.acquire() => match permit { |
| 238 | Ok(permit) => permit, |
| 239 | Err(_) => break RunEnd::Stopped, |
| 240 | }, |
| 241 | }; |
| 242 | let claimed = tokio::select! { |
| 243 | _ = shutdown.cancelled() => { |
| 244 | drop(permit); |
| 245 | break RunEnd::Stopped; |
| 246 | } |
| 247 | r = self.client.claim_with( |
| 248 | &self.config.runner_secret, |
| 249 | &self.config.labels, |
| 250 | Some(self.limiter.current()), |
| 251 | Some(MemoryClaim { |
| 252 | // Real room in the box when memory control is on, else what is promised. |
| 253 | free: self |
| 254 | .pressure |
| 255 | .as_ref() |
| 256 | .and_then(|p| p.headroom()) |
| 257 | .unwrap_or_else(|| self.memory.free()), |
| 258 | budget: self.memory.budget(), |
| 259 | reserve: self.memory.default_reserve(), |
| 260 | }), |
| 261 | ) => r, |
| 262 | }; |
| 263 | match claimed { |
| 264 | Ok(reply) => { |
| 265 | // No header means no override: back to the runner.toml value. |
| 266 | self.limiter.apply_logged(reply.concurrency); |
| 267 | self.memory.apply_logged( |
| 268 | reply.memory_budget.as_deref(), |
| 269 | reply.reserve_memory.as_deref(), |
| 270 | ); |
| 271 | if let Some(pressure) = &self.pressure |
| 272 | && pressure.budget() != self.memory.budget() |
| 273 | { |
| 274 | let pressure = pressure.clone(); |
| 275 | let budget = self.memory.budget(); |
| 276 | let _ = tokio::task::spawn_blocking(move || pressure.resize(budget)).await; |
| 277 | } |
| 278 | self.restart.observe(reply.restart); |
| 279 | if updates.observe(reply.binary_sha256.as_deref()) |
| 280 | && let Some(sha) = updates.pending() |
| 281 | { |
| 282 | tracing::info!(sha = %sha, "forge advertises a new binary, updating when idle"); |
| 283 | } |
| 284 | match reply.job { |
| 285 | Some(job) => { |
| 286 | tracing::info!( |
| 287 | job_id = %job.job_id, |
| 288 | job_name = %job.job_name, |
| 289 | repo = %job.repo, |
| 290 | "claimed job" |
| 291 | ); |
| 292 | let runner = self.clone(); |
| 293 | let cancel = jobs_cancel.child_token(); |
| 294 | // Reserved before the next claim, so that claim sees less free memory. |
| 295 | let reservation = self.memory.reserve(job.memory_bytes); |
| 296 | jobs.spawn(async move { |
| 297 | let _permit = permit; |
| 298 | let _reservation = reservation; |
| 299 | runner.process(job, cancel).await; |
| 300 | }); |
| 301 | } |
| 302 | None => drop(permit), |
| 303 | } |
| 304 | } |
| 305 | Err(e) => { |
| 306 | drop(permit); |
| 307 | tracing::warn!(error = %e, "claim failed, backing off"); |
| 308 | tokio::select! { |
| 309 | _ = shutdown.cancelled() => break RunEnd::Stopped, |
| 310 | _ = tokio::time::sleep(self.options.claim_backoff) => {} |
| 311 | } |
| 312 | } |
| 313 | } |
| 314 | while let Some(joined) = jobs.try_join_next() { |
| 315 | if let Err(e) = joined { |
| 316 | tracing::error!(error = %e, "job task panicked"); |
| 317 | } |
| 318 | } |
| 319 | }; |
| 320 | while let Some(joined) = jobs.join_next().await { |
| 321 | if let Err(e) = joined { |
| 322 | tracing::error!(error = %e, "job task panicked"); |
| 323 | } |
| 324 | } |
| 325 | tracing::info!("runner stopped"); |
| 326 | end |
| 327 | } |
| 328 | |
| 329 | /// Runs one claimed job end to end and reports its result. Returns the final outcome. |
| 330 | pub async fn process(&self, job: JobAssignment, shutdown: CancellationToken) -> Outcome { |
| 331 | // Mask the job's secret values and its own token, both raw and base64 (done by Masker). |
| 332 | let mut secret_values: Vec<String> = job.secrets.values().cloned().collect(); |
| 333 | secret_values.push(job.job_token.clone()); |
| 334 | let masker = Masker::new(secret_values); |
| 335 | |
| 336 | let (tx, rx) = mpsc::channel::<Vec<u8>>(LOG_CHANNEL); |
| 337 | let pump = { |
| 338 | let client = self.client.clone(); |
| 339 | let job_id = job.job_id.clone(); |
| 340 | let token = job.job_token.clone(); |
| 341 | let cfg = self.options.pump; |
| 342 | tokio::spawn(async move { |
| 343 | logs::pump(&client, &job_id, &token, MaskStream::new(masker), rx, cfg).await |
| 344 | }) |
| 345 | }; |
| 346 | |
| 347 | send_line( |
| 348 | &tx, |
| 349 | format!( |
| 350 | "forge-runner {}: job {} on runner {}, image {}, commit {}", |
| 351 | forge_ci::build::display(), |
| 352 | job.job_name, |
| 353 | self.config.name, |
| 354 | job.image, |
| 355 | job.commit |
| 356 | ), |
| 357 | ) |
| 358 | .await; |
| 359 | |
| 360 | let timeout = self |
| 361 | .options |
| 362 | .timeout_override |
| 363 | .unwrap_or_else(|| Duration::from_secs(60 * u64::from(job.timeout_minutes))); |
| 364 | let job_cancel = shutdown.child_token(); |
| 365 | let timed_out = Arc::new(AtomicBool::new(false)); |
| 366 | let heartbeat = self.spawn_heartbeat(&job, job_cancel.clone()); |
| 367 | let registration = self |
| 368 | .pressure |
| 369 | .as_ref() |
| 370 | .map(|p| p.register(&job.job_id, &job.job_name, tx.clone())); |
| 371 | let timer = { |
| 372 | let cancel = job_cancel.clone(); |
| 373 | let flag = timed_out.clone(); |
| 374 | let pause = registration.as_ref().map(|r| r.pause_clock()); |
| 375 | tokio::spawn(async move { |
| 376 | // Time spent frozen does not count, so the deadline moves out by the pauses. |
| 377 | let started = Instant::now(); |
| 378 | loop { |
| 379 | let paused = pause.as_ref().map(|p| p.paused()).unwrap_or_default(); |
| 380 | let due = timeout + paused; |
| 381 | let elapsed = started.elapsed(); |
| 382 | if elapsed >= due { |
| 383 | break; |
| 384 | } |
| 385 | tokio::time::sleep(due - elapsed).await; |
| 386 | } |
| 387 | flag.store(true, Ordering::SeqCst); |
| 388 | cancel.cancel(); |
| 389 | }) |
| 390 | }; |
| 391 | |
| 392 | let mut workspace_dir = None; |
| 393 | let oom = OomSink::default(); |
| 394 | let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await; |
| 395 | let mut result = match prepared { |
| 396 | Ok(dir) => { |
| 397 | if let Some(cache) = &self.cache { |
| 398 | for line in cache.restore(&job, &dir).await { |
| 399 | send_line(&tx, line).await; |
| 400 | } |
| 401 | } |
| 402 | let result = self |
| 403 | .executor |
| 404 | .run(ExecRequest { |
| 405 | job: &job, |
| 406 | workspace: &dir, |
| 407 | logs: tx.clone(), |
| 408 | cancel: job_cancel.clone(), |
| 409 | oom: oom.clone(), |
| 410 | }) |
| 411 | .await; |
| 412 | workspace_dir = Some(dir); |
| 413 | result |
| 414 | } |
| 415 | Err(e) => ExecResult { |
| 416 | outcome: Outcome::Error, |
| 417 | exit_code: None, |
| 418 | message: Some(format!("workspace: {e}")), |
| 419 | }, |
| 420 | }; |
| 421 | |
| 422 | // The memory controller killed this job to run it again later: give it back to the queue |
| 423 | // without a result. |
| 424 | if registration.as_ref().is_some_and(|r| r.requeued()) { |
| 425 | heartbeat.abort(); |
| 426 | timer.abort(); |
| 427 | drop(registration); |
| 428 | drop(tx); |
| 429 | let _ = pump.await; |
| 430 | let reason = "killed under memory pressure on the runner"; |
| 431 | if let Err(e) = self |
| 432 | .client |
| 433 | .requeue(&job.job_id, &job.job_token, reason) |
| 434 | .await |
| 435 | { |
| 436 | tracing::warn!(job_id = %job.job_id, error = %e, "requeue failed, failing the job"); |
| 437 | let failed = ExecResult { |
| 438 | outcome: Outcome::Error, |
| 439 | exit_code: None, |
| 440 | message: Some(format!( |
| 441 | "out of memory, and the forge could not requeue it: {e}" |
| 442 | )), |
| 443 | }; |
| 444 | self.finish(&job, &failed, None).await; |
| 445 | } |
| 446 | if let Some(dir) = workspace_dir |
| 447 | && let Err(e) = workspace::cleanup(&dir).await |
| 448 | { |
| 449 | tracing::warn!(job_id = %job.job_id, error = %e, "workspace cleanup failed"); |
| 450 | } |
| 451 | tracing::info!(job_id = %job.job_id, "job requeued after memory pressure"); |
| 452 | return Outcome::Cancelled; |
| 453 | } |
| 454 | |
| 455 | // Artifacts only come from a successful run. |
| 456 | let upload_error = match workspace_dir.as_deref() { |
| 457 | Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => { |
| 458 | self.upload_artifacts(&job, dir).await.err() |
| 459 | } |
| 460 | _ => None, |
| 461 | }; |
| 462 | if let Some(message) = upload_error { |
| 463 | result = ExecResult { |
| 464 | outcome: Outcome::Error, |
| 465 | exit_code: result.exit_code, |
| 466 | message: Some(message), |
| 467 | }; |
| 468 | } |
| 469 | |
| 470 | heartbeat.abort(); |
| 471 | timer.abort(); |
| 472 | // The log sender it holds must go before the log shipper can finish. |
| 473 | drop(registration); |
| 474 | if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled { |
| 475 | result = ExecResult { |
| 476 | outcome: Outcome::Failure, |
| 477 | exit_code: None, |
| 478 | message: Some(format!("timed out after {} minutes", job.timeout_minutes)), |
| 479 | }; |
| 480 | } |
| 481 | |
| 482 | if self.restart.jobs_cancelled() && result.outcome == Outcome::Cancelled { |
| 483 | result.message = Some("cancelled because an admin restarted the runner".to_owned()); |
| 484 | } |
| 485 | |
| 486 | // The save decides on the final outcome. It also clears the job's scratch dirs. |
| 487 | if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { |
| 488 | for line in cache.save(&job, result.outcome, dir).await { |
| 489 | send_line(&tx, line).await; |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | if let Some(message) = &result.message { |
| 494 | send_line(&tx, format!("runner: {message}")).await; |
| 495 | } |
| 496 | let oom_kills = oom.kills(); |
| 497 | if let Some(kills) = oom_kills { |
| 498 | send_line( |
| 499 | &tx, |
| 500 | format!( |
| 501 | "runner: the out of memory killer killed {kills} process(es) in this job; \ |
| 502 | the job's memory is limited to its `memory` plus a little slack, see docs/ci.md" |
| 503 | ), |
| 504 | ) |
| 505 | .await; |
| 506 | } |
| 507 | drop(tx); |
| 508 | match pump.await { |
| 509 | Ok(Ok(bytes)) => tracing::debug!(job_id = %job.job_id, bytes, "logs shipped"), |
| 510 | Ok(Err(e)) => tracing::warn!(job_id = %job.job_id, error = %e, "log shipping failed"), |
| 511 | Err(e) => tracing::error!(job_id = %job.job_id, error = %e, "log task panicked"), |
| 512 | } |
| 513 | |
| 514 | self.finish(&job, &result, oom_kills).await; |
| 515 | if let Some(dir) = workspace_dir |
| 516 | && let Err(e) = workspace::cleanup(&dir).await |
| 517 | { |
| 518 | tracing::warn!(job_id = %job.job_id, error = %e, "workspace cleanup failed"); |
| 519 | } |
| 520 | tracing::info!(job_id = %job.job_id, outcome = ?result.outcome, "job finished"); |
| 521 | result.outcome |
| 522 | } |
| 523 | |
| 524 | fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> { |
| 525 | let client = self.client.clone(); |
| 526 | let limiter = self.limiter.clone(); |
| 527 | let restart = self.restart.clone(); |
| 528 | let job_id = job.job_id.clone(); |
| 529 | let token = job.job_token.clone(); |
| 530 | let every = self.options.heartbeat_every; |
| 531 | tokio::spawn(async move { |
| 532 | let mut ticker = tokio::time::interval_at(Instant::now() + every, every); |
| 533 | loop { |
| 534 | ticker.tick().await; |
| 535 | match client |
| 536 | .heartbeat_with(&job_id, &token, Some(limiter.current())) |
| 537 | .await |
| 538 | { |
| 539 | Ok(beat) if beat.cancel => { |
| 540 | limiter.apply_logged(beat.concurrency); |
| 541 | restart.observe(beat.restart); |
| 542 | tracing::info!(job_id = %job_id, "forge requested cancel"); |
| 543 | cancel.cancel(); |
| 544 | return; |
| 545 | } |
| 546 | // A runner at its limit does not claim, so the heartbeat carries changes too. |
| 547 | Ok(beat) => { |
| 548 | limiter.apply_logged(beat.concurrency); |
| 549 | restart.observe(beat.restart); |
| 550 | } |
| 551 | Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"), |
| 552 | } |
| 553 | } |
| 554 | }) |
| 555 | } |
| 556 | |
| 557 | /// Collects the job's artifacts and uploads them. The error is a message for the job record. |
| 558 | async fn upload_artifacts( |
| 559 | &self, |
| 560 | job: &JobAssignment, |
| 561 | dir: &std::path::Path, |
| 562 | ) -> Result<(), String> { |
| 563 | let found = artifacts::collect(dir, &job.artifacts, MAX_ARTIFACT_BYTES) |
| 564 | .map_err(|e| format!("artifacts: {e}"))?; |
| 565 | for artifact in &found { |
| 566 | self.client |
| 567 | .upload_artifact(&job.job_id, &job.job_token, &artifact.name, &artifact.path) |
| 568 | .await |
| 569 | .map_err(|e| format!("artifact {}: {e}", artifact.name))?; |
| 570 | } |
| 571 | tracing::info!(job_id = %job.job_id, count = found.len(), "artifacts uploaded"); |
| 572 | Ok(()) |
| 573 | } |
| 574 | |
| 575 | async fn finish(&self, job: &JobAssignment, result: &ExecResult, oom_kills: Option<u32>) { |
| 576 | let req = FinishRequest { |
| 577 | outcome: result.outcome, |
| 578 | exit_code: result.exit_code, |
| 579 | message: result.message.clone(), |
| 580 | oom_killed: oom_kills.map(|_| true), |
| 581 | oom_kills, |
| 582 | }; |
| 583 | for attempt in 1..=FINISH_ATTEMPTS { |
| 584 | match self.client.finish(&job.job_id, &job.job_token, &req).await { |
| 585 | Ok(()) => return, |
| 586 | Err(e) => { |
| 587 | tracing::warn!(job_id = %job.job_id, attempt, error = %e, "finish failed"); |
| 588 | tokio::time::sleep(Duration::from_secs(2 * u64::from(attempt))).await; |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | tracing::error!( |
| 593 | job_id = %job.job_id, |
| 594 | "could not report the job result; the forge will reap it after heartbeats stop" |
| 595 | ); |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | async fn send_line(tx: &mpsc::Sender<Vec<u8>>, line: String) { |
| 600 | let mut bytes = line.into_bytes(); |
| 601 | bytes.push(b'\n'); |
| 602 | let _ = tx.send(bytes).await; |
| 603 | } |