use std::fmt;
use std::fs::File;
use std::io;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::thread::{Builder, Scope as Threads, ScopedJoinHandle};
use std::time::{Duration, Instant};
use zeroize::Zeroizing;
use crate::notice::Notice;
use crate::{Cancel, Escalation, Group, Outcome, Scope, Signal, Status, StopReason, sys};
mod finished;
mod output;
mod pipes;
mod spawn;
#[cfg(test)]
mod tests;
pub use self::finished::{ChildFinished, RunError};
pub use self::output::{Capture, Captured, LineCapture, LongLine, OverLimit, WholeCapture};
use self::output::{Keeper, OutputCopy};
use self::pipes::{Ends, Kept};
use self::spawn::AroundSpawn;
pub use self::spawn::{Spawn, Spawned};
pub const DRAIN_GRACE: Duration = Duration::from_secs(1);
pub const REAP_GRACE: Duration = Duration::from_secs(1);
#[derive(Clone, Default)]
#[non_exhaustive]
pub enum Input {
#[default]
Null,
Bytes(Zeroizing<Vec<u8>>),
Inherit,
File(Arc<File>),
}
impl fmt::Debug for Input {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Null => f.write_str("Null"),
Self::Bytes(bytes) => f
.debug_tuple("Bytes")
.field(&format_args!("{} bytes", bytes.len()))
.finish(),
Self::Inherit => f.write_str("Inherit"),
Self::File(file) => f.debug_tuple("File").field(file).finish(),
}
}
}
#[derive(Clone, Debug, Default)]
pub struct RunOptions {
stdin: Input,
stdout: Capture,
stderr: Capture,
deadline: Option<Instant>,
cancel: Option<Cancel>,
escalation: Escalation,
scope: Scope,
around_spawn: Option<AroundSpawn>,
stdout_copy: Option<OutputCopy>,
stderr_copy: Option<OutputCopy>,
report_survivors: bool,
}
impl RunOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn stdin(mut self, input: Input) -> Self {
self.stdin = input;
self
}
#[must_use]
pub fn stdout(mut self, capture: impl Into<Capture>) -> Self {
self.stdout = capture.into();
self
}
#[must_use]
pub fn stderr(mut self, capture: impl Into<Capture>) -> Self {
self.stderr = capture.into();
self
}
#[must_use]
pub const fn deadline(mut self, deadline: Instant) -> Self {
self.deadline = Some(deadline);
self
}
#[must_use]
pub fn cancel(mut self, cancel: &Cancel) -> Self {
self.cancel = Some(cancel.clone());
self
}
#[must_use]
pub fn escalation(mut self, escalation: Escalation) -> Self {
self.escalation = escalation;
self
}
#[must_use]
pub const fn scope(mut self, scope: Scope) -> Self {
self.scope = scope;
self
}
#[must_use]
pub fn around_spawn(
mut self,
hook: impl Fn(Spawn) -> io::Result<Spawned> + Send + Sync + 'static,
) -> Self {
self.around_spawn = Some(AroundSpawn::new(hook));
self
}
#[must_use]
pub fn stdout_copy(mut self, copy: impl Fn(&[u8]) + Send + Sync + 'static) -> Self {
self.stdout_copy = Some(OutputCopy::new(copy));
self
}
#[must_use]
pub fn stderr_copy(mut self, copy: impl Fn(&[u8]) + Send + Sync + 'static) -> Self {
self.stderr_copy = Some(OutputCopy::new(copy));
self
}
#[must_use]
pub const fn report_survivors(mut self) -> Self {
self.report_survivors = true;
self
}
fn stopping(&self) {
self.stdout.stopping();
self.stderr.stopping();
}
fn drain_until(&self, deadline: Instant) {
self.stdout.drain_until(deadline);
self.stderr.drain_until(deadline);
}
}
pub fn run(mut command: Command, options: &RunOptions) -> Result<ChildFinished, RunError> {
let _end = EndLines(options);
if options.cancel.as_ref().is_some_and(Cancel::is_cancelled) {
return Ok(ChildFinished {
outcome: Outcome::Stopped(StopReason::Cancelled),
status: None,
stdout: Captured::default(),
stderr: Captured::default(),
first_stdout: None,
survivors: false,
});
}
let input = match &options.stdin {
Input::Null => Stdio::null(),
Input::Inherit => Stdio::inherit(),
Input::Bytes(_) => Stdio::piped(),
Input::File(file) => Stdio::from(file.try_clone().map_err(RunError::Start)?),
};
command
.stdin(input)
.stdout(output_stdio(&options.stdout, options.stdout_copy.as_ref()))
.stderr(output_stdio(&options.stderr, options.stderr_copy.as_ref()));
let spawned = spawn::start(command, options.scope, options.around_spawn.as_ref())
.map_err(RunError::Start)?;
let (mut group, started) = spawned.into_parts();
let notice = Arc::new(Notice::default());
if let Some(cancel) = &options.cancel {
cancel.watch(¬ice);
}
let ends = Ends::default();
let followed = std::thread::scope(|threads| {
let unwind = Unwind {
group: &mut group,
ends: &ends,
options,
};
follow(threads, &mut *unwind.group, ¬ice, &ends, options)
});
let (outcome, status, stdout, stderr, survivors) = followed.map_err(RunError::Run)?;
Ok(ChildFinished {
outcome,
status: Some(status),
first_stdout: stdout.first.map(|first| first - started),
survivors,
stdout: stdout.captured,
stderr: stderr.captured,
})
}
fn output_stdio(capture: &Capture, copy: Option<&OutputCopy>) -> Stdio {
if copy.is_some() && !capture.inherits() {
Stdio::piped()
} else {
capture.stdio()
}
}
struct EndLines<'run>(&'run RunOptions);
impl Drop for EndLines<'_> {
fn drop(&mut self) {
self.0.stdout.end();
self.0.stderr.end();
}
}
struct Unwind<'a> {
group: &'a mut Group,
ends: &'a Ends,
options: &'a RunOptions,
}
impl Drop for Unwind<'_> {
fn drop(&mut self) {
let _ = self.group.signal(Signal::Kill);
self.ends.set(Instant::now());
self.options.stopping();
}
}
struct Started<'scope> {
waiter: ScopedJoinHandle<'scope, io::Result<()>>,
stdout: Option<ScopedJoinHandle<'scope, io::Result<Kept>>>,
stderr: Option<ScopedJoinHandle<'scope, io::Result<Kept>>>,
stdin: Option<ScopedJoinHandle<'scope, ()>>,
}
fn follow<'scope>(
threads: &'scope Threads<'scope, '_>,
group: &mut Group,
notice: &'scope Notice,
ends: &'scope Ends,
options: &'scope RunOptions,
) -> io::Result<(Outcome, Status, Kept, Kept, bool)> {
let pipes = (group.take_stdin(), group.take_stdout(), group.take_stderr());
let exit = group.waiter();
let waiter = match Builder::new().spawn_scoped(threads, move || {
let waited = exit.wait();
notice.set(|flags| flags.exited = true);
waited
}) {
Ok(waiter) => waiter,
Err(error) => {
let _ = group.signal(Signal::Kill);
let _ = group.reap();
return Err(error);
}
};
let mut started = Started {
waiter,
stdout: None,
stderr: None,
stdin: None,
};
let mut failure = start_pipes(threads, &mut started, pipes, notice, ends, options).err();
let stopped = if failure.is_some() {
stop(group, notice, &Escalation::default(), options);
None
} else {
control(group, notice, options)
};
let survivors =
options.report_survivors && failure.is_none() && stopped.is_none() && group.others_alive();
let status = group.reap();
let reaped = Instant::now();
let after = |grace: Duration| reaped.checked_add(grace).unwrap_or(reaped);
ends.set(after(DRAIN_GRACE));
options.drain_until(after(DRAIN_GRACE / 2));
let exited = joined(started.waiter.join());
let stdout = started.stdout.map(|reader| joined(reader.join()));
let stderr = started.stderr.map(|reader| joined(reader.join()));
if let Some(writer) = started.stdin {
let _ = writer.join();
}
if let Some(failure) = failure.take() {
return Err(failure);
}
exited?;
let status = sys::status_of(status?);
let exit = stopped.unwrap_or(Outcome::Ended(status));
let unread = || Kept {
captured: Captured::default(),
first: None,
};
Ok((
exit,
status,
stdout.transpose()?.unwrap_or_else(unread),
stderr.transpose()?.unwrap_or_else(unread),
survivors,
))
}
fn start_pipes<'scope>(
threads: &'scope Threads<'scope, '_>,
started: &mut Started<'scope>,
(stdin, stdout, stderr): (
Option<std::process::ChildStdin>,
Option<std::process::ChildStdout>,
Option<std::process::ChildStderr>,
),
notice: &'scope Notice,
ends: &'scope Ends,
options: &'scope RunOptions,
) -> io::Result<()> {
let over = || notice.set(|flags| flags.over_limit = true);
if let Some(stdout) = stdout {
let keeper = Keeper::new(&options.stdout);
let copy = options.stdout_copy.as_ref();
started.stdout = Some(Builder::new().spawn_scoped(threads, move || {
pipes::read(stdout, ends, keeper, copy, over)
})?);
}
if let Some(stderr) = stderr {
let keeper = Keeper::new(&options.stderr);
let copy = options.stderr_copy.as_ref();
started.stderr = Some(Builder::new().spawn_scoped(threads, move || {
pipes::read(stderr, ends, keeper, copy, over)
})?);
}
if let (Some(stdin), Input::Bytes(bytes)) = (stdin, &options.stdin) {
started.stdin =
Some(Builder::new().spawn_scoped(threads, move || pipes::write(stdin, bytes, ends))?);
}
Ok(())
}
fn control(group: &Group, notice: &Notice, options: &RunOptions) -> Option<Outcome> {
let flags = notice.wait(options.deadline, |flags| {
flags.exited || flags.cancelled || flags.over_limit
});
let exit = if flags.exited {
return None;
} else if flags.cancelled {
Outcome::Stopped(StopReason::Cancelled)
} else if flags.over_limit {
Outcome::Stopped(StopReason::OverLimit)
} else if group.has_exited().unwrap_or(false) {
notice.wait(None, |flags| flags.exited);
return None;
} else {
Outcome::TimedOut
};
stop(group, notice, &options.escalation, options);
Some(exit)
}
fn stop(group: &Group, notice: &Notice, escalation: &Escalation, options: &RunOptions) {
options.stopping();
if sys::GRACEFUL {
for (signal, grace) in escalation.steps() {
let _ = group.signal(signal);
if notice
.wait(Instant::now().checked_add(grace), |flags| flags.exited)
.exited
{
return;
}
}
}
let _ = group.signal(Signal::Kill);
notice.wait(None, |flags| flags.exited);
}
fn joined<T>(result: std::thread::Result<io::Result<T>>) -> io::Result<T> {
result.unwrap_or_else(|_| Err(io::Error::other("a thread of the run stopped")))
}