use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::time::Duration; use crate::executor::kill_cgroup; use crate::sandbox::{BOX_NAME, job_cgroup_base}; const CGROUP_ROOT: &str = "/sys/fs/cgroup"; const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"]; const LEFTOVER_POLLS: u32 = 50; const LEFTOVER_POLL: Duration = Duration::from_millis(100); pub fn start_box(size: u64) -> Result { let base = job_cgroup_base().map_err(|e| e.to_string())?; let parent = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base)); create_box(&parent, size) } pub fn create_box(parent: &Path, size: u64) -> Result { let dir = parent.join(BOX_NAME); match fs::create_dir(&dir) { Ok(()) => {} Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} Err(e) => return Err(format!("cannot create {}: {e}", dir.display())), } remove_leftovers(&dir); enable_controllers(parent)?; enable_controllers(&dir)?; let _ = fs::write(dir.join("memory.high"), "max"); let _ = fs::write(dir.join("memory.swap.max"), "max"); fs::write(dir.join("memory.max"), size.to_string()) .map_err(|e| format!("cannot set memory.max on the box: {e}"))?; Ok(dir) } fn remove_leftovers(box_dir: &Path) { let Ok(children) = fs::read_dir(box_dir) else { return; }; for child in children.flatten() { let path = child.path(); if !path.is_dir() { continue; } kill_cgroup(&path); for _ in 0..LEFTOVER_POLLS { if fs::remove_dir(&path).is_ok() || !path.exists() { break; } std::thread::sleep(LEFTOVER_POLL); } } } fn enable_controllers(dir: &Path) -> Result<(), String> { let file = dir.join("cgroup.subtree_control"); let have = fs::read_to_string(&file).map_err(|e| format!("cannot read {}: {e}", file.display()))?; let missing: Vec = CONTROLLERS .iter() .filter(|c| !have.split_whitespace().any(|h| h == **c)) .map(|c| format!("+{c}")) .collect(); if missing.is_empty() { return Ok(()); } fs::write(&file, missing.join(" ")).map_err(|e| { format!( "cannot enable {} in {} (the controllers are not delegated): {e}", missing.join(" "), file.display() ) }) } #[cfg(test)] mod tests { use super::*; const GIB: u64 = 1 << 30; #[test] fn create_box_enables_controllers_and_sets_limits() { let tmp = tempfile::tempdir().expect("tempdir"); let parent = tmp.path(); fs::write(parent.join("cgroup.subtree_control"), "memory pids\n").expect("parent"); fs::create_dir(parent.join(BOX_NAME)).expect("box dir"); fs::write(parent.join(BOX_NAME).join("cgroup.subtree_control"), "").expect("box"); let dir = create_box(parent, 4 * GIB).expect("box"); assert_eq!(dir, parent.join(BOX_NAME)); assert_eq!( fs::read_to_string(dir.join("memory.max")).expect("max"), (4 * GIB).to_string() ); assert_eq!( fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"), "+cpu" ); assert!(create_box(parent, 4 * GIB).is_ok()); } }