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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum OutputStream {
14 Stdout,
16 Stderr,
18}
19
20pub type OutputSink<'sink> = dyn Fn(OutputStream, &[u8]) + Send + Sync + 'sink;
26
27#[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 #[must_use]
38 pub fn stdout(&self) -> &[u8] {
39 &self.stdout
40 }
41
42 #[must_use]
44 pub fn stderr(&self) -> &[u8] {
45 &self.stderr
46 }
47
48 #[must_use]
50 pub fn status_code(&self) -> Option<i32> {
51 self.status_code
52 }
53
54 #[must_use]
56 pub fn succeeded(&self) -> bool {
57 self.status_code == Some(0)
58 }
59}
60
61#[derive(Clone, Debug)]
66pub struct ProcessRunner {
67 working_directory: PathBuf,
68}
69
70impl ProcessRunner {
71 #[must_use]
73 pub fn new(working_directory: impl Into<PathBuf>) -> Self {
74 Self {
75 working_directory: working_directory.into(),
76 }
77 }
78
79 pub fn here() -> io::Result<Self> {
81 Ok(Self::new(std::env::current_dir()?))
82 }
83
84 pub fn run(&self, request: ExecutionRequest) -> io::Result<ProcessOutput> {
86 self.run_streaming(request, None, &|_, _| {})
87 }
88
89 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 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
119fn 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
159fn 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}