use crate::node::MEM_AVAILABLE_MIN_KIB;
use krab_controllers::util::{self, ns, s};
use krab_runtime::host::meminfo;
use krab_store::MemStore;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
pub const EVICT_ANNOTATION: &str = "krab.io/evict";
const CHECK_EVERY: Duration = Duration::from_secs(10);
const COOLDOWN: Duration = Duration::from_secs(30);
const MESSAGE: &str = "The node was low on resource: memory.";
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Qos {
BestEffort,
Burstable,
Guaranteed,
}
fn qos(pod: &Value) -> Qos {
let mut any = false;
let mut all_equal = true;
let list = pod["spec"]["containers"].as_array();
for c in list.into_iter().flatten() {
let res = &c["resources"];
for k in ["cpu", "memory"] {
let (req, lim) = (&res["requests"][k], &res["limits"][k]);
any |= !req.is_null() || !lim.is_null();
all_equal &= !lim.is_null() && (req.is_null() || req == lim);
}
}
match (any, all_equal) {
(false, _) => Qos::BestEffort,
(true, true) => Qos::Guaranteed,
_ => Qos::Burstable,
}
}
fn candidate(pod: &Value, node: &str) -> Option<Qos> {
let phase = s(pod, "/status/phase");
let skip = s(pod, "/spec/nodeName") != node
|| !matches!(phase, "" | "Pending" | "Running")
|| ns(pod) == "kube-system"
|| s(pod, "/spec/priorityClassName").starts_with("system-")
|| util::terminating(pod)
|| !s(
pod,
&format!(
"/metadata/annotations/{}",
EVICT_ANNOTATION.replace('/', "~1")
),
)
.is_empty();
if skip {
return None;
}
Some(qos(pod)).filter(|q| *q != Qos::Guaranteed)
}
pub fn pick(pods: &[(String, Value)], node: &str) -> Option<String> {
pods.iter()
.filter_map(|(k, p)| {
candidate(p, node).map(|q| (q, std::cmp::Reverse(util::created(p)), k))
})
.min()
.map(|(_, _, k)| k.clone())
}
pub async fn run(store: Arc<MemStore>, node: String) {
let mut tick = tokio::time::interval(CHECK_EVERY);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tick.tick().await;
if meminfo().1 >= MEM_AVAILABLE_MIN_KIB {
continue;
}
let pods = util::list(&store, "pods/");
let Some(key) = pick(&pods, &node) else {
continue;
};
let marked = util::update(&store, &key, |p| {
p["metadata"]["annotations"][EVICT_ANNOTATION] = json!(MESSAGE);
true
});
if marked.is_some() {
eprintln!("krab-agent: evicting {key}: {MESSAGE}");
tokio::time::sleep(COOLDOWN).await;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn pod(name: &str, created: i64, containers: Value) -> (String, Value) {
(
format!("pods/default/{name}"),
json!({"metadata": {"name": name, "namespace": "default", "creationTimestamp": util::rfc3339(created)},
"spec": {"nodeName": "n1", "containers": containers}, "status": {"phase": "Running"}}),
)
}
#[test]
fn best_effort_goes_first_and_guaranteed_never() {
let guaranteed = json!([{"resources": {"requests": {"cpu": "1", "memory": "1Gi"}, "limits": {"cpu": "1", "memory": "1Gi"}}}]);
let burstable = json!([{"resources": {"requests": {"memory": "64Mi"}}}]);
let best = json!([{}]);
let pods = vec![
pod("g", 10, guaranteed),
pod("b", 20, burstable),
pod("e", 5, best),
];
assert_eq!(pick(&pods, "n1").as_deref(), Some("pods/default/e"));
assert_eq!(pick(&pods[..2], "n1").as_deref(), Some("pods/default/b"));
assert_eq!(pick(&pods[..1], "n1"), None);
assert_eq!(pick(&pods, "other"), None);
}
#[test]
fn newest_best_effort_is_chosen_and_system_is_spared() {
let mut sys = pod("s", 100, json!([{}]));
sys.1["spec"]["priorityClassName"] = json!("system-node-critical");
let pods = vec![pod("old", 1, json!([{}])), pod("new", 50, json!([{}])), sys];
assert_eq!(pick(&pods, "n1").as_deref(), Some("pods/default/new"));
}
}