forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

memory.rs355 lines, 12.9 KiBHistoryRawDownload
1//! Memory-aware admission. The runner has a memory budget for jobs and every running job holds a
2//! reservation against it. A claim tells the forge how much is free, so the forge hands out only a
3//! job that fits. The concurrency limit stays as a second cap, see [`crate::limiter`].
4//!
5//! Reservations are promises, not measurements: nothing reads what a job really uses. Each job's
6//! cgroup limit (see `Limits::for_job`) is what makes the promise hold, so a job that exceeds
7//! its reservation is OOM-killed inside its own cgroup and not by the host.
8
9use std::sync::{Arc, Mutex, PoisonError};
10
11use forge_ci::size::{format_size, parse_size};
12
13use crate::config::Limits;
14
15/// Used when a configured size does not parse. `Limits::default` carries the same value.
16const FALLBACK_RESERVE: u64 = 1 << 30;
17/// The smallest budget the runner will run with, so a typo cannot stop it from taking any job.
18const MIN_BUDGET: u64 = 256 << 20;
19
20/// Pure admission rule: a job fits when the running jobs' reservations plus its own stay within
21/// the budget.
22pub fn fits(reserved: u64, request: u64, budget: u64) -> bool {
23 reserved.saturating_add(request) <= budget
24}
25
26/// What a job reserves: its declared memory or the default, never more than the budget. A job
27/// bigger than the whole budget therefore still runs, alone, instead of waiting forever.
28pub fn reservation(declared: Option<u64>, default_reserve: u64, budget: u64) -> u64 {
29 declared.unwrap_or(default_reserve).min(budget).max(1)
30}
31
32/// The budget when none is configured: MemTotal minus the headroom, plus `swap_percent` of the
33/// swap. The headroom is the larger of `headroom` and 10% of MemTotal. Never below half of
34/// MemTotal or [`MIN_BUDGET`], so a small host still takes jobs.
35pub fn auto_budget(mem_total: u64, swap_total: u64, headroom: u64, swap_percent: u32) -> u64 {
36 let keep = headroom.max(mem_total / 10);
37 let ram = mem_total.saturating_sub(keep).max(mem_total / 2);
38 let swap = (u128::from(swap_total) * u128::from(swap_percent.min(100)) / 100) as u64;
39 ram.saturating_add(swap).max(MIN_BUDGET)
40}
41
42/// `(MemTotal, SwapTotal)` of a `/proc/meminfo` text, in bytes.
43pub fn parse_meminfo(text: &str) -> (Option<u64>, Option<u64>) {
44 let find = |key: &str| {
45 let line = text.lines().find(|l| l.starts_with(key))?;
46 let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
47 kib.checked_mul(1024)
48 };
49 (find("MemTotal:"), find("SwapTotal:"))
50}
51
52fn host_memory() -> (Option<u64>, Option<u64>) {
53 std::fs::read_to_string("/proc/meminfo")
54 .map(|t| parse_meminfo(&t))
55 .unwrap_or((None, None))
56}
57
58/// The budget `limits` asks for on a host with this much memory and swap.
59fn configured_budget(limits: &Limits, mem_total: u64, swap_total: u64) -> u64 {
60 match limits.memory_budget.as_deref() {
61 None | Some("auto") => {
62 let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30);
63 auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent)
64 }
65 Some(text) => parse_size(text).map_or_else(
66 || {
67 let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30);
68 auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent)
69 },
70 |n| n.max(MIN_BUDGET),
71 ),
72 }
73}
74
75struct State {
76 budget: u64,
77 swap: u64,
78 reserve: u64,
79 reserved: u64,
80}
81
82/// The part of the budget that is swap: `swap_percent` of the swap in `auto` mode, none with a set
83/// budget. A lone job may use it as swap on top of the rest of the budget, which is RAM.
84fn swap_share(limits: &Limits, swap_total: u64) -> u64 {
85 let set = limits
86 .memory_budget
87 .as_deref()
88 .is_some_and(|text| text != "auto" && parse_size(text).is_some());
89 if set {
90 return 0;
91 }
92 (u128::from(swap_total) * u128::from(limits.budget_swap_percent.min(100)) / 100) as u64
93}
94
95/// The runner's memory budget and the reservations against it. Cheap to share: clone the `Arc`.
96pub struct MemoryGate {
97 limits: Limits,
98 mem_total: u64,
99 swap_total: u64,
100 state: Mutex<State>,
101}
102
103/// A job's reservation. Dropping it gives the memory back.
104pub struct Reservation {
105 bytes: u64,
106 gate: Arc<MemoryGate>,
107}
108
109impl Reservation {
110 pub fn bytes(&self) -> u64 {
111 self.bytes
112 }
113}
114
115impl Drop for Reservation {
116 fn drop(&mut self) {
117 let mut state = self.gate.lock();
118 state.reserved = state.reserved.saturating_sub(self.bytes);
119 }
120}
121
122impl MemoryGate {
123 /// A gate for this host, read from `/proc/meminfo`. Without it the host is assumed to have
124 /// 8 GiB.
125 pub fn for_host(limits: &Limits) -> Arc<Self> {
126 let (mem, swap) = host_memory();
127 Self::new(limits, mem.unwrap_or(8 << 30), swap.unwrap_or(0))
128 }
129
130 pub fn new(limits: &Limits, mem_total: u64, swap_total: u64) -> Arc<Self> {
131 let budget = configured_budget(limits, mem_total, swap_total);
132 let reserve = parse_size(&limits.reserve_memory).unwrap_or(FALLBACK_RESERVE);
133 Arc::new(Self {
134 limits: limits.clone(),
135 mem_total,
136 swap_total,
137 state: Mutex::new(State {
138 budget,
139 swap: swap_share(limits, swap_total),
140 reserve,
141 reserved: 0,
142 }),
143 })
144 }
145
146 fn lock(&self) -> std::sync::MutexGuard<'_, State> {
147 self.state.lock().unwrap_or_else(PoisonError::into_inner)
148 }
149
150 pub fn budget(&self) -> u64 {
151 self.lock().budget
152 }
153
154 /// The swap part of the budget, see [`swap_share`].
155 pub fn swap(&self) -> u64 {
156 self.lock().swap
157 }
158
159 /// The RAM part of the budget: what the box and a lone job may hold in memory.
160 pub fn ram_budget(&self) -> u64 {
161 let state = self.lock();
162 state.budget.saturating_sub(state.swap).max(MIN_BUDGET)
163 }
164
165 pub fn default_reserve(&self) -> u64 {
166 self.lock().reserve
167 }
168
169 pub fn reserved(&self) -> u64 {
170 self.lock().reserved
171 }
172
173 /// What a new claim may admit: the budget minus the running jobs' reservations.
174 pub fn free(&self) -> u64 {
175 let state = self.lock();
176 state.budget.saturating_sub(state.reserved)
177 }
178
179 /// Reserves memory for a claimed job. This always succeeds: the forge has already checked the
180 /// job fits, and a job that was handed out must run. An older forge that does not check can
181 /// leave the runner over its budget, and `free` then reads 0 until jobs finish.
182 pub fn reserve(self: &Arc<Self>, declared: Option<u64>) -> Reservation {
183 let mut state = self.lock();
184 let bytes = reservation(declared, state.reserve, state.budget);
185 state.reserved = state.reserved.saturating_add(bytes);
186 Reservation {
187 bytes,
188 gate: self.clone(),
189 }
190 }
191
192 /// Applies what the forge asked for, the way `Limiter::apply` does for concurrency: `Some`
193 /// is an override, `None` brings back the `runner.toml` value. A value that does not parse
194 /// counts as no override. Returns a log line when something changed.
195 pub fn apply(&self, budget: Option<&str>, reserve: Option<&str>) -> Option<String> {
196 let mut limits = self.limits.clone();
197 if let Some(text) = budget.filter(|t| *t == "auto" || parse_size(t).is_some()) {
198 limits.memory_budget = (text != "auto").then(|| text.to_owned());
199 }
200 if let Some(text) = reserve.filter(|t| parse_size(t).is_some()) {
201 limits.reserve_memory = text.to_owned();
202 }
203 let new_budget = configured_budget(&limits, self.mem_total, self.swap_total);
204 let new_reserve = parse_size(&limits.reserve_memory).unwrap_or(FALLBACK_RESERVE);
205 let new_swap = swap_share(&limits, self.swap_total);
206 let mut state = self.lock();
207 if (state.budget, state.reserve) == (new_budget, new_reserve) {
208 return None;
209 }
210 let line = format!(
211 "runner: memory budget {} -> {}, default reservation {} -> {}",
212 format_size(state.budget),
213 format_size(new_budget),
214 format_size(state.reserve),
215 format_size(new_reserve),
216 );
217 state.budget = new_budget;
218 state.swap = new_swap;
219 state.reserve = new_reserve;
220 Some(line)
221 }
222
223 /// Like [`MemoryGate::apply`], and logs the change.
224 pub fn apply_logged(&self, budget: Option<&str>, reserve: Option<&str>) {
225 if let Some(line) = self.apply(budget, reserve) {
226 tracing::info!("{line}");
227 }
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 const GIB: u64 = 1 << 30;
236
237 #[test]
238 fn the_swap_share_is_kept_apart_from_ram() {
239 let limits = Limits {
240 budget_swap_percent: 50,
241 ..Limits::default()
242 };
243 let gate = MemoryGate::new(&limits, 8 * GIB, 8 * GIB);
244 assert_eq!(gate.swap(), 4 * GIB);
245 assert_eq!(gate.ram_budget(), gate.budget() - 4 * GIB);
246 let set = Limits {
247 memory_budget: Some("6g".into()),
248 ..limits
249 };
250 assert_eq!(MemoryGate::new(&set, 8 * GIB, 8 * GIB).swap(), 0);
251 }
252
253 #[test]
254 fn a_job_fits_when_the_sum_stays_within_the_budget() {
255 // 6.5 GiB budget, one 4 GiB job running.
256 let budget = 6 * GIB + GIB / 2;
257 assert!(fits(0, 4 * GIB, budget));
258 assert!(fits(4 * GIB, 2 * GIB, budget));
259 assert!(
260 fits(4 * GIB, 2 * GIB + GIB / 2, budget),
261 "exactly the budget"
262 );
263 assert!(!fits(4 * GIB, 4 * GIB, budget), "second heavy job waits");
264 assert!(!fits(budget, 1, budget));
265 assert!(!fits(u64::MAX, 1, budget), "no overflow");
266 }
267
268 #[test]
269 fn a_job_without_memory_reserves_the_default() {
270 assert_eq!(reservation(None, GIB, 6 * GIB), GIB);
271 assert_eq!(reservation(Some(4 * GIB), GIB, 6 * GIB), 4 * GIB);
272 // Bigger than the whole budget: capped, so it still runs when the runner is idle.
273 assert_eq!(reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB);
274 assert!(fits(0, reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB));
275 }
276
277 #[test]
278 fn auto_budget_is_mem_total_minus_headroom() {
279 // The production host: 7.6 GiB RAM, 8 GiB swap, 1 GiB headroom, swap ignored.
280 let total = 7 * GIB + 6 * GIB / 10;
281 let budget = auto_budget(total, 8 * GIB, GIB, 0);
282 assert_eq!(budget, total - GIB);
283 assert!(budget > 6 * GIB && budget < 7 * GIB);
284 // On a big host 10% wins over 1 GiB.
285 assert_eq!(auto_budget(64 * GIB, 0, GIB, 0), 64 * GIB - 64 * GIB / 10);
286 // Half of the swap counted.
287 assert_eq!(auto_budget(total, 8 * GIB, GIB, 50), total - GIB + 4 * GIB);
288 // A tiny host keeps at least half.
289 assert_eq!(auto_budget(GIB, 0, 2 * GIB, 0), GIB / 2);
290 }
291
292 #[test]
293 fn meminfo_is_parsed() {
294 let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nSwapTotal: 8388604 kB\n";
295 assert_eq!(
296 parse_meminfo(text),
297 (Some(7_971_680 * 1024), Some(8_388_604 * 1024))
298 );
299 assert_eq!(parse_meminfo(""), (None, None));
300 }
301
302 #[test]
303 fn the_gate_tracks_reservations() {
304 let limits = Limits {
305 memory_budget: Some("6g".into()),
306 ..Limits::default()
307 };
308 let gate = MemoryGate::new(&limits, 8 * GIB, 0);
309 assert_eq!(gate.budget(), 6 * GIB);
310 assert_eq!(gate.free(), 6 * GIB);
311 let heavy = gate.reserve(Some(4 * GIB));
312 assert_eq!(gate.free(), 2 * GIB);
313 let light = gate.reserve(None);
314 assert_eq!(gate.reserved(), 5 * GIB);
315 assert_eq!(gate.free(), GIB);
316 drop(heavy);
317 assert_eq!(gate.free(), 5 * GIB);
318 drop(light);
319 assert_eq!(gate.free(), 6 * GIB);
320 }
321
322 #[test]
323 fn an_old_forge_cannot_push_free_below_zero() {
324 let limits = Limits {
325 memory_budget: Some("2g".into()),
326 ..Limits::default()
327 };
328 let gate = MemoryGate::new(&limits, 8 * GIB, 0);
329 let a = gate.reserve(Some(2 * GIB));
330 let b = gate.reserve(Some(2 * GIB));
331 assert_eq!(gate.free(), 0);
332 drop(a);
333 assert_eq!(gate.free(), 0);
334 drop(b);
335 assert_eq!(gate.free(), 2 * GIB);
336 }
337
338 #[test]
339 fn the_forge_can_change_budget_and_reserve_live() {
340 let gate = MemoryGate::new(&Limits::default(), 8 * GIB, 0);
341 assert_eq!(gate.budget(), 7 * GIB);
342 let line = gate.apply(Some("5g"), Some("2g"));
343 assert!(line.is_some());
344 assert_eq!(gate.budget(), 5 * GIB);
345 assert_eq!(gate.default_reserve(), 2 * GIB);
346 assert_eq!(gate.apply(Some("5g"), Some("2g")), None, "no change");
347 // No override brings the runner.toml values back.
348 gate.apply(None, None);
349 assert_eq!(gate.default_reserve(), GIB);
350 assert_ne!(gate.budget(), 5 * GIB);
351 // Nonsense is ignored.
352 gate.apply(Some("lots"), Some("0"));
353 assert_eq!(gate.default_reserve(), GIB);
354 }
355}