Skip to content

Commit

Permalink
feat(jstzd): implement pull image
Browse files Browse the repository at this point in the history
  • Loading branch information
ryutamago committed Sep 18, 2024
1 parent b6cc1bf commit 8369aa1
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
2 changes: 2 additions & 0 deletions Cargo.lock

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

5 changes: 4 additions & 1 deletion crates/jstzd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ anyhow.workspace = true
async-dropper.workspace = true
async-trait.workspace = true
bollard.workspace = true
env_logger.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_name());
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

0 comments on commit 8369aa1

Please sign in to comment.