krab-controllers 0.1.0

Scheduler, kubelet and controllers for krabkube
Documentation
use crate::util::{self, Recorder, map_matches, name, ns, s, set_condition, terminating};
use krab_store::MemStore;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;

pub fn node_labels(store: &MemStore, node: &str) -> Value {
    util::get(store, &format!("nodes/{node}"))
        .map(|n| n["metadata"]["labels"].clone())
        .filter(Value::is_object)
        .unwrap_or_else(|| json!({"kubernetes.io/hostname": node}))
}

pub fn schedule(store: &MemStore, rec: &Recorder, node: &str) {
    let labels = node_labels(store, node);
    for (key, pod) in util::list(store, "pods/") {
        if !s(&pod, "/spec/nodeName").is_empty() || terminating(&pod) {
            continue;
        }
        if map_matches(&pod["spec"]["nodeSelector"], &labels) {
            let bound = util::update(store, &key, |p| {
                if !s(p, "/spec/nodeName").is_empty() {
                    return false;
                }
                p["spec"]["nodeName"] = json!(node);
                if p["status"]["phase"].is_null() {
                    p["status"]["phase"] = json!("Pending");
                }
                set_condition(p, "PodScheduled", true, "", "");
                true
            });
            if let Some(p) = bound {
                let msg = format!("Successfully assigned {}/{} to {node}", ns(&p), name(&p));
                rec.event(store, &p, "Scheduled", &msg, false);
            }
        } else {
            let msg =
                "0/1 nodes are available: 1 node(s) didn't match Pod's node affinity/selector.";
            let changed = util::update(store, &key, |p| {
                let mut c = set_condition(p, "PodScheduled", false, "Unschedulable", msg);
                if p["status"]["phase"].as_str() != Some("Pending") {
                    p["status"]["phase"] = json!("Pending");
                    c = true;
                }
                c
            });
            if let Some(p) = changed {
                rec.event(store, &p, "FailedScheduling", msg, true);
            }
        }
    }
}

pub async fn run(store: Arc<MemStore>, rec: Arc<Recorder>, node: String) {
    let st = store.clone();
    util::level_loop(
        &store,
        &["pods/", "nodes/"],
        Duration::from_secs(10),
        || schedule(&st, &rec, &node),
    )
    .await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn binds_and_rejects() {
        let st = MemStore::new(1 << 20, 64);
        let rec = Recorder::default();
        util::create(
            &st,
            "pods/default/a",
            json!({"metadata": {"name": "a", "namespace": "default"}, "spec": {}}),
        );
        util::create(
            &st,
            "pods/default/b",
            json!({"metadata": {"name": "b", "namespace": "default"}, "spec": {"nodeSelector": {"disk": "ssd"}}}),
        );
        schedule(&st, &rec, "n1");
        schedule(&st, &rec, "n1");
        let a = util::get(&st, "pods/default/a").unwrap();
        assert_eq!(a["spec"]["nodeName"], "n1");
        let b = util::get(&st, "pods/default/b").unwrap();
        assert!(b["spec"]["nodeName"].is_null());
        assert_eq!(b["status"]["phase"], "Pending");
        let evs: Vec<String> = util::list(&st, "events/")
            .into_iter()
            .map(|(_, e)| format!("{}:{}", e["reason"].as_str().unwrap(), e["count"]))
            .collect();
        assert!(evs.contains(&"Scheduled:1".to_string()));
        assert!(evs.contains(&"FailedScheduling:1".to_string()));
    }
}