pub mod layer;
pub mod logfile;
pub mod net;
pub mod oci;
pub mod registry;
pub mod shim;
pub mod sys;
use crate::{
ContainerInfo, ContainerSpec, ExecHandle, ExecOpts, LogOpts, MANAGED_LABEL, Mount, NAME_PREFIX,
Runtime, is_managed, seccomp_supported,
};
use bytes::Bytes;
use logfile::Render;
use registry::{ImageRecord, Manifest, Session};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs;
use std::future::Future;
use std::io::{self, Read};
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio::process::Command;
use tokio::sync::mpsc;
const LOG_MAX: u64 = 8 << 20;
#[cfg(not(test))]
const START_TRIES: u32 = 300;
#[cfg(test)]
const START_TRIES: u32 = 4;
const IMAGE_GC_MIN_AGE: u64 = 600;
const CGROUP_ROOT: &str = "/sys/fs/cgroup";
const POD_IP: &str = "127.0.0.1";
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
struct Meta {
id: String,
image: String,
image_id: String,
labels: BTreeMap<String, String>,
created: i64,
state: String,
started_at: String,
finished_at: String,
exit_code: i64,
#[serde(default)]
oom_killed: bool,
restart_count: u64,
tty: bool,
stdin: bool,
pid: i64,
restart: String,
aliases: Vec<String>,
#[serde(default)]
host_aliases: Vec<(String, String)>,
hostname: String,
no_new_privs: bool,
layers: Vec<String>,
}
struct Entry {
meta: Meta,
stopping: bool,
epoch: u64,
backoff_ms: u64,
launched: Option<Instant>,
starting: bool,
}
struct ExecState {
code: Option<i64>,
}
struct Inner {
root: PathBuf,
youki: PathBuf,
shim: PathBuf,
adopt: Mutex<Vec<(String, u64, i32)>>,
state: Mutex<HashMap<String, Entry>>,
execs: Mutex<HashMap<String, ExecState>>,
pull_locks: Mutex<HashMap<String, std::sync::Weak<tokio::sync::Mutex<()>>>>,
seq: AtomicU64,
net: Option<Arc<net::Net>>,
seccomp: Option<oci::Profile>,
}
#[derive(Clone)]
pub struct Native {
inner: Arc<Inner>,
}
fn now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
fn not_found(id: &str) -> io::Error {
io::Error::new(io::ErrorKind::NotFound, format!("no such container: {id}"))
}
fn id_ok(id: &str) -> bool {
id.len() <= 200
&& id.starts_with(NAME_PREFIX)
&& id.bytes().all(|b| {
b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-' | b'.')
})
&& crate::cgroup::native_cgroup_path(id).is_some()
}
fn exit_code(st: &std::process::ExitStatus) -> i64 {
use std::os::unix::process::ExitStatusExt;
match (st.code(), st.signal()) {
(Some(c), _) => c as i64,
(None, Some(s)) => 128 + s as i64,
_ => -1,
}
}
fn write_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
let tmp = path.with_extension("tmp");
fs::write(&tmp, data)?;
fs::rename(&tmp, path)
}
fn overlay_whiteout(p: &Path, w: layer::Whiteout) -> io::Result<()> {
match w {
layer::Whiteout::File => sys::whiteout(p),
layer::Whiteout::Opaque => sys::opaque(p),
}
}
struct Deadline<R> {
r: R,
until: Instant,
}
impl<R: Read> Read for Deadline<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if Instant::now() >= self.until {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"image pull deadline exceeded",
));
}
self.r.read(buf)
}
}
fn install_layer(
blob: &Path,
dst: &Path,
budget: layer::Limits,
lowers: &[PathBuf],
until: Instant,
) -> io::Result<layer::Limits> {
let mut budget = budget;
unpack_layer(blob, dst, &mut budget, lowers, until)?;
let _ = fs::remove_file(blob);
Ok(budget)
}
fn unpack_layer(
blob: &Path,
dst: &Path,
budget: &mut layer::Limits,
lowers: &[PathBuf],
until: Instant,
) -> io::Result<()> {
let tmp = dst.with_file_name(format!(
".tmp-{}",
dst.file_name().unwrap_or_default().to_string_lossy()
));
if tmp.exists() {
fs::remove_dir_all(&tmp)?;
}
let mut f = fs::File::open(blob)?;
let mut magic = [0u8; 4];
let n = f.read(&mut magic)?;
let f = Deadline {
r: fs::File::open(blob)?,
until,
};
let r: Box<dyn Read> = if n >= 2 && magic[..2] == [0x1f, 0x8b] {
Box::new(flate2::read::GzDecoder::new(io::BufReader::new(f)))
} else if n == 4 && magic == [0x28, 0xb5, 0x2f, 0xfd] {
return Err(io::Error::other("zstd layers are not supported"));
} else {
Box::new(io::BufReader::new(f))
};
let res = layer::unpack_in(r, &tmp, budget, lowers, &overlay_whiteout)
.and_then(|_| fs::rename(&tmp, dst));
if res.is_err() {
let _ = fs::remove_dir_all(&tmp);
}
res
}
async fn pump_chan<R: AsyncRead + Unpin>(mut r: R, tx: mpsc::Sender<Bytes>) {
let mut buf = vec![0u8; 8192];
loop {
match r.read(&mut buf).await {
Ok(0) | Err(_) => break,
Ok(n) => {
if tx.send(Bytes::copy_from_slice(&buf[..n])).await.is_err() {
break;
}
}
}
}
}
struct Starting<'a> {
n: &'a Native,
id: &'a str,
epoch: u64,
}
impl Drop for Starting<'_> {
fn drop(&mut self) {
if let Some(e) = self
.n
.lock()
.get_mut(self.id)
.filter(|e| e.epoch == self.epoch)
{
e.starting = false;
}
}
}
fn pod_key(labels: &BTreeMap<String, String>) -> io::Result<String> {
let get = |k: &str| labels.get(k).map(String::as_str).unwrap_or("");
let (ns, pod) = (get("krab.io/namespace"), get("krab.io/pod"));
if ns.is_empty() || pod.is_empty() || ns.contains('/') || pod.contains('/') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"container needs krab.io/namespace and krab.io/pod labels for its pod network",
));
}
Ok(format!("{ns}/{pod}"))
}
impl Native {
pub fn new(root: impl Into<PathBuf>, youki: impl Into<PathBuf>) -> io::Result<Self> {
Self::new_with(root, youki, None)
}
pub fn new_with(
root: impl Into<PathBuf>,
youki: impl Into<PathBuf>,
net_cfg: Option<net::NetConfig>,
) -> io::Result<Self> {
Self::new_with_profile(root, youki, net_cfg, None)
}
pub fn new_with_profile(
root: impl Into<PathBuf>,
youki: impl Into<PathBuf>,
net_cfg: Option<net::NetConfig>,
profile: Option<PathBuf>,
) -> io::Result<Self> {
let profile = profile.as_deref().map(oci::Profile::load).transpose()?;
let shim = std::env::var_os("KRAB_SHIM")
.map(PathBuf::from)
.or_else(|| std::env::current_exe().ok())
.unwrap_or_else(|| PathBuf::from("krab"));
Self::open(root.into(), youki.into(), net_cfg, shim, profile)
}
fn open(
root: PathBuf,
youki: PathBuf,
net_cfg: Option<net::NetConfig>,
shim: PathBuf,
profile: Option<oci::Profile>,
) -> io::Result<Self> {
fs::create_dir_all(&root)?;
let root = fs::canonicalize(&root)?;
if !sys::option_safe(&root) {
return Err(io::Error::other(
"native root must not contain spaces, ',' or ':'",
));
}
fs::set_permissions(&root, fs::Permissions::from_mode(0o700))?;
for d in [
"blobs",
"layers",
"images",
"containers",
"logs",
"volumes",
"youki",
] {
fs::create_dir_all(root.join(d))?;
}
let net = match net_cfg {
Some(c) => Some(Arc::new(net::Net::open(&root.join("net"), c)?)),
None => None,
};
let me = Self {
inner: Arc::new(Inner {
root,
youki,
shim,
adopt: Mutex::new(Vec::new()),
state: Mutex::new(HashMap::new()),
execs: Mutex::new(HashMap::new()),
pull_locks: Mutex::new(HashMap::new()),
seq: AtomicU64::new(0),
net,
seccomp: profile,
}),
};
me.load();
if let Some(n) = &me.inner.net {
let (live, running): (BTreeSet<String>, BTreeSet<String>) = {
let g = me.lock();
(
g.keys().cloned().collect(),
g.values()
.filter(|e| e.meta.state == "running")
.map(|e| e.meta.id.clone())
.collect(),
)
};
n.start(&live, &running)?;
me.rewrite_hosts();
}
Ok(me)
}
fn ip_of(&self, m: &Meta) -> String {
match &self.inner.net {
Some(n) => pod_key(&m.labels)
.ok()
.and_then(|k| n.pod_ip(&k))
.map(|i| i.to_string())
.unwrap_or_default(),
None => POD_IP.into(),
}
}
fn info(&self, m: &Meta) -> ContainerInfo {
let mut i = to_info(m);
i.ip = self.ip_of(m);
i
}
async fn net_release(&self, id: &str) {
if let Some(n) = self.inner.net.clone() {
let id = id.to_string();
let _ = tokio::task::spawn_blocking(move || n.release(&id)).await;
}
}
fn adopt_pending(&self) {
let pending = std::mem::take(
&mut *self
.inner
.adopt
.lock()
.unwrap_or_else(PoisonError::into_inner),
);
for (id, epoch, pid) in pending {
tokio::spawn(self.clone().watch(id, epoch, pid));
}
}
pub async fn shutdown_all(&self) {
self.adopt_pending();
let ids: Vec<String> = {
let mut g = self.lock();
for e in g.values_mut() {
e.stopping = true;
}
g.values()
.filter(|e| e.meta.state == "running")
.map(|e| e.meta.id.clone())
.collect()
};
for id in &ids {
let _ = self.youki_status(&["kill", id, "SIGKILL"]).await;
}
for id in &ids {
self.wait_not_running(id, Duration::from_secs(5)).await;
let _ = self.youki_status(&["delete", "--force", id]).await;
}
if let Some(n) = self.inner.net.clone() {
let _ = tokio::task::spawn_blocking(move || n.shutdown()).await;
}
}
fn load(&self) {
let Ok(rd) = fs::read_dir(self.inner.root.join("containers")) else {
return;
};
let mut map = HashMap::new();
for d in rd.flatten() {
let Ok(b) = fs::read(d.path().join("meta.json")) else {
continue;
};
let Ok(mut m) = serde_json::from_slice::<Meta>(&b) else {
continue;
};
if !id_ok(&m.id) || d.file_name().to_string_lossy() != m.id {
continue;
}
if m.state == "running"
&& let Some(x) = shim::read_exit(&d.path())
{
m.state = "exited".into();
m.exit_code = x.code;
m.finished_at = x.finished_at;
m.pid = 0;
let _ = self.persist(&m);
} else if m.state == "running"
&& let Some(pid) = self.shim_alive(&d.path())
{
self.inner
.adopt
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push((m.id.clone(), 0, pid));
} else if m.state == "running" {
let youki = |args: &[&str]| {
std::process::Command::new(&self.inner.youki)
.arg("--root")
.arg(self.inner.root.join("youki"))
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
};
let _ = youki(&["kill", &m.id, "SIGKILL"]);
std::thread::sleep(Duration::from_millis(200));
let _ = youki(&["delete", "--force", &m.id]);
m.state = "exited".into();
m.exit_code = 137;
m.finished_at = logfile::now_ts();
m.pid = 0;
let _ = self.persist(&m);
}
map.insert(
m.id.clone(),
Entry {
meta: m,
stopping: false,
epoch: 0,
backoff_ms: 0,
launched: None,
starting: false,
},
);
}
*self.lock() = map;
}
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Entry>> {
self.inner
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
fn execs(&self) -> std::sync::MutexGuard<'_, HashMap<String, ExecState>> {
self.inner
.execs
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
fn dir(&self, id: &str) -> PathBuf {
self.inner.root.join("containers").join(id)
}
fn rootfs(&self, id: &str) -> PathBuf {
self.dir(id).join("bundle/rootfs")
}
fn log_path(&self, id: &str) -> PathBuf {
self.inner.root.join("logs").join(format!("{id}.log"))
}
fn persist(&self, m: &Meta) -> io::Result<()> {
write_atomic(
&self.dir(&m.id).join("meta.json"),
&serde_json::to_vec(m).map_err(io::Error::other)?,
)
}
fn youki(&self) -> Command {
let mut c = Command::new(&self.inner.youki);
c.arg("--root").arg(self.inner.root.join("youki"));
c.stdin(Stdio::null());
c
}
async fn youki_status(&self, args: &[&str]) -> io::Result<std::process::Output> {
let mut c = self.youki();
c.args(args).kill_on_drop(true);
tokio::time::timeout(Duration::from_secs(30), c.output())
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "youki timed out"))?
}
fn meta(&self, id: &str) -> io::Result<Meta> {
let g = self.lock();
g.get(id)
.map(|e| e.meta.clone())
.ok_or_else(|| not_found(id))
}
fn ensure_managed(&self, id: &str) -> io::Result<Meta> {
let m = self.meta(id)?;
if is_managed(&to_info(&m)) {
Ok(m)
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("container {id} is not managed by krab"),
))
}
}
fn is_running(&self, id: &str) -> bool {
self.lock()
.get(id)
.is_some_and(|e| e.meta.state == "running")
}
fn image_path(&self, image: &str) -> PathBuf {
self.inner
.root
.join("images")
.join(format!("{}.json", registry::sha256_hex(image.as_bytes())))
}
fn load_image(&self, image: &str) -> io::Result<ImageRecord> {
let b = fs::read(self.image_path(image))
.map_err(|e| io::Error::new(e.kind(), format!("image {image} is not present: {e}")))?;
let rec: ImageRecord = serde_json::from_slice(&b).map_err(io::Error::other)?;
for l in &rec.layers {
registry::digest_hex(&format!("sha256:{l}"))?;
if !self.inner.root.join("layers").join(l).is_dir() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("image {image}: layer {l} is missing"),
));
}
}
Ok(rec)
}
fn key_lock(&self, key: &str) -> Arc<tokio::sync::Mutex<()>> {
let mut m = self
.inner
.pull_locks
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(l) = m.get(key).and_then(std::sync::Weak::upgrade) {
return l;
}
m.retain(|_, w| w.strong_count() > 0);
let l = Arc::new(tokio::sync::Mutex::new(()));
m.insert(key.to_string(), Arc::downgrade(&l));
l
}
fn mount_rootfs(&self, id: &str, layers: &[String]) -> io::Result<()> {
let rootfs = self.rootfs(id);
if sys::is_mounted(&rootfs) {
return Ok(());
}
let lower: Vec<PathBuf> = layers
.iter()
.map(|l| self.inner.root.join("layers").join(l))
.collect();
let d = self.dir(id);
sys::mount_overlay(&lower, &d.join("upper"), &d.join("work"), &rootfs)
}
fn shim_alive(&self, dir: &Path) -> Option<i32> {
let (pid, start) = shim::read_shim_pid(dir)?;
if shim::proc_starttime(pid)? != start {
return None;
}
let exe = fs::read_link(format!("/proc/{pid}/exe")).ok()?;
let exe = exe.to_string_lossy();
let want = fs::canonicalize(&self.inner.shim).unwrap_or_else(|_| self.inner.shim.clone());
(exe.trim_end_matches(" (deleted)") == want.to_string_lossy()).then_some(pid)
}
fn rewrite_hosts(&self) {
let g = self.lock();
let ips: HashMap<&str, String> = g
.values()
.map(|e| (e.meta.id.as_str(), self.ip_of(&e.meta)))
.collect();
let mut all: Vec<(String, String)> = g
.values()
.flat_map(|e| {
let ip = ips[e.meta.id.as_str()].clone();
e.meta.aliases.iter().map(move |a| (ip.clone(), a.clone()))
})
.collect();
all.sort();
all.dedup();
for e in g.values() {
let _ = fs::write(
self.dir(&e.meta.id).join("hosts"),
oci::pod_hosts_with(
&e.meta.hostname,
&ips[e.meta.id.as_str()],
&all,
&e.meta.host_aliases,
),
);
}
}
fn cleanup_dir(&self, id: &str) {
let _ = sys::umount(&self.rootfs(id));
let _ = fs::remove_dir_all(self.dir(id));
}
fn launch(
&self,
id: &str,
expect: Option<u64>,
) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'static>> {
let me = self.clone();
let id = id.to_string();
Box::pin(async move { me.launch_inner(id, expect).await })
}
async fn launch_inner(&self, id: String, expect: Option<u64>) -> io::Result<()> {
let (meta, epoch) = {
let mut g = self.lock();
let e = g.get_mut(&id).ok_or_else(|| not_found(&id))?;
if e.starting
|| e.meta.state == "running"
|| expect.is_some_and(|ep| ep != e.epoch || e.stopping)
{
return Ok(());
}
self.mount_rootfs(&id, &e.meta.layers)?;
e.starting = true;
if expect.is_some() {
e.meta.restart_count += 1;
}
e.epoch += 1;
e.launched = Some(Instant::now());
(e.meta.clone(), e.epoch)
};
let _guard = Starting {
n: self,
id: &id,
epoch,
};
self.run_launch(&id, &meta, epoch).await
}
async fn run_launch(&self, id: &str, meta: &Meta, epoch: u64) -> io::Result<()> {
let id = id.to_string();
let _ = self.youki_status(&["delete", "--force", &id]).await;
let d = self.dir(&id);
for f in ["pid", "exit", "shim.pid"] {
let _ = fs::remove_file(d.join(f));
}
let args = shim::Args {
youki: self.inner.youki.clone(),
root: self.inner.root.join("youki"),
bundle: d.join("bundle"),
dir: d.clone(),
log: self.log_path(&id),
log_max: LOG_MAX,
id: id.clone(),
stdin: meta.stdin,
tty: meta.tty,
};
let mut cmd = Command::new(&self.inner.shim);
cmd.arg("shim")
.args(args.to_args())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
let st = tokio::time::timeout(Duration::from_secs(10), cmd.status())
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "krab shim timed out"))??;
let mut pid = 0i64;
let mut early = (!st.success()).then(|| shim::Exit {
code: -1,
finished_at: logfile::now_ts(),
});
for _ in 0..START_TRIES {
if early.is_some() {
break;
}
if let Some(x) = shim::read_exit(&d) {
early = Some(x);
break;
}
if let Ok(s) = fs::read_to_string(d.join("pid"))
&& let Ok(p) = s.trim().parse::<i64>()
{
pid = p;
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
if early.is_none() && pid == 0 {
if let Some(sp) = self.shim_alive(&d) {
unsafe {
libc::kill(sp, libc::SIGKILL);
}
}
let _ = self.youki_status(&["delete", "--force", &id]).await;
early = Some(shim::Exit {
code: -1,
finished_at: logfile::now_ts(),
});
}
if let Some(x) = early {
let mut g = self.lock();
if let Some(e) = g.get_mut(&id).filter(|e| e.epoch == epoch) {
e.meta.state = "exited".into();
e.meta.exit_code = x.code;
e.meta.started_at = logfile::now_ts();
e.meta.finished_at = x.finished_at;
e.meta.pid = 0;
let _ = self.persist(&e.meta);
}
if x.code == 0 || d.join("pid").exists() {
return Ok(());
}
return Err(io::Error::other(format!(
"container {id} failed to start (exit code {}), see its logs",
x.code
)));
}
let shim_pid = self.shim_alive(&d).unwrap_or(0);
{
let mut g = self.lock();
if let Some(e) = g.get_mut(&id).filter(|e| e.epoch == epoch) {
e.meta.state = "running".into();
e.meta.started_at = logfile::now_ts();
e.meta.finished_at = String::new();
e.meta.exit_code = 0;
e.meta.oom_killed = false;
e.meta.pid = pid;
let _ = self.persist(&e.meta);
}
}
tokio::spawn(self.clone().watch(id, epoch, shim_pid));
Ok(())
}
async fn watch(self, id: String, epoch: u64, shim_pid: i32) {
let d = self.dir(&id);
wait_exit(shim_pid, &d).await;
let x = shim::read_exit(&d).unwrap_or_else(|| shim::Exit {
code: 137,
finished_at: logfile::now_ts(),
});
let code = x.code;
let oom = oom_killed(&id);
let delay = {
let mut g = self.lock();
let Some(e) = g.get_mut(&id).filter(|e| e.epoch == epoch) else {
return;
};
e.meta.state = "exited".into();
e.meta.exit_code = code;
e.meta.oom_killed = oom && code == 137;
e.meta.finished_at = x.finished_at;
e.meta.pid = 0;
let _ = self.persist(&e.meta);
let restart = !e.stopping
&& match e.meta.restart.as_str() {
"Never" => false,
"OnFailure" => code != 0,
_ => true,
};
if !restart {
None
} else {
if e.launched
.is_some_and(|t| t.elapsed() >= Duration::from_secs(10))
{
e.backoff_ms = 0;
}
e.backoff_ms = (e.backoff_ms * 2).clamp(100, 60_000);
Some(e.backoff_ms)
}
};
let Some(delay) = delay else {
if let Some(n) = self.inner.net.clone() {
let _ = tokio::task::spawn_blocking(move || n.suspend(&id)).await;
}
return;
};
tokio::time::sleep(Duration::from_millis(delay)).await;
let _ = self.launch(&id, Some(epoch)).await;
}
async fn wait_not_running(&self, id: &str, limit: Duration) -> bool {
let deadline = Instant::now() + limit;
loop {
if !self.is_running(id) {
return true;
}
if Instant::now() >= deadline {
return false;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
async fn pull_inner(&self, image: &str, until: Instant) -> io::Result<()> {
let r = registry::parse_reference(image)?;
let reference = r.reference.clone();
let mut s = Session::new(r);
let (mut digest, mut m) = s.manifest(&reference).await?;
if let Manifest::Index(list) = &m {
let d = registry::pick_platform(list, registry::host_arch())
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("{image}: no linux/{} image", registry::host_arch()),
)
})?
.digest
.clone();
registry::digest_hex(&d)?;
(digest, m) = s.manifest(&d).await?;
}
let Manifest::Image { config, layers } = m else {
return Err(io::Error::other(format!("{image}: nested image index")));
};
let cfg =
registry::image_config(&s.blob_bytes(&config.digest, registry::MAX_CONFIG).await?)?;
let mut hexes = Vec::new();
let mut budget = layer::Limits::default();
for l in &layers {
let hex = registry::digest_hex(&l.digest)?.to_string();
let dst = self.inner.root.join("layers").join(&hex);
let lowers: Vec<PathBuf> = hexes
.iter()
.rev()
.map(|h: &String| self.inner.root.join("layers").join(h))
.collect();
let ll = self.key_lock(&format!("layer:{hex}"));
let _lg = ll.lock().await;
if !dst.is_dir() {
let blob = self.inner.root.join("blobs").join(&hex);
s.blob_to_file(&l.digest, &blob, registry::MAX_LAYER)
.await?;
budget = tokio::task::spawn_blocking(move || {
install_layer(&blob, &dst, budget, &lowers, until)
})
.await
.map_err(io::Error::other)??;
}
hexes.push(hex);
}
let rec = ImageRecord {
image: image.to_string(),
digest,
config_digest: config.digest,
layers: hexes,
config: cfg,
};
write_atomic(
&self.image_path(image),
&serde_json::to_vec(&rec).map_err(io::Error::other)?,
)
}
fn exec_cmd(&self, m: &Meta, cmd: &[String], tty: bool) -> io::Result<Command> {
if cmd.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"exec: empty command",
));
}
if m.state != "running" {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("container {} is not running", m.id),
));
}
let mut c = self.youki();
c.arg("exec");
if m.no_new_privs {
c.arg("--no-new-privs");
}
if tty {
c.arg("--tty");
}
c.arg(&m.id).arg("--").args(cmd);
Ok(c)
}
fn seccomp_profile(&self, spec: &ContainerSpec) -> io::Result<Option<&Value>> {
match (&self.inner.seccomp, spec.seccomp.as_deref()) {
(Some(p), None | Some("RuntimeDefault")) => Ok(Some(p.value())),
(Some(_), Some(t @ ("Unconfined" | "Localhost"))) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("seccompProfile type {t:?} cannot opt out of the operator seccomp profile"),
)),
(Some(_), Some(t)) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("seccompProfile type {t:?} is not supported by the native runtime"),
)),
(None, t) => {
seccomp_supported("the native runtime", t, SUPPORTED_SECCOMP)?;
Ok(None)
}
}
}
}
fn oom_killed(id: &str) -> bool {
let Some(cg) = crate::cgroup::native_cgroup_path(id) else {
return false;
};
fs::read_to_string(Path::new(CGROUP_ROOT).join(cg).join("memory.events"))
.ok()
.and_then(|t| {
t.lines()
.find_map(|l| l.strip_prefix("oom_kill "))
.and_then(|n| n.trim().parse::<u64>().ok())
})
.is_some_and(|n| n > 0)
}
fn to_info(m: &Meta) -> ContainerInfo {
ContainerInfo {
id: m.id.clone(),
name: m.id.clone(),
image: m.image.clone(),
image_id: m.image_id.clone(),
state: m.state.clone(),
created: m.created,
labels: m.labels.clone(),
ports: Vec::new(),
ip: POD_IP.into(),
started_at: m.started_at.clone(),
finished_at: m.finished_at.clone(),
exit_code: m.exit_code,
oom_killed: m.oom_killed,
restart_count: m.restart_count,
tty: m.tty,
pid: m.pid,
}
}
fn ensure_volume(v: &Path) -> io::Result<()> {
match fs::create_dir(v) {
Ok(()) => fs::set_permissions(v, fs::Permissions::from_mode(0o777)),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists && v.is_dir() => Ok(()),
Err(e) => Err(e),
}
}
fn pid_alive(pid: i32) -> bool {
pid > 0 && unsafe { libc::kill(pid, 0) } == 0
}
#[cfg(target_os = "linux")]
async fn wait_pidfd(pid: i32) -> bool {
use std::os::fd::{FromRawFd, OwnedFd};
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
if fd < 0 {
return io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
}
let fd = unsafe { OwnedFd::from_raw_fd(fd as i32) };
match unsafe {
tokio::io::unix::AsyncFd::register_with_interest(fd, tokio::io::Interest::READABLE)
} {
Ok(a) => a.readable().await.is_ok(),
Err(_) => false,
}
}
#[cfg(not(target_os = "linux"))]
async fn wait_pidfd(_pid: i32) -> bool {
false
}
async fn wait_exit(shim_pid: i32, dir: &Path) {
if shim_pid > 0 && wait_pidfd(shim_pid).await {
return;
}
loop {
if shim::read_exit(dir).is_some() || (shim_pid > 0 && !pid_alive(shim_pid)) {
return;
}
if shim_pid <= 0 && !dir.exists() {
return;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
fn host_resolv() -> String {
fs::read_to_string("/etc/resolv.conf").unwrap_or_default()
}
const SUPPORTED_SECCOMP: &[&str] = &["Unconfined"];
impl Native {
fn gc_images_blocking(&self, low: u64, high: u64) -> io::Result<usize> {
let root = self.inner.root.clone();
let free = || crate::host::disk_free_percent(&root.to_string_lossy());
if free().is_none_or(|f| f >= low) {
return Ok(0);
}
let (used_imgs, mut used_layers): (BTreeSet<PathBuf>, BTreeSet<String>) = {
let g = self.lock();
(
g.values().map(|e| self.image_path(&e.meta.image)).collect(),
g.values()
.flat_map(|e| e.meta.layers.iter().cloned())
.collect(),
)
};
let mut recs: Vec<(SystemTime, PathBuf, ImageRecord)> = Vec::new();
for ent in fs::read_dir(root.join("images"))?.flatten() {
let path = ent.path();
let Ok(b) = fs::read(&path) else { continue };
let Ok(rec) = serde_json::from_slice::<ImageRecord>(&b) else {
continue;
};
let mtime = ent
.metadata()
.and_then(|m| m.modified())
.unwrap_or(UNIX_EPOCH);
let fresh = mtime
.elapsed()
.is_ok_and(|a| a < Duration::from_secs(IMAGE_GC_MIN_AGE));
if used_imgs.contains(&path) || fresh {
used_layers.extend(rec.layers.iter().cloned());
} else {
recs.push((mtime, path, rec));
}
}
recs.sort_by_key(|r| r.0);
let mut removed = 0;
let mut remaining: Vec<_> = recs.iter().collect();
for (_, path, rec) in &recs {
if free().is_none_or(|f| f >= high) {
break;
}
if fs::remove_file(path).is_err() {
continue;
}
removed += 1;
remaining.retain(|r| r.1 != *path);
let keep: BTreeSet<&String> = used_layers
.iter()
.chain(remaining.iter().flat_map(|r| r.2.layers.iter()))
.collect();
for l in &rec.layers {
if !keep.contains(l) && registry::digest_hex(&format!("sha256:{l}")).is_ok() {
let _ = fs::remove_dir_all(root.join("layers").join(l));
}
}
}
Ok(removed)
}
}
impl Runtime for Native {
async fn gc_images(&self, low: u64, high: u64) -> io::Result<usize> {
let me = self.clone();
tokio::task::spawn_blocking(move || me.gc_images_blocking(low, high))
.await
.map_err(io::Error::other)?
}
fn name(&self) -> &str {
"native"
}
async fn list(&self) -> io::Result<Vec<ContainerInfo>> {
self.adopt_pending();
Ok(self.lock().values().map(|e| self.info(&e.meta)).collect())
}
async fn inspect(&self, info: &mut ContainerInfo) -> io::Result<()> {
self.adopt_pending();
let m = self
.meta(&info.id)
.or_else(|_| self.meta(info.name.trim_start_matches('/')))?;
*info = self.info(&m);
Ok(())
}
async fn logs(
&self,
info: &ContainerInfo,
opts: &LogOpts,
) -> io::Result<mpsc::Receiver<Bytes>> {
let m = self.meta(&info.id)?;
let path = self.log_path(&m.id);
let opts = opts.clone();
let me = self.clone();
let (tx, rx) = mpsc::channel(8);
tokio::spawn(async move {
let mut render =
Render::new(opts.timestamps, opts.since_seconds.map(logfile::since_ts));
let cur = tokio::fs::read(&path).await.unwrap_or_default();
let mut ino = tokio::fs::metadata(&path).await.map(|m| m.ino()).ok();
let initial: Vec<u8> = match opts.tail {
Some(n) => {
let t = logfile::tail_lines(&cur, n);
if t.len() == cur.len() {
let mut all = tokio::fs::read(logfile::rotated(&path))
.await
.unwrap_or_default();
all.extend_from_slice(&cur);
logfile::tail_lines(&all, n).to_vec()
} else {
t.to_vec()
}
}
None => {
let mut all = tokio::fs::read(logfile::rotated(&path))
.await
.unwrap_or_default();
all.extend_from_slice(&cur);
all
}
};
let send_lines = |data: &[u8], render: &mut Render| -> Vec<Bytes> {
let mut chunks = Vec::new();
let mut out = Vec::new();
for line in data.split(|b| *b == b'\n').filter(|l| !l.is_empty()) {
if let Some(r) = logfile::parse(line)
&& render.accept(&r)
{
render.render(&r, &mut out);
if out.len() >= 32 * 1024 {
chunks.push(Bytes::from(std::mem::take(&mut out)));
}
}
}
if !out.is_empty() {
chunks.push(Bytes::from(out));
}
chunks
};
for c in send_lines(&initial, &mut render) {
if tx.send(c).await.is_err() {
return;
}
}
drop(initial);
if !opts.follow {
return;
}
let mut pos = cur.len() as u64;
drop(cur);
loop {
tokio::time::sleep(Duration::from_millis(250)).await;
if tx.is_closed() {
return;
}
let running = me.is_running(&m.id);
let Ok(md) = tokio::fs::metadata(&path).await else {
if !running {
return;
}
continue;
};
if Some(md.ino()) != ino || md.len() < pos {
ino = Some(md.ino());
pos = 0;
}
if md.len() > pos {
let Ok(mut f) = tokio::fs::File::open(&path).await else {
continue;
};
use tokio::io::AsyncSeekExt;
if f.seek(io::SeekFrom::Start(pos)).await.is_err() {
continue;
}
let want = (md.len() - pos).min(1 << 20) as usize;
let mut buf = vec![0u8; want];
let Ok(n) = f.read(&mut buf).await else {
continue;
};
buf.truncate(n);
let Some(last) = buf.iter().rposition(|b| *b == b'\n') else {
continue;
};
pos += last as u64 + 1;
for c in send_lines(&buf[..=last], &mut render) {
if tx.send(c).await.is_err() {
return;
}
}
continue;
}
if !running {
return;
}
}
});
Ok(rx)
}
async fn pull_image(&self, image: &str) -> io::Result<()> {
let lock = self.key_lock(&format!("image:{image}"));
let _g = lock.lock().await;
let until = Instant::now() + registry::PULL_DEADLINE;
tokio::time::timeout(registry::PULL_DEADLINE, self.pull_inner(image, until))
.await
.map_err(|_| {
io::Error::new(
io::ErrorKind::TimedOut,
format!(
"{image}: pull exceeded {}s",
registry::PULL_DEADLINE.as_secs()
),
)
})?
}
async fn create_container(&self, spec: &ContainerSpec) -> io::Result<String> {
if !spec.name.starts_with(NAME_PREFIX)
|| spec.labels.get(MANAGED_LABEL).map(String::as_str) != Some("true")
{
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"container spec is not krab-managed",
));
}
let seccomp = self.seccomp_profile(spec)?;
let id = spec.name.clone();
if !id_ok(&id) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("bad container name {id:?}"),
));
}
if self.lock().contains_key(&id) {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("container {id} already exists"),
));
}
let rec = self.load_image(&spec.image)?;
let cg = format!(
"/{}",
crate::cgroup::native_cgroup_path(&id).unwrap_or_default()
);
self.cleanup_dir(&id);
let attach = match self.inner.net.clone() {
Some(n) => {
let key = pod_key(&spec.labels)?;
let (aid, ports) = (id.clone(), spec.ports.clone());
Some(
tokio::task::spawn_blocking(move || n.attach(&key, &aid, &ports))
.await
.map_err(io::Error::other)??,
)
}
None => None,
};
let d = self.dir(&id);
let res = (|| -> io::Result<Meta> {
for sub in ["bundle/rootfs", "upper", "work"] {
fs::create_dir_all(d.join(sub))?;
}
fs::set_permissions(d.join("bundle"), fs::Permissions::from_mode(0o700))?;
self.mount_rootfs(&id, &rec.layers)?;
let rootfs = self.rootfs(&id);
let mut process = oci::merge(spec, &rec.config)?;
let rd = |p| {
layer::read_in_root(&rootfs, p, 1 << 20)
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_default()
};
let passwd = rd("etc/passwd");
let mut user = oci::resolve_user(&process.user, &passwd, &rd("etc/group"))?;
user.extra.extend(spec.extra_gids.iter().copied());
oci::set_home(&mut process.env, user.uid, &passwd);
for m in &spec.mounts {
if let Mount::Volume { name, .. } = m
&& crate::policy::data_key_ok(name)
&& !name.starts_with('.')
{
ensure_volume(&self.inner.root.join("volumes").join(name))?;
}
}
let hostname = spec.hostname.clone().unwrap_or_default();
fs::write(d.join("hostname"), format!("{hostname}\n"))?;
let resolv = match (&attach, &self.inner.net) {
(Some(_), Some(n)) => net::pod_resolv_with(
n.dns(),
&host_resolv(),
&fs::read_to_string("/run/systemd/resolve/resolv.conf").unwrap_or_default(),
|ip| n.may_reach(ip),
),
_ => host_resolv(),
};
fs::write(
d.join("resolv.conf"),
oci::resolv_conf(&resolv, &spec.dns_search, &spec.dns_options),
)?;
let own_ip = attach
.as_ref()
.map(|a| a.ip.to_string())
.unwrap_or_else(|| POD_IP.into());
for e in process.env.iter_mut() {
if e.contains(crate::POD_IP_TOKEN) {
*e = e.replace(crate::POD_IP_TOKEN, &own_ip);
}
}
fs::write(
d.join("hosts"),
oci::pod_hosts_with(&hostname, &own_ip, &[], &spec.host_aliases),
)?;
let b = oci::Bundle {
cgroups_path: &cg,
hosts: &d.join("hosts"),
resolv: &d.join("resolv.conf"),
hostname_file: &d.join("hostname"),
volume_root: &self.inner.root.join("volumes"),
netns: attach.as_ref().map(|a| a.netns.as_path()),
seccomp,
};
let cfg = oci::config_json(spec, &process, &user, &b)?;
fs::write(
d.join("bundle/config.json"),
serde_json::to_vec_pretty(&cfg).map_err(io::Error::other)?,
)?;
let m = Meta {
id: id.clone(),
image: spec.image.clone(),
image_id: rec.config_digest.clone(),
labels: spec.labels.clone(),
created: now_secs(),
state: "created".into(),
started_at: "0001-01-01T00:00:00Z".into(),
finished_at: "0001-01-01T00:00:00Z".into(),
tty: spec.tty,
stdin: spec.stdin,
restart: match spec.restart {
crate::RestartPolicy::Always => "Always",
crate::RestartPolicy::OnFailure => "OnFailure",
crate::RestartPolicy::Never => "Never",
}
.into(),
aliases: spec.aliases.clone(),
host_aliases: spec.host_aliases.clone(),
hostname,
no_new_privs: !spec.allow_privilege_escalation,
layers: rec.layers.clone(),
..Default::default()
};
self.persist(&m)?;
Ok(m)
})();
let m = match res {
Ok(m) => m,
Err(e) => {
self.cleanup_dir(&id);
self.net_release(&id).await;
return Err(e);
}
};
self.lock().insert(
id.clone(),
Entry {
meta: m,
stopping: false,
epoch: 0,
backoff_ms: 0,
launched: None,
starting: false,
},
);
self.rewrite_hosts();
Ok(id)
}
async fn start(&self, id: &str) -> io::Result<()> {
self.ensure_managed(id)?;
{
let mut g = self.lock();
let e = g.get_mut(id).ok_or_else(|| not_found(id))?;
if e.meta.state == "running" || e.starting {
return Ok(());
}
e.stopping = false;
}
if let Some(n) = self.inner.net.clone() {
let nid = id.to_string();
tokio::task::spawn_blocking(move || n.resume(&nid))
.await
.map_err(io::Error::other)??;
}
self.launch(id, None).await
}
async fn stop(&self, id: &str, timeout_secs: u64) -> io::Result<()> {
self.adopt_pending();
self.ensure_managed(id)?;
{
let mut g = self.lock();
if let Some(e) = g.get_mut(id) {
e.stopping = true;
}
}
if !self.is_running(id) {
return Ok(());
}
let _ = self.youki_status(&["kill", id, "SIGTERM"]).await;
if self
.wait_not_running(id, Duration::from_secs(timeout_secs))
.await
{
return Ok(());
}
let _ = self.youki_status(&["kill", id, "SIGKILL"]).await;
if self.wait_not_running(id, Duration::from_secs(10)).await {
Ok(())
} else {
Err(io::Error::other(format!("container {id} did not stop")))
}
}
async fn remove(&self, id: &str, force: bool) -> io::Result<()> {
self.ensure_managed(id)?;
if self.is_running(id) {
if !force {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("container {id} is running"),
));
}
self.stop(id, 0).await?;
}
let _ = self.youki_status(&["delete", "--force", id]).await;
self.lock().remove(id);
self.cleanup_dir(id);
self.net_release(id).await;
let log = self.log_path(id);
let _ = fs::remove_file(logfile::rotated(&log));
let _ = fs::remove_file(&log);
if let Some(cg) = crate::cgroup::native_cgroup_path(id) {
let p = Path::new(CGROUP_ROOT).join(cg);
let _ = fs::remove_dir(&p);
if let Some(parent) = p.parent() {
let _ = fs::remove_dir(parent);
}
}
self.rewrite_hosts();
Ok(())
}
async fn ensure_network(&self, _name: &str) -> io::Result<()> {
Ok(())
}
async fn remove_network(&self, _name: &str) -> io::Result<()> {
Ok(())
}
async fn connect_network(
&self,
container: &str,
_network: &str,
aliases: &[String],
) -> io::Result<()> {
self.ensure_managed(container)?;
{
let mut g = self.lock();
if let Some(e) = g.get_mut(container) {
e.meta.aliases = aliases.to_vec();
let _ = self.persist(&e.meta);
}
}
self.rewrite_hosts();
Ok(())
}
async fn disconnect_network(&self, container: &str, _network: &str) -> io::Result<()> {
self.ensure_managed(container).map(|_| ())
}
async fn remove_volume(&self, name: &str) -> io::Result<()> {
if !name.starts_with("krab") || !crate::policy::data_key_ok(name) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{name} is not managed by krab"),
));
}
match fs::remove_dir_all(self.inner.root.join("volumes").join(name)) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
async fn exec_run(&self, id: &str, cmd: &[String]) -> io::Result<(i64, Vec<u8>)> {
let m = self.ensure_managed(id)?;
let mut c = self.exec_cmd(&m, cmd, false)?;
c.kill_on_drop(true);
let out = c.output().await?;
let mut buf = out.stdout;
buf.extend_from_slice(&out.stderr);
buf.truncate(64 * 1024);
Ok((exit_code(&out.status), buf))
}
async fn exec_stream(&self, id: &str, opts: &ExecOpts) -> io::Result<ExecHandle> {
let m = self.ensure_managed(id)?;
let mut c = self.exec_cmd(&m, &opts.cmd, opts.tty)?;
c.stdin(if opts.stdin {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = c.spawn()?;
let exec_id = format!(
"exec-{}-{}",
std::process::id(),
self.inner.seq.fetch_add(1, Ordering::Relaxed)
);
let (otx, orx) = mpsc::channel::<Bytes>(16);
let (etx, erx) = mpsc::channel::<Bytes>(16);
type Sink = Box<dyn tokio::io::AsyncWrite + Unpin + Send>;
let stdin = child.stdin.take().map(|i| Box::new(i) as Sink);
if let Some(o) = child.stdout.take() {
tokio::spawn(pump_chan(o, otx));
}
if let Some(e) = child.stderr.take() {
tokio::spawn(pump_chan(e, etx));
}
{
let mut ex = self.execs();
if ex.len() > 256 {
ex.retain(|_, s| s.code.is_none());
}
ex.insert(exec_id.clone(), ExecState { code: None });
}
let me = self.clone();
let eid = exec_id.clone();
tokio::spawn(async move {
let code = child.wait().await.map(|s| exit_code(&s)).unwrap_or(-1);
if let Some(s) = me.execs().get_mut(&eid) {
s.code = Some(code);
}
});
Ok(ExecHandle {
exec_id,
stdout: orx,
stderr: erx,
stdin,
hold: None,
})
}
async fn exec_resize(&self, exec_id: &str, _width: u32, _height: u32) -> io::Result<()> {
if self.execs().contains_key(exec_id) {
Ok(())
} else {
Err(not_found(exec_id))
}
}
async fn shutdown(&self) {
self.shutdown_all().await
}
async fn exec_exit_code(&self, exec_id: &str) -> io::Result<i64> {
let mut ex = self.execs();
match ex.get(exec_id).map(|s| s.code) {
Some(Some(c)) => {
ex.remove(exec_id);
Ok(c)
}
Some(None) => Err(io::Error::other("exec is still running")),
None => Err(not_found(exec_id)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn root(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("krab-native-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
d
}
#[test]
fn ids_and_cgroups() {
assert!(id_ok("krab_default_web_nginx"));
assert!(!id_ok("krab_default_web"));
assert!(!id_ok("other_default_web_nginx"));
assert!(!id_ok("krab_default_we/b_nginx"));
assert_eq!(
crate::cgroup::native_cgroup_path("krab_default_web_nginx").as_deref(),
Some("krab/default_web/nginx")
);
}
#[tokio::test]
async fn create_rejects_unsupported_seccomp() {
let r = root("seccomp");
let n = Native::new(&r, "/nonexistent/youki").unwrap();
let mut labels = BTreeMap::new();
labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
let base = ContainerSpec {
name: "krab_default_p_c".into(),
image: "busybox:1.37".into(),
labels,
..Default::default()
};
for t in ["RuntimeDefault", "Localhost"] {
let mut spec = base.clone();
spec.seccomp = Some(t.into());
assert_eq!(
n.create_container(&spec).await.unwrap_err().kind(),
io::ErrorKind::InvalidInput,
"{t}"
);
}
for t in [None, Some("Unconfined".to_string())] {
let mut spec = base.clone();
spec.seccomp = t;
assert_ne!(
n.create_container(&spec).await.unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
}
let _ = fs::remove_dir_all(&r);
}
fn profile_file(tag: &str, body: &str) -> PathBuf {
let p =
std::env::temp_dir().join(format!("krab-seccomp-{tag}-{}.json", std::process::id()));
fs::write(&p, body).unwrap();
p
}
#[tokio::test]
async fn operator_profile_locks_seccomp_modes() {
let r = root("seccomp-profile");
let pf = profile_file(
"ok",
r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read","write","exit","exit_group"],"action":"SCMP_ACT_ALLOW"}]}"#,
);
let n = Native::new_with_profile(&r, "/nonexistent/youki", None, Some(pf.clone())).unwrap();
let mut labels = BTreeMap::new();
labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
let base = ContainerSpec {
name: "krab_default_p_c".into(),
image: "busybox:1.37".into(),
labels,
..Default::default()
};
for t in [None, Some("RuntimeDefault".to_string())] {
let mut spec = base.clone();
spec.seccomp = t;
assert_ne!(
n.create_container(&spec).await.unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
}
for t in ["Unconfined", "Localhost"] {
let mut spec = base.clone();
spec.seccomp = Some(t.into());
let e = n.create_container(&spec).await.unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::InvalidInput, "{t}");
assert!(e.to_string().contains("cannot opt out"), "{e}");
}
for t in ["DockerDefault", "runtimeDefault", ""] {
let mut spec = base.clone();
spec.seccomp = Some(t.into());
let e = n.create_container(&spec).await.unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::InvalidInput, "{t}");
assert!(e.to_string().contains("is not supported"), "{e}");
}
let _ = fs::remove_dir_all(&r);
let _ = fs::remove_file(&pf);
}
#[tokio::test]
async fn bad_profile_fails_startup_before_root() {
let r = root("seccomp-bad");
let pf = profile_file("bad", r#"{"defaultAction":"SCMP_ACT_ALLOW"}"#);
let e = match Native::new_with_profile(&r, "/nonexistent/youki", None, Some(pf.clone())) {
Ok(_) => panic!("default-allow profile accepted"),
Err(e) => e,
};
assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
assert!(e.to_string().contains("defaultAction"), "{e}");
assert!(!r.exists());
let e = match Native::new_with_profile(
&r,
"/nonexistent/youki",
None,
Some(pf.with_extension("missing")),
) {
Ok(_) => panic!("missing profile accepted"),
Err(e) => e,
};
assert_eq!(e.kind(), io::ErrorKind::NotFound);
let _ = fs::remove_file(&pf);
}
#[test]
fn loads_state_and_lists_managed() {
let r = root("load");
let n = Native::new(&r, "/nonexistent/youki").unwrap();
let id = "krab_default_p_c";
let mut labels = BTreeMap::new();
labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
let m = Meta {
id: id.into(),
labels,
state: "exited".into(),
exit_code: 3,
restart_count: 2,
..Default::default()
};
fs::create_dir_all(n.dir(id)).unwrap();
n.persist(&m).unwrap();
fs::create_dir_all(n.dir("bogus")).unwrap();
fs::write(n.dir("bogus").join("meta.json"), br#"{"id":"../x"}"#).unwrap();
let n = Native::new(&r, "/nonexistent/youki").unwrap();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
let list = n.list().await.unwrap();
assert_eq!(list.len(), 1);
assert!(is_managed(&list[0]));
assert_eq!(list[0].exit_code, 3);
assert_eq!(list[0].ip, POD_IP);
let mut info = ContainerInfo {
id: id.into(),
..Default::default()
};
n.inspect(&mut info).await.unwrap();
assert_eq!(info.restart_count, 2);
let mut missing = ContainerInfo {
id: "krab_x_y_z".into(),
..Default::default()
};
assert_eq!(
n.inspect(&mut missing).await.unwrap_err().kind(),
io::ErrorKind::NotFound
);
let spec = ContainerSpec {
name: "krab_default_q_c".into(),
image: "busybox:1.37".into(),
labels: list[0].labels.clone(),
..Default::default()
};
assert_eq!(
n.create_container(&spec).await.unwrap_err().kind(),
io::ErrorKind::NotFound
);
let foreign = ContainerSpec {
name: "other".into(),
..spec.clone()
};
assert_eq!(
n.create_container(&foreign).await.unwrap_err().kind(),
io::ErrorKind::PermissionDenied
);
assert!(n.remove_volume("../etc").await.is_err());
n.connect_network(id, "krab", &["db".into()]).await.unwrap();
assert!(
fs::read_to_string(n.dir(id).join("hosts"))
.unwrap()
.contains("\tdb\n")
);
let mut w = logfile::LogWriter::open(&n.log_path(id), 1 << 20).unwrap();
w.write(0, b"one\ntwo\nthree\n").unwrap();
let mut rx = n
.logs(
&info,
&LogOpts {
tail: Some(2),
..Default::default()
},
)
.await
.unwrap();
let mut got = Vec::new();
while let Some(b) = rx.recv().await {
got.extend_from_slice(&b);
}
assert_eq!(got, b"two\nthree\n");
assert!(n.exec_run(id, &["true".into()]).await.is_err());
});
fs::remove_dir_all(&r).unwrap();
}
fn managed(n: &Native, id: &str, state: &str) {
let mut labels = BTreeMap::new();
labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
n.lock().insert(
id.into(),
Entry {
meta: Meta {
id: id.into(),
labels,
state: state.into(),
layers: vec!["a".repeat(64)],
no_new_privs: true,
..Default::default()
},
stopping: false,
epoch: 5,
backoff_ms: 0,
launched: None,
starting: false,
},
);
}
#[test]
fn exec_separates_user_command() {
let r = root("exec");
let n = Native::new(&r, "/nonexistent/youki").unwrap();
let id = "krab_default_p_c";
managed(&n, id, "running");
let m = n.meta(id).unwrap();
let c = n
.exec_cmd(&m, &["--root".into(), "/tmp".into()], true)
.unwrap();
let args: Vec<String> = c
.as_std()
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
assert_eq!(
&args[2..],
[
"exec",
"--no-new-privs",
"--tty",
id,
"--",
"--root",
"/tmp"
]
);
fs::remove_dir_all(&r).unwrap();
}
#[test]
fn concurrent_start_does_not_relaunch() {
let r = root("race");
let n = Native::new(&r, "/nonexistent/youki").unwrap();
let id = "krab_default_p_c";
managed(&n, id, "exited");
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
n.lock().get_mut(id).unwrap().starting = true;
n.start(id).await.unwrap();
n.launch(id, None).await.unwrap();
assert_eq!(n.lock()[id].epoch, 5);
n.lock().get_mut(id).unwrap().starting = false;
n.launch(id, Some(4)).await.unwrap();
n.lock().get_mut(id).unwrap().stopping = true;
n.launch(id, Some(5)).await.unwrap();
let got = {
let g = n.lock();
(g[id].epoch, g[id].meta.restart_count)
};
assert_eq!(got, (5, 0));
n.lock().get_mut(id).unwrap().meta.state = "running".into();
n.start(id).await.unwrap();
n.launch(id, None).await.unwrap();
assert_eq!(n.lock()[id].epoch, 5);
n.lock().get_mut(id).unwrap().meta.state = "exited".into();
assert!(n.start(id).await.is_err());
let e = &n.lock()[id];
assert_eq!((e.epoch, e.starting), (5, false));
});
fs::remove_dir_all(&r).unwrap();
}
#[test]
fn empty_dir_is_world_writable() {
let r = root("vol");
fs::create_dir_all(&r).unwrap();
let v = r.join("krab_u_e");
ensure_volume(&v).unwrap();
assert_eq!(fs::metadata(&v).unwrap().mode() & 0o7777, 0o777);
fs::set_permissions(&v, fs::Permissions::from_mode(0o700)).unwrap();
ensure_volume(&v).unwrap();
assert_eq!(fs::metadata(&v).unwrap().mode() & 0o7777, 0o700);
fs::write(r.join("file"), b"").unwrap();
assert!(ensure_volume(&r.join("file")).is_err());
fs::remove_dir_all(&r).unwrap();
}
#[test]
fn pull_locks_are_per_key() {
let r = root("locks");
let n = Native::new(&r, "/nonexistent/youki").unwrap();
let a = n.key_lock("image:a");
assert!(Arc::ptr_eq(&a, &n.key_lock("image:a")));
let b = n.key_lock("image:b");
assert!(!Arc::ptr_eq(&a, &b));
let _ga = a.try_lock().unwrap();
assert!(b.try_lock().is_ok());
assert!(n.key_lock("image:a").try_lock().is_err());
drop(b);
n.key_lock("image:c");
assert!(!n.inner.pull_locks.lock().unwrap().contains_key("image:b"));
fs::remove_dir_all(&r).unwrap();
}
#[test]
fn install_layer_budget_deadline_and_blob_cleanup() {
let r = root("install");
fs::create_dir_all(&r).unwrap();
let mut b = tar::Builder::new(Vec::new());
let mut h = tar::Header::new_gnu();
h.set_path("f").unwrap();
h.set_size(3);
h.set_mode(0o644);
h.set_cksum();
b.append(&h, &b"abc"[..]).unwrap();
let data = b.into_inner().unwrap();
let blob = r.join("blob");
fs::write(&blob, &data).unwrap();
let late = Instant::now() - Duration::from_secs(1);
let err =
install_layer(&blob, &r.join("l0"), layer::Limits::default(), &[], late).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::TimedOut);
assert!(blob.exists() && !r.join("l0").exists());
let small = layer::Limits {
max_bytes: 2,
max_entries: 10,
};
let until = Instant::now() + Duration::from_secs(60);
assert!(install_layer(&blob, &r.join("l0"), small, &[], until).is_err());
assert!(blob.exists());
let left =
install_layer(&blob, &r.join("l1"), layer::Limits::default(), &[], until).unwrap();
assert_eq!(fs::read(r.join("l1/f")).unwrap(), b"abc");
assert!(!blob.exists());
assert_eq!(
(left.max_bytes, left.max_entries),
(
layer::Limits::default().max_bytes - 3,
layer::Limits::default().max_entries - 1
)
);
fs::remove_dir_all(&r).unwrap();
}
#[cfg(target_os = "linux")]
#[test]
fn running_containers_are_adopted_after_restart() {
let r = root("adopt");
let n = Native::new(&r, "/nonexistent/youki").unwrap();
let mut labels = BTreeMap::new();
labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
let mk = |id: &str| {
let m = Meta {
id: id.into(),
labels: labels.clone(),
state: "running".into(),
restart_count: 4,
pid: 42,
..Default::default()
};
fs::create_dir_all(n.dir(id)).unwrap();
n.persist(&m).unwrap();
};
let (live, done, lost) = ("krab_d_p_live", "krab_d_p_done", "krab_d_p_lost");
for id in [live, done, lost] {
mk(id);
}
let sleep = net::which("sleep").unwrap();
let mut shim = std::process::Command::new(&sleep)
.arg("30")
.spawn()
.unwrap();
let sp = shim.id() as i32;
let start = shim::proc_starttime(sp).unwrap();
fs::write(n.dir(live).join("shim.pid"), format!("{sp} {start}")).unwrap();
fs::write(n.dir(lost).join("shim.pid"), format!("{sp} {}", start + 1)).unwrap();
fs::write(
n.dir(done).join("exit"),
br#"{"code":3,"finished_at":"2026-11-30T00:00:00Z"}"#,
)
.unwrap();
drop(n);
let n = Native::open(
fs::canonicalize(&r).unwrap(),
"/nonexistent/youki".into(),
None,
fs::canonicalize(&sleep).unwrap(),
None,
)
.unwrap();
assert_eq!(n.shim_alive(&n.dir(live)), Some(sp));
let other = Native::new(r.join("other"), "/nonexistent/youki").unwrap();
assert_eq!(other.shim_alive(&n.dir(live)), None);
let get = |n: &Native, id: &str| n.meta(id).unwrap();
assert_eq!(get(&n, live).state, "running");
assert_eq!(get(&n, live).restart_count, 4);
assert_eq!(get(&n, live).pid, 42);
assert_eq!(
(get(&n, done).state.as_str(), get(&n, done).exit_code),
("exited", 3)
);
assert_eq!(
(get(&n, lost).state.as_str(), get(&n, lost).exit_code),
("exited", 137)
);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
n.list().await.unwrap();
tokio::time::sleep(Duration::from_millis(300)).await;
assert_eq!(get(&n, live).state, "running");
n.lock().get_mut(live).unwrap().stopping = true;
fs::write(
n.dir(live).join("exit"),
br#"{"code":5,"finished_at":"2026-11-30T00:00:01Z"}"#,
)
.unwrap();
shim.kill().unwrap();
shim.wait().unwrap();
assert!(n.wait_not_running(live, Duration::from_secs(5)).await);
let m = get(&n, live);
assert_eq!(
(m.exit_code, m.restart_count, m.finished_at.as_str()),
(5, 4, "2026-11-30T00:00:01Z")
);
});
fs::remove_dir_all(&r).unwrap();
}
#[test]
fn launch_without_pid_or_exit_fails() {
let r = root("nostart");
let n = Native::open(
{
fs::create_dir_all(&r).unwrap();
fs::canonicalize(&r).unwrap()
},
"/nonexistent/youki".into(),
None,
net::which("true").unwrap(),
None,
)
.unwrap();
let id = "krab_default_p_c";
managed(&n, id, "exited");
fs::create_dir_all(n.dir(id)).unwrap();
let meta = n.meta(id).unwrap();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let err = rt.block_on(n.run_launch(id, &meta, 5)).unwrap_err();
assert!(err.to_string().contains("failed to start"), "{err}");
let m = n.meta(id).unwrap();
assert_eq!((m.state.as_str(), m.exit_code), ("exited", -1));
fs::remove_dir_all(&r).unwrap();
}
#[test]
#[ignore]
fn youki_end_to_end() {
let youki = std::env::var("KRAB_YOUKI").unwrap_or_else(|_| "youki".into());
let r = root("e2e");
let n = Native::new(&r, youki).unwrap();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
n.pull_image("busybox:1.37").await.unwrap();
let mut labels = BTreeMap::new();
labels.insert(MANAGED_LABEL.to_string(), "true".to_string());
let spec = ContainerSpec {
name: "krab_default_e2e_c".into(),
image: "busybox:1.37".into(),
command: vec!["sh".into(), "-c".into(), "echo hello; sleep 30".into()],
labels,
hostname: Some("e2e".into()),
memory_bytes: Some(32 << 20),
..Default::default()
};
let id = n.create_container(&spec).await.unwrap();
n.start(&id).await.unwrap();
let (code, out) = n.exec_run(&id, &["hostname".into()]).await.unwrap();
assert_eq!((code, String::from_utf8_lossy(&out).trim()), (0, "e2e"));
tokio::time::sleep(Duration::from_millis(500)).await;
let info = to_info(&n.meta(&id).unwrap());
let mut rx = n.logs(&info, &LogOpts::default()).await.unwrap();
assert_eq!(rx.recv().await.unwrap(), Bytes::from_static(b"hello\n"));
n.stop(&id, 1).await.unwrap();
n.remove(&id, true).await.unwrap();
});
fs::remove_dir_all(&r).unwrap();
}
}