1use std::time::Duration;
4
5use bollard::exec::{CreateExecOptions, StartExecResults};
6use bytes::Bytes;
7use futures::TryStreamExt as _;
8use saluki_error::{generic_error, ErrorContext as _, GenericError};
9use tokio::{
10 io::{AsyncWrite, AsyncWriteExt as _},
11 time::{sleep, timeout_at, Instant},
12};
13
14use crate::container::{Container, Output};
15
16const EXIT_POLL_INTERVAL: Duration = Duration::from_millis(10);
18
19#[derive(Clone, Debug)]
21pub struct ExecRequest {
22 command: Vec<String>,
23 env: Vec<String>,
24 stdin: Option<Bytes>,
25}
26
27impl ExecRequest {
28 pub fn new(command: Vec<String>) -> Self {
30 Self {
31 command,
32 env: Vec::new(),
33 stdin: None,
34 }
35 }
36
37 pub fn with_env_var(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
39 self.env.push(format!("{}={}", key.as_ref(), value.as_ref()));
40 self
41 }
42
43 pub fn with_stdin(mut self, stdin: Bytes) -> Self {
46 self.stdin = Some(stdin);
47 self
48 }
49}
50
51#[derive(Clone, Debug, Eq, PartialEq)]
53pub struct ExecOutput {
54 pub exit_code: i64,
56 pub stdout: Vec<u8>,
58 pub stderr: Vec<u8>,
60}
61
62impl Container {
63 pub async fn exec(
74 &self, command: Vec<String>, stdin: Option<Bytes>, deadline: Instant,
75 ) -> Result<ExecOutput, GenericError> {
76 let mut request = ExecRequest::new(command);
77 request.stdin = stdin;
78 let mut stdout = Vec::new();
79 let mut stderr = Vec::new();
80 let exit_code = self.exec_into(request, &mut stdout, &mut stderr, deadline).await?;
81 Ok(ExecOutput {
82 exit_code,
83 stdout,
84 stderr,
85 })
86 }
87
88 pub async fn exec_into<O, E>(
98 &self, request: ExecRequest, stdout: &mut O, stderr: &mut E, deadline: Instant,
99 ) -> Result<i64, GenericError>
100 where
101 O: AsyncWrite + Unpin + ?Sized,
102 E: AsyncWrite + Unpin + ?Sized,
103 {
104 let described = format!("{:?}", request.command);
105 timeout_at(deadline, self.exec_unbounded(request, stdout, stderr))
106 .await
107 .map_err(|_| {
108 generic_error!(
109 "The deadline passed before {} in container '{}' exited.",
110 described,
111 self.name
112 )
113 })?
114 }
115
116 async fn exec_unbounded<O, E>(
117 &self, request: ExecRequest, stdout: &mut O, stderr: &mut E,
118 ) -> Result<i64, GenericError>
119 where
120 O: AsyncWrite + Unpin + ?Sized,
121 E: AsyncWrite + Unpin + ?Sized,
122 {
123 let ExecRequest { command, env, stdin } = request;
124 let options = CreateExecOptions {
125 attach_stdin: Some(stdin.is_some()),
126 attach_stdout: Some(true),
127 attach_stderr: Some(true),
128 env: Some(env),
129 cmd: Some(command.clone()),
130 ..Default::default()
131 };
132 let exec = self
133 .docker
134 .create_exec(&self.name, options)
135 .await
136 .with_error_context(|| {
137 format!(
138 "Failed to create an exec of {:?} in container '{}'.",
139 command, &self.name
140 )
141 })?;
142
143 let StartExecResults::Attached { mut output, mut input } = self
144 .docker
145 .start_exec(&exec.id, None)
146 .await
147 .with_error_context(|| format!("Failed to start {:?} in container '{}'.", command, &self.name))?
148 else {
149 return Err(generic_error!("Docker started {:?} detached from its output.", command));
150 };
151
152 let write = async {
156 if let Some(stdin) = stdin {
157 let written = async {
158 input.write_all(&stdin).await?;
159 input.shutdown().await
160 };
161 match written.await {
162 Err(e) if e.kind() != std::io::ErrorKind::BrokenPipe => return e,
163 _ => {}
164 }
165 }
166 std::future::pending().await
167 };
168 let finish = async {
169 while let Some(log) = output
170 .try_next()
171 .await
172 .with_error_context(|| format!("Failed to read the output of {:?}.", command))?
173 {
174 let written = match Output::from_log(log) {
175 Some(Output::Stdout(bytes)) => stdout.write_all(&bytes).await,
176 Some(Output::Stderr(bytes)) => stderr.write_all(&bytes).await,
177 None => Ok(()),
178 };
179 written.with_error_context(|| format!("Failed to pass on the output of {:?}.", command))?;
180 }
181 let flushed = async {
182 stdout.flush().await?;
183 stderr.flush().await
184 };
185 flushed
186 .await
187 .with_error_context(|| format!("Failed to pass on the output of {:?}.", command))?;
188
189 let inspect = loop {
191 let inspect = self
192 .docker
193 .inspect_exec(&exec.id)
194 .await
195 .with_error_context(|| format!("Failed to inspect the exec of {:?}.", command))?;
196 if inspect.running != Some(true) {
197 break inspect;
198 }
199 sleep(EXIT_POLL_INTERVAL).await;
200 };
201 inspect
202 .exit_code
203 .ok_or_else(|| generic_error!("Docker reported no exit code for {:?}.", command))
204 };
205 tokio::select! {
206 error = write => {
207 Err(error).with_error_context(|| format!("Failed to write the standard input of {:?}.", command))
208 }
209 exit_code = finish => exit_code,
210 }
211 }
212}