Skip to main content

krab_runtime/native/
mod.rs

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