use forge_ci::size::parse_size; use crate::config::Limits; const MIN_BOX: u64 = 512 << 20; const FALLBACK_TOTAL: u64 = 8 << 30; #[derive(Default)] pub struct Meminfo { pub total: Option, pub available: Option, } pub fn meminfo(text: &str) -> Meminfo { let find = |key: &str| { let line = text.lines().find(|l| l.starts_with(key))?; let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; kib.checked_mul(1024) }; Meminfo { total: find("MemTotal:"), available: find("MemAvailable:"), } } pub fn host_total() -> Option { std::fs::read_to_string("/proc/meminfo") .ok() .and_then(|t| meminfo(&t).total) } pub fn box_size_of(mem_total: u64, headroom: u64) -> u64 { mem_total.saturating_sub(headroom).max(MIN_BOX) } pub fn box_size(limits: &Limits) -> u64 { let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); box_size_of(host_total().unwrap_or(FALLBACK_TOTAL), headroom) } #[cfg(test)] mod tests { use super::*; const GIB: u64 = 1 << 30; #[test] fn box_is_host_memory_minus_headroom_with_a_floor() { assert_eq!(box_size_of(8 * GIB, GIB), 7 * GIB); assert_eq!(box_size_of(GIB, 2 * GIB), MIN_BOX); } #[test] fn meminfo_is_parsed() { let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nMemAvailable: 4000000 kB\n"; let m = meminfo(text); assert_eq!(m.total, Some(7_971_680 * 1024)); assert_eq!(m.available, Some(4_000_000 * 1024)); assert_eq!(meminfo("").total, None); } }