Skip to content

Commit

Permalink
feat(jstzd): add image_uri
Browse files Browse the repository at this point in the history
  • Loading branch information
ryutamago committed Sep 11, 2024
1 parent 818ec85 commit feae871
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 34 deletions.
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.

1 change: 1 addition & 0 deletions crates/jstzd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ anyhow.workspace = true
async-dropper-simple.workspace = true
async-trait.workspace = true
bollard.workspace = true
env_logger.workspace = true
futures-util.workspace = true
log.workspace = true
tokio.workspace = true
24 changes: 11 additions & 13 deletions crates/jstzd/src/docker/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::sync::Arc;
use crate::docker::Network;

struct ContainerInner {
name: String,
id: String,
client: Arc<Docker>,
// https://linear.app/tezos/issue/JSTZ-111/support-for-adding-network-to-a-container
// Implement network: Option<Network>,
Expand All @@ -18,9 +18,9 @@ struct ContainerInner {
pub struct Container(AsyncDropper<ContainerInner>);
impl ContainerInner {
/// Creates a new container with running `id`
pub fn new(client: Arc<Docker>, name: &str, _network: Option<Network>) -> Self {
pub fn new(client: Arc<Docker>, id: String, _network: Option<Network>) -> Self {
Self {
name: name.to_string(),
id,
client,
// network,
_private: (),
Expand All @@ -30,14 +30,14 @@ impl ContainerInner {
/// Starts the container's entrypoint
async fn start(&self) -> Result<()> {
self.client
.start_container(&self.name, None::<StartContainerOptions<String>>)
.start_container(&self.id, None::<StartContainerOptions<String>>)
.await?;
Ok(())
}

/// Stop the container
async fn stop(&self) -> Result<()> {
self.client.stop_container(&self.name, None).await?;
self.client.stop_container(&self.id, None).await?;
Ok(())
}
}
Expand All @@ -48,24 +48,22 @@ impl AsyncDrop for ContainerInner {
self.stop()
.await
.unwrap_or_else(|e| error!("Error stopping container: {}", e));
match self.client.remove_container(&self.name, None).await {
match self.client.remove_container(&self.id, None).await {
Ok(_) => {}
Err(e) => error!("Error removing container {}: {}", self.name, e),
Err(e) => error!("Error removing container {}: {}", self.id, e),
}
// TODO: https://linear.app/tezos/issue/JSTZ-111/support-for-adding-network-to-a-container
// Handle network drop
}
}

impl Container {
pub fn new(client: Arc<Docker>, name: &str, network: Option<Network>) -> Self {
Self(AsyncDropper::new(ContainerInner::new(
client, name, network,
)))
pub fn new(client: Arc<Docker>, id: String, network: Option<Network>) -> Self {
Self(AsyncDropper::new(ContainerInner::new(client, id, network)))
}

pub fn name(&self) -> &str {
&self.0.inner().name
pub fn id(&self) -> &str {
&self.0.inner().id
}

pub async fn start(&self) -> Result<()> {
Expand Down
11 changes: 7 additions & 4 deletions crates/jstzd/src/docker/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ pub trait Image: Sized {
fn image_tag(&self) -> &str {
Self::LATEST_TAG
}
fn image_uri(&self) -> String {
format!("{}:{}", self.image_name(), self.image_tag())
}
// Overrides the entrypoint of the image
fn entrypoint(&self) -> Option<&str> {
None
Expand Down Expand Up @@ -42,17 +45,17 @@ impl Image for GenericImage {
&self.image_name
}

fn entrypoint(&self) -> Option<&str> {
self.entrypoint.as_deref()
}

fn image_tag(&self) -> &str {
if let Some(tag) = &self.image_tag {
return tag;
}
Self::LATEST_TAG
}

fn entrypoint(&self) -> Option<&str> {
self.entrypoint.as_deref()
}

fn exposed_ports(&self) -> &[u16] {
if let Some(ports) = &self.exposed_ports {
return ports;
Expand Down
15 changes: 5 additions & 10 deletions crates/jstzd/src/docker/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::sync::Arc;

struct NetworkInner {
name: String,
client: Option<Arc<Docker>>,
client: Arc<Docker>,
}

pub struct Network(AsyncDropper<NetworkInner>);
Expand All @@ -20,21 +20,16 @@ impl NetworkInner {
..CreateNetworkOptions::default()
};
client.create_network(config).await?;
Ok(Self {
client: Some(client),
name,
})
Ok(Self { client, name })
}
}

#[async_trait]
impl AsyncDrop for NetworkInner {
async fn async_drop(&mut self) {
if let Some(client) = self.client.take() {
match client.remove_network(&self.name).await {
Ok(_) => {}
Err(e) => error!("Error removing network {}: {}", self.name, e),
}
match self.client.remove_network(&self.name).await {
Ok(_) => {}
Err(e) => error!("Error removing network {}: {}", self.name, e),
}
}
}
Expand Down
5 changes: 2 additions & 3 deletions crates/jstzd/src/docker/runnable_image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ impl<I: Image> RunnableImage<I> {
pub async fn create_container(&self, client: Arc<Docker>) -> Result<String> {
self.all_container_ports_are_exposed()?;
let config = Config::<String> {
image: Some(self.image.image_name().to_string()),
image: Some(self.image.image_uri().to_string()),
host_config: Some(self.host_config()),
entrypoint: self.entrypoint(),
cmd: self.overridden_cmd.clone(),
Expand Down Expand Up @@ -207,8 +207,7 @@ impl<I: Image> RunnableImage<I> {
where
T: Image + ?Sized,
{
let reference = format!("{}:{}", image.image_name(), image.image_tag());
let filters = [("reference".to_string(), vec![reference])]
let filters = [("reference".to_string(), vec![image.image_uri()])]
.into_iter()
.collect::<HashMap<_, _>>();
let images = &client
Expand Down
10 changes: 6 additions & 4 deletions crates/jstzd/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use bollard::Docker;
use env_logger::Env;
use jstzd::docker::{Container, GenericImage, Image, RunnableImage};
use std::sync::Arc;

pub async fn example() -> anyhow::Result<()> {
let docker = Docker::connect_with_socket_defaults().unwrap();
let docker = Arc::new(docker);
let image = GenericImage::new("busybox").with_tag("stable");
let image = GenericImage::new("busybox").with_tag("latest");
image.pull_image(docker.clone()).await?;
let cmd = vec![
"sh",
Expand All @@ -18,16 +19,17 @@ pub async fn example() -> anyhow::Result<()> {
let runnable_image =
RunnableImage::new(image, "busybox_test").with_overridden_cmd(cmd);
let id = runnable_image.create_container(docker.clone()).await?;
let container = Container::new(docker.clone(), &id, None);
let container = Container::new(docker.clone(), id, None);
container.start().await?;

Ok(())
}

#[tokio::main]
async fn main() {
env_logger::init_from_env(Env::default().default_filter_or("info"));
match example().await {
Ok(_) => println!("Success"),
Err(e) => eprintln!("Error: {}", e),
Ok(_) => log::info!("Success"),
Err(e) => log::error!("Error: {}", e),
}
}

0 comments on commit feae871

Please sign in to comment.