Skip to content

Commit

Permalink
refactor(jstzd): remove create_container
Browse files Browse the repository at this point in the history
  • Loading branch information
ryutamago committed Sep 17, 2024
1 parent fc310d6 commit 8a664b6
Show file tree
Hide file tree
Showing 4 changed files with 4 additions and 174 deletions.
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ base64 = "0.21.7"
bincode = "1.3.3"
boa_engine = { version = "0.17.0", features = ["fuzz"] }
boa_gc = "0.17.0"
bollard = "0.16.1"
bs58 = "0.5"
bytes = "1.4.0"
chrono = { version = "0.4.34", default-features = false, features = ["std"] }
Expand Down Expand Up @@ -101,8 +102,6 @@ urlpattern = "0.2.0"
wasm-bindgen = "0.2.92"
async-dropper = { version = "0.3.1", features = ["tokio", "simple"] }
async-trait = "0.1.82"
bollard = "0.16.1"


[workspace.dependencies.tezos-smart-rollup]
version = "0.2.2"
Expand Down
3 changes: 0 additions & 3 deletions codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@ comment:
layout: "header, files, footer"
hide_project_coverage: false

ignore:
- crates/jstzd/src/main.rs

# Configures coverage checks -- both patch and project-wide checks
# can drop by 5% before failing the CI build.
#
Expand Down
4 changes: 2 additions & 2 deletions crates/jstzd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ repository.workspace = true

[dependencies]
anyhow.workspace = true
tokio.workspace = true
async-dropper.workspace = true
async-trait.workspace = true
futures-util.workspace = true
bollard.workspace = true
futures-util.workspace = true
tokio.workspace = true
168 changes: 1 addition & 167 deletions crates/jstzd/src/docker/runnable_image.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,5 @@
use crate::docker::Image;
use anyhow::Result;
use bollard::{
container::{Config, CreateContainerOptions},
secret::{ContainerCreateResponse, HostConfig, PortBinding, PortMap},
Docker,
};
use std::{
collections::{BTreeMap, HashMap, HashSet},
net::IpAddr,
sync::Arc,
};
use std::{collections::BTreeMap, net::IpAddr};

#[derive(Debug, PartialEq, Clone)]
pub enum AccessMode {
Expand Down Expand Up @@ -111,94 +101,6 @@ impl<I: Image> RunnableImage<I> {
self.ports.insert(host_port, container_port);
self
}

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_uri().to_string()),
host_config: Some(self.host_config()),
entrypoint: self.entrypoint(),
cmd: self.overridden_cmd.clone(),
env: self.env(),
..Config::default()
};
let options = Some(CreateContainerOptions {
name: self.container_name.clone(),
platform: None,
});
match client.create_container(options, config).await {
Ok(ContainerCreateResponse { id, .. }) => Ok(id),
Err(e) => Err(e.into()),
}
}

fn env(&self) -> Option<Vec<String>> {
match self.env_vars.is_empty() {
true => None,
false => Some(
self.env_vars
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>(),
),
}
}

fn entrypoint(&self) -> Option<Vec<String>> {
self.image.entrypoint().map(|e| {
e.split_whitespace()
.map(|s| s.to_string())
.collect::<Vec<String>>()
})
}

fn host_config(&self) -> HostConfig {
let port_bindings: PortMap = self.ports.iter().fold(
HashMap::new(),
|mut acc, (host_port, container_port)| {
let container_port = container_port.to_string();
let binding = PortBinding {
host_ip: None,
host_port: Some(host_port.to_string()),
};
acc.entry(container_port)
.and_modify(|bindings| {
if let Some(vec) = bindings {
vec.push(binding.clone());
}
})
.or_insert(Some(vec![binding]));
acc
},
);
let extra_hosts = self
.hosts
.iter()
.map(|(host, ip)| format!("{}:{}", host, ip.to_string()))
.collect::<Vec<_>>();
let mut config = HostConfig::default();
if !port_bindings.is_empty() {
config.port_bindings = Some(port_bindings);
}
if !extra_hosts.is_empty() {
config.extra_hosts = Some(extra_hosts);
}
config
}

// Check if the ports use the exposed container ports from the image if any
fn all_container_ports_are_exposed(&self) -> Result<()> {
let exposed_ports: HashSet<&u16> = self.image.exposed_ports().iter().collect();
if exposed_ports.is_empty() {
return Ok(());
}
let all_ports_are_exposed =
self.ports.values().all(|port| exposed_ports.contains(port));
if !all_ports_are_exposed {
return Err(anyhow::anyhow!("Invalid ports"));
}
Ok(())
}
}

#[cfg(test)]
Expand Down Expand Up @@ -253,72 +155,4 @@ mod test {
vec![(5000, 3000)].into_iter().collect()
);
}

#[test]
fn parses_env() {
let image = GenericImage::new("busybox");
let runnable_image =
RunnableImage::new(image, "busybox_test").with_env_var("KEY", "VALUE");
let env: Option<Vec<String>> = runnable_image.env();
assert_eq!(env, Some(vec!["KEY=VALUE".to_string()]));
}

#[test]
fn parses_entrypoint() {
let image = GenericImage::new("busybox").with_entrypoint("echo hello");
let runnable_image = RunnableImage::new(image, "busybox_test");
let entrypoint: Option<Vec<String>> = runnable_image.entrypoint();
assert_eq!(
entrypoint,
Some(vec!["echo".to_string(), "hello".to_string()])
);
}

#[test]
fn parses_host_config() {
let image = GenericImage::new("busybox");
let runnable_image = RunnableImage::new(image, "busybox_test")
.with_host("hostname", Host::HostGateway)
.with_port(4000, 3000)
.with_port(5000, 3000);
let host_config = runnable_image.host_config();
assert_eq!(
host_config.extra_hosts,
Some(vec!["hostname:host-gateway".to_string()])
);

let port_bindings = host_config.port_bindings.expect("port bindings not found");
assert_eq!(
port_bindings.get("3000").unwrap(),
&Some(vec![
PortBinding {
host_ip: None,
host_port: Some("4000".to_string())
},
PortBinding {
host_ip: None,
host_port: Some("5000".to_string())
}
])
);
}

#[test]
fn throws_invalid_ports() {
let image = GenericImage::new("busybox").with_exposed_ports(&[3000]);
let runnable_image =
RunnableImage::new(image, "busybox_test").with_port(3001, 3001);
let result = runnable_image.all_container_ports_are_exposed();
assert!(result.is_err());
}

#[test]
fn validates_ports() {
let image = GenericImage::new("busybox").with_exposed_ports(&[3000, 4000]);
let runnable_image = RunnableImage::new(image, "busybox_test")
.with_port(3000, 3000)
.with_port(3000, 4000);
let result = runnable_image.all_container_ports_are_exposed();
assert!(result.is_ok());
}
}

0 comments on commit 8a664b6

Please sign in to comment.