chainguard_sandbox/workspaces/
exec.rs1use std::time::Duration;
4
5use super::pb::{ExecRequest, ExecResponse, exec_response};
6use super::{Client, DEFAULT_WORK_DIR, MAX_EXEC_STDIN};
7use crate::{Error, Result};
8
9crate::opaque_debug!(ExecOptions<'_>);
10
11pub type OutputSink<'a> = &'a mut (dyn FnMut(&[u8]) + Send);
13
14#[derive(Default)]
16pub struct ExecOptions<'a> {
17 pub dir: String,
21 pub no_dir: bool,
22 pub stdin: Vec<u8>,
24 pub timeout: Option<Duration>,
26 pub stdout: Option<OutputSink<'a>>,
28 pub stderr: Option<OutputSink<'a>>,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub struct ExecResult {
34 pub exit_code: i32,
35 pub timed_out: bool,
36}
37
38pub fn is_guest_held(e: &Error) -> bool {
43 match e {
44 Error::Rpc(s) => match s.code() {
45 tonic::Code::Aborted => s.message().contains("held"),
46 tonic::Code::FailedPrecondition => controller_busy(s.message()),
47 _ => false,
48 },
49 _ => false,
50 }
51}
52
53fn controller_busy(msg: &str) -> bool {
54 msg.contains("held by another controller") || msg.contains("Channel already in use")
55}
56
57fn interrupted(e: Error, started: bool) -> Error {
62 if matches!(e, Error::OutcomeUnknown { .. }) {
63 return e;
64 }
65 let transport = matches!(
66 e.grpc_code(),
67 Some(
68 tonic::Code::Unavailable
69 | tonic::Code::Internal
70 | tonic::Code::Unknown
71 | tonic::Code::DataLoss
72 | tonic::Code::DeadlineExceeded
73 | tonic::Code::Cancelled
74 )
75 );
76 if started || transport {
77 Error::OutcomeUnknown {
78 cause: Some(Box::new(e)),
79 result: None,
80 }
81 } else {
82 e
83 }
84}
85
86impl Client {
87 pub async fn exec(
93 &self,
94 name: &str,
95 argv: &[String],
96 o: ExecOptions<'_>,
97 ) -> Result<ExecResult> {
98 if argv.is_empty() {
99 return Err(Error::other("workspaces: empty argv"));
100 }
101 if o.stdin.len() > MAX_EXEC_STDIN {
102 return Err(Error::other(format!(
103 "workspaces: stdin is {} bytes; the limit is {MAX_EXEC_STDIN}",
104 o.stdin.len()
105 )));
106 }
107 let argv = if o.no_dir {
108 argv.to_vec()
109 } else {
110 let dir = if o.dir.is_empty() {
111 DEFAULT_WORK_DIR
112 } else {
113 &o.dir
114 };
115 with_dir(dir, argv)
116 };
117 let req = ExecRequest {
118 name: name.to_string(),
119 argv,
120 stdin: o.stdin,
121 deadline: o.timeout.filter(|t| !t.is_zero()).map(duration),
122 };
123 let (mut stream, first) = self
124 .start_exec(req)
125 .await
126 .map_err(|e| interrupted(e, false))?;
127 let (mut stdout, mut stderr) = (o.stdout, o.stderr);
128 let mut next = Some(first);
129 loop {
130 let ev = match next.take() {
131 Some(ev) => ev,
132 None => match stream.message().await {
133 Ok(Some(ev)) => ev,
134 Ok(None) => {
135 return Err(Error::OutcomeUnknown {
136 cause: None,
137 result: None,
138 });
139 }
140 Err(s) => return Err(interrupted(self.status(s), true)),
142 },
143 };
144 match ev.event {
145 Some(exec_response::Event::Stdout(b)) => {
146 if let Some(f) = stdout.as_mut() {
147 f(&b);
148 }
149 }
150 Some(exec_response::Event::Stderr(b)) => {
151 if let Some(f) = stderr.as_mut() {
152 f(&b);
153 }
154 }
155 Some(exec_response::Event::Exited(x)) => {
156 return Ok(ExecResult {
157 exit_code: x.code,
158 timed_out: x.timed_out,
159 });
160 }
161 None => {}
162 }
163 }
164 }
165
166 async fn start_exec(
170 &self,
171 req: ExecRequest,
172 ) -> Result<(tonic::Streaming<ExecResponse>, ExecResponse)> {
173 let delays = [2u64, 4, 8, 8, 8];
174 let mut i = 0;
175 loop {
176 let r = self.request(req.clone()).await?;
177 let mut stream = self.check(self.raw().exec(r).await)?.into_inner();
178 match stream.message().await {
179 Ok(Some(first)) => return Ok((stream, first)),
180 Ok(None) => {
181 return Err(Error::OutcomeUnknown {
182 cause: None,
183 result: None,
184 });
185 }
186 Err(s)
187 if s.code() == tonic::Code::FailedPrecondition
188 && controller_busy(s.message())
189 && i < delays.len() =>
190 {
191 tokio::time::sleep(Duration::from_secs(delays[i])).await;
192 i += 1;
193 }
194 Err(s) => return Err(self.status(s)),
195 }
196 }
197 }
198
199 pub async fn output(&self, name: &str, argv: &[String], o: ExecOptions<'_>) -> Result<Vec<u8>> {
201 let (mut out, mut err) = (Vec::new(), Vec::new());
202 let res = {
203 let mut fo = |b: &[u8]| out.extend_from_slice(b);
204 let mut fe = |b: &[u8]| err.extend_from_slice(b);
205 let o = ExecOptions {
206 dir: o.dir,
207 no_dir: o.no_dir,
208 stdin: o.stdin,
209 timeout: o.timeout,
210 stdout: Some(&mut fo),
211 stderr: Some(&mut fe),
212 };
213 self.exec(name, argv, o).await?
214 };
215 if res.exit_code != 0 || res.timed_out {
216 return Err(Error::Exit {
217 exit_code: res.exit_code,
218 timed_out: res.timed_out,
219 stdout: out,
220 stderr: err,
221 });
222 }
223 Ok(out)
224 }
225
226 pub async fn shell(
228 &self,
229 name: &str,
230 script: &str,
231 o: ExecOptions<'_>,
232 args: &[String],
233 ) -> Result<Vec<u8>> {
234 let mut argv = vec!["sh".to_string(), "-c".into(), script.into(), "_".into()];
235 argv.extend_from_slice(args);
236 self.output(name, &argv, o).await
237 }
238}
239
240pub(crate) fn duration(d: Duration) -> prost_types::Duration {
241 prost_types::Duration {
242 seconds: d.as_secs() as i64,
243 nanos: d.subsec_nanos() as i32,
244 }
245}
246
247const CD_SCRIPT: &str = r#"cd "$1" && shift && exec "$@""#;
249
250fn with_dir(dir: &str, argv: &[String]) -> Vec<String> {
251 let mut out = vec![
252 "sh".to_string(),
253 "-c".into(),
254 CD_SCRIPT.into(),
255 "_".into(),
256 guest_path(dir),
257 ];
258 out.extend_from_slice(argv);
259 out
260}
261
262pub fn guest_path(p: &str) -> String {
264 if p.starts_with('/') {
265 clean_path(p)
266 } else {
267 clean_path(&format!("{DEFAULT_WORK_DIR}/{p}"))
268 }
269}
270
271pub(crate) fn clean_path(p: &str) -> String {
273 if p.is_empty() {
274 return ".".into();
275 }
276 let rooted = p.starts_with('/');
277 let mut out: Vec<&str> = Vec::new();
278 for part in p.split('/') {
279 match part {
280 "" | "." => {}
281 ".." => {
282 if out.last().is_some_and(|l| *l != "..") {
283 out.pop();
284 } else if !rooted {
285 out.push("..");
286 }
287 }
288 _ => out.push(part),
289 }
290 }
291 let joined = out.join("/");
292 match (rooted, joined.is_empty()) {
293 (true, _) => format!("/{joined}"),
294 (false, true) => ".".into(),
295 (false, false) => joined,
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 #[test]
304 fn clean_path_matches_go() {
305 for (i, o) in [
306 ("/a/b/../c", "/a/c"),
307 ("/../x", "/x"),
308 ("a/./b/", "a/b"),
309 ("", "."),
310 ("../a", "../a"),
311 ("/", "/"),
312 ("a/..", "."),
313 ] {
314 assert_eq!(clean_path(i), o, "{i}");
315 }
316 assert_eq!(guest_path("x/y"), "/work/x/y");
317 assert_eq!(guest_path("/tmp/../etc"), "/etc");
318 }
319}