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!: support UDP and SCTP port mappings #655

Merged
merged 15 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
4 changes: 2 additions & 2 deletions testcontainers/src/core/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub use exec::{CmdWaitFor, ExecCommand};
pub use runnable_image::{CgroupnsMode, Host, PortMapping, RunnableImage};
pub use wait_for::WaitFor;

use super::ports::Ports;
use super::ports::{ExposedPort, Ports};
use crate::{core::mounts::Mount, TestcontainersError};

mod exec;
Expand Down Expand Up @@ -69,7 +69,7 @@ where
///
/// This method is useful when there is a need to expose some ports, but there is
/// no `EXPOSE` instruction in the Dockerfile of an image.
fn expose_ports(&self) -> &[u16] {
fn expose_ports(&self) -> &[ExposedPort] {
&[]
}

Expand Down
12 changes: 10 additions & 2 deletions testcontainers/src/core/image/runnable_image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
core::{mounts::Mount, ContainerState, ExecCommand, WaitFor},
Image, TestcontainersError,
};
use crate::core::ports::{ExposedPort, InternetProtocol};

/// Image wrapper that allows to override some of the image properties.
#[must_use]
Expand Down Expand Up @@ -31,6 +32,7 @@ pub struct RunnableImage<I: Image> {
pub struct PortMapping {
pub local: u16,
pub internal: u16,
pub protocol: InternetProtocol
}

#[derive(parse_display::Display, Debug, Clone)]
Expand Down Expand Up @@ -127,7 +129,7 @@ impl<I: Image> RunnableImage<I> {
self.image.ready_conditions()
}

pub fn expose_ports(&self) -> &[u16] {
pub fn expose_ports(&self) -> &[ExposedPort] {
self.image.expose_ports()
}

Expand Down Expand Up @@ -298,6 +300,12 @@ impl<I: Image> From<I> for RunnableImage<I> {

impl From<(u16, u16)> for PortMapping {
fn from((local, internal): (u16, u16)) -> Self {
PortMapping { local, internal }
PortMapping { local, internal, protocol: InternetProtocol::Tcp }
}
}

impl From<(u16, u16, InternetProtocol)> for PortMapping {
fn from((local, internal, protocol): (u16, u16, InternetProtocol)) -> Self {
PortMapping { local, internal, protocol }
}
}
48 changes: 48 additions & 0 deletions testcontainers/src/core/ports.rs
estigma88 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,7 +1,31 @@
use std::{collections::HashMap, net::IpAddr, num::ParseIntError};
use std::fmt::{Display, Formatter};

use bollard_stubs::models::{PortBinding, PortMap};

#[derive(Debug, Clone, Eq, PartialEq, Copy)]
pub enum InternetProtocol {
Tcp,
Udp,
Sctp
}

impl InternetProtocol {
pub fn encode(self) -> String {
match self {
Self::Tcp => String::from("tcp"),
Self::Udp => String::from("udp"),
Self::Sctp => String::from("sctp")
}
}
}

#[derive(Debug, Clone, Copy)]
pub struct ExposedPort {
pub port: u16,
pub protocol: InternetProtocol
estigma88 marked this conversation as resolved.
Show resolved Hide resolved
}

#[derive(Debug, thiserror::Error)]
pub enum PortMappingError {
#[error("failed to parse port: {0}")]
Expand Down Expand Up @@ -105,6 +129,30 @@ impl TryFrom<PortMap> for Ports {
}
}

impl Display for ExposedPort {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.port, self.protocol)
}
}

impl Display for InternetProtocol {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.encode())
}
}
DDtKey marked this conversation as resolved.
Show resolved Hide resolved

impl From<u16> for ExposedPort {
fn from(port: u16) -> Self {
ExposedPort { port ,protocol: InternetProtocol::Tcp }
}
}

impl From<(u16, InternetProtocol)> for ExposedPort {
fn from((port, protocol): (u16, InternetProtocol)) -> Self {
ExposedPort { port, protocol }
}
}
DDtKey marked this conversation as resolved.
Show resolved Hide resolved

#[cfg(test)]
mod tests {
use bollard_stubs::models::ContainerInspectResponse;
Expand Down
9 changes: 5 additions & 4 deletions testcontainers/src/images/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
core::{mounts::Mount, WaitFor},
Image,
};
use crate::core::ports::{ExposedPort};

#[must_use]
#[derive(Debug, Clone)]
Expand All @@ -15,7 +16,7 @@ pub struct GenericImage {
wait_for: Vec<WaitFor>,
entrypoint: Option<String>,
cmd: Vec<String>,
exposed_ports: Vec<u16>,
exposed_ports: Vec<ExposedPort>,
}

impl Default for GenericImage {
Expand Down Expand Up @@ -67,8 +68,8 @@ impl GenericImage {
self
}

pub fn with_exposed_port(mut self, port: u16) -> Self {
self.exposed_ports.push(port);
pub fn with_exposed_port<P: Into<ExposedPort>>(mut self, exposed_port: P) -> Self {
self.exposed_ports.push(exposed_port.into());
self
}
}
Expand Down Expand Up @@ -104,7 +105,7 @@ impl Image for GenericImage {
self.entrypoint.as_deref()
}

fn expose_ports(&self) -> &[u16] {
fn expose_ports(&self) -> &[ExposedPort] {
&self.exposed_ports
}
}
Expand Down
9 changes: 6 additions & 3 deletions testcontainers/src/runners/async_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::{
},
ContainerAsync, Image, RunnableImage,
};
use crate::core::ports::ExposedPort;

const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(60);

Expand Down Expand Up @@ -137,15 +138,17 @@ where
if !is_container_networked {
let mapped_ports = runnable_image
.ports()
.map(|ports| ports.iter().map(|p| p.internal).collect::<Vec<_>>())
.map(|ports| ports.iter()
.map(|p| ExposedPort{ port: p.internal, protocol: p.protocol.clone() })
.collect::<Vec<_>>())
.unwrap_or_default();

let ports_to_expose = runnable_image
.expose_ports()
.iter()
.copied()
.chain(mapped_ports)
.map(|p| (format!("{p}/tcp"), HashMap::new()))
.map(|p| (format!("{p}"), HashMap::new()))
.collect();

// exposed ports of the image + mapped ports
Expand All @@ -157,7 +160,7 @@ where
let empty: Vec<_> = Vec::new();
let bindings = runnable_image.ports().unwrap_or(&empty).iter().map(|p| {
(
format!("{}/tcp", p.internal),
format!("{}", ExposedPort{ port: p.internal, protocol: p.protocol.clone() }),
Some(vec![PortBinding {
host_ip: None,
host_port: Some(p.local.to_string()),
Expand Down