1use std::fmt;
5use std::io;
6use std::process::{Command, Stdio};
7use std::sync::Arc;
8use std::thread::{Builder, Scope as Threads, ScopedJoinHandle};
9use std::time::{Duration, Instant};
10
11use crate::notice::Notice;
12use crate::{Cancel, Escalation, Exit, Group, Scope, Signal, Status, Stop, sys};
13
14mod output;
15mod pipes;
16
17#[cfg(test)]
18mod tests;
19
20use self::output::Keeper;
21pub use self::output::{Capture, Captured, OverLimit};
22use self::pipes::{Ends, Kept};
23
24pub const DRAIN_GRACE: Duration = Duration::from_secs(1);
28
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum Input {
33 #[default]
35 Null,
36 Bytes(Vec<u8>),
39 Inherit,
43}
44
45#[derive(Clone, Debug, Default)]
55pub struct Run {
56 stdin: Input,
57 stdout: Capture,
58 stderr: Capture,
59 deadline: Option<Instant>,
60 cancel: Option<Cancel>,
61 escalation: Escalation,
62 scope: Scope,
63}
64
65impl Run {
66 #[must_use]
68 pub fn new() -> Self {
69 Self::default()
70 }
71
72 #[must_use]
74 pub fn stdin(mut self, input: Input) -> Self {
75 self.stdin = input;
76 self
77 }
78
79 #[must_use]
81 pub fn stdout(mut self, capture: Capture) -> Self {
82 self.stdout = capture;
83 self
84 }
85
86 #[must_use]
88 pub fn stderr(mut self, capture: Capture) -> Self {
89 self.stderr = capture;
90 self
91 }
92
93 #[must_use]
96 pub const fn deadline(mut self, deadline: Instant) -> Self {
97 self.deadline = Some(deadline);
98 self
99 }
100
101 #[must_use]
103 pub fn cancel(mut self, cancel: &Cancel) -> Self {
104 self.cancel = Some(cancel.clone());
105 self
106 }
107
108 #[must_use]
110 pub fn escalation(mut self, escalation: Escalation) -> Self {
111 self.escalation = escalation;
112 self
113 }
114
115 #[must_use]
117 pub const fn scope(mut self, scope: Scope) -> Self {
118 self.scope = scope;
119 self
120 }
121
122 fn stopping(&self) {
125 self.stdout.stopping();
126 self.stderr.stopping();
127 }
128}
129
130#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct Finished {
133 exit: Exit,
134 status: Option<Status>,
135 stdout: Captured,
136 stderr: Captured,
137 first_stdout: Option<Duration>,
138}
139
140impl Finished {
141 #[must_use]
143 pub const fn exit(&self) -> Exit {
144 self.exit
145 }
146
147 #[must_use]
156 pub const fn status(&self) -> Option<Status> {
157 self.status
158 }
159
160 #[must_use]
162 pub const fn stdout(&self) -> &Captured {
163 &self.stdout
164 }
165
166 #[must_use]
168 pub const fn stderr(&self) -> &Captured {
169 &self.stderr
170 }
171
172 #[must_use]
174 pub fn into_output(self) -> (Captured, Captured) {
175 (self.stdout, self.stderr)
176 }
177
178 #[must_use]
182 pub const fn first_stdout(&self) -> Option<Duration> {
183 self.first_stdout
184 }
185}
186
187#[derive(Debug)]
189#[non_exhaustive]
190pub enum RunError {
191 Start(io::Error),
193 Run(io::Error),
196}
197
198impl fmt::Display for RunError {
199 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200 f.write_str(match self {
201 Self::Start(_) => "cannot start the program",
202 Self::Run(_) => "cannot follow the program to its end",
203 })
204 }
205}
206
207impl std::error::Error for RunError {
208 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
209 match self {
210 Self::Start(error) | Self::Run(error) => Some(error),
211 }
212 }
213}
214
215pub fn run(mut command: Command, run: &Run) -> Result<Finished, RunError> {
246 let _end = EndLines(run);
247 if run.cancel.as_ref().is_some_and(Cancel::is_cancelled) {
248 return Ok(Finished {
249 exit: Exit::Stopped(Stop::Cancelled),
250 status: None,
251 stdout: Captured::default(),
252 stderr: Captured::default(),
253 first_stdout: None,
254 });
255 }
256 let input = match &run.stdin {
257 Input::Null => Stdio::null(),
258 Input::Inherit => Stdio::inherit(),
259 Input::Bytes(_) => Stdio::piped(),
260 };
261 command
262 .stdin(input)
263 .stdout(run.stdout.stdio())
264 .stderr(run.stderr.stdio());
265 let started = Instant::now();
266 let mut group = Group::start(command, run.scope).map_err(RunError::Start)?;
267 let notice = Arc::new(Notice::default());
268 if let Some(cancel) = &run.cancel {
269 cancel.watch(¬ice);
270 }
271 let ends = Ends::default();
272 let followed = std::thread::scope(|threads| {
273 let unwind = Unwind {
274 group: &mut group,
275 ends: &ends,
276 run,
277 };
278 follow(threads, &mut *unwind.group, ¬ice, &ends, run)
279 });
280 let (exit, status, stdout, stderr) = followed.map_err(RunError::Run)?;
281 Ok(Finished {
282 exit,
283 status: Some(status),
284 first_stdout: stdout.first.map(|first| first - started),
285 stdout: stdout.captured,
286 stderr: stderr.captured,
287 })
288}
289
290struct EndLines<'run>(&'run Run);
292
293impl Drop for EndLines<'_> {
294 fn drop(&mut self) {
295 self.0.stdout.end();
296 self.0.stderr.end();
297 }
298}
299
300struct Unwind<'a> {
307 group: &'a mut Group,
308 ends: &'a Ends,
309 run: &'a Run,
310}
311
312impl Drop for Unwind<'_> {
313 fn drop(&mut self) {
314 let _ = self.group.signal(Signal::Kill);
317 self.ends.set(Instant::now());
318 self.run.stopping();
319 }
320}
321
322struct Started<'scope> {
324 waiter: ScopedJoinHandle<'scope, io::Result<()>>,
325 stdout: Option<ScopedJoinHandle<'scope, io::Result<Kept>>>,
326 stderr: Option<ScopedJoinHandle<'scope, io::Result<Kept>>>,
327 stdin: Option<ScopedJoinHandle<'scope, ()>>,
328}
329
330fn follow<'scope>(
333 threads: &'scope Threads<'scope, '_>,
334 group: &mut Group,
335 notice: &'scope Notice,
336 ends: &'scope Ends,
337 run: &'scope Run,
338) -> io::Result<(Exit, Status, Kept, Kept)> {
339 let pipes = (group.take_stdin(), group.take_stdout(), group.take_stderr());
340 let exit = group.waiter();
341 let waiter = match Builder::new().spawn_scoped(threads, move || {
342 let waited = exit.wait();
343 notice.set(|flags| flags.exited = true);
344 waited
345 }) {
346 Ok(waiter) => waiter,
347 Err(error) => {
348 let _ = group.signal(Signal::Kill);
349 let _ = group.reap();
350 return Err(error);
351 }
352 };
353 let mut started = Started {
354 waiter,
355 stdout: None,
356 stderr: None,
357 stdin: None,
358 };
359 let mut failure = start_pipes(threads, &mut started, pipes, notice, ends, run).err();
360 let stopped = if failure.is_some() {
361 stop(group, notice, &Escalation::default(), run);
362 None
363 } else {
364 control(group, notice, run)
365 };
366 let status = group.reap();
367 ends.set(
368 Instant::now()
369 .checked_add(DRAIN_GRACE)
370 .unwrap_or_else(Instant::now),
371 );
372 let exited = joined(started.waiter.join());
373 let stdout = started.stdout.map(|reader| joined(reader.join()));
374 let stderr = started.stderr.map(|reader| joined(reader.join()));
375 if let Some(writer) = started.stdin {
376 let _ = writer.join();
377 }
378 if let Some(failure) = failure.take() {
379 return Err(failure);
380 }
381 exited?;
382 let status = sys::status_of(status?);
383 let exit = stopped.unwrap_or_else(|| status.exit());
384 let unread = || Kept {
385 captured: Captured::default(),
386 first: None,
387 };
388 Ok((
389 exit,
390 status,
391 stdout.transpose()?.unwrap_or_else(unread),
392 stderr.transpose()?.unwrap_or_else(unread),
393 ))
394}
395
396fn start_pipes<'scope>(
399 threads: &'scope Threads<'scope, '_>,
400 started: &mut Started<'scope>,
401 (stdin, stdout, stderr): (
402 Option<std::process::ChildStdin>,
403 Option<std::process::ChildStdout>,
404 Option<std::process::ChildStderr>,
405 ),
406 notice: &'scope Notice,
407 ends: &'scope Ends,
408 run: &'scope Run,
409) -> io::Result<()> {
410 let over = || notice.set(|flags| flags.over_limit = true);
411 if let Some(stdout) = stdout {
412 let keeper = Keeper::new(&run.stdout);
413 started.stdout = Some(
414 Builder::new()
415 .spawn_scoped(threads, move || pipes::read(stdout, ends, keeper, over))?,
416 );
417 }
418 if let Some(stderr) = stderr {
419 let keeper = Keeper::new(&run.stderr);
420 started.stderr = Some(
421 Builder::new()
422 .spawn_scoped(threads, move || pipes::read(stderr, ends, keeper, over))?,
423 );
424 }
425 if let (Some(stdin), Input::Bytes(bytes)) = (stdin, &run.stdin) {
426 started.stdin =
427 Some(Builder::new().spawn_scoped(threads, move || pipes::write(stdin, bytes, ends))?);
428 }
429 Ok(())
430}
431
432fn control(group: &Group, notice: &Notice, run: &Run) -> Option<Exit> {
436 let flags = notice.wait(run.deadline, |flags| {
437 flags.exited || flags.cancelled || flags.over_limit
438 });
439 let exit = if flags.exited {
440 return None;
441 } else if flags.cancelled {
442 Exit::Stopped(Stop::Cancelled)
443 } else if flags.over_limit {
444 Exit::Stopped(Stop::OverLimit)
445 } else if group.has_exited().unwrap_or(false) {
446 notice.wait(None, |flags| flags.exited);
449 return None;
450 } else {
451 Exit::TimedOut
452 };
453 stop(group, notice, &run.escalation, run);
454 Some(exit)
455}
456
457fn stop(group: &Group, notice: &Notice, escalation: &Escalation, run: &Run) {
471 run.stopping();
472 if sys::GRACEFUL {
473 for (signal, grace) in escalation.steps() {
474 let _ = group.signal(signal);
475 if notice
476 .wait(Instant::now().checked_add(grace), |flags| flags.exited)
477 .exited
478 {
479 return;
480 }
481 }
482 }
483 let _ = group.signal(Signal::Kill);
484 notice.wait(None, |flags| flags.exited);
485}
486
487fn joined<T>(result: std::thread::Result<io::Result<T>>) -> io::Result<T> {
490 result.unwrap_or_else(|_| Err(io::Error::other("a thread of the run stopped")))
491}