| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | use std::fs::{self, File, OpenOptions}; |
| 20 | use std::io::{self, Write}; |
| 21 | use std::os::fd::{AsFd, OwnedFd}; |
| 22 | use std::os::unix::fs::OpenOptionsExt; |
| 23 | use std::path::{Path, PathBuf}; |
| 24 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 25 | use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; |
| 26 | use std::time::{Duration, Instant}; |
| 27 | |
| 28 | use nix::errno::Errno; |
| 29 | use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; |
| 30 | use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify}; |
| 31 | use nix::unistd::pipe; |
| 32 | use tokio::sync::{Notify, mpsc}; |
| 33 | use tokio_util::sync::CancellationToken; |
| 34 | |
| 35 | use crate::executor::kill_cgroup; |
| 36 | use crate::sandbox::{BOX_NAME, job_cgroup_base}; |
| 37 | |
| 38 | |
| 39 | const CGROUP_ROOT: &str = "/sys/fs/cgroup"; |
| 40 | |
| 41 | const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"]; |
| 42 | |
| 43 | const PSI_TRIGGER: &str = "some 150000 2000000"; |
| 44 | |
| 45 | const HIGH_MARGIN_MIN: u64 = 512 << 20; |
| 46 | |
| 47 | const SWAPPINESS: u32 = 200; |
| 48 | |
| 49 | const RECLAIM_ATTEMPTS: u32 = 4; |
| 50 | |
| 51 | const LEFTOVER_POLLS: u32 = 50; |
| 52 | const LEFTOVER_POLL: Duration = Duration::from_millis(100); |
| 53 | |
| 54 | |
| 55 | const PRESSURE_COOLDOWN: Duration = Duration::from_secs(10); |
| 56 | |
| 57 | |
| 58 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 59 | pub enum Cause { |
| 60 | |
| 61 | Pressure, |
| 62 | |
| 63 | Jobs, |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | pub fn parse_high(text: &str) -> u64 { |
| 70 | text.lines() |
| 71 | .find_map(|line| { |
| 72 | let (key, value) = line.split_once(' ')?; |
| 73 | (key == "high").then(|| value.trim().parse().ok())? |
| 74 | }) |
| 75 | .unwrap_or(0) |
| 76 | } |
| 77 | |
| 78 | |
| 79 | |
| 80 | pub fn high_value(unfrozen: usize, budget: u64) -> Option<u64> { |
| 81 | if unfrozen < 2 { |
| 82 | return None; |
| 83 | } |
| 84 | let margin = HIGH_MARGIN_MIN.max(budget / 20); |
| 85 | Some(budget.saturating_sub(margin)) |
| 86 | } |
| 87 | |
| 88 | |
| 89 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 90 | pub struct Running { |
| 91 | |
| 92 | pub seq: u64, |
| 93 | pub frozen: bool, |
| 94 | } |
| 95 | |
| 96 | |
| 97 | pub fn pick_victim(jobs: &[Running]) -> Option<usize> { |
| 98 | let unfrozen = || jobs.iter().enumerate().filter(|(_, j)| !j.frozen); |
| 99 | if unfrozen().count() < 2 { |
| 100 | return None; |
| 101 | } |
| 102 | unfrozen().max_by_key(|(_, j)| j.seq).map(|(i, _)| i) |
| 103 | } |
| 104 | |
| 105 | |
| 106 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 107 | pub struct Parked { |
| 108 | pub seq: u64, |
| 109 | |
| 110 | pub swap: u64, |
| 111 | } |
| 112 | |
| 113 | |
| 114 | |
| 115 | pub fn pick_thaw(parked: &[Parked], unfrozen_running: usize, headroom: u64) -> Option<usize> { |
| 116 | let (index, oldest) = parked.iter().enumerate().min_by_key(|(_, p)| p.seq)?; |
| 117 | (unfrozen_running == 0 || headroom >= oldest.swap).then_some(index) |
| 118 | } |
| 119 | |
| 120 | |
| 121 | |
| 122 | pub fn hot_after(cause: Cause, over_high: bool, jobs: usize) -> bool { |
| 123 | |
| 124 | jobs > 0 && (cause == Cause::Pressure || over_high) |
| 125 | } |
| 126 | |
| 127 | |
| 128 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 129 | pub struct Gate { |
| 130 | pub frozen: usize, |
| 131 | pub hot: bool, |
| 132 | } |
| 133 | |
| 134 | impl Gate { |
| 135 | pub fn open(&self) -> bool { |
| 136 | self.frozen == 0 && !self.hot |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | |
| 141 | |
| 142 | #[derive(Default)] |
| 143 | struct PauseClock { |
| 144 | total: Duration, |
| 145 | since: Option<Instant>, |
| 146 | } |
| 147 | |
| 148 | |
| 149 | pub struct JobHandle { |
| 150 | id: String, |
| 151 | name: String, |
| 152 | log: Mutex<Option<mpsc::Sender<Vec<u8>>>>, |
| 153 | requeued: AtomicBool, |
| 154 | clock: Mutex<PauseClock>, |
| 155 | } |
| 156 | |
| 157 | impl JobHandle { |
| 158 | |
| 159 | fn log_line(&self, line: &str) { |
| 160 | let guard = self.log.lock().unwrap_or_else(PoisonError::into_inner); |
| 161 | if let Some(tx) = guard.as_ref() { |
| 162 | let mut bytes = format!("runner: {line}").into_bytes(); |
| 163 | bytes.push(b'\n'); |
| 164 | let _ = tx.try_send(bytes); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | |
| 169 | pub fn paused(&self) -> Duration { |
| 170 | let clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); |
| 171 | clock.total + clock.since.map(|s| s.elapsed()).unwrap_or_default() |
| 172 | } |
| 173 | |
| 174 | fn pause(&self) { |
| 175 | let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); |
| 176 | clock.since.get_or_insert_with(Instant::now); |
| 177 | } |
| 178 | |
| 179 | |
| 180 | fn resume(&self) -> Duration { |
| 181 | let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); |
| 182 | let lasted = clock.since.take().map(|s| s.elapsed()).unwrap_or_default(); |
| 183 | clock.total += lasted; |
| 184 | lasted |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | |
| 189 | pub struct Registration { |
| 190 | handle: Arc<JobHandle>, |
| 191 | owner: Arc<Pressure>, |
| 192 | } |
| 193 | |
| 194 | impl Registration { |
| 195 | |
| 196 | pub fn requeued(&self) -> bool { |
| 197 | self.handle.requeued.load(Ordering::SeqCst) |
| 198 | } |
| 199 | |
| 200 | |
| 201 | pub fn paused(&self) -> Duration { |
| 202 | self.handle.paused() |
| 203 | } |
| 204 | |
| 205 | |
| 206 | pub fn pause_clock(&self) -> Arc<JobHandle> { |
| 207 | self.handle.clone() |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | impl Drop for Registration { |
| 212 | fn drop(&mut self) { |
| 213 | |
| 214 | *self |
| 215 | .handle |
| 216 | .log |
| 217 | .lock() |
| 218 | .unwrap_or_else(PoisonError::into_inner) = None; |
| 219 | self.owner.remove(&self.handle); |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | struct Entry { |
| 224 | handle: Arc<JobHandle>, |
| 225 | seq: u64, |
| 226 | |
| 227 | dir: Option<PathBuf>, |
| 228 | frozen: Option<Frozen>, |
| 229 | } |
| 230 | |
| 231 | struct Frozen { |
| 232 | swap: u64, |
| 233 | } |
| 234 | |
| 235 | #[derive(Default)] |
| 236 | struct State { |
| 237 | entries: Vec<Entry>, |
| 238 | gate: Gate, |
| 239 | |
| 240 | high: Option<Option<u64>>, |
| 241 | } |
| 242 | |
| 243 | |
| 244 | pub struct Pressure { |
| 245 | dir: PathBuf, |
| 246 | budget: AtomicU64, |
| 247 | state: Mutex<State>, |
| 248 | seq: AtomicU64, |
| 249 | |
| 250 | kick: Notify, |
| 251 | |
| 252 | changed: Notify, |
| 253 | } |
| 254 | |
| 255 | impl Pressure { |
| 256 | |
| 257 | |
| 258 | |
| 259 | pub async fn start(budget: u64, shutdown: CancellationToken) -> Option<Arc<Self>> { |
| 260 | let setup = tokio::task::spawn_blocking(move || { |
| 261 | let base = job_cgroup_base().map_err(|e| e.to_string())?; |
| 262 | let parent = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base)); |
| 263 | create_box(&parent, budget) |
| 264 | }) |
| 265 | .await; |
| 266 | let dir = match setup { |
| 267 | Ok(Ok(dir)) => dir, |
| 268 | Ok(Err(e)) => { |
| 269 | tracing::warn!("memory control is off: {e}"); |
| 270 | return None; |
| 271 | } |
| 272 | Err(e) => { |
| 273 | tracing::warn!("memory control is off: {e}"); |
| 274 | return None; |
| 275 | } |
| 276 | }; |
| 277 | let this = Arc::new(Self::at(dir, budget)); |
| 278 | match Watcher::open(&this.dir) { |
| 279 | Ok(watcher) => { |
| 280 | let psi = watcher.psi_armed; |
| 281 | tokio::spawn(this.clone().watch(watcher, shutdown)); |
| 282 | tracing::info!( |
| 283 | box_dir = %this.dir.display(), |
| 284 | budget = %forge_ci::size::format_size(budget), |
| 285 | psi, |
| 286 | "memory control is on" |
| 287 | ); |
| 288 | Some(this) |
| 289 | } |
| 290 | Err(e) => { |
| 291 | tracing::warn!("memory control is off, cannot watch the box: {e}"); |
| 292 | None |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | fn at(dir: PathBuf, budget: u64) -> Self { |
| 298 | Self { |
| 299 | dir, |
| 300 | budget: AtomicU64::new(budget), |
| 301 | state: Mutex::new(State::default()), |
| 302 | seq: AtomicU64::new(0), |
| 303 | kick: Notify::new(), |
| 304 | changed: Notify::new(), |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | |
| 309 | pub fn budget(&self) -> u64 { |
| 310 | self.budget.load(Ordering::SeqCst) |
| 311 | } |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | pub fn resize(&self, budget: u64) { |
| 317 | if self.budget.swap(budget, Ordering::SeqCst) == budget { |
| 318 | return; |
| 319 | } |
| 320 | |
| 321 | for file in ["memory.max", "memory.swap.max"] { |
| 322 | if let Err(e) = fs::write(self.dir.join(file), budget.to_string()) { |
| 323 | tracing::warn!("cannot resize {file} of the box: {e}"); |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | self.lock().high = None; |
| 328 | self.kick.notify_one(); |
| 329 | tracing::info!( |
| 330 | budget = %forge_ci::size::format_size(budget), |
| 331 | "memory box resized" |
| 332 | ); |
| 333 | } |
| 334 | |
| 335 | fn lock(&self) -> MutexGuard<'_, State> { |
| 336 | self.state.lock().unwrap_or_else(PoisonError::into_inner) |
| 337 | } |
| 338 | |
| 339 | |
| 340 | pub fn register( |
| 341 | self: &Arc<Self>, |
| 342 | job_id: &str, |
| 343 | job_name: &str, |
| 344 | log: mpsc::Sender<Vec<u8>>, |
| 345 | ) -> Registration { |
| 346 | let handle = Arc::new(JobHandle { |
| 347 | id: job_id.to_owned(), |
| 348 | name: job_name.to_owned(), |
| 349 | log: Mutex::new(Some(log)), |
| 350 | requeued: AtomicBool::new(false), |
| 351 | clock: Mutex::new(PauseClock::default()), |
| 352 | }); |
| 353 | self.lock().entries.push(Entry { |
| 354 | handle: handle.clone(), |
| 355 | seq: self.seq.fetch_add(1, Ordering::SeqCst), |
| 356 | dir: None, |
| 357 | frozen: None, |
| 358 | }); |
| 359 | self.kick.notify_one(); |
| 360 | Registration { |
| 361 | handle, |
| 362 | owner: self.clone(), |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | fn remove(&self, handle: &Arc<JobHandle>) { |
| 367 | self.lock() |
| 368 | .entries |
| 369 | .retain(|e| !Arc::ptr_eq(&e.handle, handle)); |
| 370 | self.kick.notify_one(); |
| 371 | } |
| 372 | |
| 373 | |
| 374 | pub fn headroom(&self) -> Option<u64> { |
| 375 | let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget()); |
| 376 | Some(max.saturating_sub(box_usage(&self.dir)?)) |
| 377 | } |
| 378 | |
| 379 | |
| 380 | pub fn gate(&self) -> Gate { |
| 381 | self.lock().gate |
| 382 | } |
| 383 | |
| 384 | |
| 385 | |
| 386 | pub async fn wait_open(&self) { |
| 387 | loop { |
| 388 | let notified = self.changed.notified(); |
| 389 | tokio::pin!(notified); |
| 390 | notified.as_mut().enable(); |
| 391 | if self.lock().gate.open() { |
| 392 | return; |
| 393 | } |
| 394 | notified.await; |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | async fn watch(self: Arc<Self>, mut watcher: Watcher, shutdown: CancellationToken) { |
| 399 | |
| 400 | let mut recheck: Option<tokio::time::Instant> = None; |
| 401 | loop { |
| 402 | let cause = tokio::select! { |
| 403 | () = shutdown.cancelled() => return, |
| 404 | () = tokio::time::sleep_until(recheck.unwrap_or_else(tokio::time::Instant::now)), |
| 405 | if recheck.is_some() => Cause::Jobs, |
| 406 | cause = watcher.rx.recv() => { |
| 407 | let Some(cause) = cause else { |
| 408 | tracing::warn!("memory control stopped, the watcher thread ended"); |
| 409 | return; |
| 410 | }; |
| 411 | cause |
| 412 | } |
| 413 | () = self.kick.notified() => Cause::Jobs, |
| 414 | }; |
| 415 | let this = self.clone(); |
| 416 | if let Err(e) = tokio::task::spawn_blocking(move || this.settle(cause)).await { |
| 417 | tracing::error!("memory control pass panicked: {e}"); |
| 418 | } |
| 419 | recheck = self |
| 420 | .lock() |
| 421 | .gate |
| 422 | .hot |
| 423 | .then(|| tokio::time::Instant::now() + PRESSURE_COOLDOWN); |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | |
| 428 | |
| 429 | fn settle(&self, cause: Cause) { |
| 430 | let mut state = self.lock(); |
| 431 | |
| 432 | |
| 433 | let mut taken: Vec<PathBuf> = state.entries.iter().filter_map(|e| e.dir.clone()).collect(); |
| 434 | for entry in &mut state.entries { |
| 435 | if entry.dir.is_none() |
| 436 | && let Some(dir) = find_job_dir(&self.dir, &entry.handle.id, &taken) |
| 437 | { |
| 438 | taken.push(dir.clone()); |
| 439 | |
| 440 | let _ = fs::write(dir.join("memory.oom.group"), "1"); |
| 441 | entry.dir = Some(dir); |
| 442 | } |
| 443 | } |
| 444 | let mut parked_now = false; |
| 445 | if cause == Cause::Pressure { |
| 446 | let live: Vec<usize> = (0..state.entries.len()) |
| 447 | .filter(|&i| is_live(&state.entries[i])) |
| 448 | .collect(); |
| 449 | let running: Vec<Running> = live |
| 450 | .iter() |
| 451 | .map(|&i| Running { |
| 452 | seq: state.entries[i].seq, |
| 453 | frozen: false, |
| 454 | }) |
| 455 | .collect(); |
| 456 | if let Some(pick) = pick_victim(&running) { |
| 457 | let victim = live[pick]; |
| 458 | let waiting_for = live |
| 459 | .iter() |
| 460 | .filter(|&&i| i != victim) |
| 461 | .min_by_key(|&&i| state.entries[i].seq) |
| 462 | .map(|&i| state.entries[i].handle.name.clone()) |
| 463 | .unwrap_or_default(); |
| 464 | park(&mut state.entries[victim], &waiting_for); |
| 465 | parked_now = true; |
| 466 | } |
| 467 | } |
| 468 | if !parked_now { |
| 469 | self.thaw_one(&mut state); |
| 470 | } |
| 471 | let unfrozen = state.entries.iter().filter(|e| is_live(e)).count(); |
| 472 | let high = high_value(unfrozen, self.budget()); |
| 473 | if state.high != Some(high) { |
| 474 | let text = high.map_or_else(|| "max".to_owned(), |b| b.to_string()); |
| 475 | match fs::write(self.dir.join("memory.high"), text) { |
| 476 | Ok(()) => state.high = Some(high), |
| 477 | Err(e) => tracing::warn!("cannot set memory.high of the box: {e}"), |
| 478 | } |
| 479 | } |
| 480 | let over_high = high.is_some_and(|h| box_usage(&self.dir).is_some_and(|u| u >= h)); |
| 481 | state.gate = Gate { |
| 482 | frozen: state.entries.iter().filter(|e| e.frozen.is_some()).count(), |
| 483 | hot: hot_after(cause, over_high, state.entries.len()), |
| 484 | }; |
| 485 | drop(state); |
| 486 | self.changed.notify_waiters(); |
| 487 | } |
| 488 | |
| 489 | fn thaw_one(&self, state: &mut State) { |
| 490 | let parked: Vec<(usize, Parked)> = state |
| 491 | .entries |
| 492 | .iter() |
| 493 | .enumerate() |
| 494 | .filter_map(|(i, e)| { |
| 495 | let frozen = e.frozen.as_ref()?; |
| 496 | let swap = e.dir.as_deref().and_then(job_swap).unwrap_or(frozen.swap); |
| 497 | Some((i, Parked { seq: e.seq, swap })) |
| 498 | }) |
| 499 | .collect(); |
| 500 | let running = state.entries.iter().filter(|e| is_live(e)).count(); |
| 501 | |
| 502 | |
| 503 | |
| 504 | let below_high = high_value(running + 1, self.budget()).unwrap_or(0); |
| 505 | let headroom = box_usage(&self.dir) |
| 506 | .map_or(0, |usage| below_high.saturating_sub(usage)) |
| 507 | .saturating_sub(HIGH_MARGIN_MIN); |
| 508 | let list: Vec<Parked> = parked.iter().map(|(_, p)| *p).collect(); |
| 509 | let Some(pick) = pick_thaw(&list, running, headroom) else { |
| 510 | return; |
| 511 | }; |
| 512 | let entry = &mut state.entries[parked[pick].0]; |
| 513 | let Some(dir) = entry.dir.clone() else { |
| 514 | return; |
| 515 | }; |
| 516 | |
| 517 | let _ = fs::write(dir.join("memory.swap.max"), "0"); |
| 518 | if let Err(e) = fs::write(dir.join("cgroup.freeze"), "0") { |
| 519 | tracing::warn!(job_id = %entry.handle.id, "cannot thaw job: {e}"); |
| 520 | return; |
| 521 | } |
| 522 | entry.frozen = None; |
| 523 | let lasted = entry.handle.resume(); |
| 524 | entry |
| 525 | .handle |
| 526 | .log_line(&format!("resumed after {}", format_duration(lasted))); |
| 527 | tracing::info!(job_id = %entry.handle.id, "job resumed"); |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | |
| 532 | |
| 533 | fn is_live(entry: &Entry) -> bool { |
| 534 | entry.dir.is_some() && entry.frozen.is_none() && !entry.handle.requeued.load(Ordering::SeqCst) |
| 535 | } |
| 536 | |
| 537 | |
| 538 | |
| 539 | fn park(entry: &mut Entry, waiting_for: &str) { |
| 540 | let Some(dir) = entry.dir.clone() else { |
| 541 | return; |
| 542 | }; |
| 543 | let handle = entry.handle.clone(); |
| 544 | let before = read_u64(&dir, "memory.current").unwrap_or(0); |
| 545 | let anon = stat_field(&dir, "anon").unwrap_or(before); |
| 546 | let swap_free = swap_free_bytes(); |
| 547 | if swap_free.is_some_and(|free| free < anon) { |
| 548 | give_back(entry, "the host has no swap room for it"); |
| 549 | return; |
| 550 | } |
| 551 | |
| 552 | let _ = fs::write(dir.join("memory.swap.max"), "max"); |
| 553 | if let Err(e) = fs::write(dir.join("cgroup.freeze"), "1") { |
| 554 | tracing::warn!(job_id = %handle.id, "cannot freeze job: {e}"); |
| 555 | give_back(entry, "it cannot be frozen"); |
| 556 | return; |
| 557 | } |
| 558 | handle.pause(); |
| 559 | handle.log_line(&format!( |
| 560 | "paused: memory pressure, waiting for {waiting_for}" |
| 561 | )); |
| 562 | let mut after = before; |
| 563 | for _ in 0..RECLAIM_ATTEMPTS { |
| 564 | reclaim(&dir, before); |
| 565 | after = read_u64(&dir, "memory.current").unwrap_or(before); |
| 566 | if after <= before / 2 { |
| 567 | break; |
| 568 | } |
| 569 | } |
| 570 | if after > before / 2 { |
| 571 | let _ = fs::write(dir.join("cgroup.freeze"), "0"); |
| 572 | handle.resume(); |
| 573 | give_back(entry, "its memory would not go to swap"); |
| 574 | return; |
| 575 | } |
| 576 | let swap = job_swap(&dir).unwrap_or(0); |
| 577 | handle.log_line(&format!("parked {} MiB in swap", swap >> 20)); |
| 578 | tracing::info!(job_id = %handle.id, swap, "job parked in swap"); |
| 579 | entry.frozen = Some(Frozen { swap }); |
| 580 | } |
| 581 | |
| 582 | |
| 583 | |
| 584 | fn reclaim(dir: &Path, bytes: u64) { |
| 585 | let file = dir.join("memory.reclaim"); |
| 586 | match fs::write(&file, format!("{bytes} swappiness={SWAPPINESS}")) { |
| 587 | Err(e) if e.kind() == io::ErrorKind::InvalidInput => { |
| 588 | let _ = fs::write(&file, bytes.to_string()); |
| 589 | } |
| 590 | _ => {} |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | |
| 595 | |
| 596 | fn give_back(entry: &mut Entry, why: &str) { |
| 597 | entry.handle.requeued.store(true, Ordering::SeqCst); |
| 598 | entry.handle.log_line(&format!( |
| 599 | "memory pressure and {why}: stopping this job to run it again later" |
| 600 | )); |
| 601 | tracing::warn!(job_id = %entry.handle.id, "{why}, killing job to requeue it"); |
| 602 | if let Some(dir) = &entry.dir { |
| 603 | |
| 604 | let _ = fs::write(dir.join("cgroup.freeze"), "0"); |
| 605 | kill_cgroup(dir); |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | |
| 610 | |
| 611 | |
| 612 | fn find_job_dir(box_dir: &Path, job_id: &str, taken: &[PathBuf]) -> Option<PathBuf> { |
| 613 | let prefix = format!("forge-job-{job_id}-"); |
| 614 | fs::read_dir(box_dir) |
| 615 | .ok()? |
| 616 | .flatten() |
| 617 | .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix)) |
| 618 | .map(|e| e.path()) |
| 619 | .find(|path| !taken.contains(path)) |
| 620 | } |
| 621 | |
| 622 | |
| 623 | fn read_u64(dir: &Path, file: &str) -> Option<u64> { |
| 624 | fs::read_to_string(dir.join(file)).ok()?.trim().parse().ok() |
| 625 | } |
| 626 | |
| 627 | fn stat_field(dir: &Path, key: &str) -> Option<u64> { |
| 628 | let text = fs::read_to_string(dir.join("memory.stat")).ok()?; |
| 629 | text.lines().find_map(|line| { |
| 630 | let (k, v) = line.split_once(' ')?; |
| 631 | (k == key).then(|| v.trim().parse().ok())? |
| 632 | }) |
| 633 | } |
| 634 | |
| 635 | fn job_swap(dir: &Path) -> Option<u64> { |
| 636 | read_u64(dir, "memory.swap.current") |
| 637 | } |
| 638 | |
| 639 | |
| 640 | |
| 641 | fn box_usage(dir: &Path) -> Option<u64> { |
| 642 | let current = read_u64(dir, "memory.current")?; |
| 643 | Some(current.saturating_sub(stat_field(dir, "inactive_file").unwrap_or(0))) |
| 644 | } |
| 645 | |
| 646 | |
| 647 | fn swap_free_bytes() -> Option<u64> { |
| 648 | let text = fs::read_to_string("/proc/meminfo").ok()?; |
| 649 | let line = text.lines().find(|l| l.starts_with("SwapFree:"))?; |
| 650 | line.split_whitespace() |
| 651 | .nth(1)? |
| 652 | .parse::<u64>() |
| 653 | .ok()? |
| 654 | .checked_mul(1024) |
| 655 | } |
| 656 | |
| 657 | fn format_duration(d: Duration) -> String { |
| 658 | let secs = d.as_secs(); |
| 659 | if secs >= 60 { |
| 660 | format!("{}m {}s", secs / 60, secs % 60) |
| 661 | } else { |
| 662 | format!("{secs}s") |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | pub fn create_box(parent: &Path, budget: u64) -> Result<PathBuf, String> { |
| 671 | let dir = parent.join(BOX_NAME); |
| 672 | match fs::create_dir(&dir) { |
| 673 | Ok(()) => {} |
| 674 | Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} |
| 675 | Err(e) => return Err(format!("cannot create {}: {e}", dir.display())), |
| 676 | } |
| 677 | remove_leftovers(&dir); |
| 678 | enable_controllers(parent)?; |
| 679 | enable_controllers(&dir)?; |
| 680 | let set = |file: &str, value: String| { |
| 681 | fs::write(dir.join(file), value).map_err(|e| format!("cannot set {file} on the box: {e}")) |
| 682 | }; |
| 683 | set("memory.max", budget.to_string())?; |
| 684 | |
| 685 | set("memory.swap.max", budget.to_string())?; |
| 686 | set("memory.high", "max".to_owned())?; |
| 687 | Ok(dir) |
| 688 | } |
| 689 | |
| 690 | |
| 691 | |
| 692 | fn remove_leftovers(box_dir: &Path) { |
| 693 | let Ok(children) = fs::read_dir(box_dir) else { |
| 694 | return; |
| 695 | }; |
| 696 | for child in children.flatten() { |
| 697 | let path = child.path(); |
| 698 | if !path.is_dir() { |
| 699 | continue; |
| 700 | } |
| 701 | let _ = fs::write(path.join("cgroup.freeze"), "0"); |
| 702 | kill_cgroup(&path); |
| 703 | for _ in 0..LEFTOVER_POLLS { |
| 704 | if fs::remove_dir(&path).is_ok() || !path.exists() { |
| 705 | break; |
| 706 | } |
| 707 | std::thread::sleep(LEFTOVER_POLL); |
| 708 | } |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | |
| 713 | fn enable_controllers(dir: &Path) -> Result<(), String> { |
| 714 | let file = dir.join("cgroup.subtree_control"); |
| 715 | let have = |
| 716 | fs::read_to_string(&file).map_err(|e| format!("cannot read {}: {e}", file.display()))?; |
| 717 | let missing: Vec<String> = CONTROLLERS |
| 718 | .iter() |
| 719 | .filter(|c| !have.split_whitespace().any(|h| h == **c)) |
| 720 | .map(|c| format!("+{c}")) |
| 721 | .collect(); |
| 722 | if missing.is_empty() { |
| 723 | return Ok(()); |
| 724 | } |
| 725 | fs::write(&file, missing.join(" ")).map_err(|e| { |
| 726 | format!( |
| 727 | "cannot enable {} in {} (the controllers are not delegated): {e}", |
| 728 | missing.join(" "), |
| 729 | file.display() |
| 730 | ) |
| 731 | }) |
| 732 | } |
| 733 | |
| 734 | |
| 735 | |
| 736 | |
| 737 | |
| 738 | |
| 739 | struct Watcher { |
| 740 | rx: mpsc::UnboundedReceiver<Cause>, |
| 741 | psi_armed: bool, |
| 742 | _stop: OwnedFd, |
| 743 | } |
| 744 | |
| 745 | impl Watcher { |
| 746 | fn open(box_dir: &Path) -> Result<Self, String> { |
| 747 | let inotify = Inotify::init(InitFlags::IN_NONBLOCK | InitFlags::IN_CLOEXEC) |
| 748 | .map_err(|e| format!("inotify: {e}"))?; |
| 749 | inotify |
| 750 | .add_watch(&box_dir.join("memory.events"), AddWatchFlags::IN_MODIFY) |
| 751 | .map_err(|e| format!("watching memory.events: {e}"))?; |
| 752 | |
| 753 | inotify |
| 754 | .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE) |
| 755 | .map_err(|e| format!("watching the box: {e}"))?; |
| 756 | let psi = match arm_psi(box_dir) { |
| 757 | Ok(file) => Some(file), |
| 758 | Err(e) => { |
| 759 | tracing::warn!("no PSI trigger on the box, using memory.events only: {e}"); |
| 760 | None |
| 761 | } |
| 762 | }; |
| 763 | let psi_armed = psi.is_some(); |
| 764 | let (stop_rx, stop_tx) = pipe().map_err(|e| format!("stop pipe: {e}"))?; |
| 765 | let (tx, rx) = mpsc::unbounded_channel(); |
| 766 | let events_path = box_dir.join("memory.events"); |
| 767 | std::thread::Builder::new() |
| 768 | .name("forge-memory-watch".to_owned()) |
| 769 | .spawn(move || watch_thread(&inotify, psi, &stop_rx, &events_path, &tx)) |
| 770 | .map_err(|e| format!("watcher thread: {e}"))?; |
| 771 | Ok(Self { |
| 772 | rx, |
| 773 | psi_armed, |
| 774 | _stop: stop_tx, |
| 775 | }) |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | fn watch_thread( |
| 780 | inotify: &Inotify, |
| 781 | mut psi: Option<File>, |
| 782 | stop: &OwnedFd, |
| 783 | events_path: &Path, |
| 784 | tx: &mpsc::UnboundedSender<Cause>, |
| 785 | ) { |
| 786 | let read_high = || fs::read_to_string(events_path).map(|t| parse_high(&t)).ok(); |
| 787 | let mut last_high = read_high().unwrap_or(0); |
| 788 | loop { |
| 789 | let (stopped, inotify_ready, psi_ready, psi_broken) = { |
| 790 | let mut fds = vec![ |
| 791 | PollFd::new(inotify.as_fd(), PollFlags::POLLIN), |
| 792 | PollFd::new(stop.as_fd(), PollFlags::POLLIN), |
| 793 | ]; |
| 794 | if let Some(file) = &psi { |
| 795 | fds.push(PollFd::new(file.as_fd(), PollFlags::POLLPRI)); |
| 796 | } |
| 797 | match poll(&mut fds, PollTimeout::NONE) { |
| 798 | Ok(_) => {} |
| 799 | Err(Errno::EINTR) => continue, |
| 800 | Err(e) => { |
| 801 | tracing::warn!("memory control stopped, poll failed: {e}"); |
| 802 | return; |
| 803 | } |
| 804 | } |
| 805 | let flags = |i: usize| { |
| 806 | fds.get(i) |
| 807 | .and_then(PollFd::revents) |
| 808 | .unwrap_or_else(PollFlags::empty) |
| 809 | }; |
| 810 | ( |
| 811 | !flags(1).is_empty(), |
| 812 | flags(0).contains(PollFlags::POLLIN), |
| 813 | flags(2).contains(PollFlags::POLLPRI), |
| 814 | flags(2).intersects(PollFlags::POLLERR | PollFlags::POLLNVAL), |
| 815 | ) |
| 816 | }; |
| 817 | if stopped { |
| 818 | return; |
| 819 | } |
| 820 | let mut cause = None; |
| 821 | if inotify_ready { |
| 822 | let mut modified = false; |
| 823 | loop { |
| 824 | match inotify.read_events() { |
| 825 | Ok(batch) => { |
| 826 | modified |= batch |
| 827 | .iter() |
| 828 | .any(|e| e.mask.contains(AddWatchFlags::IN_MODIFY)); |
| 829 | } |
| 830 | Err(Errno::EAGAIN) => break, |
| 831 | Err(e) => { |
| 832 | tracing::warn!("cannot read inotify events: {e}"); |
| 833 | break; |
| 834 | } |
| 835 | } |
| 836 | } |
| 837 | let high = read_high().unwrap_or(last_high); |
| 838 | let moved = modified && high > last_high; |
| 839 | last_high = high; |
| 840 | cause = Some(if moved { Cause::Pressure } else { Cause::Jobs }); |
| 841 | } |
| 842 | if psi_broken { |
| 843 | tracing::warn!("memory pressure trigger failed, using memory.events only"); |
| 844 | psi = None; |
| 845 | } else if psi_ready { |
| 846 | cause = Some(Cause::Pressure); |
| 847 | } |
| 848 | if let Some(cause) = cause |
| 849 | && tx.send(cause).is_err() |
| 850 | { |
| 851 | return; |
| 852 | } |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | fn arm_psi(box_dir: &Path) -> io::Result<File> { |
| 857 | let mut file = OpenOptions::new() |
| 858 | .read(true) |
| 859 | .write(true) |
| 860 | .custom_flags(nix::libc::O_NONBLOCK) |
| 861 | .open(box_dir.join("memory.pressure"))?; |
| 862 | file.write_all(format!("{PSI_TRIGGER}\0").as_bytes())?; |
| 863 | Ok(file) |
| 864 | } |
| 865 | |
| 866 | #[cfg(test)] |
| 867 | mod tests { |
| 868 | use super::*; |
| 869 | |
| 870 | const GIB: u64 = 1 << 30; |
| 871 | |
| 872 | #[test] |
| 873 | fn parses_the_high_counter() { |
| 874 | let text = "low 0\nhigh 8\nmax 0\noom 0\noom_kill 0\n"; |
| 875 | assert_eq!(parse_high(text), 8); |
| 876 | assert_eq!(parse_high("low 0\nmax 1\n"), 0); |
| 877 | assert_eq!(parse_high(""), 0); |
| 878 | assert_eq!(parse_high("high x\n"), 0); |
| 879 | } |
| 880 | |
| 881 | #[test] |
| 882 | fn resize_follows_a_changed_budget() { |
| 883 | let (_tmp, pressure) = fake_box(2 * GIB); |
| 884 | fs::write(pressure.dir.join("memory.swap.max"), "0").expect("swap"); |
| 885 | pressure.resize(3 * GIB); |
| 886 | assert_eq!(pressure.budget(), 3 * GIB); |
| 887 | assert_eq!(read_u64(&pressure.dir, "memory.max"), Some(3 * GIB)); |
| 888 | assert_eq!(read_u64(&pressure.dir, "memory.swap.max"), Some(3 * GIB)); |
| 889 | assert_eq!(pressure.lock().high, None); |
| 890 | } |
| 891 | |
| 892 | #[test] |
| 893 | fn high_applies_only_to_two_or_more_unfrozen_jobs() { |
| 894 | assert_eq!(high_value(0, 6 * GIB), None); |
| 895 | assert_eq!(high_value(1, 6 * GIB), None); |
| 896 | |
| 897 | assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN)); |
| 898 | |
| 899 | assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB)); |
| 900 | } |
| 901 | |
| 902 | #[test] |
| 903 | fn victim_is_the_youngest_unfrozen_with_a_partner() { |
| 904 | let job = |seq, frozen| Running { seq, frozen }; |
| 905 | assert_eq!(pick_victim(&[]), None); |
| 906 | assert_eq!(pick_victim(&[job(1, false)]), None); |
| 907 | assert_eq!(pick_victim(&[job(1, false), job(2, false)]), Some(1)); |
| 908 | assert_eq!( |
| 909 | pick_victim(&[job(5, false), job(2, false), job(9, true)]), |
| 910 | Some(0) |
| 911 | ); |
| 912 | |
| 913 | assert_eq!(pick_victim(&[job(1, false), job(2, true)]), None); |
| 914 | } |
| 915 | |
| 916 | #[test] |
| 917 | fn thaw_is_the_oldest_when_there_is_room_or_nothing_runs() { |
| 918 | let parked = [ |
| 919 | Parked { seq: 7, swap: GIB }, |
| 920 | Parked { |
| 921 | seq: 3, |
| 922 | swap: 2 * GIB, |
| 923 | }, |
| 924 | ]; |
| 925 | assert_eq!(pick_thaw(&[], 0, 10 * GIB), None); |
| 926 | |
| 927 | assert_eq!(pick_thaw(&parked, 1, 3 * GIB), Some(1)); |
| 928 | assert_eq!(pick_thaw(&parked, 1, GIB), None); |
| 929 | |
| 930 | assert_eq!(pick_thaw(&parked, 0, 0), Some(1)); |
| 931 | } |
| 932 | |
| 933 | #[test] |
| 934 | fn gate_closes_for_parked_jobs_and_pressure() { |
| 935 | assert!(Gate::default().open()); |
| 936 | assert!( |
| 937 | !Gate { |
| 938 | frozen: 1, |
| 939 | hot: false |
| 940 | } |
| 941 | .open() |
| 942 | ); |
| 943 | assert!( |
| 944 | !Gate { |
| 945 | frozen: 0, |
| 946 | hot: true |
| 947 | } |
| 948 | .open() |
| 949 | ); |
| 950 | |
| 951 | assert!(hot_after(Cause::Pressure, false, 1)); |
| 952 | assert!(!hot_after(Cause::Jobs, false, 1)); |
| 953 | assert!(hot_after(Cause::Jobs, true, 1)); |
| 954 | assert!(!hot_after(Cause::Pressure, false, 0)); |
| 955 | } |
| 956 | |
| 957 | |
| 958 | fn fake_box(budget: u64) -> (tempfile::TempDir, Arc<Pressure>) { |
| 959 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 960 | let dir = tmp.path().to_path_buf(); |
| 961 | fs::write(dir.join("memory.max"), budget.to_string()).expect("max"); |
| 962 | fs::write(dir.join("memory.current"), "0").expect("current"); |
| 963 | (tmp, Arc::new(Pressure::at(dir, budget))) |
| 964 | } |
| 965 | |
| 966 | fn fake_job(box_dir: &Path, id: &str, current: u64) -> PathBuf { |
| 967 | let dir = box_dir.join(format!("forge-job-{id}-1")); |
| 968 | fs::create_dir(&dir).expect("job dir"); |
| 969 | fs::write(dir.join("memory.current"), current.to_string()).expect("current"); |
| 970 | fs::write(dir.join("memory.stat"), format!("anon {current}\n")).expect("stat"); |
| 971 | dir |
| 972 | } |
| 973 | |
| 974 | #[test] |
| 975 | fn settle_sets_high_for_two_jobs_and_relaxes_it_for_one() { |
| 976 | let (tmp, pressure) = fake_box(6 * GIB); |
| 977 | let (tx, _rx) = mpsc::channel(8); |
| 978 | let a = pressure.register("a", "build", tx.clone()); |
| 979 | let b = pressure.register("b", "test", tx); |
| 980 | fake_job(tmp.path(), "a", GIB); |
| 981 | fake_job(tmp.path(), "b", GIB); |
| 982 | pressure.settle(Cause::Jobs); |
| 983 | let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high"); |
| 984 | assert_eq!(high, (6 * GIB - HIGH_MARGIN_MIN).to_string()); |
| 985 | drop(b); |
| 986 | pressure.settle(Cause::Jobs); |
| 987 | let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high"); |
| 988 | assert_eq!(high, "max"); |
| 989 | assert!(!a.requeued()); |
| 990 | } |
| 991 | |
| 992 | #[test] |
| 993 | fn pressure_with_a_lone_job_does_nothing_but_close_the_gate() { |
| 994 | let (tmp, pressure) = fake_box(6 * GIB); |
| 995 | let (tx, mut rx) = mpsc::channel(8); |
| 996 | let a = pressure.register("a", "build", tx); |
| 997 | let dir = fake_job(tmp.path(), "a", GIB); |
| 998 | pressure.settle(Cause::Pressure); |
| 999 | assert!(!a.requeued()); |
| 1000 | assert!(!dir.join("cgroup.freeze").exists()); |
| 1001 | assert!(rx.try_recv().is_err()); |
| 1002 | assert!(!pressure.lock().gate.open()); |
| 1003 | |
| 1004 | drop(a); |
| 1005 | pressure.settle(Cause::Jobs); |
| 1006 | assert!(pressure.lock().gate.open()); |
| 1007 | } |
| 1008 | |
| 1009 | #[test] |
| 1010 | fn a_job_that_cannot_be_parked_is_killed_for_requeue() { |
| 1011 | |
| 1012 | let (tmp, pressure) = fake_box(6 * GIB); |
| 1013 | let (tx_a, _rx_a) = mpsc::channel(8); |
| 1014 | let (tx_b, mut rx_b) = mpsc::channel(8); |
| 1015 | let a = pressure.register("a", "build", tx_a); |
| 1016 | let b = pressure.register("b", "test", tx_b); |
| 1017 | fake_job(tmp.path(), "a", 2 * GIB); |
| 1018 | let dir_b = fake_job(tmp.path(), "b", 2 * GIB); |
| 1019 | |
| 1020 | fs::write(dir_b.join("memory.stat"), "anon 1\n").expect("stat"); |
| 1021 | pressure.settle(Cause::Jobs); |
| 1022 | pressure.settle(Cause::Pressure); |
| 1023 | |
| 1024 | assert!(b.requeued()); |
| 1025 | assert!(!a.requeued()); |
| 1026 | assert_eq!( |
| 1027 | fs::read_to_string(dir_b.join("cgroup.kill")).expect("kill"), |
| 1028 | "1" |
| 1029 | ); |
| 1030 | let mut lines = String::new(); |
| 1031 | while let Ok(bytes) = rx_b.try_recv() { |
| 1032 | lines.push_str(&String::from_utf8_lossy(&bytes)); |
| 1033 | } |
| 1034 | assert!(lines.contains("paused: memory pressure, waiting for build")); |
| 1035 | assert!(lines.contains("run it again later")); |
| 1036 | |
| 1037 | assert_eq!( |
| 1038 | fs::read_to_string(tmp.path().join("memory.high")).expect("high"), |
| 1039 | "max" |
| 1040 | ); |
| 1041 | } |
| 1042 | |
| 1043 | #[test] |
| 1044 | fn a_registration_tracks_pause_time_and_drops_its_log() { |
| 1045 | let (_tmp, pressure) = fake_box(GIB); |
| 1046 | let (tx, mut rx) = mpsc::channel(8); |
| 1047 | let reg = pressure.register("a", "build", tx); |
| 1048 | assert_eq!(reg.paused(), Duration::ZERO); |
| 1049 | reg.handle.pause(); |
| 1050 | std::thread::sleep(Duration::from_millis(5)); |
| 1051 | assert!(reg.paused() > Duration::ZERO); |
| 1052 | let lasted = reg.handle.resume(); |
| 1053 | assert!(lasted > Duration::ZERO); |
| 1054 | assert!(reg.paused() >= lasted); |
| 1055 | drop(reg); |
| 1056 | |
| 1057 | assert!(matches!( |
| 1058 | rx.try_recv(), |
| 1059 | Err(mpsc::error::TryRecvError::Disconnected) |
| 1060 | )); |
| 1061 | } |
| 1062 | |
| 1063 | #[test] |
| 1064 | fn create_box_enables_controllers_and_sets_limits() { |
| 1065 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1066 | let parent = tmp.path(); |
| 1067 | fs::write(parent.join("cgroup.subtree_control"), "memory pids\n").expect("parent"); |
| 1068 | fs::create_dir(parent.join(BOX_NAME)).expect("box dir"); |
| 1069 | fs::write(parent.join(BOX_NAME).join("cgroup.subtree_control"), "").expect("box"); |
| 1070 | let dir = create_box(parent, 4 * GIB).expect("box"); |
| 1071 | assert_eq!(dir, parent.join(BOX_NAME)); |
| 1072 | |
| 1073 | assert_eq!( |
| 1074 | fs::read_to_string(dir.join("memory.max")).expect("max"), |
| 1075 | (4 * GIB).to_string() |
| 1076 | ); |
| 1077 | assert_eq!( |
| 1078 | fs::read_to_string(dir.join("memory.swap.max")).expect("swap"), |
| 1079 | (4 * GIB).to_string() |
| 1080 | ); |
| 1081 | assert_eq!( |
| 1082 | fs::read_to_string(dir.join("memory.high")).expect("high"), |
| 1083 | "max" |
| 1084 | ); |
| 1085 | assert_eq!( |
| 1086 | fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"), |
| 1087 | "+cpu" |
| 1088 | ); |
| 1089 | |
| 1090 | assert!(create_box(parent, 4 * GIB).is_ok()); |
| 1091 | } |
| 1092 | |
| 1093 | #[tokio::test] |
| 1094 | async fn wait_open_returns_at_once_on_an_open_gate_and_wakes_on_change() { |
| 1095 | let (_tmp, pressure) = fake_box(GIB); |
| 1096 | pressure.wait_open().await; |
| 1097 | pressure.lock().gate.hot = true; |
| 1098 | let waiter = { |
| 1099 | let p = pressure.clone(); |
| 1100 | tokio::spawn(async move { p.wait_open().await }) |
| 1101 | }; |
| 1102 | tokio::task::yield_now().await; |
| 1103 | assert!(!waiter.is_finished()); |
| 1104 | pressure.lock().gate.hot = false; |
| 1105 | pressure.changed.notify_waiters(); |
| 1106 | tokio::time::timeout(Duration::from_secs(5), waiter) |
| 1107 | .await |
| 1108 | .expect("woken") |
| 1109 | .expect("join"); |
| 1110 | } |
| 1111 | |
| 1112 | |
| 1113 | |
| 1114 | |
| 1115 | #[tokio::test] |
| 1116 | #[ignore = "needs delegated cgroup v2 controllers"] |
| 1117 | async fn real_box_starts_and_reports_headroom() { |
| 1118 | let shutdown = CancellationToken::new(); |
| 1119 | let Some(pressure) = Pressure::start(2 * GIB, shutdown.clone()).await else { |
| 1120 | eprintln!("no delegated memory controller, skipping"); |
| 1121 | return; |
| 1122 | }; |
| 1123 | assert!(pressure.headroom().is_some()); |
| 1124 | pressure.wait_open().await; |
| 1125 | shutdown.cancel(); |
| 1126 | |
| 1127 | tokio::time::sleep(Duration::from_millis(100)).await; |
| 1128 | let _ = fs::remove_dir(&pressure.dir); |
| 1129 | } |
| 1130 | |
| 1131 | |
| 1132 | |
| 1133 | const ALLOCATOR: &str = r#" |
| 1134 | import sys, time, hashlib |
| 1135 | mib = int(sys.argv[1]); step = 50 |
| 1136 | sys.stdin.readline() |
| 1137 | chunks = []; sums = [] |
| 1138 | done = 0 |
| 1139 | while done < mib: |
| 1140 | n = min(step, mib - done) |
| 1141 | pat = bytes(((done + j * 7) % 251) for j in range(4096)) |
| 1142 | c = bytearray(pat * (n * 256)) |
| 1143 | chunks.append(c); sums.append(hashlib.sha256(c).hexdigest()) |
| 1144 | done += n |
| 1145 | time.sleep(0.25) |
| 1146 | # hold the memory for a while, then verify every chunk |
| 1147 | time.sleep(float(sys.argv[2])) |
| 1148 | for c, s in zip(chunks, sums): |
| 1149 | if hashlib.sha256(c).hexdigest() != s: |
| 1150 | print("CHECKSUM MISMATCH"); sys.exit(3) |
| 1151 | print("ok") |
| 1152 | "#; |
| 1153 | |
| 1154 | fn mib(bytes: Option<u64>) -> u64 { |
| 1155 | bytes.unwrap_or(0) >> 20 |
| 1156 | } |
| 1157 | |
| 1158 | |
| 1159 | |
| 1160 | |
| 1161 | |
| 1162 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1163 | #[ignore = "needs delegated cgroup v2 controllers, swap and python3"] |
| 1164 | async fn real_two_jobs_one_is_parked_in_swap_and_both_finish() { |
| 1165 | use std::process::Stdio; |
| 1166 | use tokio::io::AsyncWriteExt; |
| 1167 | use tokio::process::Command; |
| 1168 | |
| 1169 | let started = Instant::now(); |
| 1170 | let shutdown = CancellationToken::new(); |
| 1171 | let Some(pressure) = Pressure::start(GIB, shutdown.clone()).await else { |
| 1172 | eprintln!("no delegated memory controller, skipping"); |
| 1173 | return; |
| 1174 | }; |
| 1175 | |
| 1176 | let probe = Watcher::open(&pressure.dir).expect("watcher"); |
| 1177 | let psi_armed = probe.psi_armed; |
| 1178 | drop(probe); |
| 1179 | eprintln!("PSI trigger armed: {psi_armed}"); |
| 1180 | assert!(psi_armed, "PSI trigger must arm on this host"); |
| 1181 | |
| 1182 | let mut jobs = Vec::new(); |
| 1183 | for (id, hold) in [("e2e1", "6"), ("e2e2", "1")] { |
| 1184 | let (tx, mut rx) = mpsc::channel::<Vec<u8>>(64); |
| 1185 | tokio::spawn(async move { |
| 1186 | while let Some(line) = rx.recv().await { |
| 1187 | eprint!("[log] {}", String::from_utf8_lossy(&line)); |
| 1188 | } |
| 1189 | }); |
| 1190 | let registration = pressure.register(id, id, tx); |
| 1191 | let dir = pressure.dir.join(format!("forge-job-{id}-1")); |
| 1192 | fs::create_dir(&dir).expect("job cgroup"); |
| 1193 | fs::write(dir.join("memory.swap.max"), "0").expect("swap.max"); |
| 1194 | let mut child = Command::new("python3") |
| 1195 | .args(["-I", "-c", ALLOCATOR, "700", hold]) |
| 1196 | .stdin(Stdio::piped()) |
| 1197 | .stdout(Stdio::piped()) |
| 1198 | .kill_on_drop(true) |
| 1199 | .spawn() |
| 1200 | .expect("python3"); |
| 1201 | let pid = child.id().expect("pid"); |
| 1202 | fs::write(dir.join("cgroup.procs"), pid.to_string()).expect("join cgroup"); |
| 1203 | let mut stdin = child.stdin.take().expect("stdin"); |
| 1204 | stdin.write_all(b"go\n").await.expect("go"); |
| 1205 | jobs.push((id, dir, child, Some(registration), stdin)); |
| 1206 | |
| 1207 | tokio::time::sleep(Duration::from_secs(2)).await; |
| 1208 | } |
| 1209 | |
| 1210 | |
| 1211 | let mut parked_seen = false; |
| 1212 | let mut before_park = 0; |
| 1213 | let mut at_park = (0, 0); |
| 1214 | let mut park_at = None; |
| 1215 | let mut thaw_at = None; |
| 1216 | let mut peak_box = 0; |
| 1217 | let mut results: Vec<Option<std::process::ExitStatus>> = vec![None, None]; |
| 1218 | let deadline = Instant::now() + Duration::from_secs(150); |
| 1219 | while results.iter().any(Option::is_none) { |
| 1220 | assert!(Instant::now() < deadline, "jobs did not finish in time"); |
| 1221 | let box_cur = read_u64(&pressure.dir, "memory.current").unwrap_or(0); |
| 1222 | peak_box = peak_box.max(box_cur); |
| 1223 | for (i, (id, dir, child, registration, _)) in jobs.iter_mut().enumerate() { |
| 1224 | if results[i].is_none() |
| 1225 | && let Some(status) = child.try_wait().expect("wait") |
| 1226 | { |
| 1227 | eprintln!("{} job {id} exited: {status}", started.elapsed().as_secs()); |
| 1228 | results[i] = Some(status); |
| 1229 | |
| 1230 | drop(registration.take()); |
| 1231 | } |
| 1232 | if i == 1 && results[i].is_none() { |
| 1233 | let frozen = fs::read_to_string(dir.join("cgroup.events")) |
| 1234 | .is_ok_and(|t| t.contains("frozen 1")); |
| 1235 | let cur = read_u64(dir, "memory.current"); |
| 1236 | if frozen && !parked_seen && mib(cur) < 350 { |
| 1237 | parked_seen = true; |
| 1238 | park_at = Some(Instant::now()); |
| 1239 | at_park = (mib(cur), mib(job_swap(dir))); |
| 1240 | eprintln!( |
| 1241 | "{}s job2 parked: memory.current {} MiB, swap {} MiB (was {} MiB)", |
| 1242 | started.elapsed().as_secs(), |
| 1243 | at_park.0, |
| 1244 | at_park.1, |
| 1245 | before_park |
| 1246 | ); |
| 1247 | } |
| 1248 | if !frozen && parked_seen && thaw_at.is_none() { |
| 1249 | thaw_at = Some(Instant::now()); |
| 1250 | eprintln!("{}s job2 thawed", started.elapsed().as_secs()); |
| 1251 | } |
| 1252 | if !frozen && !parked_seen { |
| 1253 | before_park = before_park.max(mib(cur)); |
| 1254 | } |
| 1255 | } |
| 1256 | } |
| 1257 | tokio::time::sleep(Duration::from_millis(100)).await; |
| 1258 | } |
| 1259 | eprintln!( |
| 1260 | "peak box memory.current {} MiB, parked for {:?}", |
| 1261 | peak_box >> 20, |
| 1262 | park_at.zip(thaw_at).map(|(a, b)| b - a) |
| 1263 | ); |
| 1264 | |
| 1265 | let mut oom = Vec::new(); |
| 1266 | for (id, dir, _, _, _) in &jobs { |
| 1267 | let events = fs::read_to_string(dir.join("memory.events")).unwrap_or_default(); |
| 1268 | eprintln!("job {id} memory.events: {}", events.replace('\n', " ")); |
| 1269 | if events |
| 1270 | .lines() |
| 1271 | .any(|l| l.starts_with("oom_kill ") && !l.ends_with(" 0")) |
| 1272 | { |
| 1273 | oom.push(id.to_string()); |
| 1274 | } |
| 1275 | } |
| 1276 | let box_events = fs::read_to_string(pressure.dir.join("memory.events")).unwrap_or_default(); |
| 1277 | eprintln!("box memory.events: {}", box_events.replace('\n', " ")); |
| 1278 | |
| 1279 | |
| 1280 | shutdown.cancel(); |
| 1281 | for (_, dir, mut child, registration, _) in jobs { |
| 1282 | let _ = child.start_kill(); |
| 1283 | let _ = child.wait().await; |
| 1284 | drop(registration); |
| 1285 | for _ in 0..50 { |
| 1286 | if fs::remove_dir(&dir).is_ok() { |
| 1287 | break; |
| 1288 | } |
| 1289 | tokio::time::sleep(Duration::from_millis(50)).await; |
| 1290 | } |
| 1291 | } |
| 1292 | tokio::time::sleep(Duration::from_millis(200)).await; |
| 1293 | let _ = fs::remove_dir(&pressure.dir); |
| 1294 | |
| 1295 | assert!(oom.is_empty(), "oom_kill in {oom:?}"); |
| 1296 | assert!(parked_seen, "the youngest job was never parked in swap"); |
| 1297 | assert!( |
| 1298 | at_park.1 > 100, |
| 1299 | "parked job holds {} MiB in swap", |
| 1300 | at_park.1 |
| 1301 | ); |
| 1302 | assert!(thaw_at.is_some(), "the parked job never thawed"); |
| 1303 | for r in results { |
| 1304 | assert!( |
| 1305 | r.expect("exited").success(), |
| 1306 | "a job failed or its checksum broke" |
| 1307 | ); |
| 1308 | } |
| 1309 | } |
| 1310 | } |