Skip to main content

airlock/
exec.rs

1//! Commands run inside a running container.
2
3use 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
16/// How often to ask Docker whether an exec whose output has ended has exited.
17const EXIT_POLL_INTERVAL: Duration = Duration::from_millis(10);
18
19/// A command to run inside a running container.
20#[derive(Clone, Debug)]
21pub struct ExecRequest {
22    command: Vec<String>,
23    env: Vec<String>,
24    stdin: Option<Bytes>,
25}
26
27impl ExecRequest {
28    /// Creates a request that runs `command` with the container's environment and no standard input.
29    pub fn new(command: Vec<String>) -> Self {
30        Self {
31            command,
32            env: Vec::new(),
33            stdin: None,
34        }
35    }
36
37    /// Adds an environment variable for this command.
38    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    /// Writes `stdin` to the command's standard input, which is then closed. The command may exit without reading it
44    /// all.
45    pub fn with_stdin(mut self, stdin: Bytes) -> Self {
46        self.stdin = Some(stdin);
47        self
48    }
49}
50
51/// The result of a command that ran to completion inside a container.
52#[derive(Clone, Debug, Eq, PartialEq)]
53pub struct ExecOutput {
54    /// The command's exit code.
55    pub exit_code: i64,
56    /// Everything the command wrote to standard output.
57    pub stdout: Vec<u8>,
58    /// Everything the command wrote to standard error.
59    pub stderr: Vec<u8>,
60}
61
62impl Container {
63    /// Runs `command` in the running container and waits for it to exit.
64    ///
65    /// With `stdin`, the bytes are written to the command's standard input, which is then closed. The command may exit
66    /// without reading them all. Without it, the command has no standard input. A nonzero exit code is a result, not an
67    /// error.
68    ///
69    /// # Errors
70    ///
71    /// Returns an error if Docker cannot run the command, if its output cannot be read, if Docker does not report
72    /// its exit code, or if `deadline` passes before the command exits.
73    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    /// Runs `request` in the running container, writes its output to `stdout` and `stderr` as it arrives, and returns its
89    /// exit code once it exits.
90    ///
91    /// A nonzero exit code is a result, not an error.
92    ///
93    /// # Errors
94    ///
95    /// Returns an error if Docker cannot run the command, if its output cannot be read or written, if Docker does not
96    /// report its exit code, or if `deadline` passes before the command exits.
97    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        // Write and read at once, so a command that answers before reading all of its input cannot stall either side.
153        // A command that exits without reading all of its input is not an error: the write fails with a broken pipe or
154        // stalls, as Docker stops reading, and it ends when the command exits.
155        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            // Docker can still report the exec as running after its output ends.
190            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}