The runner reports OOM kills from the job cgroup, shown on the job page and in alerts
Browse files at this commitedff93be095a9cf619f5c64aaca4ddcb564a1fb3Parent: b3beedb- feat
- the runner reports OOM kills from the job cgroup, shown on the job page and in alerts
15 changed files +461 -17
- crates/forge-ci/src/proto.rs +23 -0
- crates/forge-core/migrations/0060_runner_memory.sql +4 -0
- crates/forge-core/src/ci.rs +3 -0
- crates/forge-core/src/store/ci.rs +58 -1
- crates/forge-runner/src/executor.rs +26 -5
- crates/forge-runner/src/lib.rs +1 -0
- crates/forge-runner/src/oom.rs +171 -0
- crates/forge-runner/src/runner.rs +18 -2
- crates/forge-runner/src/sandbox/helper.rs +28 -2
- crates/forge-runner/tests/builtin.rs +1 -0
- crates/forge-web/src/alerts.rs +40 -6
- crates/forge-web/src/ci/api.rs +20 -1
- crates/forge-web/src/ci/api_tests.rs +51 -0
- crates/forge-web/src/pages/ci_job.rs +6 -0
- docs/ci.md +11 -0
crates/forge-ci/src/proto.rsmodified+23 -0
| @@ -238,6 +238,15 @@ pub struct FinishRequest { | |||
| 238 | pub outcome: Outcome, | 238 | pub outcome: Outcome, |
| 239 | pub exit_code: Option<i32>, | 239 | pub exit_code: Option<i32>, |
| 240 | pub message: Option<String>, | 240 | pub message: Option<String>, |
| 241 | + /// True when the OOM killer killed a process in the job's cgroup, read from its | ||
| 242 | + /// `memory.events`. This is what shows an OOM kill that the job survived: cargo reports a | ||
| 243 | + /// killed rustc in the log and exits 101. Absent from an older runner, from a runner that | ||
| 244 | + /// cannot read the cgroup, and when nothing was killed. | ||
| 245 | + #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 246 | + pub oom_killed: Option<bool>, | ||
| 247 | + /// How many processes the OOM killer took in the job's cgroup (`oom_kill`). | ||
| 248 | + #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 249 | + pub oom_kills: Option<u32>, | ||
| 241 | } | 250 | } |
| 242 | 251 | ||
| 243 | /// Final result of a job, reported by the runner. | 252 | /// Final result of a job, reported by the runner. |
| @@ -301,14 +310,28 @@ mod tests { | |||
| 301 | outcome: Outcome::Failure, | 310 | outcome: Outcome::Failure, |
| 302 | exit_code: Some(2), | 311 | exit_code: Some(2), |
| 303 | message: None, | 312 | message: None, |
| 313 | + oom_killed: None, | ||
| 314 | + oom_kills: None, | ||
| 304 | }; | 315 | }; |
| 305 | let json = serde_json::to_string(&req).unwrap(); | 316 | let json = serde_json::to_string(&req).unwrap(); |
| 317 | + // An old runner's body, and a new runner that saw no OOM kill, look the same. | ||
| 306 | assert_eq!( | 318 | assert_eq!( |
| 307 | json, | 319 | json, |
| 308 | r#"{"outcome":"failure","exit_code":2,"message":null}"# | 320 | r#"{"outcome":"failure","exit_code":2,"message":null}"# |
| 309 | ); | 321 | ); |
| 310 | let back: FinishRequest = serde_json::from_str(&json).unwrap(); | 322 | let back: FinishRequest = serde_json::from_str(&json).unwrap(); |
| 311 | assert_eq!(back, req); | 323 | assert_eq!(back, req); |
| 324 | + let oom = FinishRequest { | ||
| 325 | + oom_killed: Some(true), | ||
| 326 | + oom_kills: Some(2), | ||
| 327 | + ..req | ||
| 328 | + }; | ||
| 329 | + let json = serde_json::to_string(&oom).unwrap(); | ||
| 330 | + assert!( | ||
| 331 | + json.contains(r#""oom_killed":true,"oom_kills":2"#), | ||
| 332 | + "{json}" | ||
| 333 | + ); | ||
| 334 | + assert_eq!(serde_json::from_str::<FinishRequest>(&json).unwrap(), oom); | ||
| 312 | } | 335 | } |
| 313 | 336 | ||
| 314 | #[test] | 337 | #[test] |
crates/forge-core/migrations/0060_runner_memory.sqlmodified+4 -0
| @@ -5,3 +5,7 @@ | |||
| 5 | ALTER TABLE ci_runners ADD COLUMN reported_memory_budget INTEGER NULL; | 5 | ALTER TABLE ci_runners ADD COLUMN reported_memory_budget INTEGER NULL; |
| 6 | ALTER TABLE ci_runners ADD COLUMN reported_memory_free INTEGER NULL; | 6 | ALTER TABLE ci_runners ADD COLUMN reported_memory_free INTEGER NULL; |
| 7 | ALTER TABLE ci_runners ADD COLUMN reported_memory_reserve INTEGER NULL; | 7 | ALTER TABLE ci_runners ADD COLUMN reported_memory_reserve INTEGER NULL; |
| 8 | + | ||
| 9 | +-- Processes the OOM killer took in a job's cgroup, as the runner read them from memory.events when | ||
| 10 | +-- the job ended. NULL when the runner did not say or nothing was killed. | ||
| 11 | +ALTER TABLE ci_jobs ADD COLUMN oom_kills INTEGER NULL; | ||
crates/forge-core/src/ci.rsmodified+3 -0
| @@ -526,6 +526,9 @@ pub struct CiJob { | |||
| 526 | pub heartbeat_at: Option<String>, | 526 | pub heartbeat_at: Option<String>, |
| 527 | pub cancel_requested: bool, | 527 | pub cancel_requested: bool, |
| 528 | pub log_bytes: i64, | 528 | pub log_bytes: i64, |
| 529 | + /// Processes the OOM killer took in the job's cgroup, as its runner reported. `None` when the | ||
| 530 | + /// runner did not say (an older runner) or nothing was killed. | ||
| 531 | + pub oom_kills: Option<u32>, | ||
| 529 | } | 532 | } |
| 530 | 533 | ||
| 531 | /// An artifact uploaded by a job. The file itself is stored outside the database. | 534 | /// An artifact uploaded by a job. The file itself is stored outside the database. |
crates/forge-core/src/store/ci.rsmodified+58 -1
| @@ -24,7 +24,7 @@ use crate::time::{now_stamp, stamp_after, stamp_to_unix}; | |||
| 24 | use crate::token::{generate_token, hash_token}; | 24 | use crate::token::{generate_token, hash_token}; |
| 25 | 25 | ||
| 26 | const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \ | 26 | const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \ |
| 27 | - started_at, finished_at, heartbeat_at, cancel_requested, log_bytes"; | 27 | + started_at, finished_at, heartbeat_at, cancel_requested, log_bytes, oom_kills"; |
| 28 | const RUN_COLS: &str = "id, repo_id, number, trigger, git_ref, commit_oid, pull_number, actor_id, \ | 28 | const RUN_COLS: &str = "id, repo_id, number, trigger, git_ref, commit_oid, pull_number, actor_id, \ |
| 29 | state, config_error, created_at, finished_at"; | 29 | state, config_error, created_at, finished_at"; |
| 30 | const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, \ | 30 | const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, \ |
| @@ -151,6 +151,7 @@ fn map_job(row: &Row) -> Result<CiJob> { | |||
| 151 | heartbeat_at: col_opt_text(row, 11)?, | 151 | heartbeat_at: col_opt_text(row, 11)?, |
| 152 | cancel_requested: col_bool(row, 12)?, | 152 | cancel_requested: col_bool(row, 12)?, |
| 153 | log_bytes: col_int(row, 13)?, | 153 | log_bytes: col_int(row, 13)?, |
| 154 | + oom_kills: opt_u32(row, 14)?, | ||
| 154 | }) | 155 | }) |
| 155 | } | 156 | } |
| 156 | 157 | ||
| @@ -1109,6 +1110,21 @@ impl Store { | |||
| 1109 | .ok_or(Error::NotFound) | 1110 | .ok_or(Error::NotFound) |
| 1110 | } | 1111 | } |
| 1111 | 1112 | ||
| 1113 | + /// Records the OOM kills a runner saw in the job's cgroup. Zero is stored as nothing. | ||
| 1114 | + pub async fn set_job_oom_kills(&self, job_id: &str, kills: u32) -> Result<()> { | ||
| 1115 | + if kills == 0 { | ||
| 1116 | + return Ok(()); | ||
| 1117 | + } | ||
| 1118 | + let conn = self.inner.conn.lock().await; | ||
| 1119 | + conn.execute( | ||
| 1120 | + "UPDATE ci_jobs SET oom_kills = ?2 WHERE id = ?1", | ||
| 1121 | + (job_id.to_string(), i64::from(kills)), | ||
| 1122 | + ) | ||
| 1123 | + .await | ||
| 1124 | + .map_err(db_err)?; | ||
| 1125 | + Ok(()) | ||
| 1126 | + } | ||
| 1127 | + | ||
| 1112 | /// Adds to the job's log size. | 1128 | /// Adds to the job's log size. |
| 1113 | pub async fn add_log_bytes(&self, job_id: &str, n: i64) -> Result<()> { | 1129 | pub async fn add_log_bytes(&self, job_id: &str, n: i64) -> Result<()> { |
| 1114 | if n < 0 { | 1130 | if n < 0 { |
| @@ -2589,6 +2605,47 @@ mod tests { | |||
| 2589 | assert_eq!(next.0.name, "small"); | 2605 | assert_eq!(next.0.name, "small"); |
| 2590 | } | 2606 | } |
| 2591 | 2607 | ||
| 2608 | + #[tokio::test] | ||
| 2609 | + async fn oom_kills_are_stored_on_the_job() { | ||
| 2610 | + let fx = fixture().await; | ||
| 2611 | + create( | ||
| 2612 | + &fx.store, | ||
| 2613 | + &fx.repo.id, | ||
| 2614 | + &fx.tahinli.id, | ||
| 2615 | + &[job("build", &[], &[])], | ||
| 2616 | + false, | ||
| 2617 | + ) | ||
| 2618 | + .await; | ||
| 2619 | + let (claimed, _, _) = fx | ||
| 2620 | + .store | ||
| 2621 | + .claim_job(&bare_runner(&[])) | ||
| 2622 | + .await | ||
| 2623 | + .unwrap() | ||
| 2624 | + .unwrap(); | ||
| 2625 | + assert_eq!(claimed.oom_kills, None); | ||
| 2626 | + fx.store.set_job_oom_kills(&claimed.id, 0).await.unwrap(); | ||
| 2627 | + assert_eq!( | ||
| 2628 | + fx.store | ||
| 2629 | + .job_by_id(&claimed.id) | ||
| 2630 | + .await | ||
| 2631 | + .unwrap() | ||
| 2632 | + .unwrap() | ||
| 2633 | + .oom_kills, | ||
| 2634 | + None, | ||
| 2635 | + "zero is nothing" | ||
| 2636 | + ); | ||
| 2637 | + fx.store.set_job_oom_kills(&claimed.id, 2).await.unwrap(); | ||
| 2638 | + assert_eq!( | ||
| 2639 | + fx.store | ||
| 2640 | + .job_by_id(&claimed.id) | ||
| 2641 | + .await | ||
| 2642 | + .unwrap() | ||
| 2643 | + .unwrap() | ||
| 2644 | + .oom_kills, | ||
| 2645 | + Some(2) | ||
| 2646 | + ); | ||
| 2647 | + } | ||
| 2648 | + | ||
| 2592 | #[tokio::test] | 2649 | #[tokio::test] |
| 2593 | async fn claim_matches_labels_and_skips_disabled() { | 2650 | async fn claim_matches_labels_and_skips_disabled() { |
| 2594 | let fx = fixture().await; | 2651 | let fx = fixture().await; |
crates/forge-runner/src/executor.rsmodified+26 -5
| @@ -31,6 +31,7 @@ use tokio_util::sync::CancellationToken; | |||
| 31 | use crate::config::{Limits, RegistryConfig}; | 31 | use crate::config::{Limits, RegistryConfig}; |
| 32 | use crate::logs::forward_lines; | 32 | use crate::logs::forward_lines; |
| 33 | use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth}; | 33 | use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth}; |
| 34 | +use crate::oom::{OomEvents, OomSink}; | ||
| 34 | use crate::sandbox::helper::EXIT_SETUP_FAILED; | 35 | use crate::sandbox::helper::EXIT_SETUP_FAILED; |
| 35 | use crate::sandbox::idmap::{IdMap, remove_tree}; | 36 | use crate::sandbox::idmap::{IdMap, remove_tree}; |
| 36 | use crate::sandbox::{SandboxRequest, job_cgroup_path}; | 37 | use crate::sandbox::{SandboxRequest, job_cgroup_path}; |
| @@ -53,6 +54,9 @@ pub struct ExecRequest<'a> { | |||
| 53 | pub logs: mpsc::Sender<Vec<u8>>, | 54 | pub logs: mpsc::Sender<Vec<u8>>, |
| 54 | /// Cancelling this stops the job. The executor then reports `Outcome::Cancelled`. | 55 | /// Cancelling this stops the job. The executor then reports `Outcome::Cancelled`. |
| 55 | pub cancel: CancellationToken, | 56 | pub cancel: CancellationToken, |
| 57 | + /// Where the executor leaves OOM kills it saw in the job's cgroup. Executors that cannot see | ||
| 58 | + /// them leave it alone. | ||
| 59 | + pub oom: OomSink, | ||
| 56 | } | 60 | } |
| 57 | 61 | ||
| 58 | /// The executor's answer. The runner adds timeouts and artifact results on top of it. | 62 | /// The executor's answer. The runner adds timeouts and artifact results on top of it. |
| @@ -308,15 +312,25 @@ struct Supervised { | |||
| 308 | status: std::io::Result<ExitStatus>, | 312 | status: std::io::Result<ExitStatus>, |
| 309 | /// The sandbox helper's last `forge-sandbox: <reason>` line on stderr, when it printed one. | 313 | /// The sandbox helper's last `forge-sandbox: <reason>` line on stderr, when it printed one. |
| 310 | sandbox_error: Option<String>, | 314 | sandbox_error: Option<String>, |
| 315 | + /// The OOM counters the helper printed, when something in the job was OOM-killed. | ||
| 316 | + oom: Option<OomEvents>, | ||
| 311 | } | 317 | } |
| 312 | 318 | ||
| 313 | /// Copies stderr lines to the log and remembers the last sandbox error line. | 319 | /// Copies stderr lines to the log and remembers the last sandbox error line. |
| 314 | async fn tap_sandbox_errors( | 320 | async fn tap_sandbox_errors( |
| 315 | mut lines: mpsc::Receiver<Vec<u8>>, | 321 | mut lines: mpsc::Receiver<Vec<u8>>, |
| 316 | logs: mpsc::Sender<Vec<u8>>, | 322 | logs: mpsc::Sender<Vec<u8>>, |
| 317 | -) -> Option<String> { | 323 | +) -> (Option<String>, Option<OomEvents>) { |
| 318 | let mut found = None; | 324 | let mut found = None; |
| 325 | + let mut oom = None; | ||
| 319 | while let Some(chunk) = lines.recv().await { | 326 | while let Some(chunk) = lines.recv().await { |
| 327 | + // The OOM line is for the runner, not for the job log. | ||
| 328 | + if chunk.starts_with(SANDBOX_PREFIX) | ||
| 329 | + && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk)) | ||
| 330 | + { | ||
| 331 | + oom = Some(events); | ||
| 332 | + continue; | ||
| 333 | + } | ||
| 320 | let is_error = chunk.starts_with(SANDBOX_PREFIX) | 334 | let is_error = chunk.starts_with(SANDBOX_PREFIX) |
| 321 | && !chunk[SANDBOX_PREFIX.len()..].starts_with(b"warning:"); | 335 | && !chunk[SANDBOX_PREFIX.len()..].starts_with(b"warning:"); |
| 322 | if is_error { | 336 | if is_error { |
| @@ -326,7 +340,7 @@ async fn tap_sandbox_errors( | |||
| 326 | break; | 340 | break; |
| 327 | } | 341 | } |
| 328 | } | 342 | } |
| 329 | - found | 343 | + (found, oom) |
| 330 | } | 344 | } |
| 331 | 345 | ||
| 332 | /// Forwards the child's output, waits for it, and reports how it ended. On cancellation the | 346 | /// Forwards the child's output, waits for it, and reports how it ended. On cancellation the |
| @@ -375,18 +389,19 @@ async fn supervise( | |||
| 375 | reader.abort(); | 389 | reader.abort(); |
| 376 | } | 390 | } |
| 377 | } | 391 | } |
| 378 | - let sandbox_error = match tap { | 392 | + let (sandbox_error, oom) = match tap { |
| 379 | Some(tap) => match tokio::time::timeout(READER_GRACE, tap).await { | 393 | Some(tap) => match tokio::time::timeout(READER_GRACE, tap).await { |
| 380 | Ok(Ok(found)) => found, | 394 | Ok(Ok(found)) => found, |
| 381 | - _ => None, | 395 | + _ => (None, None), |
| 382 | }, | 396 | }, |
| 383 | - None => None, | 397 | + None => (None, None), |
| 384 | }; | 398 | }; |
| 385 | 399 | ||
| 386 | Supervised { | 400 | Supervised { |
| 387 | cancelled, | 401 | cancelled, |
| 388 | status, | 402 | status, |
| 389 | sandbox_error, | 403 | sandbox_error, |
| 404 | + oom, | ||
| 390 | } | 405 | } |
| 391 | } | 406 | } |
| 392 | 407 | ||
| @@ -586,6 +601,7 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 586 | workspace, | 601 | workspace, |
| 587 | logs, | 602 | logs, |
| 588 | cancel, | 603 | cancel, |
| 604 | + oom: oom_sink, | ||
| 589 | } = req; | 605 | } = req; |
| 590 | if let Err(e) = validate_job_id(&job.job_id) { | 606 | if let Err(e) = validate_job_id(&job.job_id) { |
| 591 | return error_result(e.to_string()); | 607 | return error_result(e.to_string()); |
| @@ -660,6 +676,7 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 660 | cancelled, | 676 | cancelled, |
| 661 | status, | 677 | status, |
| 662 | sandbox_error, | 678 | sandbox_error, |
| 679 | + oom, | ||
| 663 | } = supervise( | 680 | } = supervise( |
| 664 | child, | 681 | child, |
| 665 | logs, | 682 | logs, |
| @@ -674,6 +691,9 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 674 | }), | 691 | }), |
| 675 | ) | 692 | ) |
| 676 | .await; | 693 | .await; |
| 694 | + if let Some(events) = oom { | ||
| 695 | + oom_sink.record(events); | ||
| 696 | + } | ||
| 677 | if cancelled { | 697 | if cancelled { |
| 678 | return cancelled_result(); | 698 | return cancelled_result(); |
| 679 | } | 699 | } |
| @@ -920,6 +940,7 @@ mod tests { | |||
| 920 | workspace: &ws, | 940 | workspace: &ws, |
| 921 | logs: tx, | 941 | logs: tx, |
| 922 | cancel: CancellationToken::new(), | 942 | cancel: CancellationToken::new(), |
| 943 | + oom: OomSink::default(), | ||
| 923 | }) | 944 | }) |
| 924 | .await; | 945 | .await; |
| 925 | assert_eq!(result.outcome, Outcome::Success, "{result:?}"); | 946 | assert_eq!(result.outcome, Outcome::Success, "{result:?}"); |
crates/forge-runner/src/lib.rsmodified+1 -0
| @@ -15,6 +15,7 @@ pub mod limiter; | |||
| 15 | pub mod logs; | 15 | pub mod logs; |
| 16 | pub mod memory; | 16 | pub mod memory; |
| 17 | pub mod oci; | 17 | pub mod oci; |
| 18 | +pub mod oom; | ||
| 18 | pub mod restart; | 19 | pub mod restart; |
| 19 | pub mod runner; | 20 | pub mod runner; |
| 20 | pub mod sandbox; | 21 | pub mod sandbox; |
crates/forge-runner/src/oom.rsadded+171 -0
| @@ -0,0 +1,171 @@ | |||
| 1 | +//! Out-of-memory kills inside a job's cgroup. The sandbox helper reads the cgroup's `memory.events` | ||
| 2 | +//! when the job's init exits, before it deletes the cgroup, and prints one line on stderr. The | ||
| 3 | +//! runner reads that line back and reports it when it finishes the job. | ||
| 4 | +//! | ||
| 5 | +//! Why the cgroup and not the exit code: when rustc is killed, cargo prints `(signal: 9, SIGKILL: | ||
| 6 | +//! kill)` in the log and itself exits 101, so neither the job's exit code nor its message shows it. | ||
| 7 | +//! | ||
| 8 | +//! Kernel semantics (`Documentation/admin-guide/cgroup-v2.rst`): in `memory.events`, `oom` counts | ||
| 9 | +//! how often the cgroup reached its limit and the OOM killer was invoked for it, and `oom_kill` | ||
| 10 | +//! counts the processes of this cgroup that were killed by any kind of OOM killer. The victim's | ||
| 11 | +//! cgroup is charged in `oom_kill_process`, so a victim of a host-wide OOM (global OOM killer, | ||
| 12 | +//! nothing hit its own `memory.max`) is still counted in `oom_kill` of the cgroup it lived in, on | ||
| 13 | +//! kernels since 4.13 that have the counter. `oom` stays 0 in that case, which is why both are | ||
| 14 | +//! read and `oom_kill` is the one to trust. Both are hierarchical in `memory.events`, so a | ||
| 15 | +//! process in a child cgroup counts too. A victim that was not in the job's cgroup at all (the | ||
| 16 | +//! runner itself) is not counted, and nothing here can see it. | ||
| 17 | + | ||
| 18 | +use std::sync::Arc; | ||
| 19 | +use std::sync::atomic::{AtomicU32, Ordering}; | ||
| 20 | + | ||
| 21 | +/// The line the helper prints. It starts with the sandbox prefix, see `SANDBOX_PREFIX`. | ||
| 22 | +pub const LINE_PREFIX: &str = "forge-sandbox: oom-events "; | ||
| 23 | + | ||
| 24 | +/// The `oom` and `oom_kill` counters of a job cgroup. | ||
| 25 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | ||
| 26 | +pub struct OomEvents { | ||
| 27 | + pub oom: u64, | ||
| 28 | + pub oom_kill: u64, | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +impl OomEvents { | ||
| 32 | + /// Reads the counters from the text of a `memory.events` file. Missing keys count as 0. | ||
| 33 | + pub fn parse_memory_events(text: &str) -> Self { | ||
| 34 | + let mut events = Self::default(); | ||
| 35 | + for line in text.lines() { | ||
| 36 | + let mut parts = line.split_whitespace(); | ||
| 37 | + let (Some(key), Some(value)) = (parts.next(), parts.next()) else { | ||
| 38 | + continue; | ||
| 39 | + }; | ||
| 40 | + let value = value.parse().unwrap_or(0); | ||
| 41 | + match key { | ||
| 42 | + "oom" => events.oom = value, | ||
| 43 | + "oom_kill" => events.oom_kill = value, | ||
| 44 | + _ => {} | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | + events | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + /// True when something in the job was OOM-killed or the cgroup hit its limit. | ||
| 51 | + pub fn any(&self) -> bool { | ||
| 52 | + self.oom > 0 || self.oom_kill > 0 | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + /// How many kills to report: `oom_kill`, or `oom` when only that one moved. | ||
| 56 | + pub fn kills(&self) -> u32 { | ||
| 57 | + u32::try_from(self.oom_kill.max(self.oom)).unwrap_or(u32::MAX) | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + /// The stderr line for the runner, without a newline. | ||
| 61 | + pub fn to_line(&self) -> String { | ||
| 62 | + format!("{LINE_PREFIX}oom={} oom_kill={}", self.oom, self.oom_kill) | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + /// Reads a line written by [`OomEvents::to_line`]. | ||
| 66 | + pub fn from_line(line: &str) -> Option<Self> { | ||
| 67 | + let rest = line.trim_end().strip_prefix(LINE_PREFIX)?; | ||
| 68 | + let mut events = Self::default(); | ||
| 69 | + for pair in rest.split_whitespace() { | ||
| 70 | + let (key, value) = pair.split_once('=')?; | ||
| 71 | + let value = value.parse().ok()?; | ||
| 72 | + match key { | ||
| 73 | + "oom" => events.oom = value, | ||
| 74 | + "oom_kill" => events.oom_kill = value, | ||
| 75 | + _ => {} | ||
| 76 | + } | ||
| 77 | + } | ||
| 78 | + Some(events) | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// Where an executor leaves the OOM kills it saw for a job. Cheap to clone and share. | ||
| 83 | +#[derive(Clone, Debug, Default)] | ||
| 84 | +pub struct OomSink(Arc<AtomicU32>); | ||
| 85 | + | ||
| 86 | +impl OomSink { | ||
| 87 | + pub fn record(&self, events: OomEvents) { | ||
| 88 | + if events.any() { | ||
| 89 | + self.0.store(events.kills().max(1), Ordering::SeqCst); | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + /// The reported kills, or `None` when nothing was killed or the executor cannot tell. | ||
| 94 | + pub fn kills(&self) -> Option<u32> { | ||
| 95 | + match self.0.load(Ordering::SeqCst) { | ||
| 96 | + 0 => None, | ||
| 97 | + n => Some(n), | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +#[cfg(test)] | ||
| 103 | +mod tests { | ||
| 104 | + use super::*; | ||
| 105 | + | ||
| 106 | + const EVENTS: &str = "low 0\nhigh 0\nmax 12\noom 2\noom_kill 3\noom_group_kill 0\n"; | ||
| 107 | + | ||
| 108 | + #[test] | ||
| 109 | + fn memory_events_are_parsed() { | ||
| 110 | + let events = OomEvents::parse_memory_events(EVENTS); | ||
| 111 | + assert_eq!( | ||
| 112 | + events, | ||
| 113 | + OomEvents { | ||
| 114 | + oom: 2, | ||
| 115 | + oom_kill: 3 | ||
| 116 | + } | ||
| 117 | + ); | ||
| 118 | + assert!(events.any()); | ||
| 119 | + assert_eq!(events.kills(), 3); | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + #[test] | ||
| 123 | + fn a_clean_cgroup_reports_nothing() { | ||
| 124 | + let events = OomEvents::parse_memory_events("low 0\nhigh 0\nmax 4\noom 0\noom_kill 0\n"); | ||
| 125 | + assert!(!events.any()); | ||
| 126 | + assert_eq!(events.kills(), 0); | ||
| 127 | + let sink = OomSink::default(); | ||
| 128 | + sink.record(events); | ||
| 129 | + assert_eq!(sink.kills(), None); | ||
| 130 | + // Older kernels have no counters at all. | ||
| 131 | + assert!(!OomEvents::parse_memory_events("low 0\nmax 1\n").any()); | ||
| 132 | + assert!(!OomEvents::parse_memory_events("").any()); | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + #[test] | ||
| 136 | + fn a_host_wide_oom_shows_in_oom_kill_only() { | ||
| 137 | + // The job's own limit was never reached, but its rustc was the global OOM victim. | ||
| 138 | + let events = OomEvents::parse_memory_events("max 0\noom 0\noom_kill 1\n"); | ||
| 139 | + assert!(events.any()); | ||
| 140 | + assert_eq!(events.kills(), 1); | ||
| 141 | + } | ||
| 142 | + | ||
| 143 | + #[test] | ||
| 144 | + fn the_stderr_line_round_trips() { | ||
| 145 | + let events = OomEvents { | ||
| 146 | + oom: 1, | ||
| 147 | + oom_kill: 2, | ||
| 148 | + }; | ||
| 149 | + assert_eq!( | ||
| 150 | + events.to_line(), | ||
| 151 | + "forge-sandbox: oom-events oom=1 oom_kill=2" | ||
| 152 | + ); | ||
| 153 | + assert_eq!(OomEvents::from_line(&events.to_line()), Some(events)); | ||
| 154 | + assert_eq!(OomEvents::from_line("forge-sandbox: setup failed"), None); | ||
| 155 | + assert_eq!( | ||
| 156 | + OomEvents::from_line("forge-sandbox: oom-events oom=x"), | ||
| 157 | + None | ||
| 158 | + ); | ||
| 159 | + } | ||
| 160 | + | ||
| 161 | + #[test] | ||
| 162 | + fn the_sink_keeps_the_count() { | ||
| 163 | + let sink = OomSink::default(); | ||
| 164 | + let shared = sink.clone(); | ||
| 165 | + shared.record(OomEvents { | ||
| 166 | + oom: 0, | ||
| 167 | + oom_kill: 2, | ||
| 168 | + }); | ||
| 169 | + assert_eq!(sink.kills(), Some(2)); | ||
| 170 | + } | ||
| 171 | +} | ||
crates/forge-runner/src/runner.rsmodified+18 -2
| @@ -20,6 +20,7 @@ use crate::executor::{ExecRequest, ExecResult, Executor}; | |||
| 20 | use crate::limiter::Limiter; | 20 | use crate::limiter::Limiter; |
| 21 | use crate::logs::{self, PumpConfig}; | 21 | use crate::logs::{self, PumpConfig}; |
| 22 | use crate::memory::MemoryGate; | 22 | use crate::memory::MemoryGate; |
| 23 | +use crate::oom::OomSink; | ||
| 23 | use crate::restart::{self, RestartState, Step}; | 24 | use crate::restart::{self, RestartState, Step}; |
| 24 | use crate::update::{self, Installed, UpdateState}; | 25 | use crate::update::{self, Installed, UpdateState}; |
| 25 | use crate::workspace; | 26 | use crate::workspace; |
| @@ -342,6 +343,7 @@ impl Runner { | |||
| 342 | }; | 343 | }; |
| 343 | 344 | ||
| 344 | let mut workspace_dir = None; | 345 | let mut workspace_dir = None; |
| 346 | + let oom = OomSink::default(); | ||
| 345 | let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await; | 347 | let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await; |
| 346 | let mut result = match prepared { | 348 | let mut result = match prepared { |
| 347 | Ok(dir) => { | 349 | Ok(dir) => { |
| @@ -357,6 +359,7 @@ impl Runner { | |||
| 357 | workspace: &dir, | 359 | workspace: &dir, |
| 358 | logs: tx.clone(), | 360 | logs: tx.clone(), |
| 359 | cancel: job_cancel.clone(), | 361 | cancel: job_cancel.clone(), |
| 362 | + oom: oom.clone(), | ||
| 360 | }) | 363 | }) |
| 361 | .await; | 364 | .await; |
| 362 | workspace_dir = Some(dir); | 365 | workspace_dir = Some(dir); |
| @@ -408,6 +411,17 @@ impl Runner { | |||
| 408 | if let Some(message) = &result.message { | 411 | if let Some(message) = &result.message { |
| 409 | send_line(&tx, format!("runner: {message}")).await; | 412 | send_line(&tx, format!("runner: {message}")).await; |
| 410 | } | 413 | } |
| 414 | + let oom_kills = oom.kills(); | ||
| 415 | + if let Some(kills) = oom_kills { | ||
| 416 | + send_line( | ||
| 417 | + &tx, | ||
| 418 | + format!( | ||
| 419 | + "runner: the out of memory killer killed {kills} process(es) in this job; \ | ||
| 420 | + the job's memory is limited to its `memory` plus a little slack, see docs/ci.md" | ||
| 421 | + ), | ||
| 422 | + ) | ||
| 423 | + .await; | ||
| 424 | + } | ||
| 411 | drop(tx); | 425 | drop(tx); |
| 412 | match pump.await { | 426 | match pump.await { |
| 413 | Ok(Ok(bytes)) => tracing::debug!(job_id = %job.job_id, bytes, "logs shipped"), | 427 | Ok(Ok(bytes)) => tracing::debug!(job_id = %job.job_id, bytes, "logs shipped"), |
| @@ -415,7 +429,7 @@ impl Runner { | |||
| 415 | Err(e) => tracing::error!(job_id = %job.job_id, error = %e, "log task panicked"), | 429 | Err(e) => tracing::error!(job_id = %job.job_id, error = %e, "log task panicked"), |
| 416 | } | 430 | } |
| 417 | 431 | ||
| 418 | - self.finish(&job, &result).await; | 432 | + self.finish(&job, &result, oom_kills).await; |
| 419 | if let Some(dir) = workspace_dir | 433 | if let Some(dir) = workspace_dir |
| 420 | && let Err(e) = workspace::cleanup(&dir).await | 434 | && let Err(e) = workspace::cleanup(&dir).await |
| 421 | { | 435 | { |
| @@ -476,11 +490,13 @@ impl Runner { | |||
| 476 | Ok(()) | 490 | Ok(()) |
| 477 | } | 491 | } |
| 478 | 492 | ||
| 479 | - async fn finish(&self, job: &JobAssignment, result: &ExecResult) { | 493 | + async fn finish(&self, job: &JobAssignment, result: &ExecResult, oom_kills: Option<u32>) { |
| 480 | let req = FinishRequest { | 494 | let req = FinishRequest { |
| 481 | outcome: result.outcome, | 495 | outcome: result.outcome, |
| 482 | exit_code: result.exit_code, | 496 | exit_code: result.exit_code, |
| 483 | message: result.message.clone(), | 497 | message: result.message.clone(), |
| 498 | + oom_killed: oom_kills.map(|_| true), | ||
| 499 | + oom_kills, | ||
| 484 | }; | 500 | }; |
| 485 | for attempt in 1..=FINISH_ATTEMPTS { | 501 | for attempt in 1..=FINISH_ATTEMPTS { |
| 486 | match self.client.finish(&job.job_id, &job.job_token, &req).await { | 502 | match self.client.finish(&job.job_id, &job.job_token, &req).await { |
crates/forge-runner/src/sandbox/helper.rsmodified+28 -2
| @@ -402,7 +402,11 @@ fn launch_and_wait(layout: &Layout, id: &str, spec: &Spec) -> Result<i32, Sandbo | |||
| 402 | return Err(e); | 402 | return Err(e); |
| 403 | } | 403 | } |
| 404 | }; | 404 | }; |
| 405 | - wait_for_init(&mut container, pid) | 405 | + let cgroup = spec |
| 406 | + .linux() | ||
| 407 | + .as_ref() | ||
| 408 | + .and_then(|linux| linux.cgroups_path().clone()); | ||
| 409 | + wait_for_init(&mut container, pid, cgroup.as_deref()) | ||
| 406 | } | 410 | } |
| 407 | 411 | ||
| 408 | /// Writes `bundle/config.json` (0600). It holds the job env and secrets, so it is removed right | 412 | /// Writes `bundle/config.json` (0600). It holds the job env and secrets, so it is removed right |
| @@ -475,7 +479,11 @@ fn kill_container(container: &mut Container) -> Result<(), String> { | |||
| 475 | 479 | ||
| 476 | /// Waits for the init process. On SIGTERM the container is killed. The child is then reaped, | 480 | /// Waits for the init process. On SIGTERM the container is killed. The child is then reaped, |
| 477 | /// and `delete` removes the container's state. Returns the job's exit code. | 481 | /// and `delete` removes the container's state. Returns the job's exit code. |
| 478 | -fn wait_for_init(container: &mut Container, pid: Pid) -> Result<i32, SandboxError> { | 482 | +fn wait_for_init( |
| 483 | + container: &mut Container, | ||
| 484 | + pid: Pid, | ||
| 485 | + cgroup: Option<&Path>, | ||
| 486 | +) -> Result<i32, SandboxError> { | ||
| 479 | let mut killed = false; | 487 | let mut killed = false; |
| 480 | loop { | 488 | loop { |
| 481 | if !killed && TERMINATE.load(Ordering::SeqCst) { | 489 | if !killed && TERMINATE.load(Ordering::SeqCst) { |
| @@ -487,10 +495,12 @@ fn wait_for_init(container: &mut Container, pid: Pid) -> Result<i32, SandboxErro | |||
| 487 | match waitpid(pid, Some(WaitPidFlag::WNOHANG)) { | 495 | match waitpid(pid, Some(WaitPidFlag::WNOHANG)) { |
| 488 | Ok(WaitStatus::StillAlive) => std::thread::sleep(POLL), | 496 | Ok(WaitStatus::StillAlive) => std::thread::sleep(POLL), |
| 489 | Ok(WaitStatus::Exited(_, code)) => { | 497 | Ok(WaitStatus::Exited(_, code)) => { |
| 498 | + report_oom(cgroup); | ||
| 490 | delete_container(container); | 499 | delete_container(container); |
| 491 | return Ok(code); | 500 | return Ok(code); |
| 492 | } | 501 | } |
| 493 | Ok(WaitStatus::Signaled(_, sig, _)) => { | 502 | Ok(WaitStatus::Signaled(_, sig, _)) => { |
| 503 | + report_oom(cgroup); | ||
| 494 | delete_container(container); | 504 | delete_container(container); |
| 495 | return Ok(128 + sig as i32); | 505 | return Ok(128 + sig as i32); |
| 496 | } | 506 | } |
| @@ -505,6 +515,22 @@ fn wait_for_init(container: &mut Container, pid: Pid) -> Result<i32, SandboxErro | |||
| 505 | } | 515 | } |
| 506 | } | 516 | } |
| 507 | 517 | ||
| 518 | +/// Prints the job cgroup's OOM counters for the runner when something was OOM-killed. It runs | ||
| 519 | +/// after the init exited and before the cgroup is deleted, the only time the file still exists. | ||
| 520 | +fn report_oom(cgroup: Option<&Path>) { | ||
| 521 | + let Some(cgroup) = cgroup else { | ||
| 522 | + return; | ||
| 523 | + }; | ||
| 524 | + let dir = Path::new("/sys/fs/cgroup").join(cgroup.strip_prefix("/").unwrap_or(cgroup)); | ||
| 525 | + let Ok(text) = fs::read_to_string(dir.join("memory.events")) else { | ||
| 526 | + return; | ||
| 527 | + }; | ||
| 528 | + let events = crate::oom::OomEvents::parse_memory_events(&text); | ||
| 529 | + if events.any() { | ||
| 530 | + eprintln!("{}", events.to_line()); | ||
| 531 | + } | ||
| 532 | +} | ||
| 533 | + | ||
| 508 | fn delete_container(container: &mut Container) { | 534 | fn delete_container(container: &mut Container) { |
| 509 | if let Err(e) = container.delete(true) { | 535 | if let Err(e) = container.delete(true) { |
| 510 | warn(format!("cannot delete container: {e}")); | 536 | warn(format!("cannot delete container: {e}")); |
crates/forge-runner/tests/builtin.rsmodified+1 -0
| @@ -127,6 +127,7 @@ async fn run_job( | |||
| 127 | workspace, | 127 | workspace, |
| 128 | logs: tx, | 128 | logs: tx, |
| 129 | cancel, | 129 | cancel, |
| 130 | + oom: forge_runner::oom::OomSink::default(), | ||
| 130 | }) | 131 | }) |
| 131 | .await; | 132 | .await; |
| 132 | let logs = collector.await.expect("log collector"); | 133 | let logs = collector.await.expect("log collector"); |
crates/forge-web/src/alerts.rsmodified+40 -6
| @@ -183,14 +183,18 @@ pub async fn runner_seen(state: &AppState, runner_id: &str) { | |||
| 183 | } | 183 | } |
| 184 | 184 | ||
| 185 | /// A job ended `Failure` or `Error`. Tells the admins once per run when it looks like the job was | 185 | /// A job ended `Failure` or `Error`. Tells the admins once per run when it looks like the job was |
| 186 | -/// killed, naming the runner. | 186 | +/// killed, naming the runner. `oom_killed` is the runner's report that the OOM killer took a |
| 187 | +/// process in the job's cgroup. | ||
| 187 | pub async fn job_ended( | 188 | pub async fn job_ended( |
| 188 | state: &AppState, | 189 | state: &AppState, |
| 189 | job: &forge_core::ci::CiJob, | 190 | job: &forge_core::ci::CiJob, |
| 190 | exit_code: Option<i64>, | 191 | exit_code: Option<i64>, |
| 191 | message: Option<&str>, | 192 | message: Option<&str>, |
| 193 | + oom_killed: bool, | ||
| 192 | ) { | 194 | ) { |
| 193 | - if !alerts::is_kill_signature(exit_code, message) { | 195 | + // The runner's own reading of the job cgroup comes first: a killed rustc leaves cargo to exit |
| 196 | + // 101 with the signal only in the log. The exit code and message are the fallback. | ||
| 197 | + if !oom_killed && !alerts::is_kill_signature(exit_code, message) { | ||
| 194 | return; | 198 | return; |
| 195 | } | 199 | } |
| 196 | let runner = match &job.runner_id { | 200 | let runner = match &job.runner_id { |
| @@ -617,14 +621,44 @@ mod tests { | |||
| 617 | heartbeat_at: None, | 621 | heartbeat_at: None, |
| 618 | cancel_requested: false, | 622 | cancel_requested: false, |
| 619 | log_bytes: 0, | 623 | log_bytes: 0, |
| 624 | + oom_kills: None, | ||
| 620 | }; | 625 | }; |
| 621 | - job_ended(&state, &job, Some(137), None).await; | 626 | + job_ended(&state, &job, Some(137), None, false).await; |
| 622 | job.name = "second".into(); | 627 | job.name = "second".into(); |
| 623 | - job_ended(&state, &job, None, Some("signal: 9")).await; | 628 | + job_ended(&state, &job, None, Some("signal: 9"), false).await; |
| 624 | - job_ended(&state, &job, Some(1), None).await; | 629 | + job_ended(&state, &job, Some(1), None, false).await; |
| 625 | assert_eq!(inbox(&state, &tahinli).await.len(), 1); | 630 | assert_eq!(inbox(&state, &tahinli).await.len(), 1); |
| 626 | job.run_id = "run-2".into(); | 631 | job.run_id = "run-2".into(); |
| 627 | - job_ended(&state, &job, Some(137), None).await; | 632 | + job_ended(&state, &job, Some(137), None, false).await; |
| 628 | assert_eq!(inbox(&state, &tahinli).await.len(), 2); | 633 | assert_eq!(inbox(&state, &tahinli).await.len(), 2); |
| 629 | } | 634 | } |
| 635 | + | ||
| 636 | + #[tokio::test] | ||
| 637 | + async fn an_oom_kill_the_job_survived_still_raises_the_alert() { | ||
| 638 | + let dir = tempfile::tempdir().unwrap(); | ||
| 639 | + let state = test_state(dir.path()).await; | ||
| 640 | + let tahinli = admin(&state, "tahinli", false).await; | ||
| 641 | + let job = forge_core::ci::CiJob { | ||
| 642 | + id: "job-1".into(), | ||
| 643 | + run_id: "run-1".into(), | ||
| 644 | + name: "build".into(), | ||
| 645 | + spec_json: "{}".into(), | ||
| 646 | + state: forge_core::ci::JobState::Failure, | ||
| 647 | + runner_id: None, | ||
| 648 | + exit_code: Some(101), | ||
| 649 | + message: None, | ||
| 650 | + queued_at: None, | ||
| 651 | + started_at: None, | ||
| 652 | + finished_at: None, | ||
| 653 | + heartbeat_at: None, | ||
| 654 | + cancel_requested: false, | ||
| 655 | + log_bytes: 0, | ||
| 656 | + oom_kills: None, | ||
| 657 | + }; | ||
| 658 | + // cargo exits 101 when rustc is killed, so the exit code and message show nothing. | ||
| 659 | + job_ended(&state, &job, Some(101), None, false).await; | ||
| 660 | + assert_eq!(inbox(&state, &tahinli).await.len(), 0); | ||
| 661 | + job_ended(&state, &job, Some(101), None, true).await; | ||
| 662 | + assert_eq!(inbox(&state, &tahinli).await.len(), 1); | ||
| 663 | + } | ||
| 630 | } | 664 | } |
crates/forge-web/src/ci/api.rsmodified+20 -1
| @@ -948,12 +948,24 @@ async fn finish_job( | |||
| 948 | .map(|other| (other.id, other.state)) | 948 | .map(|other| (other.id, other.state)) |
| 949 | .collect(); | 949 | .collect(); |
| 950 | let exit_code = request.exit_code.map(i64::from); | 950 | let exit_code = request.exit_code.map(i64::from); |
| 951 | + // The runner read the job cgroup's OOM counters. A count without the flag is believed too. | ||
| 952 | + let oom_kills = match (request.oom_killed, request.oom_kills) { | ||
| 953 | + (Some(false), _) => 0, | ||
| 954 | + (_, Some(n)) => n.max(1), | ||
| 955 | + (Some(true), None) => 1, | ||
| 956 | + (None, None) => 0, | ||
| 957 | + }; | ||
| 951 | let run = state | 958 | let run = state |
| 952 | .store | 959 | .store |
| 953 | .finish_job(&job.id, outcome, exit_code, request.message.as_deref()) | 960 | .finish_job(&job.id, outcome, exit_code, request.message.as_deref()) |
| 954 | .await | 961 | .await |
| 955 | .map_err(api::internal)?; | 962 | .map_err(api::internal)?; |
| 956 | 963 | ||
| 964 | + if oom_kills > 0 | ||
| 965 | + && let Err(e) = state.store.set_job_oom_kills(&job.id, oom_kills).await | ||
| 966 | + { | ||
| 967 | + tracing::warn!(error = %e, "ci: oom kills not stored"); | ||
| 968 | + } | ||
| 957 | let mut queued = false; | 969 | let mut queued = false; |
| 958 | let mut any_changed = false; | 970 | let mut any_changed = false; |
| 959 | for other in state | 971 | for other in state |
| @@ -980,7 +992,14 @@ async fn finish_job( | |||
| 980 | } | 992 | } |
| 981 | state.ci_live.bump_runners(); | 993 | state.ci_live.bump_runners(); |
| 982 | if matches!(outcome, JobState::Failure | JobState::Error) { | 994 | if matches!(outcome, JobState::Failure | JobState::Error) { |
| 983 | - crate::alerts::job_ended(state, job, exit_code, request.message.as_deref()).await; | 995 | + crate::alerts::job_ended( |
| 996 | + state, | ||
| 997 | + job, | ||
| 998 | + exit_code, | ||
| 999 | + request.message.as_deref(), | ||
| 1000 | + oom_kills > 0, | ||
| 1001 | + ) | ||
| 1002 | + .await; | ||
| 984 | } | 1003 | } |
| 985 | if any_changed { | 1004 | if any_changed { |
| 986 | state.ci_live.bump_run(&run.id); | 1005 | state.ci_live.bump_run(&run.id); |
crates/forge-web/src/ci/api_tests.rsmodified+51 -0
| @@ -848,6 +848,57 @@ fn finish_body(outcome: &str) -> Vec<u8> { | |||
| 848 | json_body(&json!({ "outcome": outcome, "exit_code": 0, "message": null })) | 848 | json_body(&json!({ "outcome": outcome, "exit_code": 0, "message": null })) |
| 849 | } | 849 | } |
| 850 | 850 | ||
| 851 | +async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) { | ||
| 852 | + let assignment = claim_job(&env.router, secret).await; | ||
| 853 | + let id = assignment["job_id"].as_str().unwrap().to_owned(); | ||
| 854 | + let token = assignment["job_token"].as_str().unwrap(); | ||
| 855 | + let sent = send( | ||
| 856 | + &env.router, | ||
| 857 | + "POST", | ||
| 858 | + &format!("/api/v1/ci/jobs/{id}/finish"), | ||
| 859 | + &[bearer(token)], | ||
| 860 | + json_body(&body), | ||
| 861 | + ) | ||
| 862 | + .await; | ||
| 863 | + assert_eq!(sent.status, 200, "{}", sent.json()); | ||
| 864 | + (id, sent.json()) | ||
| 865 | +} | ||
| 866 | + | ||
| 867 | +#[tokio::test] | ||
| 868 | +async fn finish_stores_the_oom_kills_the_runner_saw() { | ||
| 869 | + let env = bare(|_| {}).await; | ||
| 870 | + let (_runner, secret) = runner(&env, &[]).await; | ||
| 871 | + make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await; | ||
| 872 | + // cargo exited 101 because its rustc was killed: nothing in the exit code or message. | ||
| 873 | + let (id, _) = finish_with( | ||
| 874 | + &env, | ||
| 875 | + &secret, | ||
| 876 | + json!({"outcome": "failure", "exit_code": 101, "message": null, | ||
| 877 | + "oom_killed": true, "oom_kills": 2}), | ||
| 878 | + ) | ||
| 879 | + .await; | ||
| 880 | + let stored = env.store.job_by_id(&id).await.unwrap().unwrap(); | ||
| 881 | + assert_eq!(stored.oom_kills, Some(2)); | ||
| 882 | + assert_eq!(stored.exit_code, Some(101)); | ||
| 883 | +} | ||
| 884 | + | ||
| 885 | +#[tokio::test] | ||
| 886 | +async fn an_old_runner_finish_body_without_oom_fields_still_works() { | ||
| 887 | + let env = bare(|_| {}).await; | ||
| 888 | + let (_runner, secret) = runner(&env, &[]).await; | ||
| 889 | + make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await; | ||
| 890 | + let (id, _) = finish_with( | ||
| 891 | + &env, | ||
| 892 | + &secret, | ||
| 893 | + json!({"outcome": "failure", "exit_code": 1, "message": null}), | ||
| 894 | + ) | ||
| 895 | + .await; | ||
| 896 | + assert_eq!( | ||
| 897 | + env.store.job_by_id(&id).await.unwrap().unwrap().oom_kills, | ||
| 898 | + None | ||
| 899 | + ); | ||
| 900 | +} | ||
| 901 | + | ||
| 851 | async fn two_step_run(env: &Bare) -> CiRun { | 902 | async fn two_step_run(env: &Bare) -> CiRun { |
| 852 | make_run( | 903 | make_run( |
| 853 | env, | 904 | env, |
crates/forge-web/src/pages/ci_job.rsmodified+6 -0
| @@ -261,6 +261,8 @@ struct JobView { | |||
| 261 | runner: String, | 261 | runner: String, |
| 262 | exit_code: String, | 262 | exit_code: String, |
| 263 | message: String, | 263 | message: String, |
| 264 | + /// The processes the OOM killer took in the job, when its runner reported any. | ||
| 265 | + oom_kills: Option<u32>, | ||
| 264 | started: String, | 266 | started: String, |
| 265 | started_full: String, | 267 | started_full: String, |
| 266 | finished: String, | 268 | finished: String, |
| @@ -321,6 +323,9 @@ async fn job_body( | |||
| 321 | if !job.message.is_empty() { | 323 | if !job.message.is_empty() { |
| 322 | <p>(job.message.as_str())</p> | 324 | <p>(job.message.as_str())</p> |
| 323 | } | 325 | } |
| 326 | + if let Some(kills) = job.oom_kills { | ||
| 327 | + <p class="alert" title=(format!("oom_kill {kills}"))>(if matches!(lang, Lang::Tr) { "sonlandırıldı: bellek yetersiz" } else { "killed: out of memory" })</p> | ||
| 328 | + } | ||
| 324 | if let Some((action, csrf)) = job.rerun.as_ref() { | 329 | if let Some((action, csrf)) = job.rerun.as_ref() { |
| 325 | <div class="ci-actions"> | 330 | <div class="ci-actions"> |
| 326 | <form method="post" action=(action.as_str()) class="inline-form"> | 331 | <form method="post" action=(action.as_str()) class="inline-form"> |
| @@ -418,6 +423,7 @@ async fn job_page(cx: &Cx) -> Result<impl View> { | |||
| 418 | .map(|code| code.to_string()) | 423 | .map(|code| code.to_string()) |
| 419 | .unwrap_or_default(), | 424 | .unwrap_or_default(), |
| 420 | message: job.message.clone().unwrap_or_default(), | 425 | message: job.message.clone().unwrap_or_default(), |
| 426 | + oom_kills: job.oom_kills, | ||
| 421 | started: job | 427 | started: job |
| 422 | .started_at | 428 | .started_at |
| 423 | .as_deref() | 429 | .as_deref() |
docs/ci.mdmodified+11 -0
| @@ -93,6 +93,14 @@ How it is used: | |||
| 93 | OOM-killed inside its own cgroup. Without `memory`, the limit is the larger of the runner's | 93 | OOM-killed inside its own cgroup. Without `memory`, the limit is the larger of the runner's |
| 94 | `limits.memory` and `limits.reserve_memory`. | 94 | `limits.memory` and `limits.reserve_memory`. |
| 95 | - It is the same for every job in a matrix. | 95 | - It is the same for every job in a matrix. |
| 96 | +- OOM kills are reported. When a job ends, the builtin executor reads the job cgroup's | ||
| 97 | + `memory.events` before the cgroup is deleted, and the runner sends `oom_killed` and `oom_kills` | ||
| 98 | + in the finish request. A job where rustc was killed still ends with exit 101 and only a | ||
| 99 | + `signal: 9` line in its log, so the exit code never showed it. The job page then says "killed: | ||
| 100 | + out of memory", and the admin alert for killed jobs fires. The counters are the kernel's | ||
| 101 | + `oom_kill` (processes of the cgroup killed by any OOM killer, a host-wide one included, since | ||
| 102 | + Linux 4.13) and `oom` (the cgroup hit its own limit). A process killed outside the job's cgroup is | ||
| 103 | + not counted. The podman executor does not report this. | ||
| 96 | 104 | ||
| 97 | Runners and forges that predate `memory` still work together. A runner that does not report free | 105 | Runners and forges that predate `memory` still work together. A runner that does not report free |
| 98 | memory gets the oldest queued job as before, and a runner that gets a job with no `memory` field | 106 | memory gets the oldest queued job as before, and a runner that gets a job with no `memory` field |
| @@ -749,6 +757,9 @@ The claim response (`JobAssignment`) carries the repository, the commit, the job | |||
| 749 | image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull | 757 | image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull |
| 750 | request runs, and `memory_bytes` when the job declares `memory`. | 758 | request runs, and `memory_bytes` when the job declares `memory`. |
| 751 | 759 | ||
| 760 | +The finish request (`outcome`, `exit_code`, `message`) may also carry `oom_killed` and `oom_kills`, | ||
| 761 | +see [Memory](#memory). Both are optional and left out by an older runner. | ||
| 762 | + | ||
| 752 | A claim body also carries the runner's host facts and, for memory-aware admission, | 763 | A claim body also carries the runner's host facts and, for memory-aware admission, |
| 753 | `free_memory_bytes` (budget minus the running jobs' reservations), `memory_budget_bytes` and | 764 | `free_memory_bytes` (budget minus the running jobs' reservations), `memory_budget_bytes` and |
| 754 | `reserve_memory_bytes`. All of these are optional. Without `free_memory_bytes` the forge takes the | 765 | `reserve_memory_bytes`. All of these are optional. Without `free_memory_bytes` the forge takes the |