forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

oom.rs171 lines, 6.0 KiBHistoryRawDownload
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
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU32, Ordering};
20
21/// The line the helper prints. It starts with the sandbox prefix, see `SANDBOX_PREFIX`.
22pub 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)]
26pub struct OomEvents {
27 pub oom: u64,
28 pub oom_kill: u64,
29}
30
31impl 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)]
84pub struct OomSink(Arc<AtomicU32>);
85
86impl 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)]
103mod 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}