Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(jstzd): implement pull image #558

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion crates/jstzd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ async-trait.workspace = true
bollard.workspace = true
futures-util.workspace = true
tokio.workspace = true
log.workspace = true

[[bin]]
name = "jstzd"
path = "src/main.rs"
path = "src/main.rs"

51 changes: 51 additions & 0 deletions crates/jstzd/src/docker/image.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
use anyhow::Result;
use bollard::{
image::{CreateImageOptions, ListImagesOptions},
Docker,
};
use futures_util::StreamExt;
use log::info;
use std::{collections::HashMap, sync::Arc};
#[async_trait::async_trait]
pub trait Image: Sized {
const LATEST_TAG: &'static str = "latest";
fn image_name(&self) -> &str;
Expand All @@ -15,6 +24,48 @@ pub trait Image: Sized {
fn exposed_ports(&self) -> &[u16] {
&[]
}
async fn pull_image(&self, client: Arc<Docker>) -> Result<()> {
if Self::image_exists(self, client.clone()).await {
info!("Image: {:?} already exists ", self.image_uri());
return Ok(());
}
self.create_image(client.clone()).await
}
async fn image_exists(&self, client: Arc<Docker>) -> bool {
let filters = [("reference".to_string(), vec![self.image_uri()])]
.into_iter()
.collect::<HashMap<_, _>>();
let images = &client
.list_images(Some(ListImagesOptions::<String> {
all: true,
filters,
..Default::default()
}))
.await;
match images {
Ok(images) => !images.is_empty(),
Err(_) => false,
}
}
async fn create_image(&self, client: Arc<Docker>) -> anyhow::Result<()> {
let options = Some(CreateImageOptions {
from_image: self.image_name(),
tag: self.image_tag(),
..Default::default()
});
let mut stream = client.create_image(options, None, None);
while let Some(create_info) = stream.next().await {
match create_info {
Ok(info) => {
if let Some(status) = info.status {
println!("{:?}", status)
}
}
Err(e) => return Err(e.into()),
}
}
Ok(())
}
}

pub struct GenericImage {
Expand Down
41 changes: 41 additions & 0 deletions crates/jstzd/tests/pull_image.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use std::{collections::HashMap, sync::Arc};

use anyhow::Result;
use bollard::{image::ListImagesOptions, secret::ImageSummary, Docker};
use jstzd::docker::{GenericImage, Image};

// search image locally
async fn search_local_image(
image_uri: String,
client: Arc<Docker>,
) -> Result<Vec<ImageSummary>> {
let filters = [("reference".to_string(), vec![image_uri])]
.into_iter()
.collect::<HashMap<_, _>>();
let images = &client
.list_images(Some(ListImagesOptions::<String> {
all: true,
filters,
..Default::default()
}))
.await;
match images {
Ok(images) => Ok(images.clone()),
Err(_) => Err(anyhow::anyhow!("Image not found")),
}
}

#[tokio::test]
async fn test_pull_image() -> Result<()> {
let docker = Docker::connect_with_socket_defaults().unwrap();
let docker = Arc::new(docker);
let image = GenericImage::new("busybox").with_tag("stable");
let _ = docker.remove_image(&image.image_uri(), None, None).await;
image.pull_image(docker.clone()).await?;
let expected_image_digest =
"sha256:7db2ddde018a2a56e929855445bc7f30bc83db514a23404bd465a07d2770ac5f";
let images = search_local_image(image.image_uri(), docker.clone()).await?;
assert!(images.iter().any(|image| image.id == expected_image_digest));
let _ = docker.remove_image(&image.image_uri(), None, None).await;
Ok(())
}
Loading