use std::cmp::Ordering;
use std::fmt;
use serde_json::Value;
use crate::serve::capacity::{Capacity, over_caps, over_note};
use crate::serve::snapshots::{LinkState, Machine, Routed};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MachineRef {
Local,
Machine(String),
}
impl fmt::Display for MachineRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MachineRef::Local => f.write_str("this host"),
MachineRef::Machine(name) => f.write_str(name),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Spec {
pub sandbox: String,
pub config_hash: Option<String>,
pub build_hash: Option<String>,
pub repo: Option<String>,
pub requester: MachineRef,
pub pinned: Option<MachineRef>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
pub machine: MachineRef,
pub reachable: bool,
pub capacity: Option<Capacity>,
pub has_image: bool,
pub has_repo: bool,
}
impl Candidate {
pub fn local<'a>(spec: &Spec, capacity: Option<Capacity>, roots: impl IntoIterator<Item = &'a Value>) -> Candidate {
Candidate {
machine: MachineRef::Local,
reachable: true,
capacity,
has_image: has_image(spec, roots),
has_repo: false,
}
}
pub fn from_machine(spec: &Spec, m: &Machine) -> Candidate {
Candidate {
machine: MachineRef::Machine(m.name.clone()),
reachable: reachable(m.state),
capacity: m.capacity(),
has_image: has_image(spec, m.rows.values().map(|v| v.as_ref())),
has_repo: false,
}
}
pub fn from_routed(r: &Routed) -> Candidate {
Candidate {
machine: MachineRef::Machine(r.name.clone()),
reachable: reachable(r.state),
capacity: r.capacity.clone(),
has_image: false,
has_repo: false,
}
}
}
pub fn reachable(state: LinkState) -> bool {
state == LinkState::Connected
}
pub fn has_image<'a>(spec: &Spec, roots: impl IntoIterator<Item = &'a Value>) -> bool {
let Some(config_hash) = spec.config_hash.as_deref().filter(|h| !h.is_empty()) else { return false };
let str_of = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);
roots.into_iter().any(|snap| {
let rows = |k: &str| snap.get(k).and_then(Value::as_array).into_iter().flatten();
rows("sandboxes").any(|s| {
let matches = str_of(s, "name").as_deref() == Some(&spec.sandbox)
&& str_of(s, "config_hash").as_deref() == Some(config_hash)
&& spec.build_hash.as_ref().is_none_or(|b| str_of(s, "build_hash").as_ref() == Some(b));
let root = str_of(s, "root").or_else(|| str_of(snap, "dir"));
matches
&& root.is_some()
&& rows("instances").any(|i| {
str_of(i, "sandbox").as_deref() == Some(&spec.sandbox)
&& str_of(i, "root") == root
&& i.get("drift").and_then(Value::as_bool) == Some(false)
&& i.get("phase").is_none_or(Value::is_null)
})
})
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Placement {
pub machine: MachineRef,
pub warnings: Vec<String>,
pub score: i64,
pub reasons: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NoPlace {
UnknownPin(MachineRef),
PinUnreachable(MachineRef),
NoCandidate(Vec<(MachineRef, &'static str)>),
}
impl fmt::Display for NoPlace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NoPlace::UnknownPin(m) => write!(f, "no machine `{m}`"),
NoPlace::PinUnreachable(m) => write!(f, "{m} is unreachable"),
NoPlace::NoCandidate(skipped) if skipped.is_empty() => f.write_str("no machine to place on"),
NoPlace::NoCandidate(skipped) => {
let why: Vec<String> = skipped.iter().map(|(m, why)| format!("{m}: {why}")).collect();
write!(f, "no machine takes new work ({})", why.join(", "))
}
}
}
}
impl std::error::Error for NoPlace {}
pub const NEUTRAL: i64 = 50;
pub const W_MEM: i64 = 3;
pub const W_DISK: i64 = 2;
pub const W_SLOTS: i64 = 2;
pub const W_CPU: i64 = 1;
pub const OVER: i64 = 2000;
pub const IMAGE: i64 = 300;
pub const REPO: i64 = 150;
pub const REQUESTER: i64 = 50;
pub fn place(spec: &Spec, candidates: &[Candidate]) -> Result<Placement, NoPlace> {
if let Some(pin) = &spec.pinned {
let c = candidates.iter().find(|c| &c.machine == pin).ok_or_else(|| NoPlace::UnknownPin(pin.clone()))?;
if !c.reachable {
return Err(NoPlace::PinUnreachable(pin.clone()));
}
return Ok(scored(spec, c));
}
let mut skipped = Vec::new();
let mut best: Option<Placement> = None;
for c in candidates {
if !c.reachable {
skipped.push((c.machine.clone(), "unreachable"));
continue;
}
let p = scored(spec, c);
let better = best.as_ref().is_none_or(|b| match p.score.cmp(&b.score) {
Ordering::Greater => true,
Ordering::Equal => p.machine < b.machine,
Ordering::Less => false,
});
if better {
best = Some(p);
}
}
best.ok_or(NoPlace::NoCandidate(skipped))
}
fn scored(spec: &Spec, c: &Candidate) -> Placement {
let (score, reasons) = score(spec, c);
let warnings = c.capacity.as_ref().and_then(over_note).into_iter().map(|n| format!("{}: {n}", c.machine)).collect();
Placement { machine: c.machine.clone(), warnings, score, reasons }
}
pub fn score(spec: &Spec, c: &Candidate) -> (i64, Vec<String>) {
let mut reasons = Vec::new();
let mut total = 0;
let h = headroom(c.capacity.as_ref());
for (name, w, pts) in [("mem", W_MEM, h.mem), ("disk", W_DISK, h.disk), ("slots", W_SLOTS, h.slots), ("cpu", W_CPU, h.cpu)] {
match pts {
Some(p) => {
total += w * p;
reasons.push(format!("{name} {p}% free"));
}
None => total += w * NEUTRAL,
}
}
if let Some(cap) = &c.capacity {
let over = over_caps(cap);
total -= OVER * over.len() as i64;
if let Some(note) = over_note(cap) {
reasons.push(note);
}
} else {
reasons.push("no capacity report".into());
}
if c.has_image {
total += IMAGE;
reasons.push("image built".into());
}
if c.has_repo {
total += REPO;
reasons.push("repo there".into());
}
if c.machine == spec.requester {
total += REQUESTER;
reasons.push("requester's host".into());
}
(total, reasons)
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Headroom {
mem: Option<i64>,
disk: Option<i64>,
slots: Option<i64>,
cpu: Option<i64>,
}
fn headroom(c: Option<&Capacity>) -> Headroom {
let Some(c) = c else { return Headroom::default() };
let caps = c.caps.clone().unwrap_or_default();
let pct = |num: u64, den: u64| (den > 0).then(|| (num.min(den) as u128 * 100 / den as u128) as i64);
let room = |used: Option<u64>, cap: Option<u64>| pct(cap?.saturating_sub(used?), cap?);
let min = |a: Option<i64>, b: Option<i64>| match (a, b) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
let used = |total: Option<u64>, free: Option<u64>| Some(total?.saturating_sub(free?));
let running = c.running as u64;
let cpus = match (c.cpus, caps.cpus) {
(Some(n), Some(cap)) => Some(n.min(cap)),
(n, cap) => n.or(cap),
};
Headroom {
mem: min(c.mem_total.zip(c.mem_available).and_then(|(t, a)| pct(a, t)), room(used(c.mem_total, c.mem_available), caps.mem)),
disk: min(c.disk_total.zip(c.disk_free).and_then(|(t, f)| pct(f, t)), room(used(c.disk_total, c.disk_free), caps.disk)),
slots: room(Some(running), caps.instances),
cpu: cpus.and_then(|n| pct(n.saturating_sub(running), n)),
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
use serde_json::json;
use super::*;
use crate::serve::capacity::Caps;
use crate::serve::machines::MachineKind;
const G: u64 = 1 << 30;
fn m(name: &str) -> MachineRef {
MachineRef::Machine(name.into())
}
fn spec() -> Spec {
Spec {
sandbox: "web".into(),
config_hash: Some("c1".into()),
build_hash: None,
repo: None,
requester: MachineRef::Local,
pinned: None,
}
}
fn cap(avail: u64, free_disk: u64, running: usize) -> Capacity {
Capacity {
cpus: Some(8),
mem_total: Some(32 * G),
mem_available: Some(avail * G),
disk_free: Some(free_disk * G),
disk_total: Some(500 * G),
running,
caps: None,
}
}
fn cand(machine: MachineRef, capacity: Option<Capacity>) -> Candidate {
Candidate { machine, reachable: true, capacity, has_image: false, has_repo: false }
}
fn over_mem(c: Capacity) -> Capacity {
Capacity { caps: Some(Caps { mem: Some(16 * G), ..Caps::default() }), ..c }
}
#[test]
fn the_rules() {
struct Case {
name: &'static str,
spec: Spec,
candidates: Vec<Candidate>,
want: Result<MachineRef, NoPlace>,
warnings: &'static [&'static str],
}
let local = || cand(MachineRef::Local, Some(cap(16, 250, 2)));
let roomy = || cand(m("big"), Some(cap(28, 450, 0)));
let pinned = |p: MachineRef| Spec { pinned: Some(p), ..spec() };
let cases = vec![
Case { name: "more headroom wins", spec: spec(), candidates: vec![local(), roomy()], want: Ok(m("big")), warnings: &[] },
Case {
name: "the requester's bias breaks a near tie",
spec: spec(),
candidates: vec![cand(MachineRef::Local, Some(cap(16, 250, 2))), cand(m("a"), Some(cap(16, 250, 2)))],
want: Ok(MachineRef::Local),
warnings: &[],
},
Case {
name: "a remote requester's own host",
spec: Spec { requester: m("b"), ..spec() },
candidates: vec![local(), cand(m("b"), Some(cap(16, 250, 2)))],
want: Ok(m("b")),
warnings: &[],
},
Case {
name: "an exact tie goes to the lowest name",
spec: Spec { requester: m("nobody"), ..spec() },
candidates: vec![cand(m("b"), Some(cap(16, 250, 2))), cand(m("a"), Some(cap(16, 250, 2)))],
want: Ok(m("a")),
warnings: &[],
},
Case {
name: "this host sorts before any machine in a tie",
spec: Spec { requester: m("nobody"), ..spec() },
candidates: vec![cand(m("a"), None), cand(MachineRef::Local, None)],
want: Ok(MachineRef::Local),
warnings: &[],
},
Case {
name: "an image built beats more headroom",
spec: spec(),
candidates: vec![roomy(), Candidate { has_image: true, ..local() }],
want: Ok(MachineRef::Local),
warnings: &[],
},
Case {
name: "a repo there tips a close call",
spec: Spec { requester: m("nobody"), ..spec() },
candidates: vec![cand(m("a"), Some(cap(20, 250, 1))), Candidate { has_repo: true, ..cand(m("b"), Some(cap(16, 250, 2))) }],
want: Ok(m("b")),
warnings: &[],
},
Case {
name: "over a cap ranks below in-cap, even with its image",
spec: spec(),
candidates: vec![Candidate { has_image: true, ..cand(MachineRef::Local, Some(over_mem(cap(4, 250, 2)))) }, cand(m("small"), Some(cap(2, 10, 7)))],
want: Ok(m("small")),
warnings: &[],
},
Case {
name: "all over cap: the best, warned",
spec: spec(),
candidates: vec![cand(MachineRef::Local, Some(over_mem(cap(14, 250, 2)))), cand(m("a"), Some(over_mem(cap(4, 250, 2))))],
want: Ok(MachineRef::Local),
warnings: &["this host: over cap: mem 18G/16G"],
},
Case {
name: "unknown capacity is neutral, not zero",
spec: Spec { requester: m("nobody"), ..spec() },
candidates: vec![cand(m("a"), Some(cap(4, 40, 6))), cand(m("b"), None)],
want: Ok(m("b")),
warnings: &[],
},
Case {
name: "unknown capacity loses to plenty",
spec: Spec { requester: m("nobody"), ..spec() },
candidates: vec![cand(m("a"), Some(cap(28, 450, 0))), cand(m("b"), None)],
want: Ok(m("a")),
warnings: &[],
},
Case {
name: "an unreachable machine takes no new work",
spec: spec(),
candidates: vec![
Candidate { reachable: false, ..cand(m("gone"), Some(cap(30, 490, 0))) },
local(),
],
want: Ok(MachineRef::Local),
warnings: &[],
},
Case {
name: "nothing takes new work",
spec: spec(),
candidates: vec![Candidate { reachable: false, ..roomy() }, Candidate { reachable: false, ..local() }],
want: Err(NoPlace::NoCandidate(vec![(m("big"), "unreachable"), (MachineRef::Local, "unreachable")])),
warnings: &[],
},
Case {
name: "no candidates",
spec: spec(),
candidates: vec![],
want: Err(NoPlace::NoCandidate(vec![])),
warnings: &[],
},
Case { name: "a pin wins over the score", spec: pinned(MachineRef::Local), candidates: vec![roomy(), local()], want: Ok(MachineRef::Local), warnings: &[] },
Case {
name: "a pin over cap is warned",
spec: pinned(m("a")),
candidates: vec![local(), cand(m("a"), Some(over_mem(cap(4, 250, 2))))],
want: Ok(m("a")),
warnings: &["a: over cap: mem 28G/16G"],
},
Case {
name: "a pin on an unreachable machine is refused",
spec: pinned(m("big")),
candidates: vec![local(), Candidate { reachable: false, ..roomy() }],
want: Err(NoPlace::PinUnreachable(m("big"))),
warnings: &[],
},
Case { name: "a pin on an unknown machine is refused", spec: pinned(m("nope")), candidates: vec![local()], want: Err(NoPlace::UnknownPin(m("nope"))), warnings: &[] },
];
for case in cases {
let got = place(&case.spec, &case.candidates);
match (&got, &case.want) {
(Ok(p), Ok(want)) => {
assert_eq!(&p.machine, want, "{}: {p:?}", case.name);
assert_eq!(p.warnings, case.warnings, "{}", case.name);
}
(got, want) => assert_eq!(got.as_ref().map(|p| &p.machine), want.as_ref(), "{}", case.name),
}
}
}
#[test]
fn the_score_and_its_reasons() {
let c = cand(MachineRef::Local, Some(cap(16, 250, 2)));
let (s, reasons) = score(&spec(), &c);
assert_eq!(s, 425 + REQUESTER);
assert_eq!(reasons, ["mem 50% free", "disk 50% free", "cpu 75% free", "requester's host"]);
let capped = Capacity { caps: Some(Caps { cpus: Some(4), mem: Some(20 * G), disk: None, instances: Some(4) }), ..cap(16, 250, 2) };
let (s, reasons) = score(&Spec { requester: m("x"), ..spec() }, &Candidate { has_image: true, has_repo: true, ..cand(m("a"), Some(capped)) });
assert_eq!(s, 3 * 20 + 2 * 50 + 2 * 50 + 50 + IMAGE + REPO);
assert_eq!(reasons, ["mem 20% free", "disk 50% free", "slots 50% free", "cpu 50% free", "image built", "repo there"]);
let (s, reasons) = score(&Spec { requester: m("x"), ..spec() }, &cand(m("a"), None));
assert_eq!(s, (W_MEM + W_DISK + W_SLOTS + W_CPU) * NEUTRAL);
assert_eq!(reasons, ["no capacity report"]);
let over = Capacity { caps: Some(Caps { instances: Some(1), mem: Some(8 * G), ..Caps::default() }), ..cap(16, 250, 2) };
let (s, reasons) = score(&Spec { requester: m("x"), ..spec() }, &cand(m("a"), Some(over)));
assert_eq!(s, 2 * 50 + 75 - 2 * OVER, "mem and slots at 0");
assert!(reasons.contains(&"over cap: mem 16G/8G, instances 2/1".to_string()), "{reasons:?}");
}
#[test]
fn reachable_while_the_link_is_up() {
use LinkState::*;
for (state, want) in [(Idle, false), (Connecting, false), (Connected, true), (Unreachable, false)] {
assert_eq!(reachable(state), want, "{state:?}");
}
}
fn root_snapshot(drift: bool, phase: Value) -> Value {
json!({
"dir": "/r",
"sandboxes": [{"name": "web", "config_hash": "c1", "build_hash": "b1", "root": "/r"}, {"name": "api", "config_hash": "c9", "build_hash": "", "root": "/r"}],
"instances": [
{"name": "web-1", "sandbox": "web", "root": "/r", "drift": drift, "phase": phase},
{"name": "other", "sandbox": "web", "root": "/elsewhere", "drift": false},
],
})
}
#[test]
fn has_image_wants_a_ready_matching_instance_from_the_same_root() {
let ok = root_snapshot(false, Value::Null);
assert!(has_image(&spec(), [&ok]));
assert!(has_image(&Spec { build_hash: Some("b1".into()), ..spec() }, [&ok]));
assert!(!has_image(&Spec { build_hash: Some("b2".into()), ..spec() }, [&ok]), "build hash differs");
assert!(!has_image(&Spec { config_hash: Some("c2".into()), ..spec() }, [&ok]), "config hash differs");
assert!(!has_image(&Spec { config_hash: None, ..spec() }, [&ok]), "unknown hash");
assert!(!has_image(&Spec { sandbox: "api".into(), config_hash: Some("c9".into()), ..spec() }, [&ok]), "no instance of it");
assert!(!has_image(&spec(), [&root_snapshot(true, Value::Null)]), "drifted");
assert!(!has_image(&spec(), [&root_snapshot(false, json!({"in_flight": {"step": "build"}}))]), "not ready");
assert!(!has_image(&spec(), []));
let mut moved = ok.clone();
moved["instances"][0]["root"] = json!("/x");
assert!(!has_image(&spec(), [&moved]));
let mut bare = ok.clone();
bare["sandboxes"][0].as_object_mut().unwrap().remove("root");
assert!(has_image(&spec(), [&bare]));
}
#[test]
fn candidates_from_the_daemons_state() {
let ok = root_snapshot(false, Value::Null);
let local = Candidate::local(&spec(), Some(cap(16, 250, 2)), [&ok]);
assert_eq!((local.machine, local.reachable, local.has_image), (MachineRef::Local, true, true));
let mut snap = ok.clone();
snap["capacity"] = serde_json::to_value(cap(8, 100, 1)).unwrap();
let w = Machine {
name: "w".into(),
kind: MachineKind::Ssh,
roots: vec![PathBuf::from("/r")],
state: LinkState::Connected,
rows: BTreeMap::from([(PathBuf::from("/r"), Arc::new(snap))]),
..Machine::default()
};
let c = Candidate::from_machine(&spec(), &w);
assert_eq!((c.machine.clone(), c.reachable, c.has_image, c.has_repo), (m("w"), true, true, false));
assert_eq!(c.capacity.as_ref().map(|c| c.running), Some(1));
let bare = Machine { name: "s".into(), state: LinkState::Idle, ..Machine::default() };
let c = Candidate::from_machine(&spec(), &bare);
assert_eq!((c.reachable, c.capacity, c.has_image), (false, None, false));
let inbound = Machine { kind: MachineKind::Inbound, ..w.clone() };
let c = Candidate::from_machine(&spec(), &inbound);
assert_eq!((c.reachable, c.has_image), (true, true));
let fresh = Machine { name: "f".into(), state: LinkState::Connected, ..Machine::default() };
let c = Candidate::from_machine(&spec(), &fresh);
assert_eq!((c.reachable, c.capacity), (true, None));
let down = Machine { state: LinkState::Idle, ..w };
assert!(!Candidate::from_machine(&spec(), &down).reachable);
}
#[test]
fn no_place_says_why() {
assert_eq!(NoPlace::UnknownPin(m("x")).to_string(), "no machine `x`");
assert_eq!(NoPlace::PinUnreachable(m("x")).to_string(), "x is unreachable");
assert_eq!(NoPlace::NoCandidate(vec![]).to_string(), "no machine to place on");
assert_eq!(
NoPlace::NoCandidate(vec![(m("a"), "unreachable"), (MachineRef::Local, "unreachable")]).to_string(),
"no machine takes new work (a: unreachable, this host: unreachable)"
);
}
}