| 1 | use forge_ci::size::parse_size; |
| 2 | |
| 3 | use crate::config::Limits; |
| 4 | |
| 5 | const MIN_BOX: u64 = 512 << 20; |
| 6 | const FALLBACK_TOTAL: u64 = 8 << 30; |
| 7 | |
| 8 | #[derive(Default)] |
| 9 | pub struct Meminfo { |
| 10 | pub total: Option<u64>, |
| 11 | pub available: Option<u64>, |
| 12 | } |
| 13 | |
| 14 | pub fn meminfo(text: &str) -> Meminfo { |
| 15 | let find = |key: &str| { |
| 16 | let line = text.lines().find(|l| l.starts_with(key))?; |
| 17 | let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; |
| 18 | kib.checked_mul(1024) |
| 19 | }; |
| 20 | Meminfo { |
| 21 | total: find("MemTotal:"), |
| 22 | available: find("MemAvailable:"), |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | pub fn host_total() -> Option<u64> { |
| 27 | std::fs::read_to_string("/proc/meminfo") |
| 28 | .ok() |
| 29 | .and_then(|t| meminfo(&t).total) |
| 30 | } |
| 31 | |
| 32 | pub fn box_size_of(mem_total: u64, headroom: u64) -> u64 { |
| 33 | mem_total.saturating_sub(headroom).max(MIN_BOX) |
| 34 | } |
| 35 | |
| 36 | pub fn box_size(limits: &Limits) -> u64 { |
| 37 | let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); |
| 38 | box_size_of(host_total().unwrap_or(FALLBACK_TOTAL), headroom) |
| 39 | } |
| 40 | |
| 41 | #[cfg(test)] |
| 42 | mod tests { |
| 43 | use super::*; |
| 44 | |
| 45 | const GIB: u64 = 1 << 30; |
| 46 | |
| 47 | #[test] |
| 48 | fn box_is_host_memory_minus_headroom_with_a_floor() { |
| 49 | assert_eq!(box_size_of(8 * GIB, GIB), 7 * GIB); |
| 50 | assert_eq!(box_size_of(GIB, 2 * GIB), MIN_BOX); |
| 51 | } |
| 52 | |
| 53 | #[test] |
| 54 | fn meminfo_is_parsed() { |
| 55 | let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nMemAvailable: 4000000 kB\n"; |
| 56 | let m = meminfo(text); |
| 57 | assert_eq!(m.total, Some(7_971_680 * 1024)); |
| 58 | assert_eq!(m.available, Some(4_000_000 * 1024)); |
| 59 | assert_eq!(meminfo("").total, None); |
| 60 | } |
| 61 | } |