Skip to main content

airlock/
image.rs

1//! Images the Docker daemon must have before a container can be created from them.
2
3use bollard::{query_parameters::CreateImageOptions, Docker};
4use futures::TryStreamExt as _;
5use saluki_error::{generic_error, GenericError};
6use tokio::time::{timeout_at, Instant};
7use tracing::debug;
8
9use crate::removal::is_not_found;
10
11/// Pulls `image` unless the Docker daemon already has it.
12///
13/// # Errors
14///
15/// Returns an error if Docker cannot inspect the image, if the pull fails, or if `deadline` passes first.
16pub async fn ensure_image(docker: &Docker, image: &str, deadline: Instant) -> Result<(), GenericError> {
17    timeout_at(deadline, ensure_image_unbounded(docker, image))
18        .await
19        .map_err(|_| generic_error!("The deadline passed before image '{}' was available.", image))?
20}
21
22async fn ensure_image_unbounded(docker: &Docker, image: &str) -> Result<(), GenericError> {
23    match docker.inspect_image(image).await {
24        Ok(_) => return Ok(()),
25        Err(e) if is_not_found(&e) => {}
26        Err(e) => return Err(generic_error!("Failed to inspect image '{}': {}", image, e)),
27    }
28
29    debug!("Pulling image '{}'...", image);
30    let options = CreateImageOptions {
31        from_image: Some(image.to_string()),
32        // Without a tag, Docker pulls every tag.
33        tag: (!names_tag_or_digest(image)).then(|| "latest".to_string()),
34        ..Default::default()
35    };
36    docker
37        .create_image(Some(options), None, None)
38        .try_for_each(|_| async { Ok(()) })
39        .await
40        .map_err(|e| generic_error!("Failed to pull image '{}': {}", image, e))
41}
42
43/// Whether `image` names a tag or a digest. A colon before the last slash is a registry port, not a tag.
44fn names_tag_or_digest(image: &str) -> bool {
45    let name = image.rsplit_once('/').map_or(image, |(_, name)| name);
46    name.contains([':', '@'])
47}
48
49/// The image of the tests that need a Docker daemon.
50///
51/// CI cannot reach Docker Hub, so this comes from the internal registry's mirror. It is multi-arch and has a shell.
52#[cfg(any(test, feature = "test-util"))]
53pub const DAEMON_TEST_IMAGE: &str = "registry.ddbuild.io/images/mirror/alpine:3.20";
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn tag_or_digest_follows_the_last_slash() {
61        assert!(!names_tag_or_digest("alpine"));
62        assert!(!names_tag_or_digest("localhost:5000/img"));
63        assert!(names_tag_or_digest("localhost:5000/img:1.0"));
64        assert!(names_tag_or_digest("alpine@sha256:0123"));
65    }
66}