Skip to main content

airlock/
container.rs

1//! Named containers in a case scope: create, start, observe, stop and remove.
2//!
3//! Creating and starting are separate, so files can be placed between them. A container joins the case network
4//! under its participant name, mounts the case volume when its scope has one, and can publish TCP ports on the runner's
5//! `127.0.0.1`. Docker chooses each host port, and [`Container::status`] reads it back after start.
6
7use std::{collections::HashMap, pin::Pin, time::Duration};
8
9use bollard::{
10    container::LogOutput,
11    errors::Error,
12    models::{
13        ContainerCreateBody, ContainerStateStatusEnum, EndpointSettings, HostConfig, HostConfigCgroupnsModeEnum, Mount,
14        MountType, NetworkingConfig, PortBinding,
15    },
16    query_parameters::{
17        CreateContainerOptionsBuilder, LogsOptionsBuilder, RemoveContainerOptionsBuilder, StopContainerOptionsBuilder,
18        WaitContainerOptionsBuilder,
19    },
20    Docker,
21};
22use bytes::Bytes;
23use futures::{Stream, StreamExt as _};
24use saluki_error::{generic_error, ErrorContext as _, GenericError};
25use tokio::time::{timeout_at, Instant};
26
27use crate::{
28    removal::{bounded, RequestError},
29    retry::with_transient_error_retry,
30    scope::CaseScope,
31};
32
33/// The host address published ports bind to.
34const PUBLISH_HOST_IP: &str = "127.0.0.1";
35
36/// The ephemeral port range of a Linux container, for `net.ipv4.ip_local_port_range`. It stays above every fixed port a
37/// test process listens on, so an outbound socket cannot take one.
38pub const LINUX_EPHEMERAL_PORT_RANGE: &str = "60000 65535";
39
40/// What to run in a container, and how it joins its case scope.
41#[derive(Clone, Debug, Default)]
42pub struct ContainerSpec {
43    image: String,
44    entrypoint: Option<Vec<String>>,
45    command: Option<Vec<String>>,
46    env: Vec<String>,
47    published_ports: Vec<u16>,
48    mounts: Vec<Mount>,
49    sysctls: HashMap<String, String>,
50    host_pid: bool,
51    host_cgroup_namespace: bool,
52}
53
54impl ContainerSpec {
55    /// Creates a spec that runs `image` with its own entrypoint and command.
56    pub fn new(image: impl Into<String>) -> Self {
57        Self {
58            image: image.into(),
59            ..Default::default()
60        }
61    }
62
63    /// Replaces the image's entrypoint.
64    pub fn with_entrypoint(mut self, entrypoint: Vec<String>) -> Self {
65        self.entrypoint = Some(entrypoint);
66        self
67    }
68
69    /// Replaces the image's command.
70    pub fn with_command(mut self, command: Vec<String>) -> Self {
71        self.command = Some(command);
72        self
73    }
74
75    /// Adds an environment variable.
76    pub fn with_env_var(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
77        self.env.push(format!("{}={}", key.as_ref(), value.as_ref()));
78        self
79    }
80
81    /// Publishes a TCP port of the container on the runner's `127.0.0.1`, at a host port Docker chooses.
82    pub fn with_published_port(mut self, port: u16) -> Self {
83        self.published_ports.push(port);
84        self
85    }
86
87    /// Mounts the host path `host` at `path` in the container. Creating the container fails if `host` does not exist.
88    pub fn with_bind(mut self, host: impl Into<String>, path: impl Into<String>, read_only: bool) -> Self {
89        self.mounts.push(Mount {
90            source: Some(host.into()),
91            target: Some(path.into()),
92            typ: Some(MountType::BIND),
93            read_only: Some(read_only),
94            ..Default::default()
95        });
96        self
97    }
98
99    /// Sets a kernel parameter in the container's namespaces, such as `net.ipv4.ip_local_port_range`.
100    pub fn with_sysctl(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
101        self.sysctls.insert(key.into(), value.into());
102        self
103    }
104
105    /// Runs the container in the host's PID namespace.
106    pub fn with_host_pid(mut self) -> Self {
107        self.host_pid = true;
108        self
109    }
110
111    /// Runs the container in the host's cgroup namespace.
112    pub fn with_host_cgroup_namespace(mut self) -> Self {
113        self.host_cgroup_namespace = true;
114        self
115    }
116}
117
118/// One output chunk of a container or an exec.
119#[derive(Clone, Debug, Eq, PartialEq)]
120pub enum Output {
121    /// Bytes written to standard output.
122    Stdout(Bytes),
123    /// Bytes written to standard error.
124    Stderr(Bytes),
125}
126
127impl Output {
128    pub(crate) fn from_log(log: LogOutput) -> Option<Self> {
129        match log {
130            LogOutput::StdOut { message } | LogOutput::Console { message } => Some(Self::Stdout(message)),
131            LogOutput::StdErr { message } => Some(Self::Stderr(message)),
132            LogOutput::StdIn { .. } => None,
133        }
134    }
135}
136
137/// A stream of a container's output.
138pub type OutputStream = Pin<Box<dyn Stream<Item = Result<Output, GenericError>> + Send>>;
139
140/// A container that exists in Docker, created by [`CaseScope::create_container`].
141#[derive(Clone, Debug)]
142pub struct Container {
143    pub(crate) docker: Docker,
144    pub(crate) name: String,
145    pub(crate) id: String,
146    /// The case network the container joined.
147    pub(crate) network: String,
148}
149
150/// What Docker reports of a container after its start.
151#[derive(Clone, Debug, Default, Eq, PartialEq)]
152pub struct Status {
153    /// Whether the container is running.
154    pub running: bool,
155    /// The container's address on the case network, while it runs.
156    pub ip: Option<String>,
157    /// The host port Docker chose for each published TCP port, while the container runs.
158    pub published_ports: HashMap<u16, u16>,
159}
160
161impl CaseScope {
162    /// Creates the container for `participant` from `spec`, without starting it.
163    ///
164    /// The container is named [`CaseScope::container_name`], joins the case network under the participant's name, which
165    /// is also its host name, and carries the scope's labels, so [`CaseScope::reclaim`] removes it.
166    ///
167    /// # Errors
168    ///
169    /// Returns an error if Docker refuses the container, for example because the image is missing or the name is
170    /// taken, or if `deadline` passes first.
171    pub async fn create_container(
172        &self, participant: &str, spec: ContainerSpec, deadline: Instant,
173    ) -> Result<Container, GenericError> {
174        let name = self.container_name(participant);
175        let network = self.resource_name();
176
177        let networking_config = NetworkingConfig {
178            endpoints_config: Some(HashMap::from([(
179                network.clone(),
180                EndpointSettings {
181                    aliases: Some(vec![participant.to_string()]),
182                    ..Default::default()
183                },
184            )])),
185        };
186
187        let binds = self.platform.volume_path.map(|path| {
188            // The case volume has the network's name (see `CaseScope::resource_name`).
189            let volume = self.resource_name();
190            vec![format!("{}:{}", volume, path)]
191        });
192
193        let exposed_ports: Vec<String> = spec
194            .published_ports
195            .iter()
196            .map(|port| format!("{}/tcp", port))
197            .collect();
198        let port_bindings: HashMap<String, Option<Vec<PortBinding>>> = exposed_ports
199            .iter()
200            .map(|port| {
201                let binding = PortBinding {
202                    host_ip: Some(PUBLISH_HOST_IP.to_string()),
203                    host_port: None,
204                };
205                (port.clone(), Some(vec![binding]))
206            })
207            .collect();
208
209        let body = ContainerCreateBody {
210            hostname: Some(participant.to_string()),
211            image: Some(spec.image),
212            entrypoint: spec.entrypoint,
213            cmd: spec.command,
214            env: Some(spec.env),
215            labels: Some(self.labels()),
216            exposed_ports: Some(exposed_ports),
217            host_config: Some(HostConfig {
218                binds,
219                mounts: (!spec.mounts.is_empty()).then_some(spec.mounts),
220                network_mode: Some(network.clone()),
221                port_bindings: Some(port_bindings),
222                sysctls: (!spec.sysctls.is_empty()).then_some(spec.sysctls),
223                pid_mode: spec.host_pid.then(|| "host".to_string()),
224                cgroupns_mode: spec.host_cgroup_namespace.then_some(HostConfigCgroupnsModeEnum::HOST),
225                ..Default::default()
226            }),
227            networking_config: Some(networking_config),
228            ..Default::default()
229        };
230        let options = CreateContainerOptionsBuilder::default().name(&name).build();
231        let created = bounded(Some(deadline), self.docker.create_container(Some(options), body))
232            .await
233            .map_err(|e| generic_error!("Failed to create container '{}': {}", name, e))?;
234
235        Ok(Container {
236            docker: self.docker.clone(),
237            name,
238            id: created.id,
239            network,
240        })
241    }
242}
243
244impl Container {
245    /// Opens the container Docker already has under `name`, which belongs to no case scope: it has no case network, so
246    /// [`Self::status`] reports no address.
247    ///
248    /// # Errors
249    ///
250    /// Returns an error if Docker has no such container, or if `deadline` passes first.
251    pub async fn existing(docker: &Docker, name: &str, deadline: Instant) -> Result<Self, GenericError> {
252        let inspect = bounded(Some(deadline), docker.inspect_container(name, None))
253            .await
254            .map_err(|e| generic_error!("Failed to inspect container '{}': {}", name, e))?;
255        let id = inspect
256            .id
257            .ok_or_else(|| generic_error!("Docker reports no ID for container '{}'.", name))?;
258        Ok(Self {
259            docker: docker.clone(),
260            name: name.to_string(),
261            id,
262            network: String::new(),
263        })
264    }
265
266    /// Returns the container's name.
267    pub fn name(&self) -> &str {
268        &self.name
269    }
270
271    /// Returns the ID Docker gave the container.
272    pub fn id(&self) -> &str {
273        &self.id
274    }
275
276    /// Starts the container.
277    ///
278    /// # Errors
279    ///
280    /// Returns an error if Docker cannot start the container, for example because its command does not exist, or if
281    /// `deadline` passes first.
282    pub async fn start(&self, deadline: Instant) -> Result<(), GenericError> {
283        // Retrying is safe: the daemon treats starting a running container as a no-op.
284        let start = with_transient_error_retry("container start", &self.name, || async {
285            self.docker
286                .start_container(&self.name, None)
287                .await
288                .with_error_context(|| format!("Failed to start container '{}'.", self.name))
289        });
290        // The deadline bounds the waits between attempts, too.
291        timeout_at(deadline, start).await.unwrap_or_else(|_| {
292            Err(generic_error!(
293                "Failed to start container '{}': {}",
294                self.name,
295                RequestError::DeadlineExceeded
296            ))
297        })
298    }
299
300    /// Returns the host port Docker chose for the published TCP `port`. Call it after [`Self::start`].
301    ///
302    /// # Errors
303    ///
304    /// Returns an error if inspecting the container fails, if Docker reports no binding of `port` on `127.0.0.1`, or if
305    /// `deadline` passes first.
306    pub async fn published_port(&self, port: u16, deadline: Instant) -> Result<u16, GenericError> {
307        self.status(deadline)
308            .await?
309            .published_ports
310            .get(&port)
311            .copied()
312            .ok_or_else(|| {
313                generic_error!(
314                    "Docker reports no host port for port {} of container '{}'.",
315                    port,
316                    self.name
317                )
318            })
319    }
320
321    /// Returns whether the container is running, with its address and published ports. Call it after [`Self::start`].
322    ///
323    /// # Errors
324    ///
325    /// Returns an error if inspecting the container fails, or if `deadline` passes first.
326    pub async fn status(&self, deadline: Instant) -> Result<Status, GenericError> {
327        let inspect = bounded(Some(deadline), self.docker.inspect_container(&self.name, None))
328            .await
329            .map_err(|e| generic_error!("Failed to inspect container '{}': {}", self.name, e))?;
330        let running = inspect.state.and_then(|state| state.running).unwrap_or(false);
331        let settings = inspect.network_settings.unwrap_or_default();
332        let ip = settings
333            .networks
334            .and_then(|mut networks| networks.remove(&self.network))
335            .and_then(|endpoint| endpoint.ip_address)
336            .filter(|ip| !ip.is_empty());
337        let published_ports = settings
338            .ports
339            .into_iter()
340            .flatten()
341            .filter_map(|(key, bindings)| {
342                let port = key.strip_suffix("/tcp")?.parse().ok()?;
343                let host_port = bindings
344                    .into_iter()
345                    .flatten()
346                    .filter(|binding| binding.host_ip.as_deref() == Some(PUBLISH_HOST_IP))
347                    .find_map(|binding| binding.host_port.and_then(|host_port| host_port.parse().ok()))?;
348                Some((port, host_port))
349            })
350            .collect();
351        Ok(Status {
352            running,
353            ip,
354            published_ports,
355        })
356    }
357
358    /// Waits for the container to stop running and returns its exit code. Call it after [`Self::start`].
359    ///
360    /// Death by signal `n` is reported as code 128 + `n`.
361    ///
362    /// # Errors
363    ///
364    /// Returns an error if Docker cannot report the exit, for example because the container was removed, if the
365    /// container never ran, because it was not started or its start failed, or if `deadline` passes before the
366    /// container exits.
367    pub async fn wait(&self, deadline: Instant) -> Result<i64, GenericError> {
368        let options = WaitContainerOptionsBuilder::default().condition("not-running").build();
369        let waited = match timeout_at(deadline, self.docker.wait_container(&self.name, Some(options)).next()).await {
370            Err(_) => Err(RequestError::DeadlineExceeded.to_string()),
371            Ok(Some(Ok(response))) => match response.error.and_then(|error| error.message).filter(|m| !m.is_empty()) {
372                Some(message) => Err(message),
373                None => Ok(response.status_code),
374            },
375            // `bollard` turns a nonzero exit into this error, with Docker's message if it sent one.
376            Ok(Some(Err(Error::DockerContainerWaitError { error, code }))) if error.is_empty() => Ok(code),
377            Ok(Some(Err(Error::DockerContainerWaitError { error, .. }))) => Err(error),
378            Ok(Some(Err(e))) => Err(e.to_string()),
379            Ok(None) => Err("Docker ended the wait without an exit".to_string()),
380        };
381        let code = waited
382            .map_err(|message| generic_error!("Failed to wait for container '{}' to exit: {}", self.name, message))?;
383
384        // Docker also ends the wait of a container that never ran, with a code that no process returned.
385        let state = bounded(Some(deadline), self.docker.inspect_container(&self.name, None))
386            .await
387            .map_err(|e| generic_error!("Failed to inspect container '{}' after its exit: {}", self.name, e))?
388            .state
389            .unwrap_or_default();
390        if state.status == Some(ContainerStateStatusEnum::CREATED) {
391            return Err(generic_error!(
392                "Container '{}' never ran: {}",
393                self.name,
394                state
395                    .error
396                    .filter(|error| !error.is_empty())
397                    .as_deref()
398                    .unwrap_or("it was not started")
399            ));
400        }
401        Ok(code)
402    }
403
404    /// Follows the container's output from its start until it exits.
405    pub fn logs(&self) -> OutputStream {
406        let options = LogsOptionsBuilder::default()
407            .follow(true)
408            .stdout(true)
409            .stderr(true)
410            .build();
411        let name = self.name.clone();
412        let logs = self.docker.logs(&self.name, Some(options)).filter_map(move |log| {
413            let output = match log {
414                Ok(log) => Output::from_log(log).map(Ok),
415                Err(e) => Some(Err(generic_error!(
416                    "Failed to read the output of container '{}': {}",
417                    name,
418                    e
419                ))),
420            };
421            async move { output }
422        });
423        Box::pin(logs)
424    }
425
426    /// Stops the container: signals its main process, then kills it if it is still running after `grace`.
427    ///
428    /// Docker counts the grace in whole seconds, so a fraction of a second is rounded up.
429    ///
430    /// A container that is already stopped or gone counts as stopped.
431    ///
432    /// # Errors
433    ///
434    /// Returns an error if Docker fails to stop the container, or if `deadline` passes first.
435    pub async fn stop(&self, grace: Duration, deadline: Instant) -> Result<(), GenericError> {
436        let seconds = grace.as_secs() + u64::from(grace.subsec_nanos() > 0);
437        let grace = i32::try_from(seconds).unwrap_or(i32::MAX);
438        let options = StopContainerOptionsBuilder::default().t(grace).build();
439        match bounded(Some(deadline), self.docker.stop_container(&self.name, Some(options))).await {
440            Err(e) if !e.is_not_found() => Err(generic_error!("Failed to stop container '{}': {}", self.name, e)),
441            _ => Ok(()),
442        }
443    }
444
445    /// Force-removes the container and its anonymous volumes, killing it if it is running. A container that is already
446    /// gone counts as removed.
447    ///
448    /// # Errors
449    ///
450    /// Returns an error if Docker fails to remove the container, or if `deadline` passes first.
451    pub async fn remove(&self, deadline: Instant) -> Result<(), GenericError> {
452        let options = RemoveContainerOptionsBuilder::default().force(true).v(true).build();
453        match bounded(Some(deadline), self.docker.remove_container(&self.name, Some(options))).await {
454            Err(e) if !e.is_not_found() => Err(generic_error!("Failed to remove container '{}': {}", self.name, e)),
455            _ => Ok(()),
456        }
457    }
458}