1use super::logfile::{self, LogWriter};
2use serde::{Deserialize, Serialize};
3use std::ffi::OsString;
4use std::fs;
5use std::io::{self, Read};
6use std::os::fd::AsRawFd;
7use std::path::{Path, PathBuf};
8use std::process::{Command, Stdio};
9use std::time::{Duration, Instant};
10
11#[derive(Clone, Debug, Default, PartialEq)]
12pub struct Args {
13 pub youki: PathBuf,
14 pub root: PathBuf,
15 pub bundle: PathBuf,
16 pub dir: PathBuf,
17 pub log: PathBuf,
18 pub log_max: u64,
19 pub id: String,
20 pub stdin: bool,
21 pub tty: bool,
22}
23
24#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
25pub struct Exit {
26 pub code: i64,
27 pub finished_at: String,
28}
29
30impl Args {
31 pub fn to_args(&self) -> Vec<OsString> {
32 let mut v: Vec<OsString> = Vec::new();
33 for (k, p) in [
34 ("--youki", &self.youki),
35 ("--root", &self.root),
36 ("--bundle", &self.bundle),
37 ("--dir", &self.dir),
38 ("--log", &self.log),
39 ] {
40 v.push(k.into());
41 v.push(p.into());
42 }
43 v.extend(["--log-max".into(), self.log_max.to_string().into()]);
44 v.extend(["--id".into(), self.id.clone().into()]);
45 if self.stdin {
46 v.push("--stdin".into());
47 }
48 if self.tty {
49 v.push("--tty".into());
50 }
51 v
52 }
53
54 pub fn parse(a: &[String]) -> Option<Self> {
55 let mut out = Args::default();
56 let mut it = a.iter();
57 while let Some(k) = it.next() {
58 match k.as_str() {
59 "--stdin" => out.stdin = true,
60 "--tty" => out.tty = true,
61 _ => {
62 let v = it.next()?;
63 match k.as_str() {
64 "--youki" => out.youki = v.into(),
65 "--root" => out.root = v.into(),
66 "--bundle" => out.bundle = v.into(),
67 "--dir" => out.dir = v.into(),
68 "--log" => out.log = v.into(),
69 "--log-max" => out.log_max = v.parse().ok()?,
70 "--id" => out.id = v.clone(),
71 _ => return None,
72 }
73 }
74 }
75 }
76 (!out.id.is_empty() && out.dir.is_absolute()).then_some(out)
77 }
78}
79
80pub fn proc_starttime(pid: i32) -> Option<u64> {
81 let s = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
82 s.rsplit_once(')')?
83 .1
84 .split_whitespace()
85 .nth(19)?
86 .parse()
87 .ok()
88}
89
90pub fn read_shim_pid(dir: &Path) -> Option<(i32, u64)> {
91 let s = fs::read_to_string(dir.join("shim.pid")).ok()?;
92 let mut it = s.split_whitespace();
93 let pid = it.next()?.parse().ok().filter(|p: &i32| *p > 0)?;
94 Some((pid, it.next()?.parse().ok()?))
95}
96
97pub fn read_exit(dir: &Path) -> Option<Exit> {
98 serde_json::from_slice(&fs::read(dir.join("exit")).ok()?).ok()
99}
100
101fn write_exit(dir: &Path, code: i64) -> io::Result<()> {
102 let e = Exit {
103 code,
104 finished_at: logfile::now_ts(),
105 };
106 let tmp = dir.join("exit.tmp");
107 fs::write(&tmp, serde_json::to_vec(&e).map_err(io::Error::other)?)?;
108 fs::rename(&tmp, dir.join("exit"))
109}
110
111fn decode(st: libc::c_int) -> i64 {
112 if libc::WIFEXITED(st) {
113 libc::WEXITSTATUS(st) as i64
114 } else if libc::WIFSIGNALED(st) {
115 128 + libc::WTERMSIG(st) as i64
116 } else {
117 -1
118 }
119}
120
121fn status_code(st: std::process::ExitStatus) -> i64 {
122 use std::os::unix::process::ExitStatusExt;
123 match (st.code(), st.signal()) {
124 (Some(c), _) => c as i64,
125 (None, Some(s)) => 128 + s as i64,
126 _ => -1,
127 }
128}
129
130fn pump(log: &mut LogWriter, mut r: [Option<io::PipeReader>; 2], mut done: impl FnMut() -> bool) {
131 let mut buf = vec![0u8; 8192];
132 let mut until: Option<Instant> = None;
133 while r.iter().any(Option::is_some) {
134 if until.is_none() && done() {
135 until = Some(Instant::now() + Duration::from_secs(2));
136 }
137 if until.is_some_and(|t| Instant::now() >= t) {
138 break;
139 }
140 let mut p: Vec<libc::pollfd> = r
141 .iter()
142 .flatten()
143 .map(|f| libc::pollfd {
144 fd: f.as_raw_fd(),
145 events: libc::POLLIN,
146 revents: 0,
147 })
148 .collect();
149 let n = unsafe { libc::poll(p.as_mut_ptr(), p.len() as libc::nfds_t, 500) };
150 if n < 0 {
151 if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
152 continue;
153 }
154 break;
155 }
156 let mut k = 0;
157 for (i, slot) in r.iter_mut().enumerate() {
158 let Some(f) = slot else { continue };
159 let re = p[k].revents;
160 k += 1;
161 if re == 0 {
162 continue;
163 }
164 match f.read(&mut buf) {
165 Ok(0) => *slot = None,
166 Ok(n) => {
167 let _ = log.write(i, &buf[..n]);
168 }
169 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
170 Err(_) => *slot = None,
171 }
172 }
173 }
174 let _ = log.flush_partial();
175}
176
177fn reap(pid: i32, code: &mut Option<i64>) {
178 let mut st = 0;
179 if code.is_none() && unsafe { libc::waitpid(pid, &mut st, libc::WNOHANG) } == pid {
180 *code = Some(decode(st));
181 }
182}
183
184pub fn run(a: &Args) -> io::Result<i64> {
185 let mut log = LogWriter::open(&a.log, a.log_max)?;
186 let (or, ow) = io::pipe()?;
187 let (er, ew) = io::pipe()?;
188 let (stdin, _hold) = if a.stdin {
189 let (r, w) = io::pipe()?;
190 (Stdio::from(r), Some(w))
191 } else {
192 (Stdio::null(), None)
193 };
194 let youki = || {
195 let mut c = Command::new(&a.youki);
196 c.arg("--root").arg(&a.root);
197 c
198 };
199 let pidfile = a.dir.join("pid");
200 if a.tty {
201 let mut child = youki()
202 .arg("run")
203 .arg("--bundle")
204 .arg(&a.bundle)
205 .arg("--pid-file")
206 .arg(&pidfile)
207 .arg(&a.id)
208 .stdin(stdin)
209 .stdout(ow)
210 .stderr(ew)
211 .spawn()?;
212 pump(&mut log, [Some(or), Some(er)], || {
213 matches!(child.try_wait(), Ok(Some(_)))
214 });
215 return child.wait().map(status_code);
216 }
217 let st = youki()
218 .arg("create")
219 .arg("--bundle")
220 .arg(&a.bundle)
221 .arg("--pid-file")
222 .arg(&pidfile)
223 .arg(&a.id)
224 .stdin(stdin)
225 .stdout(ow)
226 .stderr(ew)
227 .status()?;
228 let pid = fs::read_to_string(&pidfile)
229 .ok()
230 .and_then(|s| s.trim().parse::<i32>().ok())
231 .filter(|p| *p > 0);
232 let started = st.success()
233 && pid.is_some()
234 && youki()
235 .arg("start")
236 .arg(&a.id)
237 .stdin(Stdio::null())
238 .stdout(Stdio::null())
239 .stderr(Stdio::null())
240 .status()
241 .is_ok_and(|s| s.success());
242 let Some(pid) = pid.filter(|_| started) else {
243 let _ = youki()
244 .args(["delete", "--force", &a.id])
245 .stdin(Stdio::null())
246 .stdout(Stdio::null())
247 .stderr(Stdio::null())
248 .status();
249 pump(&mut log, [Some(or), Some(er)], || true);
250 return Ok(if st.success() { 1 } else { status_code(st) });
251 };
252 let mut code = None;
253 pump(&mut log, [Some(or), Some(er)], || {
254 reap(pid, &mut code);
255 code.is_some()
256 });
257 if code.is_none() {
258 let mut s = 0;
259 if unsafe { libc::waitpid(pid, &mut s, 0) } == pid {
260 code = Some(decode(s));
261 }
262 }
263 Ok(code.unwrap_or(-1))
264}
265
266#[cfg(target_os = "linux")]
267fn set_subreaper() {
268 unsafe {
269 libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0);
270 }
271}
272
273#[cfg(not(target_os = "linux"))]
274fn set_subreaper() {}
275
276pub fn main(args: &[String]) -> i32 {
277 let Some(a) = Args::parse(args) else {
278 eprintln!(
279 "usage: krab shim --youki P --root P --bundle P --dir P --log P --log-max N --id ID [--stdin] [--tty]"
280 );
281 return 2;
282 };
283 match unsafe { libc::fork() } {
284 -1 => return 1,
285 0 => {}
286 _ => return 0,
287 }
288 unsafe {
289 libc::setsid();
290 }
291 set_subreaper();
292 let me = std::process::id() as i32;
293 let Some(start) = proc_starttime(me) else {
294 return 1;
295 };
296 if fs::write(a.dir.join("shim.pid"), format!("{me} {start}")).is_err() {
297 return 1;
298 }
299 let code = run(&a).unwrap_or(-1);
300 if write_exit(&a.dir, code).is_err() {
301 return 1;
302 }
303 0
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309
310 #[test]
311 fn args_roundtrip() {
312 let a = Args {
313 youki: "/usr/bin/youki".into(),
314 root: "/r/youki".into(),
315 bundle: "/r/c/x/bundle".into(),
316 dir: "/r/c/x".into(),
317 log: "/r/logs/x.log".into(),
318 log_max: 4096,
319 id: "krab_default_p_c".into(),
320 stdin: true,
321 tty: false,
322 };
323 let s: Vec<String> = a
324 .to_args()
325 .into_iter()
326 .map(|x| x.into_string().unwrap())
327 .collect();
328 assert_eq!(Args::parse(&s), Some(a));
329 assert_eq!(Args::parse(&["--id".into()]), None);
330 assert_eq!(Args::parse(&["--bogus".into(), "x".into()]), None);
331 assert_eq!(
332 Args::parse(&["--id".into(), "x".into(), "--dir".into(), "rel".into()]),
333 None
334 );
335 }
336
337 #[cfg(target_os = "linux")]
338 #[test]
339 fn shim_runs_container_writes_logs_and_exit_code() {
340 use std::os::unix::fs::PermissionsExt;
341 let d = std::env::temp_dir().join(format!("krab-shim-{}", std::process::id()));
342 let _ = fs::remove_dir_all(&d);
343 fs::create_dir_all(&d).unwrap();
344 let fake = d.join("youki");
345 fs::write(
346 &fake,
347 "#!/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",
348 )
349 .unwrap();
350 fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap();
351 set_subreaper();
352 let a = Args {
353 youki: fake,
354 root: d.join("root"),
355 bundle: d.join("bundle"),
356 dir: d.clone(),
357 log: d.join("c.log"),
358 log_max: 1 << 20,
359 id: d.join("pid").to_string_lossy().into_owned(),
360 stdin: false,
361 tty: false,
362 };
363 std::process::Command::new("mkfifo")
364 .arg(d.join("pid.go"))
365 .status()
366 .unwrap();
367 assert_eq!(run(&a).unwrap(), 7);
368 let log = fs::read_to_string(d.join("c.log")).unwrap();
369 assert!(log.contains(" stdout F hello\n"), "{log}");
370 assert!(log.contains(" stderr F oops\n"), "{log}");
371 write_exit(&d, 7).unwrap();
372 assert_eq!(read_exit(&d).unwrap().code, 7);
373 fs::remove_dir_all(&d).unwrap();
374 }
375}