1pub mod layer;
2pub mod logfile;
3pub mod net;
4pub mod oci;
5pub mod registry;
6pub mod shim;
7pub mod sys;
8
9use crate::{
10 ContainerInfo, ContainerSpec, ExecHandle, ExecOpts, LogOpts, MANAGED_LABEL, Mount, NAME_PREFIX,
11 Runtime, is_managed, seccomp_supported,
12};
13use bytes::Bytes;
14use logfile::Render;
15use registry::{ImageRecord, Manifest, Session};
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18use std::collections::{BTreeMap, BTreeSet, HashMap};
19use std::fs;
20use std::future::Future;
21use std::io::{self, Read};
22use std::os::unix::fs::{MetadataExt, PermissionsExt};
23use std::path::{Path, PathBuf};
24use std::pin::Pin;
25use std::process::Stdio;
26use std::sync::atomic::{AtomicU64, Ordering};
27use std::sync::{Arc, Mutex, PoisonError};
28use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
29use tokio::io::{AsyncRead, AsyncReadExt};
30use tokio::process::Command;
31use tokio::sync::mpsc;
32
33const LOG_MAX: u64 = 8 << 20;
34#[cfg(not(test))]
35const START_TRIES: u32 = 300;
36#[cfg(test)]
37const START_TRIES: u32 = 4;
38const IMAGE_GC_MIN_AGE: u64 = 600;
39const CGROUP_ROOT: &str = "/sys/fs/cgroup";
40const POD_IP: &str = "127.0.0.1";
41
42#[derive(Clone, Debug, Default, Serialize, Deserialize)]
43struct Meta {
44 id: String,
45 image: String,
46 image_id: String,
47 labels: BTreeMap<String, String>,
48 created: i64,
49 state: String,
50 started_at: String,
51 finished_at: String,
52 exit_code: i64,
53 #[serde(default)]
54 oom_killed: bool,
55 restart_count: u64,
56 tty: bool,
57 stdin: bool,
58 pid: i64,
59 restart: String,
60 aliases: Vec<String>,
61 hostname: String,
62 no_new_privs: bool,
63 layers: Vec<String>,
64}
65
66struct Entry {
67 meta: Meta,
68 stopping: bool,
69 epoch: u64,
70 backoff_ms: u64,
71 launched: Option<Instant>,
72 starting: bool,
73}
74
75struct ExecState {
76 code: Option<i64>,
77}
78
79struct Inner {
80 root: PathBuf,
81 youki: PathBuf,
82 shim: PathBuf,
83 adopt: Mutex<Vec<(String, u64, i32)>>,
84 state: Mutex<HashMap<String, Entry>>,
85 execs: Mutex<HashMap<String, ExecState>>,
86 pull_locks: Mutex<HashMap<String, std::sync::Weak<tokio::sync::Mutex<()>>>>,
87 seq: AtomicU64,
88 net: Option<Arc<net::Net>>,
89 seccomp: Option<oci::Profile>,
90}
91
92#[derive(Clone)]
93pub struct Native {
94 inner: Arc<Inner>,
95}
96
97fn now_secs() -> i64 {
98 SystemTime::now()
99 .duration_since(UNIX_EPOCH)
100 .map(|d| d.as_secs() as i64)
101 .unwrap_or(0)
102}
103
104fn not_found(id: &str) -> io::Error {
105 io::Error::new(io::ErrorKind::NotFound, format!("no such container: {id}"))
106}
107
108fn id_ok(id: &str) -> bool {
109 id.len() <= 200
110 && id.starts_with(NAME_PREFIX)
111 && id.bytes().all(|b| {
112 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-' | b'.')
113 })
114 && crate::cgroup::native_cgroup_path(id).is_some()
115}
116
117fn exit_code(st: &std::process::ExitStatus) -> i64 {
118 use std::os::unix::process::ExitStatusExt;
119 match (st.code(), st.signal()) {
120 (Some(c), _) => c as i64,
121 (None, Some(s)) => 128 + s as i64,
122 _ => -1,
123 }
124}
125
126fn write_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
127 let tmp = path.with_extension("tmp");
128 fs::write(&tmp, data)?;
129 fs::rename(&tmp, path)
130}
131
132fn overlay_whiteout(p: &Path, w: layer::Whiteout) -> io::Result<()> {
133 match w {
134 layer::Whiteout::File => sys::whiteout(p),
135 layer::Whiteout::Opaque => sys::opaque(p),
136 }
137}
138
139struct Deadline<R> {
140 r: R,
141 until: Instant,
142}
143
144impl<R: Read> Read for Deadline<R> {
145 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
146 if Instant::now() >= self.until {
147 return Err(io::Error::new(
148 io::ErrorKind::TimedOut,
149 "image pull deadline exceeded",
150 ));
151 }
152 self.r.read(buf)
153 }
154}
155
156fn install_layer(
157 blob: &Path,
158 dst: &Path,
159 budget: layer::Limits,
160 lowers: &[PathBuf],
161 until: Instant,
162) -> io::Result<layer::Limits> {
163 let mut budget = budget;
164 unpack_layer(blob, dst, &mut budget, lowers, until)?;
165 let _ = fs::remove_file(blob);
166 Ok(budget)
167}
168
169fn unpack_layer(
170 blob: &Path,
171 dst: &Path,
172 budget: &mut layer::Limits,
173 lowers: &[PathBuf],
174 until: Instant,
175) -> io::Result<()> {
176 let tmp = dst.with_file_name(format!(
177 ".tmp-{}",
178 dst.file_name().unwrap_or_default().to_string_lossy()
179 ));
180 if tmp.exists() {
181 fs::remove_dir_all(&tmp)?;
182 }
183 let mut f = fs::File::open(blob)?;
184 let mut magic = [0u8; 4];
185 let n = f.read(&mut magic)?;
186 let f = Deadline {
187 r: fs::File::open(blob)?,
188 until,
189 };
190 let r: Box<dyn Read> = if n >= 2 && magic[..2] == [0x1f, 0x8b] {
191 Box::new(flate2::read::GzDecoder::new(io::BufReader::new(f)))
192 } else if n == 4 && magic == [0x28, 0xb5, 0x2f, 0xfd] {
193 return Err(io::Error::other("zstd layers are not supported"));
194 } else {
195 Box::new(io::BufReader::new(f))
196 };
197 let res = layer::unpack_in(r, &tmp, budget, lowers, &overlay_whiteout)
198 .and_then(|_| fs::rename(&tmp, dst));
199 if res.is_err() {
200 let _ = fs::remove_dir_all(&tmp);
201 }
202 res
203}
204
205async fn pump_chan<R: AsyncRead + Unpin>(mut r: R, tx: mpsc::Sender<Bytes>) {
206 let mut buf = vec![0u8; 8192];
207 loop {
208 match r.read(&mut buf).await {
209 Ok(0) | Err(_) => break,
210 Ok(n) => {
211 if tx.send(Bytes::copy_from_slice(&buf[..n])).await.is_err() {
212 break;
213 }
214 }
215 }
216 }
217}
218
219struct Starting<'a> {
220 n: &'a Native,
221 id: &'a str,
222 epoch: u64,
223}
224
225impl Drop for Starting<'_> {
226 fn drop(&mut self) {
227 if let Some(e) = self
228 .n
229 .lock()
230 .get_mut(self.id)
231 .filter(|e| e.epoch == self.epoch)
232 {
233 e.starting = false;
234 }
235 }
236}
237
238fn pod_key(labels: &BTreeMap<String, String>) -> io::Result<String> {
239 let get = |k: &str| labels.get(k).map(String::as_str).unwrap_or("");
240 let (ns, pod) = (get("krab.io/namespace"), get("krab.io/pod"));
241 if ns.is_empty() || pod.is_empty() || ns.contains('/') || pod.contains('/') {
242 return Err(io::Error::new(
243 io::ErrorKind::InvalidInput,
244 "container needs krab.io/namespace and krab.io/pod labels for its pod network",
245 ));
246 }
247 Ok(format!("{ns}/{pod}"))
248}
249
250impl Native {
251 pub fn new(root: impl Into<PathBuf>, youki: impl Into<PathBuf>) -> io::Result<Self> {
252 Self::new_with(root, youki, None)
253 }
254
255 pub fn new_with(
256 root: impl Into<PathBuf>,
257 youki: impl Into<PathBuf>,
258 net_cfg: Option<net::NetConfig>,
259 ) -> io::Result<Self> {
260 Self::new_with_profile(root, youki, net_cfg, None)
261 }
262
263 pub fn new_with_profile(
264 root: impl Into<PathBuf>,
265 youki: impl Into<PathBuf>,
266 net_cfg: Option<net::NetConfig>,
267 profile: Option<PathBuf>,
268 ) -> io::Result<Self> {
269 let profile = profile.as_deref().map(oci::Profile::load).transpose()?;
270 let shim = std::env::var_os("KRAB_SHIM")
271 .map(PathBuf::from)
272 .or_else(|| std::env::current_exe().ok())
273 .unwrap_or_else(|| PathBuf::from("krab"));
274 Self::open(root.into(), youki.into(), net_cfg, shim, profile)
275 }
276
277 fn open(
278 root: PathBuf,
279 youki: PathBuf,
280 net_cfg: Option<net::NetConfig>,
281 shim: PathBuf,
282 profile: Option<oci::Profile>,
283 ) -> io::Result<Self> {
284 fs::create_dir_all(&root)?;
285 let root = fs::canonicalize(&root)?;
286 if !sys::option_safe(&root) {
287 return Err(io::Error::other(
288 "native root must not contain spaces, ',' or ':'",
289 ));
290 }
291 fs::set_permissions(&root, fs::Permissions::from_mode(0o700))?;
292 for d in [
293 "blobs",
294 "layers",
295 "images",
296 "containers",
297 "logs",
298 "volumes",
299 "youki",
300 ] {
301 fs::create_dir_all(root.join(d))?;
302 }
303 let net = match net_cfg {
304 Some(c) => Some(Arc::new(net::Net::open(&root.join("net"), c)?)),
305 None => None,
306 };
307 let me = Self {
308 inner: Arc::new(Inner {
309 root,
310 youki,
311 shim,
312 adopt: Mutex::new(Vec::new()),
313 state: Mutex::new(HashMap::new()),
314 execs: Mutex::new(HashMap::new()),
315 pull_locks: Mutex::new(HashMap::new()),
316 seq: AtomicU64::new(0),
317 net,
318 seccomp: profile,
319 }),
320 };
321 me.load();
322 if let Some(n) = &me.inner.net {
323 let (live, running): (BTreeSet<String>, BTreeSet<String>) = {
324 let g = me.lock();
325 (
326 g.keys().cloned().collect(),
327 g.values()
328 .filter(|e| e.meta.state == "running")
329 .map(|e| e.meta.id.clone())
330 .collect(),
331 )
332 };
333 n.start(&live, &running)?;
334 me.rewrite_hosts();
335 }
336 Ok(me)
337 }
338
339 fn ip_of(&self, m: &Meta) -> String {
340 match &self.inner.net {
341 Some(n) => pod_key(&m.labels)
342 .ok()
343 .and_then(|k| n.pod_ip(&k))
344 .map(|i| i.to_string())
345 .unwrap_or_default(),
346 None => POD_IP.into(),
347 }
348 }
349
350 fn info(&self, m: &Meta) -> ContainerInfo {
351 let mut i = to_info(m);
352 i.ip = self.ip_of(m);
353 i
354 }
355
356 async fn net_release(&self, id: &str) {
357 if let Some(n) = self.inner.net.clone() {
358 let id = id.to_string();
359 let _ = tokio::task::spawn_blocking(move || n.release(&id)).await;
360 }
361 }
362
363 fn adopt_pending(&self) {
364 let pending = std::mem::take(
365 &mut *self
366 .inner
367 .adopt
368 .lock()
369 .unwrap_or_else(PoisonError::into_inner),
370 );
371 for (id, epoch, pid) in pending {
372 tokio::spawn(self.clone().watch(id, epoch, pid));
373 }
374 }
375
376 pub async fn shutdown_all(&self) {
377 self.adopt_pending();
378 let ids: Vec<String> = {
379 let mut g = self.lock();
380 for e in g.values_mut() {
381 e.stopping = true;
382 }
383 g.values()
384 .filter(|e| e.meta.state == "running")
385 .map(|e| e.meta.id.clone())
386 .collect()
387 };
388 for id in &ids {
389 let _ = self.youki_status(&["kill", id, "SIGKILL"]).await;
390 }
391 for id in &ids {
392 self.wait_not_running(id, Duration::from_secs(5)).await;
393 let _ = self.youki_status(&["delete", "--force", id]).await;
394 }
395 if let Some(n) = self.inner.net.clone() {
396 let _ = tokio::task::spawn_blocking(move || n.shutdown()).await;
397 }
398 }
399
400 fn load(&self) {
401 let Ok(rd) = fs::read_dir(self.inner.root.join("containers")) else {
402 return;
403 };
404 let mut map = HashMap::new();
405 for d in rd.flatten() {
406 let Ok(b) = fs::read(d.path().join("meta.json")) else {
407 continue;
408 };
409 let Ok(mut m) = serde_json::from_slice::<Meta>(&b) else {
410 continue;
411 };
412 if !id_ok(&m.id) || d.file_name().to_string_lossy() != m.id {
413 continue;
414 }
415 if m.state == "running"
416 && let Some(x) = shim::read_exit(&d.path())
417 {
418 m.state = "exited".into();
419 m.exit_code = x.code;
420 m.finished_at = x.finished_at;
421 m.pid = 0;
422 let _ = self.persist(&m);
423 } else if m.state == "running"
424 && let Some(pid) = self.shim_alive(&d.path())
425 {
426 self.inner
427 .adopt
428 .lock()
429 .unwrap_or_else(PoisonError::into_inner)
430 .push((m.id.clone(), 0, pid));
431 } else if m.state == "running" {
432 let youki = |args: &[&str]| {
433 std::process::Command::new(&self.inner.youki)
434 .arg("--root")
435 .arg(self.inner.root.join("youki"))
436 .args(args)
437 .stdin(Stdio::null())
438 .stdout(Stdio::null())
439 .stderr(Stdio::null())
440 .status()
441 };
442 let _ = youki(&["kill", &m.id, "SIGKILL"]);
443 std::thread::sleep(Duration::from_millis(200));
444 let _ = youki(&["delete", "--force", &m.id]);
445 m.state = "exited".into();
446 m.exit_code = 137;
447 m.finished_at = logfile::now_ts();
448 m.pid = 0;
449 let _ = self.persist(&m);
450 }
451 map.insert(
452 m.id.clone(),
453 Entry {
454 meta: m,
455 stopping: false,
456 epoch: 0,
457 backoff_ms: 0,
458 launched: None,
459 starting: false,
460 },
461 );
462 }
463 *self.lock() = map;
464 }
465
466 fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Entry>> {
467 self.inner
468 .state
469 .lock()
470 .unwrap_or_else(PoisonError::into_inner)
471 }
472
473 fn execs(&self) -> std::sync::MutexGuard<'_, HashMap<String, ExecState>> {
474 self.inner
475 .execs
476 .lock()
477 .unwrap_or_else(PoisonError::into_inner)
478 }
479
480 fn dir(&self, id: &str) -> PathBuf {
481 self.inner.root.join("containers").join(id)
482 }
483
484 fn rootfs(&self, id: &str) -> PathBuf {
485 self.dir(id).join("bundle/rootfs")
486 }
487
488 fn log_path(&self, id: &str) -> PathBuf {
489 self.inner.root.join("logs").join(format!("{id}.log"))
490 }
491
492 fn persist(&self, m: &Meta) -> io::Result<()> {
493 write_atomic(
494 &self.dir(&m.id).join("meta.json"),
495 &serde_json::to_vec(m).map_err(io::Error::other)?,
496 )
497 }
498
499 fn youki(&self) -> Command {
500 let mut c = Command::new(&self.inner.youki);
501 c.arg("--root").arg(self.inner.root.join("youki"));
502 c.stdin(Stdio::null());
503 c
504 }
505
506 async fn youki_status(&self, args: &[&str]) -> io::Result<std::process::Output> {
507 let mut c = self.youki();
508 c.args(args).kill_on_drop(true);
509 tokio::time::timeout(Duration::from_secs(30), c.output())
510 .await
511 .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "youki timed out"))?
512 }
513
514 fn meta(&self, id: &str) -> io::Result<Meta> {
515 let g = self.lock();
516 g.get(id)
517 .map(|e| e.meta.clone())
518 .ok_or_else(|| not_found(id))
519 }
520
521 fn ensure_managed(&self, id: &str) -> io::Result<Meta> {
522 let m = self.meta(id)?;
523 if is_managed(&to_info(&m)) {
524 Ok(m)
525 } else {
526 Err(io::Error::new(
527 io::ErrorKind::PermissionDenied,
528 format!("container {id} is not managed by krab"),
529 ))
530 }
531 }
532
533 fn is_running(&self, id: &str) -> bool {
534 self.lock()
535 .get(id)
536 .is_some_and(|e| e.meta.state == "running")
537 }
538
539 fn image_path(&self, image: &str) -> PathBuf {
540 self.inner
541 .root
542 .join("images")
543 .join(format!("{}.json", registry::sha256_hex(image.as_bytes())))
544 }
545
546 fn load_image(&self, image: &str) -> io::Result<ImageRecord> {
547 let b = fs::read(self.image_path(image))
548 .map_err(|e| io::Error::new(e.kind(), format!("image {image} is not present: {e}")))?;
549 let rec: ImageRecord = serde_json::from_slice(&b).map_err(io::Error::other)?;
550 for l in &rec.layers {
551 registry::digest_hex(&format!("sha256:{l}"))?;
552 if !self.inner.root.join("layers").join(l).is_dir() {
553 return Err(io::Error::new(
554 io::ErrorKind::NotFound,
555 format!("image {image}: layer {l} is missing"),
556 ));
557 }
558 }
559 Ok(rec)
560 }
561
562 fn key_lock(&self, key: &str) -> Arc<tokio::sync::Mutex<()>> {
563 let mut m = self
564 .inner
565 .pull_locks
566 .lock()
567 .unwrap_or_else(PoisonError::into_inner);
568 if let Some(l) = m.get(key).and_then(std::sync::Weak::upgrade) {
569 return l;
570 }
571 m.retain(|_, w| w.strong_count() > 0);
572 let l = Arc::new(tokio::sync::Mutex::new(()));
573 m.insert(key.to_string(), Arc::downgrade(&l));
574 l
575 }
576
577 fn mount_rootfs(&self, id: &str, layers: &[String]) -> io::Result<()> {
578 let rootfs = self.rootfs(id);
579 if sys::is_mounted(&rootfs) {
580 return Ok(());
581 }
582 let lower: Vec<PathBuf> = layers
583 .iter()
584 .map(|l| self.inner.root.join("layers").join(l))
585 .collect();
586 let d = self.dir(id);
587 sys::mount_overlay(&lower, &d.join("upper"), &d.join("work"), &rootfs)
588 }
589
590 fn shim_alive(&self, dir: &Path) -> Option<i32> {
591 let (pid, start) = shim::read_shim_pid(dir)?;
592 if shim::proc_starttime(pid)? != start {
593 return None;
594 }
595 let exe = fs::read_link(format!("/proc/{pid}/exe")).ok()?;
596 let exe = exe.to_string_lossy();
597 let want = fs::canonicalize(&self.inner.shim).unwrap_or_else(|_| self.inner.shim.clone());
598 (exe.trim_end_matches(" (deleted)") == want.to_string_lossy()).then_some(pid)
599 }
600
601 fn rewrite_hosts(&self) {
602 let g = self.lock();
603 let ips: HashMap<&str, String> = g
604 .values()
605 .map(|e| (e.meta.id.as_str(), self.ip_of(&e.meta)))
606 .collect();
607 let mut all: Vec<(String, String)> = g
608 .values()
609 .flat_map(|e| {
610 let ip = ips[e.meta.id.as_str()].clone();
611 e.meta.aliases.iter().map(move |a| (ip.clone(), a.clone()))
612 })
613 .collect();
614 all.sort();
615 all.dedup();
616 for e in g.values() {
617 let _ = fs::write(
618 self.dir(&e.meta.id).join("hosts"),
619 oci::pod_hosts(&e.meta.hostname, &ips[e.meta.id.as_str()], &all),
620 );
621 }
622 }
623
624 fn cleanup_dir(&self, id: &str) {
625 let _ = sys::umount(&self.rootfs(id));
626 let _ = fs::remove_dir_all(self.dir(id));
627 }
628
629 fn launch(
630 &self,
631 id: &str,
632 expect: Option<u64>,
633 ) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'static>> {
634 let me = self.clone();
635 let id = id.to_string();
636 Box::pin(async move { me.launch_inner(id, expect).await })
637 }
638
639 async fn launch_inner(&self, id: String, expect: Option<u64>) -> io::Result<()> {
640 let (meta, epoch) = {
641 let mut g = self.lock();
642 let e = g.get_mut(&id).ok_or_else(|| not_found(&id))?;
643 if e.starting
644 || e.meta.state == "running"
645 || expect.is_some_and(|ep| ep != e.epoch || e.stopping)
646 {
647 return Ok(());
648 }
649 self.mount_rootfs(&id, &e.meta.layers)?;
650 e.starting = true;
651 if expect.is_some() {
652 e.meta.restart_count += 1;
653 }
654 e.epoch += 1;
655 e.launched = Some(Instant::now());
656 (e.meta.clone(), e.epoch)
657 };
658 let _guard = Starting {
659 n: self,
660 id: &id,
661 epoch,
662 };
663 self.run_launch(&id, &meta, epoch).await
664 }
665
666 async fn run_launch(&self, id: &str, meta: &Meta, epoch: u64) -> io::Result<()> {
667 let id = id.to_string();
668 let _ = self.youki_status(&["delete", "--force", &id]).await;
669 let d = self.dir(&id);
670 for f in ["pid", "exit", "shim.pid"] {
671 let _ = fs::remove_file(d.join(f));
672 }
673 let args = shim::Args {
674 youki: self.inner.youki.clone(),
675 root: self.inner.root.join("youki"),
676 bundle: d.join("bundle"),
677 dir: d.clone(),
678 log: self.log_path(&id),
679 log_max: LOG_MAX,
680 id: id.clone(),
681 stdin: meta.stdin,
682 tty: meta.tty,
683 };
684 let mut cmd = Command::new(&self.inner.shim);
685 cmd.arg("shim")
686 .args(args.to_args())
687 .stdin(Stdio::null())
688 .stdout(Stdio::null())
689 .stderr(Stdio::null())
690 .kill_on_drop(true);
691 let st = tokio::time::timeout(Duration::from_secs(10), cmd.status())
692 .await
693 .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "krab shim timed out"))??;
694 let mut pid = 0i64;
695 let mut early = (!st.success()).then(|| shim::Exit {
696 code: -1,
697 finished_at: logfile::now_ts(),
698 });
699 for _ in 0..START_TRIES {
700 if early.is_some() {
701 break;
702 }
703 if let Some(x) = shim::read_exit(&d) {
704 early = Some(x);
705 break;
706 }
707 if let Ok(s) = fs::read_to_string(d.join("pid"))
708 && let Ok(p) = s.trim().parse::<i64>()
709 {
710 pid = p;
711 break;
712 }
713 tokio::time::sleep(Duration::from_millis(50)).await;
714 }
715 if early.is_none() && pid == 0 {
716 if let Some(sp) = self.shim_alive(&d) {
717 unsafe {
718 libc::kill(sp, libc::SIGKILL);
719 }
720 }
721 let _ = self.youki_status(&["delete", "--force", &id]).await;
722 early = Some(shim::Exit {
723 code: -1,
724 finished_at: logfile::now_ts(),
725 });
726 }
727 if let Some(x) = early {
728 let mut g = self.lock();
729 if let Some(e) = g.get_mut(&id).filter(|e| e.epoch == epoch) {
730 e.meta.state = "exited".into();
731 e.meta.exit_code = x.code;
732 e.meta.started_at = logfile::now_ts();
733 e.meta.finished_at = x.finished_at;
734 e.meta.pid = 0;
735 let _ = self.persist(&e.meta);
736 }
737 if x.code == 0 || d.join("pid").exists() {
738 return Ok(());
739 }
740 return Err(io::Error::other(format!(
741 "container {id} failed to start (exit code {}), see its logs",
742 x.code
743 )));
744 }
745 let shim_pid = self.shim_alive(&d).unwrap_or(0);
746 {
747 let mut g = self.lock();
748 if let Some(e) = g.get_mut(&id).filter(|e| e.epoch == epoch) {
749 e.meta.state = "running".into();
750 e.meta.started_at = logfile::now_ts();
751 e.meta.finished_at = String::new();
752 e.meta.exit_code = 0;
753 e.meta.oom_killed = false;
754 e.meta.pid = pid;
755 let _ = self.persist(&e.meta);
756 }
757 }
758 tokio::spawn(self.clone().watch(id, epoch, shim_pid));
759 Ok(())
760 }
761
762 async fn watch(self, id: String, epoch: u64, shim_pid: i32) {
763 let d = self.dir(&id);
764 wait_exit(shim_pid, &d).await;
765 let x = shim::read_exit(&d).unwrap_or_else(|| shim::Exit {
766 code: 137,
767 finished_at: logfile::now_ts(),
768 });
769 let code = x.code;
770 let oom = oom_killed(&id);
771 let delay = {
772 let mut g = self.lock();
773 let Some(e) = g.get_mut(&id).filter(|e| e.epoch == epoch) else {
774 return;
775 };
776 e.meta.state = "exited".into();
777 e.meta.exit_code = code;
778 e.meta.oom_killed = oom && code == 137;
779 e.meta.finished_at = x.finished_at;
780 e.meta.pid = 0;
781 let _ = self.persist(&e.meta);
782 let restart = !e.stopping
783 && match e.meta.restart.as_str() {
784 "Never" => false,
785 "OnFailure" => code != 0,
786 _ => true,
787 };
788 if !restart {
789 None
790 } else {
791 if e.launched
792 .is_some_and(|t| t.elapsed() >= Duration::from_secs(10))
793 {
794 e.backoff_ms = 0;
795 }
796 e.backoff_ms = (e.backoff_ms * 2).clamp(100, 60_000);
797 Some(e.backoff_ms)
798 }
799 };
800 let Some(delay) = delay else {
801 if let Some(n) = self.inner.net.clone() {
802 let _ = tokio::task::spawn_blocking(move || n.suspend(&id)).await;
803 }
804 return;
805 };
806 tokio::time::sleep(Duration::from_millis(delay)).await;
807 let _ = self.launch(&id, Some(epoch)).await;
808 }
809
810 async fn wait_not_running(&self, id: &str, limit: Duration) -> bool {
811 let deadline = Instant::now() + limit;
812 loop {
813 if !self.is_running(id) {
814 return true;
815 }
816 if Instant::now() >= deadline {
817 return false;
818 }
819 tokio::time::sleep(Duration::from_millis(100)).await;
820 }
821 }
822
823 async fn pull_inner(&self, image: &str, until: Instant) -> io::Result<()> {
824 let r = registry::parse_reference(image)?;
825 let reference = r.reference.clone();
826 let mut s = Session::new(r);
827 let (mut digest, mut m) = s.manifest(&reference).await?;
828 if let Manifest::Index(list) = &m {
829 let d = registry::pick_platform(list, registry::host_arch())
830 .ok_or_else(|| {
831 io::Error::new(
832 io::ErrorKind::NotFound,
833 format!("{image}: no linux/{} image", registry::host_arch()),
834 )
835 })?
836 .digest
837 .clone();
838 registry::digest_hex(&d)?;
839 (digest, m) = s.manifest(&d).await?;
840 }
841 let Manifest::Image { config, layers } = m else {
842 return Err(io::Error::other(format!("{image}: nested image index")));
843 };
844 let cfg =
845 registry::image_config(&s.blob_bytes(&config.digest, registry::MAX_CONFIG).await?)?;
846 let mut hexes = Vec::new();
847 let mut budget = layer::Limits::default();
848 for l in &layers {
849 let hex = registry::digest_hex(&l.digest)?.to_string();
850 let dst = self.inner.root.join("layers").join(&hex);
851 let lowers: Vec<PathBuf> = hexes
852 .iter()
853 .rev()
854 .map(|h: &String| self.inner.root.join("layers").join(h))
855 .collect();
856 let ll = self.key_lock(&format!("layer:{hex}"));
857 let _lg = ll.lock().await;
858 if !dst.is_dir() {
859 let blob = self.inner.root.join("blobs").join(&hex);
860 s.blob_to_file(&l.digest, &blob, registry::MAX_LAYER)
861 .await?;
862 budget = tokio::task::spawn_blocking(move || {
863 install_layer(&blob, &dst, budget, &lowers, until)
864 })
865 .await
866 .map_err(io::Error::other)??;
867 }
868 hexes.push(hex);
869 }
870 let rec = ImageRecord {
871 image: image.to_string(),
872 digest,
873 config_digest: config.digest,
874 layers: hexes,
875 config: cfg,
876 };
877 write_atomic(
878 &self.image_path(image),
879 &serde_json::to_vec(&rec).map_err(io::Error::other)?,
880 )
881 }
882
883 fn exec_cmd(&self, m: &Meta, cmd: &[String], tty: bool) -> io::Result<Command> {
884 if cmd.is_empty() {
885 return Err(io::Error::new(
886 io::ErrorKind::InvalidInput,
887 "exec: empty command",
888 ));
889 }
890 if m.state != "running" {
891 return Err(io::Error::new(
892 io::ErrorKind::AlreadyExists,
893 format!("container {} is not running", m.id),
894 ));
895 }
896 let mut c = self.youki();
897 c.arg("exec");
898 if m.no_new_privs {
899 c.arg("--no-new-privs");
900 }
901 if tty {
902 c.arg("--tty");
903 }
904 c.arg(&m.id).arg("--").args(cmd);
905 Ok(c)
906 }
907
908 fn seccomp_profile(&self, spec: &ContainerSpec) -> io::Result<Option<&Value>> {
909 match (&self.inner.seccomp, spec.seccomp.as_deref()) {
910 (Some(p), None | Some("RuntimeDefault")) => Ok(Some(p.value())),
911 (Some(_), Some(t @ ("Unconfined" | "Localhost"))) => Err(io::Error::new(
912 io::ErrorKind::InvalidInput,
913 format!("seccompProfile type {t:?} cannot opt out of the operator seccomp profile"),
914 )),
915 (Some(_), Some(t)) => Err(io::Error::new(
916 io::ErrorKind::InvalidInput,
917 format!("seccompProfile type {t:?} is not supported by the native runtime"),
918 )),
919 (None, t) => {
920 seccomp_supported("the native runtime", t, SUPPORTED_SECCOMP)?;
921 Ok(None)
922 }
923 }
924 }
925}
926
927fn oom_killed(id: &str) -> bool {
928 let Some(cg) = crate::cgroup::native_cgroup_path(id) else {
929 return false;
930 };
931 fs::read_to_string(Path::new(CGROUP_ROOT).join(cg).join("memory.events"))
932 .ok()
933 .and_then(|t| {
934 t.lines()
935 .find_map(|l| l.strip_prefix("oom_kill "))
936 .and_then(|n| n.trim().parse::<u64>().ok())
937 })
938 .is_some_and(|n| n > 0)
939}
940
941fn to_info(m: &Meta) -> ContainerInfo {
942 ContainerInfo {
943 id: m.id.clone(),
944 name: m.id.clone(),
945 image: m.image.clone(),
946 image_id: m.image_id.clone(),
947 state: m.state.clone(),
948 created: m.created,
949 labels: m.labels.clone(),
950 ports: Vec::new(),
951 ip: POD_IP.into(),
952 started_at: m.started_at.clone(),
953 finished_at: m.finished_at.clone(),
954 exit_code: m.exit_code,
955 oom_killed: m.oom_killed,
956 restart_count: m.restart_count,
957 tty: m.tty,
958 pid: m.pid,
959 }
960}
961
962fn ensure_volume(v: &Path) -> io::Result<()> {
963 match fs::create_dir(v) {
964 Ok(()) => fs::set_permissions(v, fs::Permissions::from_mode(0o777)),
965 Err(e) if e.kind() == io::ErrorKind::AlreadyExists && v.is_dir() => Ok(()),
966 Err(e) => Err(e),
967 }
968}
969
970fn pid_alive(pid: i32) -> bool {
971 pid > 0 && unsafe { libc::kill(pid, 0) } == 0
972}
973
974#[cfg(target_os = "linux")]
975async fn wait_pidfd(pid: i32) -> bool {
976 use std::os::fd::{FromRawFd, OwnedFd};
977 let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
978 if fd < 0 {
979 return io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
980 }
981 let fd = unsafe { OwnedFd::from_raw_fd(fd as i32) };
982 match unsafe {
983 tokio::io::unix::AsyncFd::register_with_interest(fd, tokio::io::Interest::READABLE)
984 } {
985 Ok(a) => a.readable().await.is_ok(),
986 Err(_) => false,
987 }
988}
989
990#[cfg(not(target_os = "linux"))]
991async fn wait_pidfd(_pid: i32) -> bool {
992 false
993}
994
995async fn wait_exit(shim_pid: i32, dir: &Path) {
996 if shim_pid > 0 && wait_pidfd(shim_pid).await {
997 return;
998 }
999 loop {
1000 if shim::read_exit(dir).is_some() || (shim_pid > 0 && !pid_alive(shim_pid)) {
1001 return;
1002 }
1003 if shim_pid <= 0 && !dir.exists() {
1004 return;
1005 }
1006 tokio::time::sleep(Duration::from_millis(500)).await;
1007 }
1008}
1009
1010fn host_resolv() -> String {
1011 fs::read_to_string("/etc/resolv.conf").unwrap_or_default()
1012}
1013
1014const SUPPORTED_SECCOMP: &[&str] = &["Unconfined"];
1015
1016impl Native {
1017 fn gc_images_blocking(&self, low: u64, high: u64) -> io::Result<usize> {
1018 let root = self.inner.root.clone();
1019 let free = || crate::host::disk_free_percent(&root.to_string_lossy());
1020 if free().is_none_or(|f| f >= low) {
1021 return Ok(0);
1022 }
1023 let (used_imgs, mut used_layers): (BTreeSet<PathBuf>, BTreeSet<String>) = {
1024 let g = self.lock();
1025 (
1026 g.values().map(|e| self.image_path(&e.meta.image)).collect(),
1027 g.values()
1028 .flat_map(|e| e.meta.layers.iter().cloned())
1029 .collect(),
1030 )
1031 };
1032 let mut recs: Vec<(SystemTime, PathBuf, ImageRecord)> = Vec::new();
1033 for ent in fs::read_dir(root.join("images"))?.flatten() {
1034 let path = ent.path();
1035 let Ok(b) = fs::read(&path) else { continue };
1036 let Ok(rec) = serde_json::from_slice::<ImageRecord>(&b) else {
1037 continue;
1038 };
1039 let mtime = ent
1040 .metadata()
1041 .and_then(|m| m.modified())
1042 .unwrap_or(UNIX_EPOCH);
1043 let fresh = mtime
1044 .elapsed()
1045 .is_ok_and(|a| a < Duration::from_secs(IMAGE_GC_MIN_AGE));
1046 if used_imgs.contains(&path) || fresh {
1047 used_layers.extend(rec.layers.iter().cloned());
1048 } else {
1049 recs.push((mtime, path, rec));
1050 }
1051 }
1052 recs.sort_by_key(|r| r.0);
1053 let mut removed = 0;
1054 let mut remaining: Vec<_> = recs.iter().collect();
1055 for (_, path, rec) in &recs {
1056 if free().is_none_or(|f| f >= high) {
1057 break;
1058 }
1059 if fs::remove_file(path).is_err() {
1060 continue;
1061 }
1062 removed += 1;
1063 remaining.retain(|r| r.1 != *path);
1064 let keep: BTreeSet<&String> = used_layers
1065 .iter()
1066 .chain(remaining.iter().flat_map(|r| r.2.layers.iter()))
1067 .collect();
1068 for l in &rec.layers {
1069 if !keep.contains(l) && registry::digest_hex(&format!("sha256:{l}")).is_ok() {
1070 let _ = fs::remove_dir_all(root.join("layers").join(l));
1071 }
1072 }
1073 }
1074 Ok(removed)
1075 }
1076}
1077
1078impl Runtime for Native {
1079 async fn gc_images(&self, low: u64, high: u64) -> io::Result<usize> {
1080 let me = self.clone();
1081 tokio::task::spawn_blocking(move || me.gc_images_blocking(low, high))
1082 .await
1083 .map_err(io::Error::other)?
1084 }
1085
1086 fn name(&self) -> &str {
1087 "native"
1088 }
1089
1090 async fn list(&self) -> io::Result<Vec<ContainerInfo>> {
1091 self.adopt_pending();
1092 Ok(self.lock().values().map(|e| self.info(&e.meta)).collect())
1093 }
1094
1095 async fn inspect(&self, info: &mut ContainerInfo) -> io::Result<()> {
1096 self.adopt_pending();
1097 let m = self
1098 .meta(&info.id)
1099 .or_else(|_| self.meta(info.name.trim_start_matches('/')))?;
1100 *info = self.info(&m);
1101 Ok(())
1102 }
1103
1104 async fn logs(
1105 &self,
1106 info: &ContainerInfo,
1107 opts: &LogOpts,
1108 ) -> io::Result<mpsc::Receiver<Bytes>> {
1109 let m = self.meta(&info.id)?;
1110 let path = self.log_path(&m.id);
1111 let opts = opts.clone();
1112 let me = self.clone();
1113 let (tx, rx) = mpsc::channel(8);
1114 tokio::spawn(async move {
1115 let mut render =
1116 Render::new(opts.timestamps, opts.since_seconds.map(logfile::since_ts));
1117 let cur = tokio::fs::read(&path).await.unwrap_or_default();
1118 let mut ino = tokio::fs::metadata(&path).await.map(|m| m.ino()).ok();
1119 let initial: Vec<u8> = match opts.tail {
1120 Some(n) => {
1121 let t = logfile::tail_lines(&cur, n);
1122 if t.len() == cur.len() {
1123 let mut all = tokio::fs::read(logfile::rotated(&path))
1124 .await
1125 .unwrap_or_default();
1126 all.extend_from_slice(&cur);
1127 logfile::tail_lines(&all, n).to_vec()
1128 } else {
1129 t.to_vec()
1130 }
1131 }
1132 None => {
1133 let mut all = tokio::fs::read(logfile::rotated(&path))
1134 .await
1135 .unwrap_or_default();
1136 all.extend_from_slice(&cur);
1137 all
1138 }
1139 };
1140 let send_lines = |data: &[u8], render: &mut Render| -> Vec<Bytes> {
1141 let mut chunks = Vec::new();
1142 let mut out = Vec::new();
1143 for line in data.split(|b| *b == b'\n').filter(|l| !l.is_empty()) {
1144 if let Some(r) = logfile::parse(line)
1145 && render.accept(&r)
1146 {
1147 render.render(&r, &mut out);
1148 if out.len() >= 32 * 1024 {
1149 chunks.push(Bytes::from(std::mem::take(&mut out)));
1150 }
1151 }
1152 }
1153 if !out.is_empty() {
1154 chunks.push(Bytes::from(out));
1155 }
1156 chunks
1157 };
1158 for c in send_lines(&initial, &mut render) {
1159 if tx.send(c).await.is_err() {
1160 return;
1161 }
1162 }
1163 drop(initial);
1164 if !opts.follow {
1165 return;
1166 }
1167 let mut pos = cur.len() as u64;
1168 drop(cur);
1169 loop {
1170 tokio::time::sleep(Duration::from_millis(250)).await;
1171 if tx.is_closed() {
1172 return;
1173 }
1174 let running = me.is_running(&m.id);
1175 let Ok(md) = tokio::fs::metadata(&path).await else {
1176 if !running {
1177 return;
1178 }
1179 continue;
1180 };
1181 if Some(md.ino()) != ino || md.len() < pos {
1182 ino = Some(md.ino());
1183 pos = 0;
1184 }
1185 if md.len() > pos {
1186 let Ok(mut f) = tokio::fs::File::open(&path).await else {
1187 continue;
1188 };
1189 use tokio::io::AsyncSeekExt;
1190 if f.seek(io::SeekFrom::Start(pos)).await.is_err() {
1191 continue;
1192 }
1193 let want = (md.len() - pos).min(1 << 20) as usize;
1194 let mut buf = vec![0u8; want];
1195 let Ok(n) = f.read(&mut buf).await else {
1196 continue;
1197 };
1198 buf.truncate(n);
1199 let Some(last) = buf.iter().rposition(|b| *b == b'\n') else {
1200 continue;
1201 };
1202 pos += last as u64 + 1;
1203 for c in send_lines(&buf[..=last], &mut render) {
1204 if tx.send(c).await.is_err() {
1205 return;
1206 }
1207 }
1208 continue;
1209 }
1210 if !running {
1211 return;
1212 }
1213 }
1214 });
1215 Ok(rx)
1216 }
1217
1218 async fn pull_image(&self, image: &str) -> io::Result<()> {
1219 let lock = self.key_lock(&format!("image:{image}"));
1220 let _g = lock.lock().await;
1221 let until = Instant::now() + registry::PULL_DEADLINE;
1222 tokio::time::timeout(registry::PULL_DEADLINE, self.pull_inner(image, until))
1223 .await
1224 .map_err(|_| {
1225 io::Error::new(
1226 io::ErrorKind::TimedOut,
1227 format!(
1228 "{image}: pull exceeded {}s",
1229 registry::PULL_DEADLINE.as_secs()
1230 ),
1231 )
1232 })?
1233 }
1234
1235 async fn create_container(&self, spec: &ContainerSpec) -> io::Result<String> {
1236 if !spec.name.starts_with(NAME_PREFIX)
1237 || spec.labels.get(MANAGED_LABEL).map(String::as_str) != Some("true")
1238 {
1239 return Err(io::Error::new(
1240 io::ErrorKind::PermissionDenied,
1241 "container spec is not krab-managed",
1242 ));
1243 }
1244 let seccomp = self.seccomp_profile(spec)?;
1245 let id = spec.name.clone();
1246 if !id_ok(&id) {
1247 return Err(io::Error::new(
1248 io::ErrorKind::InvalidInput,
1249 format!("bad container name {id:?}"),
1250 ));
1251 }
1252 if self.lock().contains_key(&id) {
1253 return Err(io::Error::new(
1254 io::ErrorKind::AlreadyExists,
1255 format!("container {id} already exists"),
1256 ));
1257 }
1258 let rec = self.load_image(&spec.image)?;
1259 let cg = format!(
1260 "/{}",
1261 crate::cgroup::native_cgroup_path(&id).unwrap_or_default()
1262 );
1263 self.cleanup_dir(&id);
1264 let attach = match self.inner.net.clone() {
1265 Some(n) => {
1266 let key = pod_key(&spec.labels)?;
1267 let (aid, ports) = (id.clone(), spec.ports.clone());
1268 Some(
1269 tokio::task::spawn_blocking(move || n.attach(&key, &aid, &ports))
1270 .await
1271 .map_err(io::Error::other)??,
1272 )
1273 }
1274 None => None,
1275 };
1276 let d = self.dir(&id);
1277 let res = (|| -> io::Result<Meta> {
1278 for sub in ["bundle/rootfs", "upper", "work"] {
1279 fs::create_dir_all(d.join(sub))?;
1280 }
1281 fs::set_permissions(d.join("bundle"), fs::Permissions::from_mode(0o700))?;
1282 self.mount_rootfs(&id, &rec.layers)?;
1283 let rootfs = self.rootfs(&id);
1284 let mut process = oci::merge(spec, &rec.config)?;
1285 let rd = |p| {
1286 layer::read_in_root(&rootfs, p, 1 << 20)
1287 .map(|b| String::from_utf8_lossy(&b).into_owned())
1288 .unwrap_or_default()
1289 };
1290 let passwd = rd("etc/passwd");
1291 let user = oci::resolve_user(&process.user, &passwd, &rd("etc/group"))?;
1292 oci::set_home(&mut process.env, user.uid, &passwd);
1293 for m in &spec.mounts {
1294 if let Mount::Volume { name, .. } = m
1295 && crate::policy::data_key_ok(name)
1296 && !name.starts_with('.')
1297 {
1298 ensure_volume(&self.inner.root.join("volumes").join(name))?;
1299 }
1300 }
1301 let hostname = spec.hostname.clone().unwrap_or_default();
1302 fs::write(d.join("hostname"), format!("{hostname}\n"))?;
1303 let resolv = match (&attach, &self.inner.net) {
1304 (Some(_), Some(n)) => net::pod_resolv_with(
1305 n.dns(),
1306 &host_resolv(),
1307 &fs::read_to_string("/run/systemd/resolve/resolv.conf").unwrap_or_default(),
1308 |ip| n.may_reach(ip),
1309 ),
1310 _ => host_resolv(),
1311 };
1312 fs::write(
1313 d.join("resolv.conf"),
1314 oci::resolv_conf(&resolv, &spec.dns_search, &spec.dns_options),
1315 )?;
1316 let own_ip = attach
1317 .as_ref()
1318 .map(|a| a.ip.to_string())
1319 .unwrap_or_else(|| POD_IP.into());
1320 for e in process.env.iter_mut() {
1321 if e.contains(crate::POD_IP_TOKEN) {
1322 *e = e.replace(crate::POD_IP_TOKEN, &own_ip);
1323 }
1324 }
1325 fs::write(d.join("hosts"), oci::pod_hosts(&hostname, &own_ip, &[]))?;
1326 let b = oci::Bundle {
1327 cgroups_path: &cg,
1328 hosts: &d.join("hosts"),
1329 resolv: &d.join("resolv.conf"),
1330 hostname_file: &d.join("hostname"),
1331 volume_root: &self.inner.root.join("volumes"),
1332 netns: attach.as_ref().map(|a| a.netns.as_path()),
1333 seccomp,
1334 };
1335 let cfg = oci::config_json(spec, &process, &user, &b)?;
1336 fs::write(
1337 d.join("bundle/config.json"),
1338 serde_json::to_vec_pretty(&cfg).map_err(io::Error::other)?,
1339 )?;
1340 let m = Meta {
1341 id: id.clone(),
1342 image: spec.image.clone(),
1343 image_id: rec.config_digest.clone(),
1344 labels: spec.labels.clone(),
1345 created: now_secs(),
1346 state: "created".into(),
1347 started_at: "0001-01-01T00:00:00Z".into(),
1348 finished_at: "0001-01-01T00:00:00Z".into(),
1349 tty: spec.tty,
1350 stdin: spec.stdin,
1351 restart: match spec.restart {
1352 crate::RestartPolicy::Always => "Always",
1353 crate::RestartPolicy::OnFailure => "OnFailure",
1354 crate::RestartPolicy::Never => "Never",
1355 }
1356 .into(),
1357 aliases: spec.aliases.clone(),
1358 hostname,
1359 no_new_privs: !spec.allow_privilege_escalation,
1360 layers: rec.layers.clone(),
1361 ..Default::default()
1362 };
1363 self.persist(&m)?;
1364 Ok(m)
1365 })();
1366 let m = match res {
1367 Ok(m) => m,
1368 Err(e) => {
1369 self.cleanup_dir(&id);
1370 self.net_release(&id).await;
1371 return Err(e);
1372 }
1373 };
1374 self.lock().insert(
1375 id.clone(),
1376 Entry {
1377 meta: m,
1378 stopping: false,
1379 epoch: 0,
1380 backoff_ms: 0,
1381 launched: None,
1382 starting: false,
1383 },
1384 );
1385 self.rewrite_hosts();
1386 Ok(id)
1387 }
1388
1389 async fn start(&self, id: &str) -> io::Result<()> {
1390 self.ensure_managed(id)?;
1391 {
1392 let mut g = self.lock();
1393 let e = g.get_mut(id).ok_or_else(|| not_found(id))?;
1394 if e.meta.state == "running" || e.starting {
1395 return Ok(());
1396 }
1397 e.stopping = false;
1398 }
1399 if let Some(n) = self.inner.net.clone() {
1400 let nid = id.to_string();
1401 tokio::task::spawn_blocking(move || n.resume(&nid))
1402 .await
1403 .map_err(io::Error::other)??;
1404 }
1405 self.launch(id, None).await
1406 }
1407
1408 async fn stop(&self, id: &str, timeout_secs: u64) -> io::Result<()> {
1409 self.adopt_pending();
1410 self.ensure_managed(id)?;
1411 {
1412 let mut g = self.lock();
1413 if let Some(e) = g.get_mut(id) {
1414 e.stopping = true;
1415 }
1416 }
1417 if !self.is_running(id) {
1418 return Ok(());
1419 }
1420 let _ = self.youki_status(&["kill", id, "SIGTERM"]).await;
1421 if self
1422 .wait_not_running(id, Duration::from_secs(timeout_secs))
1423 .await
1424 {
1425 return Ok(());
1426 }
1427 let _ = self.youki_status(&["kill", id, "SIGKILL"]).await;
1428 if self.wait_not_running(id, Duration::from_secs(10)).await {
1429 Ok(())
1430 } else {
1431 Err(io::Error::other(format!("container {id} did not stop")))
1432 }
1433 }
1434
1435 async fn remove(&self, id: &str, force: bool) -> io::Result<()> {
1436 self.ensure_managed(id)?;
1437 if self.is_running(id) {
1438 if !force {
1439 return Err(io::Error::new(
1440 io::ErrorKind::AlreadyExists,
1441 format!("container {id} is running"),
1442 ));
1443 }
1444 self.stop(id, 0).await?;
1445 }
1446 let _ = self.youki_status(&["delete", "--force", id]).await;
1447 self.lock().remove(id);
1448 self.cleanup_dir(id);
1449 self.net_release(id).await;
1450 let log = self.log_path(id);
1451 let _ = fs::remove_file(logfile::rotated(&log));
1452 let _ = fs::remove_file(&log);
1453 if let Some(cg) = crate::cgroup::native_cgroup_path(id) {
1454 let p = Path::new(CGROUP_ROOT).join(cg);
1455 let _ = fs::remove_dir(&p);
1456 if let Some(parent) = p.parent() {
1457 let _ = fs::remove_dir(parent);
1458 }
1459 }
1460 self.rewrite_hosts();
1461 Ok(())
1462 }
1463
1464 async fn ensure_network(&self, _name: &str) -> io::Result<()> {
1465 Ok(())
1466 }
1467
1468 async fn remove_network(&self, _name: &str) -> io::Result<()> {
1469 Ok(())
1470 }
1471
1472 async fn connect_network(
1473 &self,
1474 container: &str,
1475 _network: &str,
1476 aliases: &[String],
1477 ) -> io::Result<()> {
1478 self.ensure_managed(container)?;
1479 {
1480 let mut g = self.lock();
1481 if let Some(e) = g.get_mut(container) {
1482 e.meta.aliases = aliases.to_vec();
1483 let _ = self.persist(&e.meta);
1484 }
1485 }
1486 self.rewrite_hosts();
1487 Ok(())
1488 }
1489
1490 async fn disconnect_network(&self, container: &str, _network: &str) -> io::Result<()> {
1491 self.ensure_managed(container).map(|_| ())
1492 }
1493
1494 async fn remove_volume(&self, name: &str) -> io::Result<()> {
1495 if !name.starts_with("krab") || !crate::policy::data_key_ok(name) {
1496 return Err(io::Error::new(
1497 io::ErrorKind::PermissionDenied,
1498 format!("{name} is not managed by krab"),
1499 ));
1500 }
1501 match fs::remove_dir_all(self.inner.root.join("volumes").join(name)) {
1502 Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
1503 _ => Ok(()),
1504 }
1505 }
1506
1507 async fn exec_run(&self, id: &str, cmd: &[String]) -> io::Result<(i64, Vec<u8>)> {
1508 let m = self.ensure_managed(id)?;
1509 let mut c = self.exec_cmd(&m, cmd, false)?;
1510 c.kill_on_drop(true);
1511 let out = c.output().await?;
1512 let mut buf = out.stdout;
1513 buf.extend_from_slice(&out.stderr);
1514 buf.truncate(64 * 1024);
1515 Ok((exit_code(&out.status), buf))
1516 }
1517
1518 async fn exec_stream(&self, id: &str, opts: &ExecOpts) -> io::Result<ExecHandle> {
1519 let m = self.ensure_managed(id)?;
1520 let mut c = self.exec_cmd(&m, &opts.cmd, opts.tty)?;
1521 c.stdin(if opts.stdin {
1522 Stdio::piped()
1523 } else {
1524 Stdio::null()
1525 })
1526 .stdout(Stdio::piped())
1527 .stderr(Stdio::piped());
1528 let mut child = c.spawn()?;
1529 let exec_id = format!(
1530 "exec-{}-{}",
1531 std::process::id(),
1532 self.inner.seq.fetch_add(1, Ordering::Relaxed)
1533 );
1534 let (otx, orx) = mpsc::channel::<Bytes>(16);
1535 let (etx, erx) = mpsc::channel::<Bytes>(16);
1536 type Sink = Box<dyn tokio::io::AsyncWrite + Unpin + Send>;
1537 let stdin = child.stdin.take().map(|i| Box::new(i) as Sink);
1538 if let Some(o) = child.stdout.take() {
1539 tokio::spawn(pump_chan(o, otx));
1540 }
1541 if let Some(e) = child.stderr.take() {
1542 tokio::spawn(pump_chan(e, etx));
1543 }
1544 {
1545 let mut ex = self.execs();
1546 if ex.len() > 256 {
1547 ex.retain(|_, s| s.code.is_none());
1548 }
1549 ex.insert(exec_id.clone(), ExecState { code: None });
1550 }
1551 let me = self.clone();
1552 let eid = exec_id.clone();
1553 tokio::spawn(async move {
1554 let code = child.wait().await.map(|s| exit_code(&s)).unwrap_or(-1);
1555 if let Some(s) = me.execs().get_mut(&eid) {
1556 s.code = Some(code);
1557 }
1558 });
1559 Ok(ExecHandle {
1560 exec_id,
1561 stdout: orx,
1562 stderr: erx,
1563 stdin,
1564 hold: None,
1565 })
1566 }
1567
1568 async fn exec_resize(&self, exec_id: &str, _width: u32, _height: u32) -> io::Result<()> {
1569 if self.execs().contains_key(exec_id) {
1570 Ok(())
1571 } else {
1572 Err(not_found(exec_id))
1573 }
1574 }
1575
1576 async fn shutdown(&self) {
1577 self.shutdown_all().await
1578 }
1579
1580 async fn exec_exit_code(&self, exec_id: &str) -> io::Result<i64> {
1581 let mut ex = self.execs();
1582 match ex.get(exec_id).map(|s| s.code) {
1583 Some(Some(c)) => {
1584 ex.remove(exec_id);
1585 Ok(c)
1586 }
1587 Some(None) => Err(io::Error::other("exec is still running")),
1588 None => Err(not_found(exec_id)),
1589 }
1590 }
1591}
1592
1593#[cfg(test)]
1594mod tests {
1595 use super::*;
1596
1597 fn root(tag: &str) -> PathBuf {
1598 let d = std::env::temp_dir().join(format!("krab-native-{tag}-{}", std::process::id()));
1599 let _ = fs::remove_dir_all(&d);
1600 d
1601 }
1602
1603 #[test]
1604 fn ids_and_cgroups() {
1605 assert!(id_ok("krab_default_web_nginx"));
1606 assert!(!id_ok("krab_default_web"));
1607 assert!(!id_ok("other_default_web_nginx"));
1608 assert!(!id_ok("krab_default_we/b_nginx"));
1609 assert_eq!(
1610 crate::cgroup::native_cgroup_path("krab_default_web_nginx").as_deref(),
1611 Some("krab/default_web/nginx")
1612 );
1613 }
1614
1615 #[tokio::test]
1616 async fn create_rejects_unsupported_seccomp() {
1617 let r = root("seccomp");
1618 let n = Native::new(&r, "/nonexistent/youki").unwrap();
1619 let mut labels = BTreeMap::new();
1620 labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
1621 let base = ContainerSpec {
1622 name: "krab_default_p_c".into(),
1623 image: "busybox:1.37".into(),
1624 labels,
1625 ..Default::default()
1626 };
1627 for t in ["RuntimeDefault", "Localhost"] {
1628 let mut spec = base.clone();
1629 spec.seccomp = Some(t.into());
1630 assert_eq!(
1631 n.create_container(&spec).await.unwrap_err().kind(),
1632 io::ErrorKind::InvalidInput,
1633 "{t}"
1634 );
1635 }
1636 for t in [None, Some("Unconfined".to_string())] {
1637 let mut spec = base.clone();
1638 spec.seccomp = t;
1639 assert_ne!(
1640 n.create_container(&spec).await.unwrap_err().kind(),
1641 io::ErrorKind::InvalidInput
1642 );
1643 }
1644 let _ = fs::remove_dir_all(&r);
1645 }
1646
1647 fn profile_file(tag: &str, body: &str) -> PathBuf {
1648 let p =
1649 std::env::temp_dir().join(format!("krab-seccomp-{tag}-{}.json", std::process::id()));
1650 fs::write(&p, body).unwrap();
1651 p
1652 }
1653
1654 #[tokio::test]
1655 async fn operator_profile_locks_seccomp_modes() {
1656 let r = root("seccomp-profile");
1657 let pf = profile_file(
1658 "ok",
1659 r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read","write","exit","exit_group"],"action":"SCMP_ACT_ALLOW"}]}"#,
1660 );
1661 let n = Native::new_with_profile(&r, "/nonexistent/youki", None, Some(pf.clone())).unwrap();
1662 let mut labels = BTreeMap::new();
1663 labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
1664 let base = ContainerSpec {
1665 name: "krab_default_p_c".into(),
1666 image: "busybox:1.37".into(),
1667 labels,
1668 ..Default::default()
1669 };
1670 for t in [None, Some("RuntimeDefault".to_string())] {
1671 let mut spec = base.clone();
1672 spec.seccomp = t;
1673 assert_ne!(
1674 n.create_container(&spec).await.unwrap_err().kind(),
1675 io::ErrorKind::InvalidInput
1676 );
1677 }
1678 for t in ["Unconfined", "Localhost"] {
1679 let mut spec = base.clone();
1680 spec.seccomp = Some(t.into());
1681 let e = n.create_container(&spec).await.unwrap_err();
1682 assert_eq!(e.kind(), io::ErrorKind::InvalidInput, "{t}");
1683 assert!(e.to_string().contains("cannot opt out"), "{e}");
1684 }
1685 for t in ["DockerDefault", "runtimeDefault", ""] {
1686 let mut spec = base.clone();
1687 spec.seccomp = Some(t.into());
1688 let e = n.create_container(&spec).await.unwrap_err();
1689 assert_eq!(e.kind(), io::ErrorKind::InvalidInput, "{t}");
1690 assert!(e.to_string().contains("is not supported"), "{e}");
1691 }
1692 let _ = fs::remove_dir_all(&r);
1693 let _ = fs::remove_file(&pf);
1694 }
1695
1696 #[tokio::test]
1697 async fn bad_profile_fails_startup_before_root() {
1698 let r = root("seccomp-bad");
1699 let pf = profile_file("bad", r#"{"defaultAction":"SCMP_ACT_ALLOW"}"#);
1700 let e = match Native::new_with_profile(&r, "/nonexistent/youki", None, Some(pf.clone())) {
1701 Ok(_) => panic!("default-allow profile accepted"),
1702 Err(e) => e,
1703 };
1704 assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
1705 assert!(e.to_string().contains("defaultAction"), "{e}");
1706 assert!(!r.exists());
1707 let e = match Native::new_with_profile(
1708 &r,
1709 "/nonexistent/youki",
1710 None,
1711 Some(pf.with_extension("missing")),
1712 ) {
1713 Ok(_) => panic!("missing profile accepted"),
1714 Err(e) => e,
1715 };
1716 assert_eq!(e.kind(), io::ErrorKind::NotFound);
1717 let _ = fs::remove_file(&pf);
1718 }
1719
1720 #[test]
1721 fn loads_state_and_lists_managed() {
1722 let r = root("load");
1723 let n = Native::new(&r, "/nonexistent/youki").unwrap();
1724 let id = "krab_default_p_c";
1725 let mut labels = BTreeMap::new();
1726 labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
1727 let m = Meta {
1728 id: id.into(),
1729 labels,
1730 state: "exited".into(),
1731 exit_code: 3,
1732 restart_count: 2,
1733 ..Default::default()
1734 };
1735 fs::create_dir_all(n.dir(id)).unwrap();
1736 n.persist(&m).unwrap();
1737 fs::create_dir_all(n.dir("bogus")).unwrap();
1738 fs::write(n.dir("bogus").join("meta.json"), br#"{"id":"../x"}"#).unwrap();
1739 let n = Native::new(&r, "/nonexistent/youki").unwrap();
1740 let rt = tokio::runtime::Builder::new_current_thread()
1741 .enable_all()
1742 .build()
1743 .unwrap();
1744 rt.block_on(async {
1745 let list = n.list().await.unwrap();
1746 assert_eq!(list.len(), 1);
1747 assert!(is_managed(&list[0]));
1748 assert_eq!(list[0].exit_code, 3);
1749 assert_eq!(list[0].ip, POD_IP);
1750 let mut info = ContainerInfo {
1751 id: id.into(),
1752 ..Default::default()
1753 };
1754 n.inspect(&mut info).await.unwrap();
1755 assert_eq!(info.restart_count, 2);
1756 let mut missing = ContainerInfo {
1757 id: "krab_x_y_z".into(),
1758 ..Default::default()
1759 };
1760 assert_eq!(
1761 n.inspect(&mut missing).await.unwrap_err().kind(),
1762 io::ErrorKind::NotFound
1763 );
1764 let spec = ContainerSpec {
1765 name: "krab_default_q_c".into(),
1766 image: "busybox:1.37".into(),
1767 labels: list[0].labels.clone(),
1768 ..Default::default()
1769 };
1770 assert_eq!(
1771 n.create_container(&spec).await.unwrap_err().kind(),
1772 io::ErrorKind::NotFound
1773 );
1774 let foreign = ContainerSpec {
1775 name: "other".into(),
1776 ..spec.clone()
1777 };
1778 assert_eq!(
1779 n.create_container(&foreign).await.unwrap_err().kind(),
1780 io::ErrorKind::PermissionDenied
1781 );
1782 assert!(n.remove_volume("../etc").await.is_err());
1783 n.connect_network(id, "krab", &["db".into()]).await.unwrap();
1784 assert!(
1785 fs::read_to_string(n.dir(id).join("hosts"))
1786 .unwrap()
1787 .contains("\tdb\n")
1788 );
1789 let mut w = logfile::LogWriter::open(&n.log_path(id), 1 << 20).unwrap();
1790 w.write(0, b"one\ntwo\nthree\n").unwrap();
1791 let mut rx = n
1792 .logs(
1793 &info,
1794 &LogOpts {
1795 tail: Some(2),
1796 ..Default::default()
1797 },
1798 )
1799 .await
1800 .unwrap();
1801 let mut got = Vec::new();
1802 while let Some(b) = rx.recv().await {
1803 got.extend_from_slice(&b);
1804 }
1805 assert_eq!(got, b"two\nthree\n");
1806 assert!(n.exec_run(id, &["true".into()]).await.is_err());
1807 });
1808 fs::remove_dir_all(&r).unwrap();
1809 }
1810
1811 fn managed(n: &Native, id: &str, state: &str) {
1812 let mut labels = BTreeMap::new();
1813 labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
1814 n.lock().insert(
1815 id.into(),
1816 Entry {
1817 meta: Meta {
1818 id: id.into(),
1819 labels,
1820 state: state.into(),
1821 layers: vec!["a".repeat(64)],
1822 no_new_privs: true,
1823 ..Default::default()
1824 },
1825 stopping: false,
1826 epoch: 5,
1827 backoff_ms: 0,
1828 launched: None,
1829 starting: false,
1830 },
1831 );
1832 }
1833
1834 #[test]
1835 fn exec_separates_user_command() {
1836 let r = root("exec");
1837 let n = Native::new(&r, "/nonexistent/youki").unwrap();
1838 let id = "krab_default_p_c";
1839 managed(&n, id, "running");
1840 let m = n.meta(id).unwrap();
1841 let c = n
1842 .exec_cmd(&m, &["--root".into(), "/tmp".into()], true)
1843 .unwrap();
1844 let args: Vec<String> = c
1845 .as_std()
1846 .get_args()
1847 .map(|a| a.to_string_lossy().into_owned())
1848 .collect();
1849 assert_eq!(
1850 &args[2..],
1851 [
1852 "exec",
1853 "--no-new-privs",
1854 "--tty",
1855 id,
1856 "--",
1857 "--root",
1858 "/tmp"
1859 ]
1860 );
1861 fs::remove_dir_all(&r).unwrap();
1862 }
1863
1864 #[test]
1865 fn concurrent_start_does_not_relaunch() {
1866 let r = root("race");
1867 let n = Native::new(&r, "/nonexistent/youki").unwrap();
1868 let id = "krab_default_p_c";
1869 managed(&n, id, "exited");
1870 let rt = tokio::runtime::Builder::new_current_thread()
1871 .enable_all()
1872 .build()
1873 .unwrap();
1874 rt.block_on(async {
1875 n.lock().get_mut(id).unwrap().starting = true;
1876 n.start(id).await.unwrap();
1877 n.launch(id, None).await.unwrap();
1878 assert_eq!(n.lock()[id].epoch, 5);
1879 n.lock().get_mut(id).unwrap().starting = false;
1880 n.launch(id, Some(4)).await.unwrap();
1881 n.lock().get_mut(id).unwrap().stopping = true;
1882 n.launch(id, Some(5)).await.unwrap();
1883 let got = {
1884 let g = n.lock();
1885 (g[id].epoch, g[id].meta.restart_count)
1886 };
1887 assert_eq!(got, (5, 0));
1888 n.lock().get_mut(id).unwrap().meta.state = "running".into();
1889 n.start(id).await.unwrap();
1890 n.launch(id, None).await.unwrap();
1891 assert_eq!(n.lock()[id].epoch, 5);
1892 n.lock().get_mut(id).unwrap().meta.state = "exited".into();
1893 assert!(n.start(id).await.is_err());
1894 let e = &n.lock()[id];
1895 assert_eq!((e.epoch, e.starting), (5, false));
1896 });
1897 fs::remove_dir_all(&r).unwrap();
1898 }
1899
1900 #[test]
1901 fn empty_dir_is_world_writable() {
1902 let r = root("vol");
1903 fs::create_dir_all(&r).unwrap();
1904 let v = r.join("krab_u_e");
1905 ensure_volume(&v).unwrap();
1906 assert_eq!(fs::metadata(&v).unwrap().mode() & 0o7777, 0o777);
1907 fs::set_permissions(&v, fs::Permissions::from_mode(0o700)).unwrap();
1908 ensure_volume(&v).unwrap();
1909 assert_eq!(fs::metadata(&v).unwrap().mode() & 0o7777, 0o700);
1910 fs::write(r.join("file"), b"").unwrap();
1911 assert!(ensure_volume(&r.join("file")).is_err());
1912 fs::remove_dir_all(&r).unwrap();
1913 }
1914
1915 #[test]
1916 fn pull_locks_are_per_key() {
1917 let r = root("locks");
1918 let n = Native::new(&r, "/nonexistent/youki").unwrap();
1919 let a = n.key_lock("image:a");
1920 assert!(Arc::ptr_eq(&a, &n.key_lock("image:a")));
1921 let b = n.key_lock("image:b");
1922 assert!(!Arc::ptr_eq(&a, &b));
1923 let _ga = a.try_lock().unwrap();
1924 assert!(b.try_lock().is_ok());
1925 assert!(n.key_lock("image:a").try_lock().is_err());
1926 drop(b);
1927 n.key_lock("image:c");
1928 assert!(!n.inner.pull_locks.lock().unwrap().contains_key("image:b"));
1929 fs::remove_dir_all(&r).unwrap();
1930 }
1931
1932 #[test]
1933 fn install_layer_budget_deadline_and_blob_cleanup() {
1934 let r = root("install");
1935 fs::create_dir_all(&r).unwrap();
1936 let mut b = tar::Builder::new(Vec::new());
1937 let mut h = tar::Header::new_gnu();
1938 h.set_path("f").unwrap();
1939 h.set_size(3);
1940 h.set_mode(0o644);
1941 h.set_cksum();
1942 b.append(&h, &b"abc"[..]).unwrap();
1943 let data = b.into_inner().unwrap();
1944 let blob = r.join("blob");
1945 fs::write(&blob, &data).unwrap();
1946 let late = Instant::now() - Duration::from_secs(1);
1947 let err =
1948 install_layer(&blob, &r.join("l0"), layer::Limits::default(), &[], late).unwrap_err();
1949 assert_eq!(err.kind(), io::ErrorKind::TimedOut);
1950 assert!(blob.exists() && !r.join("l0").exists());
1951 let small = layer::Limits {
1952 max_bytes: 2,
1953 max_entries: 10,
1954 };
1955 let until = Instant::now() + Duration::from_secs(60);
1956 assert!(install_layer(&blob, &r.join("l0"), small, &[], until).is_err());
1957 assert!(blob.exists());
1958 let left =
1959 install_layer(&blob, &r.join("l1"), layer::Limits::default(), &[], until).unwrap();
1960 assert_eq!(fs::read(r.join("l1/f")).unwrap(), b"abc");
1961 assert!(!blob.exists());
1962 assert_eq!(
1963 (left.max_bytes, left.max_entries),
1964 (
1965 layer::Limits::default().max_bytes - 3,
1966 layer::Limits::default().max_entries - 1
1967 )
1968 );
1969 fs::remove_dir_all(&r).unwrap();
1970 }
1971
1972 #[cfg(target_os = "linux")]
1973 #[test]
1974 fn running_containers_are_adopted_after_restart() {
1975 let r = root("adopt");
1976 let n = Native::new(&r, "/nonexistent/youki").unwrap();
1977 let mut labels = BTreeMap::new();
1978 labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
1979 let mk = |id: &str| {
1980 let m = Meta {
1981 id: id.into(),
1982 labels: labels.clone(),
1983 state: "running".into(),
1984 restart_count: 4,
1985 pid: 42,
1986 ..Default::default()
1987 };
1988 fs::create_dir_all(n.dir(id)).unwrap();
1989 n.persist(&m).unwrap();
1990 };
1991 let (live, done, lost) = ("krab_d_p_live", "krab_d_p_done", "krab_d_p_lost");
1992 for id in [live, done, lost] {
1993 mk(id);
1994 }
1995 let sleep = net::which("sleep").unwrap();
1996 let mut shim = std::process::Command::new(&sleep)
1997 .arg("30")
1998 .spawn()
1999 .unwrap();
2000 let sp = shim.id() as i32;
2001 let start = shim::proc_starttime(sp).unwrap();
2002 fs::write(n.dir(live).join("shim.pid"), format!("{sp} {start}")).unwrap();
2003 fs::write(n.dir(lost).join("shim.pid"), format!("{sp} {}", start + 1)).unwrap();
2004 fs::write(
2005 n.dir(done).join("exit"),
2006 br#"{"code":3,"finished_at":"2026-11-30T00:00:00Z"}"#,
2007 )
2008 .unwrap();
2009 drop(n);
2010 let n = Native::open(
2011 fs::canonicalize(&r).unwrap(),
2012 "/nonexistent/youki".into(),
2013 None,
2014 fs::canonicalize(&sleep).unwrap(),
2015 None,
2016 )
2017 .unwrap();
2018 assert_eq!(n.shim_alive(&n.dir(live)), Some(sp));
2019 let other = Native::new(r.join("other"), "/nonexistent/youki").unwrap();
2020 assert_eq!(other.shim_alive(&n.dir(live)), None);
2021 let get = |n: &Native, id: &str| n.meta(id).unwrap();
2022 assert_eq!(get(&n, live).state, "running");
2023 assert_eq!(get(&n, live).restart_count, 4);
2024 assert_eq!(get(&n, live).pid, 42);
2025 assert_eq!(
2026 (get(&n, done).state.as_str(), get(&n, done).exit_code),
2027 ("exited", 3)
2028 );
2029 assert_eq!(
2030 (get(&n, lost).state.as_str(), get(&n, lost).exit_code),
2031 ("exited", 137)
2032 );
2033 let rt = tokio::runtime::Builder::new_current_thread()
2034 .enable_all()
2035 .build()
2036 .unwrap();
2037 rt.block_on(async {
2038 n.list().await.unwrap();
2039 tokio::time::sleep(Duration::from_millis(300)).await;
2040 assert_eq!(get(&n, live).state, "running");
2041 n.lock().get_mut(live).unwrap().stopping = true;
2042 fs::write(
2043 n.dir(live).join("exit"),
2044 br#"{"code":5,"finished_at":"2026-11-30T00:00:01Z"}"#,
2045 )
2046 .unwrap();
2047 shim.kill().unwrap();
2048 shim.wait().unwrap();
2049 assert!(n.wait_not_running(live, Duration::from_secs(5)).await);
2050 let m = get(&n, live);
2051 assert_eq!(
2052 (m.exit_code, m.restart_count, m.finished_at.as_str()),
2053 (5, 4, "2026-11-30T00:00:01Z")
2054 );
2055 });
2056 fs::remove_dir_all(&r).unwrap();
2057 }
2058
2059 #[test]
2060 fn launch_without_pid_or_exit_fails() {
2061 let r = root("nostart");
2062 let n = Native::open(
2063 {
2064 fs::create_dir_all(&r).unwrap();
2065 fs::canonicalize(&r).unwrap()
2066 },
2067 "/nonexistent/youki".into(),
2068 None,
2069 net::which("true").unwrap(),
2070 None,
2071 )
2072 .unwrap();
2073 let id = "krab_default_p_c";
2074 managed(&n, id, "exited");
2075 fs::create_dir_all(n.dir(id)).unwrap();
2076 let meta = n.meta(id).unwrap();
2077 let rt = tokio::runtime::Builder::new_current_thread()
2078 .enable_all()
2079 .build()
2080 .unwrap();
2081 let err = rt.block_on(n.run_launch(id, &meta, 5)).unwrap_err();
2082 assert!(err.to_string().contains("failed to start"), "{err}");
2083 let m = n.meta(id).unwrap();
2084 assert_eq!((m.state.as_str(), m.exit_code), ("exited", -1));
2085 fs::remove_dir_all(&r).unwrap();
2086 }
2087
2088 #[test]
2089 #[ignore]
2090 fn youki_end_to_end() {
2091 let youki = std::env::var("KRAB_YOUKI").unwrap_or_else(|_| "youki".into());
2092 let r = root("e2e");
2093 let n = Native::new(&r, youki).unwrap();
2094 let rt = tokio::runtime::Builder::new_current_thread()
2095 .enable_all()
2096 .build()
2097 .unwrap();
2098 rt.block_on(async {
2099 n.pull_image("busybox:1.37").await.unwrap();
2100 let mut labels = BTreeMap::new();
2101 labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
2102 let spec = ContainerSpec {
2103 name: "krab_default_e2e_c".into(),
2104 image: "busybox:1.37".into(),
2105 command: vec!["sh".into(), "-c".into(), "echo hello; sleep 30".into()],
2106 labels,
2107 hostname: Some("e2e".into()),
2108 memory_bytes: Some(32 << 20),
2109 ..Default::default()
2110 };
2111 let id = n.create_container(&spec).await.unwrap();
2112 n.start(&id).await.unwrap();
2113 let (code, out) = n.exec_run(&id, &["hostname".into()]).await.unwrap();
2114 assert_eq!((code, String::from_utf8_lossy(&out).trim()), (0, "e2e"));
2115 tokio::time::sleep(Duration::from_millis(500)).await;
2116 let info = to_info(&n.meta(&id).unwrap());
2117 let mut rx = n.logs(&info, &LogOpts::default()).await.unwrap();
2118 assert_eq!(rx.recv().await.unwrap(), Bytes::from_static(b"hello\n"));
2119 n.stop(&id, 1).await.unwrap();
2120 n.remove(&id, true).await.unwrap();
2121 });
2122 fs::remove_dir_all(&r).unwrap();
2123 }
2124}