krab_controllers/
scheduler.rs1use crate::util::{self, Recorder, map_matches, name, ns, s, set_condition, terminating};
2use krab_store::MemStore;
3use serde_json::{Value, json};
4use std::sync::Arc;
5use std::time::Duration;
6
7pub fn node_labels(store: &MemStore, node: &str) -> Value {
8 util::get(store, &format!("nodes/{node}"))
9 .map(|n| n["metadata"]["labels"].clone())
10 .filter(Value::is_object)
11 .unwrap_or_else(|| json!({"kubernetes.io/hostname": node}))
12}
13
14pub fn schedule(store: &MemStore, rec: &Recorder, node: &str) {
15 let labels = node_labels(store, node);
16 for (key, pod) in util::list(store, "pods/") {
17 if !s(&pod, "/spec/nodeName").is_empty() || terminating(&pod) {
18 continue;
19 }
20 if map_matches(&pod["spec"]["nodeSelector"], &labels) {
21 let bound = util::update(store, &key, |p| {
22 if !s(p, "/spec/nodeName").is_empty() {
23 return false;
24 }
25 p["spec"]["nodeName"] = json!(node);
26 if p["status"]["phase"].is_null() {
27 p["status"]["phase"] = json!("Pending");
28 }
29 set_condition(p, "PodScheduled", true, "", "");
30 true
31 });
32 if let Some(p) = bound {
33 let msg = format!("Successfully assigned {}/{} to {node}", ns(&p), name(&p));
34 rec.event(store, &p, "Scheduled", &msg, false);
35 }
36 } else {
37 let msg =
38 "0/1 nodes are available: 1 node(s) didn't match Pod's node affinity/selector.";
39 let changed = util::update(store, &key, |p| {
40 let mut c = set_condition(p, "PodScheduled", false, "Unschedulable", msg);
41 if p["status"]["phase"].as_str() != Some("Pending") {
42 p["status"]["phase"] = json!("Pending");
43 c = true;
44 }
45 c
46 });
47 if let Some(p) = changed {
48 rec.event(store, &p, "FailedScheduling", msg, true);
49 }
50 }
51 }
52}
53
54pub async fn run(store: Arc<MemStore>, rec: Arc<Recorder>, node: String) {
55 let st = store.clone();
56 util::level_loop(
57 &store,
58 &["pods/", "nodes/"],
59 Duration::from_secs(10),
60 || schedule(&st, &rec, &node),
61 )
62 .await
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68
69 #[test]
70 fn binds_and_rejects() {
71 let st = MemStore::new(1 << 20, 64);
72 let rec = Recorder::default();
73 util::create(
74 &st,
75 "pods/default/a",
76 json!({"metadata": {"name": "a", "namespace": "default"}, "spec": {}}),
77 );
78 util::create(
79 &st,
80 "pods/default/b",
81 json!({"metadata": {"name": "b", "namespace": "default"}, "spec": {"nodeSelector": {"disk": "ssd"}}}),
82 );
83 schedule(&st, &rec, "n1");
84 schedule(&st, &rec, "n1");
85 let a = util::get(&st, "pods/default/a").unwrap();
86 assert_eq!(a["spec"]["nodeName"], "n1");
87 let b = util::get(&st, "pods/default/b").unwrap();
88 assert!(b["spec"]["nodeName"].is_null());
89 assert_eq!(b["status"]["phase"], "Pending");
90 let evs: Vec<String> = util::list(&st, "events/")
91 .into_iter()
92 .map(|(_, e)| format!("{}:{}", e["reason"].as_str().unwrap(), e["count"]))
93 .collect();
94 assert!(evs.contains(&"Scheduled:1".to_string()));
95 assert!(evs.contains(&"FailedScheduling:1".to_string()));
96 }
97}