Skip to main content

beez_process/
runner.rs

1use std::io::{self, BufRead, BufReader, Read};
2use std::path::PathBuf;
3use std::process::{Command, Stdio};
4use std::sync::Mutex;
5
6use beez_policy::SandboxPolicy;
7use beez_sandbox::SandboxedCommand;
8
9use crate::execution::ExecutionRequest;
10
11/// One of a child process's output streams.
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum OutputStream {
14    /// Standard output.
15    Stdout,
16    /// Standard error.
17    Stderr,
18}
19
20/// Receives every output line while a process runs.
21///
22/// The slice holds the line as the child wrote it, with the trailing newline
23/// when the child wrote one. The sink runs on the reader threads, so it must
24/// work when two threads call it at the same time.
25pub type OutputSink<'sink> = dyn Fn(OutputStream, &[u8]) + Send + Sync + 'sink;
26
27/// Captured child-process streams and exit status.
28#[derive(Clone, Debug, Eq, PartialEq)]
29pub struct ProcessOutput {
30    stdout: Vec<u8>,
31    stderr: Vec<u8>,
32    status_code: Option<i32>,
33}
34
35impl ProcessOutput {
36    /// Captured standard output.
37    #[must_use]
38    pub fn stdout(&self) -> &[u8] {
39        &self.stdout
40    }
41
42    /// Captured standard error.
43    #[must_use]
44    pub fn stderr(&self) -> &[u8] {
45        &self.stderr
46    }
47
48    /// Returns `None` after signal termination.
49    #[must_use]
50    pub fn status_code(&self) -> Option<i32> {
51        self.status_code
52    }
53
54    /// True only when the process exits with status zero.
55    #[must_use]
56    pub fn succeeded(&self) -> bool {
57        self.status_code == Some(0)
58    }
59}
60
61/// Runs Beez process requests in one working directory.
62///
63/// The directory is explicit, because one process can run tasks of several
64/// workflows at the same time, and a process has only one current directory.
65#[derive(Clone, Debug)]
66pub struct ProcessRunner {
67    working_directory: PathBuf,
68}
69
70impl ProcessRunner {
71    /// Runs requests in `working_directory`.
72    #[must_use]
73    pub fn new(working_directory: impl Into<PathBuf>) -> Self {
74        Self {
75            working_directory: working_directory.into(),
76        }
77    }
78
79    /// Runs requests in this process's own working directory.
80    pub fn here() -> io::Result<Self> {
81        Ok(Self::new(std::env::current_dir()?))
82    }
83
84    /// Starts a request and captures its output.
85    pub fn run(&self, request: ExecutionRequest) -> io::Result<ProcessOutput> {
86        self.run_streaming(request, None, &|_, _| {})
87    }
88
89    /// Runs a request and hands every output line to `sink` while it runs.
90    ///
91    /// The returned output holds the same bytes the sink received.
92    pub fn run_streaming(
93        &self,
94        request: ExecutionRequest,
95        sandbox: Option<&SandboxPolicy>,
96        sink: &OutputSink<'_>,
97    ) -> io::Result<ProcessOutput> {
98        let harness = request.harness();
99        let (program, arguments) = request.into_parts();
100
101        if let Some(policy) = sandbox {
102            // The sandbox must outlive the child, because it owns the proxy.
103            let mut sandboxed = SandboxedCommand::new(
104                policy,
105                harness,
106                &program,
107                &arguments,
108                &self.working_directory,
109            )?;
110            relay(sandboxed.command_mut(), sink)
111        } else {
112            let mut command = Command::new(program);
113            command.args(arguments).current_dir(&self.working_directory);
114            relay(&mut command, sink)
115        }
116    }
117}
118
119/// Runs `command` with piped output, forwarding and collecting every line.
120fn relay(command: &mut Command, sink: &OutputSink<'_>) -> io::Result<ProcessOutput> {
121    command.stdout(Stdio::piped()).stderr(Stdio::piped());
122    let mut child = command.spawn()?;
123    let stdout = child.stdout.take();
124    let stderr = child.stderr.take();
125    let collected = Mutex::new((Vec::new(), Vec::new()));
126
127    let collect = |stream: OutputStream, line: &[u8]| {
128        if let Ok(mut collected) = collected.lock() {
129            match stream {
130                OutputStream::Stdout => collected.0.extend_from_slice(line),
131                OutputStream::Stderr => collected.1.extend_from_slice(line),
132            }
133        }
134        sink(stream, line);
135    };
136    let collect: &OutputSink<'_> = &collect;
137
138    std::thread::scope(|scope| {
139        if let Some(stdout) = stdout {
140            scope.spawn(move || forward(stdout, OutputStream::Stdout, collect));
141        }
142        if let Some(stderr) = stderr {
143            scope.spawn(move || forward(stderr, OutputStream::Stderr, collect));
144        }
145    });
146
147    let status = child.wait()?;
148    let (stdout, stderr) = collected
149        .into_inner()
150        .map_err(|_| io::Error::other("output collection lock is poisoned"))?;
151
152    Ok(ProcessOutput {
153        stdout,
154        stderr,
155        status_code: status.code(),
156    })
157}
158
159/// Reads whole lines until the stream ends.
160fn forward(reader: impl Read, stream: OutputStream, sink: &OutputSink<'_>) {
161    let mut reader = BufReader::new(reader);
162    let mut line = Vec::new();
163    loop {
164        line.clear();
165        match reader.read_until(b'\n', &mut line) {
166            Ok(0) | Err(_) => return,
167            Ok(_) => sink(stream, &line),
168        }
169    }
170}