Skip to content
Merged
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
20 changes: 15 additions & 5 deletions testcontainers/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ rustdoc-args = ["--cfg", "docsrs"]

[dependencies]
async-trait = { version = "0.1" }
bollard = { version = "0.19.1"}
bollard = { version = "0.19.1", features = ["buildkit"] }
bollard-stubs = "=1.48.3-rc.28.0.4"
bytes = "1.6.0"
conquer-once = { version = "0.4", optional = true }
Expand All @@ -29,7 +29,14 @@ log = "0.4"
memchr = "2.7.2"
parse-display = "0.9.0"
pin-project-lite = "0.2.14"
reqwest = { version = "0.12.5", features = ["rustls-tls", "rustls-tls-native-roots", "hickory-dns", "json", "charset", "http2"], default-features = false, optional = true }
reqwest = { version = "0.12.5", features = [
"rustls-tls",
"rustls-tls-native-roots",
"hickory-dns",
"json",
"charset",
"http2",
], default-features = false, optional = true }
serde = { version = "1", features = ["derive"] }
serde-java-properties = { version = "0.2.0", optional = true }
serde_json = "1"
Expand All @@ -40,7 +47,7 @@ tokio = { version = "1", features = ["macros", "fs", "rt-multi-thread"] }
tokio-stream = "0.1.15"
tokio-tar = "0.3.1"
tokio-util = { version = "0.7.10", features = ["io"] }
ulid = { version = "1.1.3", optional = true }
ulid = { version = "1.1.3" }
url = { version = "2", features = ["serde"] }

[features]
Expand All @@ -52,12 +59,15 @@ blocking = []
watchdog = ["signal-hook", "conquer-once"]
http_wait = ["reqwest"]
properties-config = ["serde-java-properties"]
reusable-containers = ["dep:ulid"]
reusable-containers = []

[dev-dependencies]
anyhow = "1.0.86"
pretty_env_logger = "0.5"
reqwest = { version = "0.12.4", features = ["blocking"], default-features = false }
reqwest = { version = "0.12.4", features = [
"blocking",
], default-features = false }
temp-dir = "0.1.13"
tempfile = "3.20"
testimages.workspace = true
tokio = { version = "1", features = ["macros"] }
59 changes: 59 additions & 0 deletions testcontainers/src/buildables/generic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use std::path::PathBuf;

use crate::{
core::{copy::CopyToContainerCollection, BuildContextBuilder},
BuildableImage, GenericImage,
};

#[derive(Debug)]
pub struct GenericBuildableImage {
name: String,
tag: String,
build_context_builder: BuildContextBuilder,
}

impl GenericBuildableImage {
pub fn new(name: impl Into<String>, tag: impl Into<String>) -> Self {
Self {
name: name.into(),
tag: tag.into(),
build_context_builder: BuildContextBuilder::default(),
}
}

pub fn with_dockerfile(mut self, source: impl Into<PathBuf>) -> Self {
self.build_context_builder = self.build_context_builder.with_dockerfile(source);
self
}

pub fn with_dockerfile_string(mut self, content: impl Into<String>) -> Self {
self.build_context_builder = self.build_context_builder.with_dockerfile_string(content);
self
}

pub fn with_file(mut self, source: impl Into<PathBuf>, target: impl Into<String>) -> Self {
self.build_context_builder = self.build_context_builder.with_file(source, target);
self
}

pub fn with_data(mut self, data: impl Into<Vec<u8>>, target: impl Into<String>) -> Self {
self.build_context_builder = self.build_context_builder.with_data(data, target);
self
}
}

impl BuildableImage for GenericBuildableImage {
type Built = GenericImage;

fn build_context(&self) -> CopyToContainerCollection {
self.build_context_builder.as_copy_to_container_collection()
}

fn descriptor(&self) -> String {
format!("{}:{}", self.name, self.tag)
}

fn into_image(self) -> Self::Built {
GenericImage::new(&self.name, &self.tag)
}
}
1 change: 1 addition & 0 deletions testcontainers/src/buildables/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod generic;
5 changes: 5 additions & 0 deletions testcontainers/src/core.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
#[cfg(feature = "reusable-containers")]
pub use self::image::ReuseDirective;
pub use self::{
build_context::BuildContextBuilder,
buildable::BuildableImage,
containers::*,
copy::{CopyDataSource, CopyToContainer, CopyToContainerCollection, CopyToContainerError},
healthcheck::Healthcheck,
image::{ContainerState, ExecCommand, Image, ImageExt},
mounts::{AccessMode, Mount, MountType},
ports::{ContainerPort, IntoContainerPort},
wait::{cmd_wait::CmdWaitFor, WaitFor},
};

mod buildable;
mod image;

pub(crate) mod async_drop;
pub(crate) mod build_context;
pub mod client;
pub(crate) mod containers;
pub(crate) mod copy;
Expand Down
38 changes: 38 additions & 0 deletions testcontainers/src/core/build_context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use std::path::PathBuf;

use crate::{core::copy::CopyToContainerCollection, CopyToContainer};

#[derive(Debug, Default, Clone)]
pub struct BuildContextBuilder {
build_context_parts: Vec<CopyToContainer>,
}

impl BuildContextBuilder {
pub fn with_dockerfile(self, source: impl Into<PathBuf>) -> Self {
self.with_file(source.into(), "Dockerfile")
}

pub fn with_dockerfile_string(self, content: impl Into<String>) -> Self {
self.with_data(content.into(), "Dockerfile")
}

pub fn with_file(mut self, source: impl Into<PathBuf>, target: impl Into<String>) -> Self {
self.build_context_parts
.push(CopyToContainer::new(source.into(), target));
self
}

pub fn with_data(mut self, data: impl Into<Vec<u8>>, target: impl Into<String>) -> Self {
self.build_context_parts
.push(CopyToContainer::new(data.into(), target));
self
}

pub fn collect(self) -> CopyToContainerCollection {
CopyToContainerCollection::new(self.build_context_parts)
}

pub fn as_copy_to_container_collection(&self) -> CopyToContainerCollection {
CopyToContainerCollection::new(self.build_context_parts.clone())
}
}
10 changes: 10 additions & 0 deletions testcontainers/src/core/buildable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use crate::{core::copy::CopyToContainerCollection, Image};

pub trait BuildableImage {
type Built: Image;

fn build_context(&self) -> CopyToContainerCollection;
fn descriptor(&self) -> String;

fn into_image(self) -> Self::Built;
}
67 changes: 59 additions & 8 deletions testcontainers/src/core/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ use bollard::{
exec::{CreateExecOptions, StartExecOptions, StartExecResults},
models::{ContainerCreateBody, NetworkCreateRequest},
query_parameters::{
CreateContainerOptions, CreateImageOptionsBuilder, InspectContainerOptions,
InspectContainerOptionsBuilder, InspectNetworkOptions, InspectNetworkOptionsBuilder,
ListContainersOptionsBuilder, ListNetworksOptions, LogsOptionsBuilder,
RemoveContainerOptionsBuilder, StartContainerOptions, StopContainerOptionsBuilder,
UploadToContainerOptionsBuilder,
BuildImageOptionsBuilder, BuilderVersion, CreateContainerOptions,
CreateImageOptionsBuilder, InspectContainerOptions, InspectContainerOptionsBuilder,
InspectNetworkOptions, InspectNetworkOptionsBuilder, ListContainersOptionsBuilder,
ListNetworksOptions, LogsOptionsBuilder, RemoveContainerOptionsBuilder,
StartContainerOptions, StopContainerOptionsBuilder, UploadToContainerOptionsBuilder,
},
Docker,
};
Expand All @@ -27,9 +27,8 @@ use url::Url;

use crate::core::{
client::exec::ExecResult,
copy::{CopyToContainer, CopyToContainerError},
env,
env::ConfigurationError,
copy::{CopyToContainer, CopyToContainerCollection, CopyToContainerError},
env::{self, ConfigurationError},
logs::{
stream::{LogStream, RawLogStream},
LogFrame, LogSource, WaitingStreamWrapper,
Expand Down Expand Up @@ -68,6 +67,11 @@ pub enum ClientError {
descriptor: String,
err: BollardError,
},
#[error("failed to build the image '{descriptor}', error: {err}")]
BuildImage {
descriptor: String,
err: BollardError,
},
#[error("failed to map ports: {0}")]
PortMapping(#[from] PortMappingError),

Expand Down Expand Up @@ -394,6 +398,53 @@ impl Client {
Ok(state.exit_code)
}

pub(crate) async fn build_image(
&self,
descriptor: &str,
build_context: &CopyToContainerCollection,
) -> Result<(), ClientError> {
let tar = build_context
.tar()
.await
.map_err(ClientError::CopyToContainerError)?;

let session = ulid::Ulid::new().to_string();

let options = BuildImageOptionsBuilder::new()
.dockerfile("Dockerfile")
.t(descriptor)
.rm(true)
.nocache(false)
.version(BuilderVersion::BuilderBuildKit)
.session(&session)
.build();

let credentials = None;

let mut building = self
.bollard
.build_image(options, credentials, Some(body_full(tar)));

while let Some(result) = building.next().await {
match result {
Ok(r) => {
if let Some(s) = r.stream {
log::info!("{}", s);
}
}
Err(err) => {
log::error!("{:?}", err);
return Err(ClientError::BuildImage {
descriptor: descriptor.into(),
err,
});
}
};
}

Ok(())
}

pub(crate) async fn pull_image(&self, descriptor: &str) -> Result<(), ClientError> {
let pull_options = CreateImageOptionsBuilder::new()
.from_image(descriptor)
Expand Down
Loading
Loading