1use std::collections::BTreeMap;
12use std::path::PathBuf;
13use std::process::Stdio;
14use std::time::Duration;
15
16use bytes::Bytes;
17use futures::stream::{self, StreamExt as _};
18use saluki_error::{generic_error, ErrorContext as _, GenericError};
19use tokio::io::{AsyncRead, AsyncWriteExt as _};
20use tokio::process::Command;
21use tokio::sync::{mpsc, watch};
22use tokio_util::io::ReaderStream;
23
24use crate::container::{Output, OutputStream};
25
26#[cfg(unix)]
28const KILL_WAIT: Duration = Duration::from_secs(2);
29
30const OUTPUT_BUFFER: usize = 64;
32
33#[cfg(unix)]
35const GROUP_POLL: Duration = Duration::from_millis(20);
36
37#[derive(Clone, Debug)]
39pub struct HostCommand {
40 pub name: String,
42 pub program: PathBuf,
44 pub args: Vec<String>,
46 pub env: BTreeMap<String, String>,
48 pub dir: PathBuf,
50 pub stdin: Option<Bytes>,
52}
53
54#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub struct HostExit {
57 pub code: Option<i32>,
59 pub signal: Option<i32>,
61}
62
63pub type ExitWatch = watch::Receiver<Option<Result<HostExit, String>>>;
65
66#[derive(Debug)]
74pub struct HostProcess {
75 name: String,
76 #[cfg(unix)]
77 exit: ExitWatch,
78 #[cfg(unix)]
80 group: Option<i32>,
81}
82
83impl HostProcess {
84 pub fn spawn(command: HostCommand) -> Result<(Self, OutputStream, ExitWatch), GenericError> {
92 let HostCommand {
93 name,
94 program,
95 args,
96 env,
97 dir,
98 stdin,
99 } = command;
100 let mut process = Command::new(&program);
101 process
102 .args(args)
103 .env_clear()
104 .envs(env)
105 .current_dir(dir)
106 .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
107 .stdout(Stdio::piped())
108 .stderr(Stdio::piped())
109 .kill_on_drop(true);
110 #[cfg(unix)]
111 process.process_group(0);
112 let mut child = process
113 .spawn()
114 .with_error_context(|| format!("Failed to start '{}' ({}).", name, program.display()))?;
115
116 #[cfg(unix)]
117 let group = child.id().and_then(|id| i32::try_from(id).ok());
118 let stdout = child
119 .stdout
120 .take()
121 .ok_or_else(|| generic_error!("No standard output."))?;
122 let stderr = child
123 .stderr
124 .take()
125 .ok_or_else(|| generic_error!("No standard error."))?;
126 if let (Some(payload), Some(mut input)) = (stdin, child.stdin.take()) {
127 tokio::spawn(async move {
129 let _ = input.write_all(&payload).await;
130 let _ = input.shutdown().await;
131 });
132 }
133
134 let stdout = output_of(stdout, &name, "output", Output::Stdout);
135 let stderr = output_of(stderr, &name, "error", Output::Stderr);
136 let output = keep_draining(stream::select(stdout, stderr).boxed());
137
138 let (sender, exit) = watch::channel(None);
139 let waited = name.clone();
140 tokio::spawn(async move {
142 let exited = match child.wait().await {
143 Ok(status) => Ok(HostExit {
144 code: status.code(),
145 signal: signal_of(&status),
146 }),
147 Err(e) => Err(format!("Failed to wait for '{}': {}", waited, e)),
148 };
149 sender.send_replace(Some(exited));
150 });
151
152 let process = Self {
153 name,
154 #[cfg(unix)]
155 exit: exit.clone(),
156 #[cfg(unix)]
157 group,
158 };
159 Ok((process, output, exit))
160 }
161
162 pub fn name(&self) -> &str {
164 &self.name
165 }
166
167 #[cfg_attr(not(unix), allow(unused_mut, unused_variables))]
178 pub async fn stop(mut self, grace: Duration) -> Result<(), GenericError> {
179 #[cfg(unix)]
180 {
181 use tokio::time::timeout;
182
183 if self.exit.borrow().is_none() {
184 self.signal(libc::SIGTERM);
185 let _ = timeout(grace, self.exit.wait_for(Option::is_some)).await;
186 }
187 self.signal(libc::SIGKILL);
188 let group = self.group.take();
189 let gone = async {
190 let _ = self.exit.wait_for(Option::is_some).await;
191 if let Some(group) = group {
192 while group_has_live_member(group) {
193 tokio::time::sleep(GROUP_POLL).await;
194 }
195 }
196 };
197 if timeout(KILL_WAIT, gone).await.is_err() {
198 return Err(generic_error!(
199 "'{}' or something in its process group did not exit within {:?} of SIGKILL",
200 self.name,
201 KILL_WAIT
202 ));
203 }
204 }
205 Ok(())
206 }
207
208 #[cfg_attr(not(unix), allow(unused_mut))]
211 pub fn kill(mut self) {
212 #[cfg(unix)]
213 {
214 self.signal(libc::SIGKILL);
215 self.group = None;
216 }
217 }
218
219 #[cfg(unix)]
221 fn signal(&self, signal: libc::c_int) {
222 if let Some(group) = self.group {
223 unsafe {
225 libc::killpg(group, signal);
226 }
227 }
228 }
229}
230
231impl Drop for HostProcess {
232 fn drop(&mut self) {
233 #[cfg(unix)]
234 if self.group.is_some() {
235 self.signal(libc::SIGKILL);
236 tracing::warn!(name = %self.name, "A host process was dropped before it was stopped. Killed its group.");
237 }
238 }
239}
240
241fn output_of<R>(reader: R, name: &str, stream: &'static str, tag: fn(Bytes) -> Output) -> OutputStream
243where
244 R: AsyncRead + Send + Unpin + 'static,
245{
246 let name = name.to_string();
247 ReaderStream::new(reader)
248 .map(move |chunk| match chunk {
249 Ok(bytes) => Ok(tag(bytes)),
250 Err(e) => Err(generic_error!(
251 "Failed to read the standard {} of '{}': {}",
252 stream,
253 name,
254 e
255 )),
256 })
257 .boxed()
258}
259
260#[cfg(unix)]
265fn group_has_live_member(group: i32) -> bool {
266 #[cfg(target_os = "linux")]
268 if let Ok(entries) = std::fs::read_dir("/proc") {
269 return entries.flatten().any(|entry| {
270 let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
272 return false;
273 };
274 let Some((_, rest)) = stat.rsplit_once(')') else {
276 return false;
277 };
278 let mut fields = rest.split_whitespace();
279 let state = fields.next();
280 let pgrp = fields.nth(1).and_then(|pgrp| pgrp.parse::<i32>().ok());
281 pgrp == Some(group) && !matches!(state, Some("Z" | "X"))
282 });
283 }
284
285 let sent = unsafe { libc::killpg(group, 0) };
288 sent == 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
290}
291
292fn keep_draining(mut output: OutputStream) -> OutputStream {
297 let (sender, receiver) = mpsc::channel(OUTPUT_BUFFER);
298 tokio::spawn(async move {
299 let mut observed = true;
300 while let Some(chunk) = output.next().await {
301 if observed && sender.send(chunk).await.is_err() {
302 observed = false;
303 }
304 }
305 });
306 stream::unfold(receiver, |mut receiver| async move {
307 receiver.recv().await.map(|chunk| (chunk, receiver))
308 })
309 .boxed()
310}
311
312#[cfg(unix)]
313fn signal_of(status: &std::process::ExitStatus) -> Option<i32> {
314 std::os::unix::process::ExitStatusExt::signal(status)
315}
316
317#[cfg(not(unix))]
318fn signal_of(_status: &std::process::ExitStatus) -> Option<i32> {
319 None
320}
321
322#[cfg(all(test, unix))]
323mod tests {
324 use futures::StreamExt as _;
325
326 use super::*;
327
328 const WAIT: Duration = Duration::from_secs(5);
329
330 fn text_of(chunk: Output) -> String {
331 match chunk {
332 Output::Stdout(bytes) | Output::Stderr(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
333 }
334 }
335
336 #[tokio::test]
337 async fn stop_signals_the_whole_group_and_kills_what_ignores_sigterm() {
338 let script = "trap 'echo got-term' TERM; (trap '' TERM; sleep 60) & echo ready; wait";
340 let command = HostCommand {
341 name: "test".to_string(),
342 program: PathBuf::from("/bin/sh"),
343 args: vec!["-c".to_string(), script.to_string()],
344 env: BTreeMap::from([("PATH".to_string(), std::env::var("PATH").unwrap_or_default())]),
345 dir: std::env::temp_dir(),
346 stdin: None,
347 };
348 let (process, mut output, _exit) = HostProcess::spawn(command).unwrap();
349
350 let mut text = String::new();
351 tokio::time::timeout(WAIT, async {
352 while !text.contains("ready") {
353 text.push_str(&text_of(
354 output.next().await.expect("output ended before ready").unwrap(),
355 ));
356 }
357 })
358 .await
359 .expect("the program should say ready");
360
361 tokio::time::timeout(WAIT, process.stop(Duration::from_millis(500)))
362 .await
363 .expect("stop should return")
364 .expect("stop should confirm the exit");
365
366 tokio::time::timeout(WAIT, async {
368 while let Some(chunk) = output.next().await {
369 text.push_str(&text_of(chunk.unwrap()));
370 }
371 })
372 .await
373 .expect("a process still holds the output pipes");
374 assert!(text.contains("got-term"), "{text}");
375 }
376}