1use futures::future::BoxFuture;
10use futures::stream::BoxStream;
11use futures::StreamExt;
12use std::collections::BTreeSet;
13use std::process::Stdio;
14use std::sync::{Arc, Mutex};
15use tokio::io::AsyncReadExt;
16use tokio_util::sync::CancellationToken;
17
18use base::interface::exec::{
19 ExecError, ExitStatus, OutputChunk, OutputStream, Process, ProcessHandle, ProcessSpec,
20 SubprocessEnv,
21};
22
23#[derive(Debug, Clone, Default)]
24pub struct LocalProcess {
25 env: SubprocessEnv,
26 ledger: Option<Arc<GroupLedger>>,
27}
28
29impl LocalProcess {
30 pub fn new(env: SubprocessEnv) -> Self {
31 Self { env, ledger: None }
32 }
33
34 pub fn with_ledger(env: SubprocessEnv, ledger: Arc<GroupLedger>) -> Self {
35 Self {
36 env,
37 ledger: Some(ledger),
38 }
39 }
40}
41
42#[derive(Debug, Default)]
43pub struct GroupLedger {
44 groups: Mutex<BTreeSet<i32>>,
45}
46
47impl GroupLedger {
48 pub fn new() -> Arc<Self> {
49 Arc::new(Self::default())
50 }
51
52 pub fn record(&self, group: i32) {
55 let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
56 forget_emptied(&mut groups);
57 groups.insert(group);
58 }
59
60 pub fn groups(&self) -> Vec<i32> {
61 let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
62 forget_emptied(&mut groups);
63 groups.iter().copied().collect()
64 }
65
66 pub async fn reap(&self, grace: std::time::Duration) {
67 let targets: Vec<i32> = {
68 let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
69 std::mem::take(&mut *groups)
70 .into_iter()
71 .filter(|g| group_alive(*g))
72 .collect()
73 };
74 if targets.is_empty() {
75 return;
76 }
77 let _forget = ForgetOnDrop(&targets);
78 #[cfg(unix)]
79 {
80 for g in &targets {
81 signal_group(*g, libc::SIGTERM);
82 }
83 let deadline = tokio::time::Instant::now() + grace;
84 while tokio::time::Instant::now() < deadline && targets.iter().any(|g| group_alive(*g))
85 {
86 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
87 }
88 for g in &targets {
89 if group_alive(*g) {
90 signal_group(*g, libc::SIGKILL);
91 }
92 }
93 }
94 #[cfg(not(unix))]
95 let _ = grace;
96 }
97}
98
99fn forget_emptied(groups: &mut BTreeSet<i32>) {
100 groups.retain(|g| {
101 let alive = group_alive(*g);
102 if !alive {
103 crate::orphans::stopped(*g);
104 }
105 alive
106 });
107}
108
109struct ForgetOnDrop<'a>(&'a [i32]);
112
113impl Drop for ForgetOnDrop<'_> {
114 fn drop(&mut self) {
115 for g in self.0 {
116 crate::orphans::stopped(*g);
117 }
118 }
119}
120
121#[cfg(unix)]
122pub(crate) fn group_alive(group: i32) -> bool {
123 unsafe { libc::killpg(group, 0) == 0 }
125}
126
127#[cfg(not(unix))]
128pub(crate) fn group_alive(_group: i32) -> bool {
129 false
130}
131
132#[cfg(unix)]
134const TERM_GRACE: std::time::Duration = std::time::Duration::from_millis(500);
135
136#[async_trait::async_trait]
137impl Process for LocalProcess {
138 async fn spawn(
139 &self,
140 spec: ProcessSpec,
141 cancel: CancellationToken,
142 ) -> Result<Box<dyn ProcessHandle>, ExecError> {
143 let mut cmd = tokio::process::Command::new(&spec.program);
144 cmd.args(&spec.args)
145 .current_dir(&spec.cwd)
146 .stdout(Stdio::piped())
147 .stderr(Stdio::piped())
148 .stdin(if spec.stdin.is_some() {
149 Stdio::piped()
150 } else {
151 Stdio::null()
152 });
153 crate::env::apply_subprocess_env_in(&self.env, spec.env_scope, &mut cmd);
154 for (k, v) in &spec.env {
155 cmd.env(k, v);
156 }
157 cmd.kill_on_drop(true);
161 #[cfg(unix)]
168 unsafe {
170 cmd.pre_exec(|| {
171 if libc::setsid() == -1 {
172 return Err(std::io::Error::last_os_error());
173 }
174 Ok(())
175 });
176 }
177
178 let mut child = cmd
179 .spawn()
180 .map_err(|e| ExecError::failed(format!("{}: {e}", spec.program)))?;
181
182 if let Some(bytes) = spec.stdin {
183 if let Some(mut stdin) = child.stdin.take() {
184 tokio::spawn(async move {
189 use tokio::io::AsyncWriteExt;
190 let _ = stdin.write_all(&bytes).await;
191 });
192 }
193 }
194
195 #[cfg(unix)]
196 let group = child.id().map(|pid| pid as libc::pid_t);
197 #[cfg(unix)]
198 if let Some(group) = group {
199 crate::orphans::started(group);
200 if let Some(ledger) = &self.ledger {
201 ledger.record(group);
202 }
203 }
204 #[cfg(unix)]
205 let cancel_watch = group.map(|group| stop_on_cancel(group, cancel));
206 #[cfg(not(unix))]
207 drop(cancel);
208 let stdout = child.stdout.take();
209 let stderr = child.stderr.take();
210 Ok(Box::new(LocalHandle {
211 child,
212 #[cfg(unix)]
213 group,
214 #[cfg(unix)]
215 cancel_watch,
216 kept: self.ledger.is_some(),
217 output: Some(interleave(stdout, stderr)),
218 }))
219 }
220}
221
222#[cfg(unix)]
225fn stop_on_cancel(group: libc::pid_t, cancel: CancellationToken) -> tokio_util::sync::DropGuard {
226 let handle_gone = CancellationToken::new();
227 let watching = handle_gone.clone();
228 tokio::spawn(async move {
229 tokio::select! {
230 _ = watching.cancelled() => {}
231 _ = cancel.cancelled() => {
232 signal_group(group, libc::SIGTERM);
233 let deadline = tokio::time::Instant::now() + TERM_GRACE;
234 while tokio::time::Instant::now() < deadline && group_alive(group) {
235 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
236 }
237 signal_group(group, libc::SIGKILL);
238 }
239 }
240 });
241 handle_gone.drop_guard()
242}
243
244fn interleave(
249 stdout: Option<tokio::process::ChildStdout>,
250 stderr: Option<tokio::process::ChildStderr>,
251) -> BoxStream<'static, Result<OutputChunk, ExecError>> {
252 fn chunks<R: AsyncReadExt + Unpin + Send + 'static>(
253 reader: Option<R>,
254 stream: OutputStream,
255 ) -> BoxStream<'static, Result<OutputChunk, ExecError>> {
256 let Some(reader) = reader else {
257 return futures::stream::empty().boxed();
258 };
259 futures::stream::unfold(Some((reader, Vec::new())), move |state| async move {
263 let (mut reader, mut buf) = state?;
264 buf.resize(8192, 0);
265 match reader.read(&mut buf).await {
266 Ok(0) => None,
267 Ok(n) => {
268 buf.truncate(n);
269 let chunk = OutputChunk {
270 stream,
271 bytes: std::mem::take(&mut buf),
272 };
273 Some((Ok(chunk), Some((reader, buf))))
274 }
275 Err(e) => Some((Err(ExecError::failed(e)), None)),
276 }
277 })
278 .boxed()
279 }
280 futures::stream::select(
281 chunks(stdout, OutputStream::Stdout),
282 chunks(stderr, OutputStream::Stderr),
283 )
284 .boxed()
285}
286
287struct LocalHandle {
288 child: tokio::process::Child,
289 #[cfg(unix)]
290 group: Option<libc::pid_t>,
291 #[cfg(unix)]
292 cancel_watch: Option<tokio_util::sync::DropGuard>,
293 kept: bool,
296 output: Option<BoxStream<'static, Result<OutputChunk, ExecError>>>,
297}
298
299#[cfg(unix)]
300pub(crate) fn signal_group(group: libc::pid_t, signal: libc::c_int) {
301 unsafe {
304 libc::killpg(group, signal);
305 }
306}
307
308impl Drop for LocalHandle {
309 fn drop(&mut self) {
310 #[cfg(unix)]
311 if let Some(group) = self.group {
312 if matches!(self.child.try_wait(), Ok(None)) {
313 signal_group(group, libc::SIGKILL);
314 }
315 if !self.kept {
316 crate::orphans::stopped(group);
317 }
318 }
319 }
320}
321
322impl ProcessHandle for LocalHandle {
323 fn output(&mut self) -> Option<BoxStream<'static, Result<OutputChunk, ExecError>>> {
324 self.output.take()
325 }
326
327 fn kill(&mut self) -> BoxFuture<'_, ()> {
328 Box::pin(async move {
329 #[cfg(unix)]
330 if let Some(group) = self.group {
331 signal_group(group, libc::SIGTERM);
332 let _ = tokio::time::timeout(TERM_GRACE, self.child.wait()).await;
333 signal_group(group, libc::SIGKILL);
334 }
335 let _ = self.child.kill().await;
336 })
337 }
338
339 fn wait(&mut self) -> BoxFuture<'_, Result<ExitStatus, ExecError>> {
340 Box::pin(async move {
341 let s = self.child.wait().await.map_err(ExecError::failed)?;
342 #[cfg(unix)]
343 if self.group.is_some_and(|group| !group_alive(group)) {
344 self.cancel_watch = None;
345 }
346 Ok(ExitStatus {
347 code: s.code(),
348 success: s.success(),
349 })
350 })
351 }
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357
358 async fn run(spec: ProcessSpec) -> (String, String, ExitStatus) {
359 run_with(LocalProcess::default(), spec).await
360 }
361
362 async fn run_with(process: LocalProcess, spec: ProcessSpec) -> (String, String, ExitStatus) {
363 let mut h = process.spawn(spec, CancellationToken::new()).await.unwrap();
364 let mut out = h.output().expect("first call yields the stream");
365 let (mut o, mut e) = (Vec::new(), Vec::new());
366 while let Some(chunk) = out.next().await {
367 let c = chunk.unwrap();
368 match c.stream {
369 OutputStream::Stdout => o.extend(c.bytes),
370 OutputStream::Stderr => e.extend(c.bytes),
371 }
372 }
373 let status = h.wait().await.unwrap();
374 (
375 String::from_utf8_lossy(&o).into_owned(),
376 String::from_utf8_lossy(&e).into_owned(),
377 status,
378 )
379 }
380
381 fn sh(command: &str) -> ProcessSpec {
382 ProcessSpec::new("bash", std::env::temp_dir()).args(["-c".to_string(), command.to_string()])
383 }
384
385 #[tokio::test]
386 async fn both_pipes_arrive_tagged_and_the_exit_status_comes_back() {
387 let (out, err, status) = run(sh("echo hi; echo bad >&2; exit 3")).await;
388 assert_eq!(out.trim(), "hi");
389 assert_eq!(err.trim(), "bad");
390 assert_eq!(status.code, Some(3));
391 assert!(!status.success);
392 }
393
394 #[tokio::test]
395 async fn the_stream_is_taken_once() {
396 let mut h = LocalProcess::default()
397 .spawn(sh("true"), CancellationToken::new())
398 .await
399 .unwrap();
400 assert!(h.output().is_some());
401 assert!(h.output().is_none(), "the stream owns the pipes");
402 let _ = h.wait().await;
403 }
404
405 #[tokio::test]
406 async fn stdin_reaches_the_child_and_then_ends() {
407 let mut spec = sh("cat");
408 spec.stdin = Some(b"fed in".to_vec());
409 let (out, _, status) = run(spec).await;
410 assert_eq!(out, "fed in");
411 assert!(
412 status.success,
413 "a child reading to EOF has to see the pipe close"
414 );
415 }
416
417 #[tokio::test]
420 async fn output_arrives_before_the_process_exits() {
421 let mut h = LocalProcess::default()
422 .spawn(
423 sh("echo first; sleep 5; echo never"),
424 CancellationToken::new(),
425 )
426 .await
427 .unwrap();
428 let mut out = h.output().unwrap();
429 let first = tokio::time::timeout(std::time::Duration::from_secs(2), out.next())
430 .await
431 .expect("the first chunk must not wait for the exit")
432 .unwrap()
433 .unwrap();
434 assert_eq!(String::from_utf8_lossy(&first.bytes).trim(), "first");
435 h.kill().await;
436 }
437
438 #[tokio::test]
439 async fn a_minimal_spec_starts_from_what_a_shell_needs_and_its_own_variables() {
440 if std::env::var_os("CARGO_MANIFEST_DIR").is_none() {
441 return;
442 }
443 let mut spec = sh(
444 "printenv CARGO_MANIFEST_DIR; printenv PATH >/dev/null && echo has-path; printenv OWN",
445 );
446 spec.env_scope = base::interface::exec::EnvScope::Minimal;
447 spec.env.push(("OWN".into(), "mine".into()));
448 let (out, _, _) = run(spec).await;
449 assert!(!out.contains(env!("CARGO_MANIFEST_DIR")), "{out}");
450 assert!(out.contains("has-path"), "{out}");
451 assert!(out.contains("mine"), "{out}");
452 }
453
454 #[tokio::test]
455 async fn the_environment_policy_reaches_the_child() {
456 if std::env::var_os("CARGO_MANIFEST_DIR").is_none() {
459 return;
460 }
461 let probe = || sh("printenv CARGO_MANIFEST_DIR; printenv PATH >/dev/null && echo has-path");
462 let (inherited, _, _) = run(probe()).await;
463 assert!(inherited.contains(env!("CARGO_MANIFEST_DIR")));
464
465 let allowlist = SubprocessEnv {
466 mode: base::interface::exec::SubprocessEnvMode::Allowlist,
467 allow: vec![],
468 };
469 let (out, _, _) = run_with(LocalProcess::new(allowlist), probe()).await;
470 assert_eq!(out.trim(), "has-path");
471 }
472
473 #[cfg(unix)]
474 async fn gone_within(pid: libc::pid_t, limit: std::time::Duration) -> bool {
475 let deadline = std::time::Instant::now() + limit;
476 while std::time::Instant::now() < deadline {
477 if unsafe { libc::kill(pid, 0) } != 0 {
479 return true;
480 }
481 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
482 }
483 false
484 }
485
486 #[cfg(unix)]
487 async fn first_line(out: &mut BoxStream<'static, Result<OutputChunk, ExecError>>) -> String {
488 let chunk = tokio::time::timeout(std::time::Duration::from_secs(5), out.next())
489 .await
490 .expect("the background pid is printed straight away")
491 .unwrap()
492 .unwrap();
493 String::from_utf8_lossy(&chunk.bytes).trim().to_string()
494 }
495
496 #[cfg(unix)]
497 #[tokio::test]
498 async fn kill_takes_the_background_children_with_it() {
499 let mut h = LocalProcess::default()
500 .spawn(sh("sleep 300 & echo $!; wait"), CancellationToken::new())
501 .await
502 .unwrap();
503 let mut out = h.output().unwrap();
504 let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
505 h.kill().await;
506 assert!(
507 gone_within(pid, std::time::Duration::from_secs(3)).await,
508 "the background sleep outlived the kill"
509 );
510 }
511
512 #[cfg(unix)]
513 #[tokio::test]
514 async fn kill_after_exit_still_reaches_what_was_left_running() {
515 let mut h = LocalProcess::default()
516 .spawn(sh("sleep 300 & echo $!"), CancellationToken::new())
517 .await
518 .unwrap();
519 let mut out = h.output().unwrap();
520 let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
521 assert!(h.wait().await.unwrap().success);
522 h.kill().await;
523 assert!(
524 gone_within(pid, std::time::Duration::from_secs(3)).await,
525 "the orphaned sleep survived a kill issued after its parent exited"
526 );
527 }
528
529 #[cfg(unix)]
530 #[tokio::test]
531 async fn the_ledger_reaps_what_a_finished_command_left_running() {
532 let ledger = GroupLedger::new();
533 let process = LocalProcess::with_ledger(SubprocessEnv::default(), ledger.clone());
534 let mut h = process
535 .spawn(
536 sh("sleep 300 >/dev/null 2>&1 & echo $!"),
537 CancellationToken::new(),
538 )
539 .await
540 .unwrap();
541 let mut out = h.output().unwrap();
542 let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
543 assert!(h.wait().await.unwrap().success);
544 drop(out);
545 drop(h);
546 assert!(
547 !gone_within(pid, std::time::Duration::from_millis(200)).await,
548 "dropping a finished handle leaves the background sleep alone"
549 );
550 assert_eq!(ledger.groups().len(), 1, "the group is still on record");
551
552 ledger.reap(std::time::Duration::from_millis(500)).await;
553 let reaped = gone_within(pid, std::time::Duration::from_secs(3)).await;
554 if !reaped {
555 unsafe { libc::kill(pid, libc::SIGKILL) };
556 }
557 assert!(reaped, "reap stops the background sleep");
558 assert!(ledger.groups().is_empty());
559 }
560
561 #[cfg(unix)]
562 #[tokio::test]
563 async fn an_emptied_group_drops_off_the_ledger() {
564 let ledger = GroupLedger::new();
565 let process = LocalProcess::with_ledger(SubprocessEnv::default(), ledger.clone());
566 let (_, _, status) = run_with(process, sh("true")).await;
567 assert!(status.success);
568 assert!(ledger.groups().is_empty(), "{:?}", ledger.groups());
569 }
570
571 #[cfg(unix)]
572 #[tokio::test]
573 async fn cancelling_the_spawn_token_stops_the_whole_group() {
574 let cancel = CancellationToken::new();
575 let mut h = LocalProcess::default()
576 .spawn(sh("sleep 300 & echo $!; wait"), cancel.clone())
577 .await
578 .unwrap();
579 let mut out = h.output().unwrap();
580 let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
581 cancel.cancel();
582 let stopped = gone_within(pid, std::time::Duration::from_secs(3)).await;
583 if !stopped {
584 unsafe { libc::kill(pid, libc::SIGKILL) };
585 }
586 assert!(stopped, "the background sleep outlived the cancellation");
587 assert!(!h.wait().await.unwrap().success);
588 }
589
590 #[cfg(unix)]
591 #[tokio::test]
592 async fn dropping_a_running_handle_stops_the_whole_group() {
593 let mut h = LocalProcess::default()
594 .spawn(sh("sleep 300 & echo $!; wait"), CancellationToken::new())
595 .await
596 .unwrap();
597 let mut out = h.output().unwrap();
598 let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
599 drop(h);
600 assert!(gone_within(pid, std::time::Duration::from_secs(3)).await);
601 }
602
603 #[cfg(unix)]
606 #[tokio::test]
607 async fn a_finished_group_is_no_longer_watched() {
608 let mut h = LocalProcess::default()
609 .spawn(sh("true"), CancellationToken::new())
610 .await
611 .unwrap();
612 let mut out = h.output().unwrap();
613 while out.next().await.is_some() {}
614 assert!(h.wait().await.unwrap().success);
615 for _ in 0..10 {
616 tokio::task::yield_now().await;
617 }
618 let alive = tokio::runtime::Handle::current()
619 .metrics()
620 .num_alive_tasks();
621 assert_eq!(alive, 0, "the cancellation watcher outlived the group");
622 }
623
624 #[cfg(unix)]
625 #[tokio::test]
626 async fn a_group_that_outlives_its_leader_is_still_stopped_on_cancel() {
627 let cancel = CancellationToken::new();
628 let mut h = LocalProcess::default()
629 .spawn(sh("sleep 300 & echo $!"), cancel.clone())
630 .await
631 .unwrap();
632 let mut out = h.output().unwrap();
633 let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
634 assert!(h.wait().await.unwrap().success);
635 cancel.cancel();
636 let stopped = gone_within(pid, std::time::Duration::from_secs(3)).await;
637 if !stopped {
638 unsafe { libc::kill(pid, libc::SIGKILL) };
639 }
640 assert!(stopped, "the background sleep outlived the cancellation");
641 }
642}