use super::logfile::{self, LogWriter};
use serde::{Deserialize, Serialize};
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read};
use std::os::fd::AsRawFd;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Args {
pub youki: PathBuf,
pub root: PathBuf,
pub bundle: PathBuf,
pub dir: PathBuf,
pub log: PathBuf,
pub log_max: u64,
pub id: String,
pub stdin: bool,
pub tty: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Exit {
pub code: i64,
pub finished_at: String,
}
impl Args {
pub fn to_args(&self) -> Vec<OsString> {
let mut v: Vec<OsString> = Vec::new();
for (k, p) in [
("--youki", &self.youki),
("--root", &self.root),
("--bundle", &self.bundle),
("--dir", &self.dir),
("--log", &self.log),
] {
v.push(k.into());
v.push(p.into());
}
v.extend(["--log-max".into(), self.log_max.to_string().into()]);
v.extend(["--id".into(), self.id.clone().into()]);
if self.stdin {
v.push("--stdin".into());
}
if self.tty {
v.push("--tty".into());
}
v
}
pub fn parse(a: &[String]) -> Option<Self> {
let mut out = Args::default();
let mut it = a.iter();
while let Some(k) = it.next() {
match k.as_str() {
"--stdin" => out.stdin = true,
"--tty" => out.tty = true,
_ => {
let v = it.next()?;
match k.as_str() {
"--youki" => out.youki = v.into(),
"--root" => out.root = v.into(),
"--bundle" => out.bundle = v.into(),
"--dir" => out.dir = v.into(),
"--log" => out.log = v.into(),
"--log-max" => out.log_max = v.parse().ok()?,
"--id" => out.id = v.clone(),
_ => return None,
}
}
}
}
(!out.id.is_empty() && out.dir.is_absolute()).then_some(out)
}
}
pub fn proc_starttime(pid: i32) -> Option<u64> {
let s = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
s.rsplit_once(')')?
.1
.split_whitespace()
.nth(19)?
.parse()
.ok()
}
pub fn read_shim_pid(dir: &Path) -> Option<(i32, u64)> {
let s = fs::read_to_string(dir.join("shim.pid")).ok()?;
let mut it = s.split_whitespace();
let pid = it.next()?.parse().ok().filter(|p: &i32| *p > 0)?;
Some((pid, it.next()?.parse().ok()?))
}
pub fn read_exit(dir: &Path) -> Option<Exit> {
serde_json::from_slice(&fs::read(dir.join("exit")).ok()?).ok()
}
fn write_exit(dir: &Path, code: i64) -> io::Result<()> {
let e = Exit {
code,
finished_at: logfile::now_ts(),
};
let tmp = dir.join("exit.tmp");
fs::write(&tmp, serde_json::to_vec(&e).map_err(io::Error::other)?)?;
fs::rename(&tmp, dir.join("exit"))
}
fn decode(st: libc::c_int) -> i64 {
if libc::WIFEXITED(st) {
libc::WEXITSTATUS(st) as i64
} else if libc::WIFSIGNALED(st) {
128 + libc::WTERMSIG(st) as i64
} else {
-1
}
}
fn status_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 pump(log: &mut LogWriter, mut r: [Option<io::PipeReader>; 2], mut done: impl FnMut() -> bool) {
let mut buf = vec![0u8; 8192];
let mut until: Option<Instant> = None;
while r.iter().any(Option::is_some) {
if until.is_none() && done() {
until = Some(Instant::now() + Duration::from_secs(2));
}
if until.is_some_and(|t| Instant::now() >= t) {
break;
}
let mut p: Vec<libc::pollfd> = r
.iter()
.flatten()
.map(|f| libc::pollfd {
fd: f.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
})
.collect();
let n = unsafe { libc::poll(p.as_mut_ptr(), p.len() as libc::nfds_t, 500) };
if n < 0 {
if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
continue;
}
break;
}
let mut k = 0;
for (i, slot) in r.iter_mut().enumerate() {
let Some(f) = slot else { continue };
let re = p[k].revents;
k += 1;
if re == 0 {
continue;
}
match f.read(&mut buf) {
Ok(0) => *slot = None,
Ok(n) => {
let _ = log.write(i, &buf[..n]);
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(_) => *slot = None,
}
}
}
let _ = log.flush_partial();
}
fn reap(pid: i32, code: &mut Option<i64>) {
let mut st = 0;
if code.is_none() && unsafe { libc::waitpid(pid, &mut st, libc::WNOHANG) } == pid {
*code = Some(decode(st));
}
}
pub fn run(a: &Args) -> io::Result<i64> {
let mut log = LogWriter::open(&a.log, a.log_max)?;
let (or, ow) = io::pipe()?;
let (er, ew) = io::pipe()?;
let (stdin, _hold) = if a.stdin {
let (r, w) = io::pipe()?;
(Stdio::from(r), Some(w))
} else {
(Stdio::null(), None)
};
let youki = || {
let mut c = Command::new(&a.youki);
c.arg("--root").arg(&a.root);
c
};
let pidfile = a.dir.join("pid");
if a.tty {
let mut child = youki()
.arg("run")
.arg("--bundle")
.arg(&a.bundle)
.arg("--pid-file")
.arg(&pidfile)
.arg(&a.id)
.stdin(stdin)
.stdout(ow)
.stderr(ew)
.spawn()?;
pump(&mut log, [Some(or), Some(er)], || {
matches!(child.try_wait(), Ok(Some(_)))
});
return child.wait().map(status_code);
}
let st = youki()
.arg("create")
.arg("--bundle")
.arg(&a.bundle)
.arg("--pid-file")
.arg(&pidfile)
.arg(&a.id)
.stdin(stdin)
.stdout(ow)
.stderr(ew)
.status()?;
let pid = fs::read_to_string(&pidfile)
.ok()
.and_then(|s| s.trim().parse::<i32>().ok())
.filter(|p| *p > 0);
let started = st.success()
&& pid.is_some()
&& youki()
.arg("start")
.arg(&a.id)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|s| s.success());
let Some(pid) = pid.filter(|_| started) else {
let _ = youki()
.args(["delete", "--force", &a.id])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
pump(&mut log, [Some(or), Some(er)], || true);
return Ok(if st.success() { 1 } else { status_code(st) });
};
let mut code = None;
pump(&mut log, [Some(or), Some(er)], || {
reap(pid, &mut code);
code.is_some()
});
if code.is_none() {
let mut s = 0;
if unsafe { libc::waitpid(pid, &mut s, 0) } == pid {
code = Some(decode(s));
}
}
Ok(code.unwrap_or(-1))
}
#[cfg(target_os = "linux")]
fn set_subreaper() {
unsafe {
libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0);
}
}
#[cfg(not(target_os = "linux"))]
fn set_subreaper() {}
pub fn main(args: &[String]) -> i32 {
let Some(a) = Args::parse(args) else {
eprintln!(
"usage: krab shim --youki P --root P --bundle P --dir P --log P --log-max N --id ID [--stdin] [--tty]"
);
return 2;
};
match unsafe { libc::fork() } {
-1 => return 1,
0 => {}
_ => return 0,
}
unsafe {
libc::setsid();
}
set_subreaper();
let me = std::process::id() as i32;
let Some(start) = proc_starttime(me) else {
return 1;
};
if fs::write(a.dir.join("shim.pid"), format!("{me} {start}")).is_err() {
return 1;
}
let code = run(&a).unwrap_or(-1);
if write_exit(&a.dir, code).is_err() {
return 1;
}
0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn args_roundtrip() {
let a = Args {
youki: "/usr/bin/youki".into(),
root: "/r/youki".into(),
bundle: "/r/c/x/bundle".into(),
dir: "/r/c/x".into(),
log: "/r/logs/x.log".into(),
log_max: 4096,
id: "krab_default_p_c".into(),
stdin: true,
tty: false,
};
let s: Vec<String> = a
.to_args()
.into_iter()
.map(|x| x.into_string().unwrap())
.collect();
assert_eq!(Args::parse(&s), Some(a));
assert_eq!(Args::parse(&["--id".into()]), None);
assert_eq!(Args::parse(&["--bogus".into(), "x".into()]), None);
assert_eq!(
Args::parse(&["--id".into(), "x".into(), "--dir".into(), "rel".into()]),
None
);
}
#[cfg(target_os = "linux")]
#[test]
fn shim_runs_container_writes_logs_and_exit_code() {
use std::os::unix::fs::PermissionsExt;
let d = std::env::temp_dir().join(format!("krab-shim-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
let fake = d.join("youki");
fs::write(
&fake,
"#!/bin/sh\nshift 2\ncase \"$1\" in\ncreate) sh -c 'read x < \"$0\"; echo hello; echo oops >&2; exit 7' \"$5.go\" & echo $! > \"$5\" ;;\nstart) echo > \"$2.go\" ;;\nesac\n",
)
.unwrap();
fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap();
set_subreaper();
let a = Args {
youki: fake,
root: d.join("root"),
bundle: d.join("bundle"),
dir: d.clone(),
log: d.join("c.log"),
log_max: 1 << 20,
id: d.join("pid").to_string_lossy().into_owned(),
stdin: false,
tty: false,
};
std::process::Command::new("mkfifo")
.arg(d.join("pid.go"))
.status()
.unwrap();
assert_eq!(run(&a).unwrap(), 7);
let log = fs::read_to_string(d.join("c.log")).unwrap();
assert!(log.contains(" stdout F hello\n"), "{log}");
assert!(log.contains(" stderr F oops\n"), "{log}");
write_exit(&d, 7).unwrap();
assert_eq!(read_exit(&d).unwrap().code, 7);
fs::remove_dir_all(&d).unwrap();
}
}