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 _ = std::fs::remove_dir_all(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 probes_gate_readiness_and_restart() {
328 let st = MemStore::new(1 << 22, 1024);
329 let rt = Arc::new(Fake::with_images(&["app:1"]));
330 let _t = start(&st, &rt, cfg("pr"));
331 rt.set_exec("krab_default_p_c", 1);
332 util::create(
333 &st,
334 "pods/default/p",
335 pod(
336 "p",
337 "u-p",
338 json!({"containers": [{"name": "c", "image": "app:1",
339 "readinessProbe": {"exec": {"command": ["true"]}, "periodSeconds": 1, "failureThreshold": 1},
340 "livenessProbe": {"exec": {"command": ["true"]}, "initialDelaySeconds": 30, "periodSeconds": 1, "failureThreshold": 2}}]}),
341 ),
342 );
343 wait(|| status(&st, "pods/default/p")["phase"] == "Running").await;
344 tokio::time::sleep(Duration::from_secs(3)).await;
345 let p = util::get(&st, "pods/default/p").unwrap();
346 assert!(!util::pod_ready(&p));
347 assert_eq!(p["status"]["containerStatuses"][0]["ready"], false);
348 assert!(reasons(&st).contains(&"Unhealthy".to_string()));
349 rt.set_exec("krab_default_p_c", 0);
350 wait(|| util::pod_ready(&util::get(&st, "pods/default/p").unwrap())).await;
351 assert_eq!(rt.count("stop"), 0);
352 rt.set_exec("krab_default_p_c", 1);
353 wait(|| status(&st, "pods/default/p")["containerStatuses"][0]["restartCount"] == 1).await;
354 assert!(rt.count("stop") >= 1);
355 assert!(rt.count("start") >= 2);
356 assert!(
357 status(&st, "pods/default/p")["containerStatuses"][0]["lastState"]["terminated"]
358 .is_object()
359 );
360 }
361
362 #[tokio::test(start_paused = true)]
363 async fn restart_policy_and_backoff() {
364 let st = MemStore::new(1 << 22, 1024);
365 let rt = Arc::new(Fake::with_images(&["app:1"]));
366 let _t = start(&st, &rt, cfg("rs"));
367 util::create(
368 &st,
369 "pods/default/a",
370 pod(
371 "a",
372 "u-a",
373 json!({"containers": [{"name": "c", "image": "app:1"}]}),
374 ),
375 );
376 util::create(
377 &st,
378 "pods/default/n",
379 pod(
380 "n",
381 "u-n",
382 json!({"restartPolicy": "Never", "containers": [{"name": "c", "image": "app:1"}]}),
383 ),
384 );
385 wait(|| rt.running().len() == 2).await;
386 rt.set_state("krab_default_a_c", "exited", 1);
387 rt.set_state("krab_default_n_c", "exited", 0);
388 wait(|| {
389 status(&st, "pods/default/a")["containerStatuses"][0]["state"]["waiting"]["reason"]
390 == "CrashLoopBackOff"
391 })
392 .await;
393 wait(|| status(&st, "pods/default/a")["containerStatuses"][0]["restartCount"] == 1).await;
394 assert_eq!(rt.by_name("krab_default_a_c").unwrap().state, "running");
395 assert!(reasons(&st).contains(&"BackOff".to_string()));
396 wait(|| status(&st, "pods/default/n")["phase"] == "Succeeded").await;
397 assert_eq!(rt.by_name("krab_default_n_c").unwrap().state, "exited");
398 }
399
400 #[tokio::test(start_paused = true)]
401 async fn init_containers_run_first() {
402 let st = MemStore::new(1 << 22, 1024);
403 let rt = Arc::new(Fake::with_images(&["busybox:1", "app:1"]));
404 let _t = start(&st, &rt, cfg("in"));
405 util::create(
406 &st,
407 "pods/default/p",
408 pod(
409 "p",
410 "u-i",
411 json!({
412 "initContainers": [{"name": "i1", "image": "busybox:1"}, {"name": "i2", "image": "busybox:1"}],
413 "containers": [{"name": "c", "image": "app:1"}]}),
414 ),
415 );
416 wait(|| {
417 rt.by_name("krab_default_p_i1")
418 .is_some_and(|c| c.state == "running")
419 })
420 .await;
421 tokio::time::sleep(Duration::from_secs(2)).await;
422 assert!(rt.by_name("krab_default_p_i2").is_none());
423 assert!(rt.by_name("krab_default_p_c").is_none());
424 assert_eq!(status(&st, "pods/default/p")["phase"], "Pending");
425 rt.set_state("krab_default_p_i1", "exited", 0);
426 wait(|| rt.by_name("krab_default_p_i2").is_some()).await;
427 rt.set_state("krab_default_p_i2", "exited", 0);
428 wait(|| {
429 rt.by_name("krab_default_p_c")
430 .is_some_and(|c| c.state == "running")
431 })
432 .await;
433 wait(|| {
434 util::condition(&util::get(&st, "pods/default/p").unwrap(), "Initialized")
435 .is_some_and(|c| c["status"] == "True")
436 })
437 .await;
438 assert_eq!(
439 status(&st, "pods/default/p")["initContainerStatuses"][1]["ready"],
440 true
441 );
442 }
443
444 #[tokio::test(start_paused = true)]
445 async fn service_aliases_follow_endpoints() {
446 let st = MemStore::new(1 << 22, 1024);
447 let rt = Arc::new(Fake::with_images(&["app:1"]));
448 let _t = start(&st, &rt, cfg("al"));
449 util::create(
450 &st,
451 "pods/default/p",
452 pod(
453 "p",
454 "u-al",
455 json!({"containers": [{"name": "c", "image": "app:1"}]}),
456 ),
457 );
458 wait(|| rt.running().len() == 1).await;
459 util::create(
460 &st,
461 "endpoints/default/web",
462 json!({"metadata": {"name": "web", "namespace": "default"},
463 "subsets": [{"addresses": [{"ip": "127.0.0.1", "targetRef": {"kind": "Pod", "uid": "u-al"}}], "ports": [{"port": 80}]}]}),
464 );
465 let id = rt.by_name("krab_default_p_c").unwrap().id;
466 wait(|| {
467 rt.st.lock().unwrap().aliases.get(&id)
468 == Some(&vec![
469 "web".to_string(),
470 "web.default.svc.cluster.local".to_string(),
471 ])
472 })
473 .await;
474 }
475
476 #[test]
477 fn orphan_volume_dirs_are_swept() {
478 let root = std::env::temp_dir().join(format!("krab-sweep-{}", util::rand_suffix(6)));
479 let live = "0123abcd-0000-4000-8000-00000000aaaa";
480 let dead = "0123abcd-0000-4000-8000-00000000bbbb";
481 for d in [live, dead, "keep-me"] {
482 std::fs::create_dir_all(root.join(d).join("s")).unwrap();
483 }
484 sweep_volume_dirs(&root, &HashSet::from([live.to_string()]));
485 assert!(root.join(live).exists());
486 assert!(!root.join(dead).exists());
487 assert!(root.join("keep-me").exists());
488 std::fs::remove_dir_all(&root).unwrap();
489 }
490
491 #[tokio::test]
492 async fn http_and_tcp_probes() {
493 let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
494 let port = l.local_addr().unwrap().port();
495 tokio::spawn(async move {
496 use tokio::io::{AsyncReadExt, AsyncWriteExt};
497 loop {
498 let (mut s, _) = l.accept().await.unwrap();
499 let mut buf = [0u8; 512];
500 let n = s.read(&mut buf).await.unwrap_or(0);
501 let req = String::from_utf8_lossy(&buf[..n]).to_string();
502 let code = if req.starts_with("GET /ok ") {
503 "200 OK"
504 } else {
505 "500 Internal"
506 };
507 let _ = s
508 .write_all(format!("HTTP/1.1 {code}\r\nContent-Length: 0\r\n\r\n").as_bytes())
509 .await;
510 }
511 });
512 let rt = Fake::default();
513 let c = json!({"ports": [{"name": "http", "containerPort": port}]});
514 let ok = json!({"httpGet": {"path": "/ok", "port": "http"}});
515 let bad = json!({"httpGet": {"path": "/bad", "port": port}});
516 let tcp = json!({"tcpSocket": {"port": port}});
517 let closed = json!({"tcpSocket": {"port": 1}});
518 assert!(probe::run(&rt, "x", &c, &ok, "127.0.0.1").await.is_ok());
519 assert!(
520 probe::run(&rt, "x", &c, &bad, "127.0.0.1")
521 .await
522 .unwrap_err()
523 .contains("500")
524 );
525 assert!(probe::run(&rt, "x", &c, &tcp, "127.0.0.1").await.is_ok());
526 let inject = json!({"httpGet": {"path": "/ok HTTP/1.1\r\nX-A: b", "port": port}});
527 assert!(
528 probe::run(&rt, "x", &c, &inject, "127.0.0.1")
529 .await
530 .unwrap_err()
531 .contains("forbidden")
532 );
533 let hdr = json!({"httpGet": {"path": "/ok", "port": port, "httpHeaders": [{"name": "A", "value": "b\r\nPOST / HTTP/1.1"}]}});
534 assert!(probe::run(&rt, "x", &c, &hdr, "127.0.0.1").await.is_err());
535 let hosted = json!({"httpGet": {"path": "/ok", "port": port, "host": "192.0.2.1"}});
536 assert!(probe::run(&rt, "x", &c, &hosted, "127.0.0.1").await.is_ok());
537 assert!(
538 probe::run(&rt, "x", &c, &closed, "127.0.0.1")
539 .await
540 .is_err()
541 );
542 }
543}