use std::fmt;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use super::fleet::member::SoftCaps;
use crate::runtime::identity::EngineInfo;
pub const ENGINE_TTL: Duration = Duration::from_secs(60);
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Caps {
pub cpus: Option<u64>,
pub mem: Option<u64>,
pub disk: Option<u64>,
pub instances: Option<u64>,
}
impl Caps {
pub fn of(soft: &SoftCaps) -> Option<Caps> {
let size = |s: &Option<String>| s.as_deref().and_then(|s| parse_size(s).ok());
let caps = Caps { cpus: soft.cpus, mem: size(&soft.mem), disk: size(&soft.disk), instances: soft.instances };
(caps != Caps::default()).then_some(caps)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Capacity {
pub cpus: Option<u64>,
pub mem_total: Option<u64>,
pub mem_available: Option<u64>,
pub disk_free: Option<u64>,
pub disk_total: Option<u64>,
pub running: usize,
pub caps: Option<Caps>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Own {
pub caps: SoftCaps,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct HostFacts {
pub mem_available: Option<u64>,
pub disk_free: Option<u64>,
pub disk_total: Option<u64>,
}
impl HostFacts {
pub fn read(engine: Option<&EngineInfo>) -> HostFacts {
let Some(engine) = engine.filter(|e| e.native && cfg!(target_os = "linux")) else {
return HostFacts::default();
};
let mem_available = std::fs::read_to_string("/proc/meminfo").ok().and_then(|t| parse_meminfo(&t));
let (disk_free, disk_total) = engine.root_dir.as_deref().and_then(statvfs).map_or((None, None), |(f, t)| (Some(f), Some(t)));
HostFacts { mem_available, disk_free, disk_total }
}
}
impl Capacity {
pub fn build(engine: Option<&EngineInfo>, host: HostFacts, running: usize, own: &Own) -> Capacity {
Capacity {
cpus: engine.and_then(|e| e.cpus),
mem_total: engine.and_then(|e| e.mem_total),
mem_available: host.mem_available,
disk_free: host.disk_free,
disk_total: host.disk_total,
running,
caps: Caps::of(&own.caps),
}
}
pub fn with_own(self, own: &Own) -> Capacity {
Capacity { caps: Caps::of(&own.caps), ..self }
}
}
pub type EngineInfoFn = Arc<dyn Fn() -> Result<EngineInfo> + Send + Sync>;
pub struct HostCapacity {
engine: Mutex<EngineCache>,
running: AtomicUsize,
info: EngineInfoFn,
}
impl HostCapacity {
pub fn new(info: EngineInfoFn) -> HostCapacity {
HostCapacity { engine: Mutex::default(), running: AtomicUsize::new(0), info }
}
pub fn set_running(&self, running: usize) {
self.running.store(running, Ordering::Release);
}
pub fn report(&self, own: &Own) -> Capacity {
let info = self.engine.lock().unwrap_or_else(|e| e.into_inner()).get(Instant::now(), || (self.info)()).cloned();
Capacity::build(info.as_ref(), HostFacts::read(info.as_ref()), self.running.load(Ordering::Acquire), own)
}
}
#[derive(Debug, Default)]
pub struct EngineCache {
last: Option<(Instant, Option<EngineInfo>)>,
}
impl EngineCache {
pub fn get(&mut self, now: Instant, fetch: impl FnOnce() -> Result<EngineInfo>) -> Option<&EngineInfo> {
let due = self.last.as_ref().is_none_or(|(at, _)| now >= *at + ENGINE_TTL);
if due {
let prev = self.last.take().and_then(|(_, info)| info);
self.last = Some((now, fetch().ok().or(prev)));
}
self.last.as_ref().and_then(|(_, info)| info.as_ref())
}
}
pub fn parse_meminfo(text: &str) -> Option<u64> {
let line = text.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?;
let mut words = line.split_whitespace();
let n: u64 = words.next()?.parse().ok()?;
match words.next() {
Some("kB") => n.checked_mul(1024),
None => Some(n),
Some(_) => None,
}
}
fn statvfs(path: &Path) -> Option<(u64, u64)> {
use std::os::unix::ffi::OsStrExt;
let c = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
return None;
}
let frsize = st.f_frsize as u64;
Some((st.f_bavail as u64 * frsize, st.f_blocks as u64 * frsize))
}
pub fn parse_size(text: &str) -> Result<u64> {
let t = text.trim();
let split = t.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(t.len());
let (num, unit) = t.split_at(split);
let value: f64 = match num.parse() {
Ok(v) if num.chars().next().is_some_and(|c| c.is_ascii_digit()) => v,
_ => bail!("`{text}` isn't a size (like `16G`)"),
};
let unit = unit.trim().to_ascii_lowercase();
let unit = unit.trim_end_matches('b').trim_end_matches('i');
let shift = match unit {
"" => 0,
"k" => 10,
"m" => 20,
"g" => 30,
"t" => 40,
_ => bail!("`{text}` isn't a size (like `16G`)"),
};
Ok((value * (1u64 << shift) as f64) as u64)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Over {
pub item: CapItem,
pub used: u64,
pub cap: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CapItem {
Mem,
Disk,
Instances,
}
impl CapItem {
pub fn as_str(self) -> &'static str {
match self {
CapItem::Mem => "mem",
CapItem::Disk => "disk",
CapItem::Instances => "instances",
}
}
}
impl fmt::Display for Over {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.item {
CapItem::Instances => write!(f, "instances {}/{}", self.used, self.cap),
item => write!(f, "{} {}/{}", item.as_str(), size(self.used), size(self.cap)),
}
}
}
pub fn over_caps(c: &Capacity) -> Vec<Over> {
let Some(caps) = &c.caps else { return Vec::new() };
let used = |total: Option<u64>, free: Option<u64>| Some(total?.saturating_sub(free?));
[
(CapItem::Mem, used(c.mem_total, c.mem_available), caps.mem),
(CapItem::Disk, used(c.disk_total, c.disk_free), caps.disk),
(CapItem::Instances, Some(c.running as u64), caps.instances),
]
.into_iter()
.filter_map(|(item, used, cap)| {
let (used, cap) = (used?, cap?);
(used > cap).then_some(Over { item, used, cap })
})
.collect()
}
pub fn over_note(c: &Capacity) -> Option<String> {
let over = over_caps(c);
(!over.is_empty()).then(|| format!("over cap: {}", over.iter().map(Over::to_string).collect::<Vec<_>>().join(", ")))
}
pub fn summary(c: Option<&Capacity>) -> String {
let Some(c) = c else { return "-".into() };
let mut parts = Vec::new();
if let Some(n) = c.cpus {
parts.push(format!("{n} cpu"));
}
match (c.mem_total, c.mem_available) {
(Some(total), Some(avail)) => {
let unit = unit_of(total);
parts.push(format!("{}/{}{}", number(total.saturating_sub(avail), unit), number(total, unit), UNITS[unit]));
}
(Some(total), None) => parts.push(size(total)),
_ => {}
}
if let Some(free) = c.disk_free {
parts.push(format!("{} free", size(free)));
}
parts.push(format!("{} run", c.running));
parts.join(" · ")
}
const UNITS: [&str; 5] = ["B", "K", "M", "G", "T"];
fn unit_of(bytes: u64) -> usize {
let mut unit = 0;
while unit < UNITS.len() - 1 && bytes >= 1u64 << (10 * (unit + 1)) {
unit += 1;
}
unit
}
fn number(bytes: u64, unit: usize) -> String {
let v = bytes as f64 / (1u64 << (10 * unit)) as f64;
if v >= 10.0 || unit == 0 {
format!("{v:.0}")
} else {
let s = format!("{v:.1}");
s.strip_suffix(".0").map(str::to_string).unwrap_or(s)
}
}
pub fn size(bytes: u64) -> String {
let unit = unit_of(bytes);
format!("{}{}", number(bytes, unit), UNITS[unit])
}
#[cfg(test)]
mod tests {
use super::*;
const G: u64 = 1 << 30;
#[test]
fn the_host_report_on_demand() {
let asked = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&asked);
let host = HostCapacity::new(Arc::new(move || {
counted.fetch_add(1, Ordering::SeqCst);
Ok(EngineInfo { cpus: Some(4), mem_total: Some(8 * G), root_dir: None, native: false })
}));
host.set_running(2);
let capped = Own { caps: SoftCaps { cpus: Some(2), ..SoftCaps::default() } };
let r = host.report(&capped);
assert_eq!((r.cpus, r.mem_total, r.mem_available, r.running), (Some(4), Some(8 * G), None, 2));
assert_eq!(r.caps.as_ref().and_then(|c| c.cpus), Some(2));
assert_eq!(host.report(&Own::default()).caps, None);
assert_eq!(asked.load(Ordering::SeqCst), 1, "cached");
assert_eq!(r.clone().with_own(&capped), r.clone());
assert_eq!(r.clone().with_own(&Own::default()), Capacity { caps: None, ..r });
let down = HostCapacity::new(Arc::new(|| bail!("no runtime")));
down.set_running(1);
assert_eq!(down.report(&Own::default()), Capacity { running: 1, ..Capacity::default() });
}
#[test]
fn meminfo_gives_mem_available_in_bytes() {
let text = "MemTotal: 32582664 kB\nMemFree: 1234567 kB\nMemAvailable: 12582912 kB\nBuffers: 123 kB\n";
assert_eq!(parse_meminfo(text), Some(12 * G));
assert_eq!(parse_meminfo("MemTotal: 1 kB\n"), None, "an old kernel without it");
assert_eq!(parse_meminfo("MemAvailable: x kB\n"), None);
assert_eq!(parse_meminfo("MemAvailable: 5 MB\n"), None);
assert_eq!(parse_meminfo(""), None);
}
#[test]
fn sizes_parse_in_binary_units() {
assert_eq!(parse_size("16G").unwrap(), 16 * G);
assert_eq!(parse_size("16GiB").unwrap(), 16 * G);
assert_eq!(parse_size("16 gb").unwrap(), 16 * G);
assert_eq!(parse_size("1.5T").unwrap(), 1536 * G);
assert_eq!(parse_size("512M").unwrap(), 512 << 20);
assert_eq!(parse_size("4096").unwrap(), 4096);
for bad in ["", "G", "lots", "-1G", "16X", ".5G", "1.2.3G"] {
assert!(parse_size(bad).is_err(), "{bad:?}");
}
}
#[test]
fn sizes_print_short() {
assert_eq!(size(18 * G), "18G");
assert_eq!(size(3 * G / 2), "1.5G");
assert_eq!(size(8 * G), "8G");
assert_eq!(size(512 << 20), "512M");
assert_eq!(size(2048 * G), "2T");
assert_eq!(size(100), "100B");
}
#[test]
fn the_engine_cache_asks_every_ttl_and_keeps_the_last_answer() {
let info = |cpus| EngineInfo { cpus: Some(cpus), ..EngineInfo::default() };
let mut cache = EngineCache::default();
let t0 = Instant::now();
assert_eq!(cache.get(t0, || Ok(info(4))).unwrap().cpus, Some(4));
let never = || -> Result<EngineInfo> { panic!("asked within the ttl") };
assert_eq!(cache.get(t0 + ENGINE_TTL - Duration::from_millis(1), never).unwrap().cpus, Some(4));
assert_eq!(cache.get(t0 + ENGINE_TTL, || Ok(info(8))).unwrap().cpus, Some(8));
let t1 = t0 + 2 * ENGINE_TTL;
assert_eq!(cache.get(t1, || bail!("down")).unwrap().cpus, Some(8));
assert_eq!(cache.get(t1 + Duration::from_secs(1), never).unwrap().cpus, Some(8));
let mut empty = EngineCache::default();
assert!(empty.get(t0, || bail!("down")).is_none());
}
fn own(caps: SoftCaps) -> Own {
Own { caps }
}
#[test]
fn the_report_from_its_parts() {
let engine = EngineInfo { cpus: Some(8), mem_total: Some(32 * G), root_dir: None, native: true };
let host = HostFacts { mem_available: Some(20 * G), disk_free: Some(120 * G), disk_total: Some(500 * G) };
let soft = SoftCaps { mem: Some("16G".into()), instances: Some(3), ..SoftCaps::default() };
let c = Capacity::build(Some(&engine), host, 3, &own(soft));
assert_eq!(
c,
Capacity {
cpus: Some(8),
mem_total: Some(32 * G),
mem_available: Some(20 * G),
disk_free: Some(120 * G),
disk_total: Some(500 * G),
running: 3,
caps: Some(Caps { cpus: None, mem: Some(16 * G), disk: None, instances: Some(3) }),
}
);
assert_eq!(summary(Some(&c)), "8 cpu · 12/32G · 120G free · 3 run");
let bare = Capacity::build(None, HostFacts::default(), 0, &Own::default());
assert_eq!((bare.cpus, bare.caps.as_ref()), (None, None));
assert_eq!(summary(Some(&bare)), "0 run");
assert_eq!(summary(None), "-");
let vm = Capacity { mem_total: Some(8 * G), ..bare.clone() };
assert_eq!(summary(Some(&vm)), "8G · 0 run");
assert_eq!(Capacity::build(None, HostFacts::default(), 0, &own(SoftCaps::default())).caps, None);
let vm_engine = EngineInfo { native: false, root_dir: Some("/".into()), ..engine };
assert_eq!(HostFacts::read(Some(&vm_engine)), HostFacts::default());
assert_eq!(HostFacts::read(None), HostFacts::default());
}
#[cfg(target_os = "linux")]
#[test]
fn host_facts_read_this_hosts_memory_and_the_roots_disk() {
let engine = EngineInfo { native: true, root_dir: Some(std::env::temp_dir()), ..EngineInfo::default() };
let facts = HostFacts::read(Some(&engine));
assert!(facts.mem_available.is_some_and(|m| m > 0), "{facts:?}");
let (free, total) = (facts.disk_free.unwrap(), facts.disk_total.unwrap());
assert!(total > 0 && free <= total, "{facts:?}");
let gone = EngineInfo { root_dir: Some("/nonexistent/devsandbox".into()), ..engine };
assert_eq!(HostFacts::read(Some(&gone)).disk_free, None);
}
#[test]
fn npm_typings_match() {
use crate::serve::dts::assert_matches;
let caps = Caps { cpus: Some(4), mem: Some(G), disk: None, instances: Some(2) };
let c = Capacity { caps: Some(caps), ..Capacity::default() };
let v = serde_json::to_value(&c).unwrap();
assert_matches("Capacity", &v);
assert_matches("Caps", &v["caps"]);
assert!(v.get("lending").is_none());
assert_eq!(crate::serve::dts::prop_type("InstancesSnapshot", "capacity").as_deref(), Some("Capacity"));
}
#[test]
fn over_caps_lists_each_exceeded_cap() {
let c = Capacity {
mem_total: Some(32 * G),
mem_available: Some(14 * G),
disk_free: Some(400 * G),
disk_total: Some(500 * G),
running: 4,
caps: Some(Caps { cpus: Some(2), mem: Some(16 * G), disk: Some(200 * G), instances: Some(3) }),
..Capacity::default()
};
let over = over_caps(&c);
assert_eq!(
over,
[Over { item: CapItem::Mem, used: 18 * G, cap: 16 * G }, Over { item: CapItem::Instances, used: 4, cap: 3 }]
);
assert_eq!(over_note(&c).as_deref(), Some("over cap: mem 18G/16G, instances 4/3"));
let at = Capacity { running: 3, mem_available: None, ..c.clone() };
assert_eq!(over_caps(&at), []);
let disk = Capacity { disk_free: Some(100 * G), ..at.clone() };
assert_eq!(over_note(&disk).as_deref(), Some("over cap: disk 400G/200G"));
assert_eq!(over_note(&Capacity { caps: None, ..c }), None);
}
}