1use 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
11pub 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 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
43fn names_tag_or_digest(image: &str) -> bool {
45 let name = image.rsplit_once('/').map_or(image, |(_, name)| name);
46 name.contains([':', '@'])
47}
48
49#[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}