Skip to main content

krab_controllers/kubelet/
mod.rs

1pub mod probe;
2pub mod spec;
3mod worker;
4
5use crate::util::{self, Recorder, s, uid};
6use krab_runtime::{Runtime, is_managed};
7use krab_store::{Event, EventKind, MemStore};
8use serde_json::Value;
9use std::collections::{HashMap, HashSet};
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use std::time::Duration;
13use tokio::sync::Notify;
14use tokio::sync::broadcast::error::RecvError;
15use tokio::task::JoinHandle;
16
17pub struct Config {
18    pub node_name: String,
19    pub network: String,
20    pub volume_root: PathBuf,
21    pub sync_period: Duration,
22    pub resync: Duration,
23    pub allow_host_paths: Vec<PathBuf>,
24}
25
26impl Config {
27    pub fn new(node_name: impl Into<String>) -> Self {
28        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
29        Self {
30            node_name: node_name.into(),
31            network: "krab".into(),
32            volume_root: PathBuf::from(home).join(".krab/volumes"),
33            sync_period: Duration::from_secs(1),
34            resync: Duration::from_secs(10),
35            allow_host_paths: Vec::new(),
36        }
37    }
38}
39
40pub struct Shared<R> {
41    pub store: Arc<MemStore>,
42    pub rt: Arc<R>,
43    pub rec: Arc<Recorder>,
44    pub cfg: Config,
45    pub net: tokio::sync::Mutex<bool>,
46}
47
48struct Handle {
49    notify: Arc<Notify>,
50    task: JoinHandle<()>,
51}
52
53impl Drop for Handle {
54    fn drop(&mut self) {
55        self.task.abort();
56    }
57}
58
59fn mine(cfg: &Config, pod: &Value) -> bool {
60    s(pod, "/spec/nodeName") == cfg.node_name
61        && pod["metadata"]["annotations"]["krab.io/source"].as_str() != Some("docker")
62}
63
64fn spawn<R: Runtime>(
65    sh: &Arc<Shared<R>>,
66    workers: &mut HashMap<String, Handle>,
67    key: &str,
68    pod: &Value,
69) {
70    let notify = Arc::new(Notify::new());
71    let w = worker::Worker::new(sh.clone(), key.to_string(), pod.clone());
72    let task = tokio::spawn(w.run(notify.clone()));
73    workers.insert(uid(pod).to_string(), Handle { notify, task });
74}
75
76fn on_event<R: Runtime>(sh: &Arc<Shared<R>>, workers: &mut HashMap<String, Handle>, e: &Event) {
77    if e.key.starts_with("endpoints/") {
78        for h in workers.values() {
79            h.notify.notify_one();
80        }
81        return;
82    }
83    if !e.key.starts_with("pods/") {
84        return;
85    }
86    let Some(pod) = util::parse(&e.obj) else {
87        return;
88    };
89    match workers.get(uid(&pod)) {
90        Some(h) => h.notify.notify_one(),
91        None if e.kind != EventKind::Deleted && mine(&sh.cfg, &pod) => {
92            spawn(sh, workers, &e.key, &pod)
93        }
94        None => {}
95    }
96}
97
98fn uid_like(s: &str) -> bool {
99    s.len() == 36
100        && s.bytes().enumerate().all(|(i, b)| {
101            matches!(i, 8 | 13 | 18 | 23) == (b == b'-') && (b == b'-' || b.is_ascii_hexdigit())
102        })
103}
104
105fn sweep_volume_dirs(root: &Path, live: &HashSet<String>) {
106    let Ok(rd) = std::fs::read_dir(root) else {
107        return;
108    };
109    for e in rd.flatten() {
110        let name = e.file_name().to_string_lossy().into_owned();
111        if uid_like(&name) && !live.contains(&name) && e.file_type().is_ok_and(|t| t.is_dir()) {
112            let _ = krab_runtime::subpath::remove_dir_safely(&e.path());
113        }
114    }
115}
116
117async fn resync<R: Runtime>(sh: &Arc<Shared<R>>, workers: &mut HashMap<String, Handle>) {
118    workers.retain(|_, h| !h.task.is_finished());
119    let mut live: HashSet<String> = workers.keys().cloned().collect();
120    for (key, pod) in util::list(&sh.store, "pods/") {
121        live.insert(uid(&pod).to_string());
122        if mine(&sh.cfg, &pod) && !workers.contains_key(uid(&pod)) {
123            spawn(sh, workers, &key, &pod);
124        }
125    }
126    sweep_volume_dirs(&sh.cfg.volume_root, &live);
127    let Ok(list) = sh.rt.list().await else { return };
128    let mut left = 0;
129    let node = Some(&sh.cfg.node_name);
130    for c in list
131        .iter()
132        .filter(|c| is_managed(c) && c.labels.get("krab.io/node") == node)
133    {
134        let owner = c
135            .labels
136            .get("krab.io/uid")
137            .map(String::as_str)
138            .unwrap_or("");
139        if workers.contains_key(owner) {
140            left += 1;
141            continue;
142        }
143        let _ = sh.rt.stop(&c.id, 10).await;
144        if sh.rt.remove(&c.id, true).await.is_err() {
145            left += 1;
146        }
147    }
148    if workers.is_empty() && left == 0 {
149        let mut net = sh.net.lock().await;
150        if *net && sh.rt.remove_network(&sh.cfg.network).await.is_ok() {
151            *net = false;
152        }
153    }
154}
155
156pub async fn run<R: Runtime>(store: Arc<MemStore>, rt: Arc<R>, rec: Arc<Recorder>, cfg: Config) {
157    let sh = Arc::new(Shared {
158        store,
159        rt,
160        rec,
161        cfg,
162        net: tokio::sync::Mutex::new(false),
163    });
164    let mut workers: HashMap<String, Handle> = HashMap::new();
165    let mut rx = util::subscribe(&sh.store);
166    let mut tick = tokio::time::interval(sh.cfg.resync);
167    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
168    loop {
169        tokio::select! {
170            ev = rx.recv() => match ev {
171                Ok(e) => on_event(&sh, &mut workers, &e),
172                Err(RecvError::Lagged(_)) => resync(&sh, &mut workers).await,
173                Err(RecvError::Closed) => return,
174            },
175            _ = tick.tick() => resync(&sh, &mut workers).await,
176        }
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use crate::fake::Fake;
184    use serde_json::json;
185
186    fn cfg(tag: &str) -> Config {
187        let mut c = Config::new("n1");
188        c.volume_root =
189            std::env::temp_dir().join(format!("krab-kubelet-{tag}-{}", util::rand_suffix(6)));
190        c
191    }
192
193    fn pod(name: &str, uid: &str, spec: serde_json::Value) -> serde_json::Value {
194        let mut spec = spec;
195        spec["nodeName"] = json!("n1");
196        json!({"apiVersion": "v1", "kind": "Pod", "metadata": {"name": name, "namespace": "default", "uid": uid}, "spec": spec})
197    }
198
199    async fn wait(mut f: impl FnMut() -> bool) {
200        for _ in 0..600 {
201            if f() {
202                return;
203            }
204            tokio::time::sleep(Duration::from_millis(100)).await;
205        }
206        panic!("condition not reached");
207    }
208
209    fn start(st: &Arc<MemStore>, rt: &Arc<Fake>, c: Config) -> crate::Tasks {
210        crate::Tasks(vec![tokio::spawn(run(
211            st.clone(),
212            rt.clone(),
213            Arc::new(Recorder::default()),
214            c,
215        ))])
216    }
217
218    fn status(st: &MemStore, key: &str) -> serde_json::Value {
219        util::get(st, key)
220            .map(|p| p["status"].clone())
221            .unwrap_or_default()
222    }
223
224    fn reasons(st: &MemStore) -> Vec<String> {
225        util::list(st, "events/")
226            .into_iter()
227            .map(|(_, e)| e["reason"].as_str().unwrap_or("").to_string())
228            .collect()
229    }
230
231    #[tokio::test(start_paused = true)]
232    async fn creates_and_deletes_containers() {
233        let st = MemStore::new(1 << 22, 1024);
234        let rt = Arc::new(Fake::with_images(&[]));
235        let _t = start(&st, &rt, cfg("cd"));
236        util::create(
237            &st,
238            "pods/default/p1",
239            pod(
240                "p1",
241                "u-1",
242                json!({"containers": [{"name": "c", "image": "nginx:alpine", "ports": [{"containerPort": 80}]}]}),
243            ),
244        );
245        util::create(
246            &st,
247            "pods/default/other",
248            json!({"metadata": {"name": "other", "namespace": "default", "uid": "u-x"}, "spec": {"nodeName": "n2", "containers": [{"name": "c", "image": "nginx:alpine"}]}}),
249        );
250        wait(|| {
251            status(&st, "pods/default/p1")["phase"] == "Running"
252                && util::pod_ready(&util::get(&st, "pods/default/p1").unwrap())
253        })
254        .await;
255        let c = rt.by_name("krab_default_p1_c").unwrap();
256        assert_eq!(c.labels["krab.io/uid"], "u-1");
257        assert_eq!(c.labels["krab.io/managed"], "true");
258        assert!(rt.by_name("krab_default_other_c").is_none());
259        let s = status(&st, "pods/default/p1");
260        assert_eq!(s["podIP"], "127.0.0.1");
261        assert_eq!(
262            s["containerStatuses"][0]["containerID"],
263            format!("docker://{}", c.id)
264        );
265        assert!(s["containerStatuses"][0]["state"]["running"].is_object());
266        assert!(rt.st.lock().unwrap().networks.contains(&"krab".to_string()));
267        let r = reasons(&st);
268        for want in ["Pulling", "Pulled", "Created", "Started"] {
269            assert!(r.contains(&want.to_string()), "{want} missing in {r:?}");
270        }
271        util::update(&st, "pods/default/p1", |p| {
272            p["metadata"]["deletionTimestamp"] = json!(util::now_rfc());
273            true
274        });
275        wait(|| rt.by_name("krab_default_p1_c").is_none() && st.get("pods/default/p1").is_none())
276            .await;
277        assert!(reasons(&st).contains(&"Killing".to_string()));
278        util::create(
279            &st,
280            "pods/default/p2",
281            pod(
282                "p2",
283                "u-2",
284                json!({"containers": [{"name": "c", "image": "nginx:alpine"}]}),
285            ),
286        );
287        wait(|| {
288            rt.by_name("krab_default_p2_c")
289                .is_some_and(|c| c.state == "running")
290        })
291        .await;
292        util::delete(&st, "pods/default/p2");
293        wait(|| rt.by_name("krab_default_p2_c").is_none()).await;
294        wait(|| rt.st.lock().unwrap().networks.is_empty()).await;
295    }
296
297    #[tokio::test(start_paused = true)]
298    async fn recreated_pod_with_same_name_gets_new_container() {
299        let st = MemStore::new(1 << 22, 1024);
300        let rt = Arc::new(Fake::with_images(&["nginx:alpine"]));
301        let _t = start(&st, &rt, cfg("re"));
302        let spec = json!({"containers": [{"name": "c", "image": "nginx:alpine"}]});
303        util::create(&st, "pods/default/p", pod("p", "old-uid", spec.clone()));
304        wait(|| {
305            rt.by_name("krab_default_p_c")
306                .is_some_and(|c| c.state == "running")
307        })
308        .await;
309        util::delete(&st, "pods/default/p");
310        util::create(&st, "pods/default/p", pod("p", "new-uid", spec));
311        wait(|| {
312            rt.by_name("krab_default_p_c")
313                .is_some_and(|c| c.labels["krab.io/uid"] == "new-uid" && c.state == "running")
314                && status(&st, "pods/default/p")["phase"] == "Running"
315        })
316        .await;
317        tokio::time::sleep(Duration::from_secs(15)).await;
318        let all = rt.st.lock().unwrap().containers.len();
319        assert_eq!(all, 1);
320        assert_eq!(
321            rt.by_name("krab_default_p_c").unwrap().labels["krab.io/uid"],
322            "new-uid"
323        );
324    }
325
326    #[tokio::test(start_paused = true)]
327    async fn restart_adopts_containers_and_recreates_changed_spec() {
328        let st = MemStore::new(1 << 22, 1024);
329        let rt = Arc::new(Fake::with_images(&["app:1", "app:2"]));
330        let c = cfg("ad");
331        let root = c.volume_root.clone();
332        let t = start(&st, &rt, c);
333        util::create(
334            &st,
335            "pods/default/p",
336            pod(
337                "p",
338                "u-ad",
339                json!({"containers": [{"name": "c", "image": "app:1"}]}),
340            ),
341        );
342        wait(|| rt.running().len() == 1).await;
343        let first = rt.by_name("krab_default_p_c").unwrap().id;
344        drop(t);
345        util::update(&st, "pods/default/p", |p| {
346            p["status"]["containerStatuses"][0]["restartCount"] = json!(3);
347            true
348        });
349        let mut c = cfg("ad");
350        c.volume_root = root.clone();
351        let t = start(&st, &rt, c);
352        tokio::time::sleep(Duration::from_secs(15)).await;
353        assert_eq!(rt.by_name("krab_default_p_c").unwrap().id, first);
354        assert_eq!(rt.count("create"), 1);
355        assert_eq!(rt.count("stop"), 0);
356        assert_eq!(
357            status(&st, "pods/default/p")["containerStatuses"][0]["restartCount"],
358            3
359        );
360        drop(t);
361        util::update(&st, "pods/default/p", |p| {
362            p["spec"]["containers"][0]["image"] = json!("app:2");
363            true
364        });
365        let mut c = cfg("ad");
366        c.volume_root = root;
367        let _t = start(&st, &rt, c);
368        wait(|| {
369            rt.by_name("krab_default_p_c")
370                .is_some_and(|c| c.image == "app:2" && c.state == "running")
371        })
372        .await;
373        assert_eq!(rt.count("create"), 2);
374        assert!(rt.by_name("krab_default_p_c").unwrap().id != first);
375        wait(|| status(&st, "pods/default/p")["containerStatuses"][0]["restartCount"] == 4).await;
376    }
377
378    #[tokio::test(start_paused = true)]
379    async fn probes_gate_readiness_and_restart() {
380        let st = MemStore::new(1 << 22, 1024);
381        let rt = Arc::new(Fake::with_images(&["app:1"]));
382        let _t = start(&st, &rt, cfg("pr"));
383        rt.set_exec("krab_default_p_c", 1);
384        util::create(
385            &st,
386            "pods/default/p",
387            pod(
388                "p",
389                "u-p",
390                json!({"containers": [{"name": "c", "image": "app:1",
391            "readinessProbe": {"exec": {"command": ["true"]}, "periodSeconds": 1, "failureThreshold": 1},
392            "livenessProbe": {"exec": {"command": ["true"]}, "initialDelaySeconds": 30, "periodSeconds": 1, "failureThreshold": 2}}]}),
393            ),
394        );
395        wait(|| status(&st, "pods/default/p")["phase"] == "Running").await;
396        tokio::time::sleep(Duration::from_secs(3)).await;
397        let p = util::get(&st, "pods/default/p").unwrap();
398        assert!(!util::pod_ready(&p));
399        assert_eq!(p["status"]["containerStatuses"][0]["ready"], false);
400        assert!(reasons(&st).contains(&"Unhealthy".to_string()));
401        rt.set_exec("krab_default_p_c", 0);
402        wait(|| util::pod_ready(&util::get(&st, "pods/default/p").unwrap())).await;
403        assert_eq!(rt.count("stop"), 0);
404        rt.set_exec("krab_default_p_c", 1);
405        wait(|| status(&st, "pods/default/p")["containerStatuses"][0]["restartCount"] == 1).await;
406        assert!(rt.count("stop") >= 1);
407        assert!(rt.count("start") >= 2);
408        assert!(
409            status(&st, "pods/default/p")["containerStatuses"][0]["lastState"]["terminated"]
410                .is_object()
411        );
412    }
413
414    #[tokio::test(start_paused = true)]
415    async fn restart_policy_and_backoff() {
416        let st = MemStore::new(1 << 22, 1024);
417        let rt = Arc::new(Fake::with_images(&["app:1"]));
418        let _t = start(&st, &rt, cfg("rs"));
419        util::create(
420            &st,
421            "pods/default/a",
422            pod(
423                "a",
424                "u-a",
425                json!({"containers": [{"name": "c", "image": "app:1"}]}),
426            ),
427        );
428        util::create(
429            &st,
430            "pods/default/n",
431            pod(
432                "n",
433                "u-n",
434                json!({"restartPolicy": "Never", "containers": [{"name": "c", "image": "app:1"}]}),
435            ),
436        );
437        wait(|| rt.running().len() == 2).await;
438        rt.set_state("krab_default_a_c", "exited", 1);
439        rt.set_state("krab_default_n_c", "exited", 0);
440        wait(|| {
441            status(&st, "pods/default/a")["containerStatuses"][0]["state"]["waiting"]["reason"]
442                == "CrashLoopBackOff"
443        })
444        .await;
445        wait(|| status(&st, "pods/default/a")["containerStatuses"][0]["restartCount"] == 1).await;
446        assert_eq!(rt.by_name("krab_default_a_c").unwrap().state, "running");
447        assert!(reasons(&st).contains(&"BackOff".to_string()));
448        wait(|| status(&st, "pods/default/n")["phase"] == "Succeeded").await;
449        assert_eq!(rt.by_name("krab_default_n_c").unwrap().state, "exited");
450    }
451
452    #[tokio::test(start_paused = true)]
453    async fn init_containers_run_first() {
454        let st = MemStore::new(1 << 22, 1024);
455        let rt = Arc::new(Fake::with_images(&["busybox:1", "app:1"]));
456        let _t = start(&st, &rt, cfg("in"));
457        util::create(
458            &st,
459            "pods/default/p",
460            pod(
461                "p",
462                "u-i",
463                json!({
464            "initContainers": [{"name": "i1", "image": "busybox:1"}, {"name": "i2", "image": "busybox:1"}],
465            "containers": [{"name": "c", "image": "app:1"}]}),
466            ),
467        );
468        wait(|| {
469            rt.by_name("krab_default_p_i1")
470                .is_some_and(|c| c.state == "running")
471        })
472        .await;
473        tokio::time::sleep(Duration::from_secs(2)).await;
474        assert!(rt.by_name("krab_default_p_i2").is_none());
475        assert!(rt.by_name("krab_default_p_c").is_none());
476        assert_eq!(status(&st, "pods/default/p")["phase"], "Pending");
477        rt.set_state("krab_default_p_i1", "exited", 0);
478        wait(|| rt.by_name("krab_default_p_i2").is_some()).await;
479        rt.set_state("krab_default_p_i2", "exited", 0);
480        wait(|| {
481            rt.by_name("krab_default_p_c")
482                .is_some_and(|c| c.state == "running")
483        })
484        .await;
485        wait(|| {
486            util::condition(&util::get(&st, "pods/default/p").unwrap(), "Initialized")
487                .is_some_and(|c| c["status"] == "True")
488        })
489        .await;
490        assert_eq!(
491            status(&st, "pods/default/p")["initContainerStatuses"][1]["ready"],
492            true
493        );
494    }
495
496    #[tokio::test(start_paused = true)]
497    async fn service_aliases_follow_endpoints() {
498        let st = MemStore::new(1 << 22, 1024);
499        let rt = Arc::new(Fake::with_images(&["app:1"]));
500        let _t = start(&st, &rt, cfg("al"));
501        util::create(
502            &st,
503            "pods/default/p",
504            pod(
505                "p",
506                "u-al",
507                json!({"containers": [{"name": "c", "image": "app:1"}]}),
508            ),
509        );
510        wait(|| rt.running().len() == 1).await;
511        util::create(
512            &st,
513            "endpoints/default/web",
514            json!({"metadata": {"name": "web", "namespace": "default"},
515            "subsets": [{"addresses": [{"ip": "127.0.0.1", "targetRef": {"kind": "Pod", "uid": "u-al"}}], "ports": [{"port": 80}]}]}),
516        );
517        let id = rt.by_name("krab_default_p_c").unwrap().id;
518        wait(|| {
519            rt.st.lock().unwrap().aliases.get(&id)
520                == Some(&vec![
521                    "web".to_string(),
522                    "web.default.svc.cluster.local".to_string(),
523                ])
524        })
525        .await;
526    }
527
528    #[test]
529    fn orphan_volume_dirs_are_swept() {
530        let root = std::env::temp_dir().join(format!("krab-sweep-{}", util::rand_suffix(6)));
531        let live = "0123abcd-0000-4000-8000-00000000aaaa";
532        let dead = "0123abcd-0000-4000-8000-00000000bbbb";
533        for d in [live, dead, "keep-me"] {
534            std::fs::create_dir_all(root.join(d).join("s")).unwrap();
535        }
536        sweep_volume_dirs(&root, &HashSet::from([live.to_string()]));
537        assert!(root.join(live).exists());
538        assert!(!root.join(dead).exists());
539        assert!(root.join("keep-me").exists());
540        std::fs::remove_dir_all(&root).unwrap();
541    }
542
543    #[tokio::test]
544    async fn http_and_tcp_probes() {
545        let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
546        let port = l.local_addr().unwrap().port();
547        tokio::spawn(async move {
548            use tokio::io::{AsyncReadExt, AsyncWriteExt};
549            loop {
550                let (mut s, _) = l.accept().await.unwrap();
551                let mut buf = [0u8; 512];
552                let n = s.read(&mut buf).await.unwrap_or(0);
553                let req = String::from_utf8_lossy(&buf[..n]).to_string();
554                let code = if req.starts_with("GET /ok ") {
555                    "200 OK"
556                } else {
557                    "500 Internal"
558                };
559                let _ = s
560                    .write_all(format!("HTTP/1.1 {code}\r\nContent-Length: 0\r\n\r\n").as_bytes())
561                    .await;
562            }
563        });
564        let rt = Fake::default();
565        let c = json!({"ports": [{"name": "http", "containerPort": port}]});
566        let ok = json!({"httpGet": {"path": "/ok", "port": "http"}});
567        let bad = json!({"httpGet": {"path": "/bad", "port": port}});
568        let tcp = json!({"tcpSocket": {"port": port}});
569        let closed = json!({"tcpSocket": {"port": 1}});
570        assert!(probe::run(&rt, "x", &c, &ok, "127.0.0.1").await.is_ok());
571        assert!(
572            probe::run(&rt, "x", &c, &bad, "127.0.0.1")
573                .await
574                .unwrap_err()
575                .contains("500")
576        );
577        assert!(probe::run(&rt, "x", &c, &tcp, "127.0.0.1").await.is_ok());
578        let inject = json!({"httpGet": {"path": "/ok HTTP/1.1\r\nX-A: b", "port": port}});
579        assert!(
580            probe::run(&rt, "x", &c, &inject, "127.0.0.1")
581                .await
582                .unwrap_err()
583                .contains("forbidden")
584        );
585        let hdr = json!({"httpGet": {"path": "/ok", "port": port, "httpHeaders": [{"name": "A", "value": "b\r\nPOST / HTTP/1.1"}]}});
586        assert!(probe::run(&rt, "x", &c, &hdr, "127.0.0.1").await.is_err());
587        let hosted = json!({"httpGet": {"path": "/ok", "port": port, "host": "192.0.2.1"}});
588        assert!(probe::run(&rt, "x", &c, &hosted, "127.0.0.1").await.is_ok());
589        assert!(
590            probe::run(&rt, "x", &c, &closed, "127.0.0.1")
591                .await
592                .is_err()
593        );
594    }
595}