DockerUtil

Struct DockerUtil 

Source
pub struct DockerUtil { /* private fields */ }

Implementations§

Source§

impl DockerUtil

Source

pub fn new() -> Result<Self, DockerError>

Create a new instance of the DockerUtil struct.

§Returns

Returns a new instance of the DockerUtil struct with default values.

§Example
use docker_utils::{DockerUtil, ContainerConfig};
use wait_utils::WaitStrategy;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let docker = DockerUtil::new()?;
    Ok(())
}
Source

pub fn with_debug() -> Result<Self, DockerError>

Create a new instance of the DockerUtil struct with debug mode enabled.

§Returns

Returns a Result containing a new instance of the DockerUtil struct with debug mode enabled, or a DockerError if an error occurred.

§Example
use docker_utils::{DockerUtil, ContainerConfig};
use wait_utils::WaitStrategy;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let docker = DockerUtil::with_debug()?;
    Ok(())
}
Source

pub fn setup_container( &self, container_config: &ContainerConfig<'_>, ) -> Result<(String, u16), DockerError>

Sets up a Docker container based on the provided configuration, handling existence checks and version management.

§Arguments
  • container_config - Reference to a ContainerConfig containing the container configuration:
    • Container name
    • Image tag
    • Other container-specific settings
§Returns

Returns a Result<(String, u16), DockerError>:

  • Ok((container_name, port)) - A tuple containing:
    • container_name: String - The name of the running container
    • port: u16 - The exposed port number of the container
  • Err(DockerError) - If any Docker operation fails
§Example
use docker_utils::{DockerUtil, ContainerConfig};
use wait_utils::WaitStrategy;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let docker = DockerUtil::new()?;

    let config = ContainerConfig::new(
        "postgres",
        "postgres",
        "14",
        "0.0.0.0",
        5432,
        None,
        Some(&["POSTGRES_PASSWORD=secret"]),
        None,
        true,
        false,
        WaitStrategy::WaitUntilConsoleOutputContains(
            "PostgreSQL init process complete; ready for start up.".to_string(),
            15,
        ),
    );

    let (container_name, port) = docker.setup_container(&config)?;
    println!("Container {} running on port {}", container_name, port);
    Ok(())
}
§Errors

Returns a DockerError if:

  • Container existence check fails
  • Container tag verification fails
  • Container stop operation fails (when tag mismatch)
  • Container start operation fails
  • Port mapping operation fails
  • Docker API communication fails
§Panics

This function will panic if:

  • Container existence check critically fails
  • Tag verification critically fails
  • Container stop operation critically fails
  • Container setup critically fails
§Implementation Notes

This function performs the following steps:

  1. Checks if a container with the given name already exists
  2. If exists, verifies if it uses the target tag
  3. If tag mismatch, stops the existing container
  4. Creates or reuses the container with correct configuration
  5. Returns the container name and exposed port
Source

pub fn get_or_start_container( &self, container_config: &ContainerConfig<'_>, ) -> Result<(String, u16), DockerError>

Gets an existing container or starts a new one with the specified configuration

§Arguments
  • container_config - The configuration of the container.
§Returns

Returns a tuple containing the container name and port if successful, or a DockerError if an error occurs.

§Example
use docker_utils::{DockerUtil, ContainerConfig};
use wait_utils::WaitStrategy;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let docker = DockerUtil::new()?;

    let config = ContainerConfig::new(
        "redis",
        "redis",
        "latest",
        "0.0.0.0",
        6379,
        None,
        None,
        None,
        true,
        false,
        WaitStrategy::default(),
    );

    let (container_name, port) = docker.get_or_start_container(&config)?;
    println!("Redis container {} available on port {}", container_name, port);
    Ok(())
}
Source

pub fn check_if_container_is_running( &self, container_id: &str, ) -> Result<bool, DockerError>

Check if a container exists by its ID.

§Arguments
  • container_id - The ID of the container to check.
§Returns

Returns Ok(true) if the container exists, Ok(false) if the container does not exist, or Err(DockerError) if an error occurred.

§Example
use docker_utils::DockerUtil;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let docker = DockerUtil::new()?;

    let container_id = "redis-6379";  // Example container ID
    match docker.check_if_container_is_running(container_id)? {
        true => println!("Container {} is running", container_id),
        false => println!("Container {} is not running", container_id),
    }
    Ok(())
}
Source

pub fn stop_container( &self, container_id: &str, delete: bool, ) -> Result<(), DockerError>

Stop a container

§Arguments
  • container_id - The ID of the container to stop.
  • delete - Whether to delete the container after stopping.
§Returns

Returns Ok(()) if the container was successfully stopped, or Err(DockerError) if an error occurred.

§Example
use docker_utils::DockerUtil;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let docker = DockerUtil::new()?;

    let container_id = "redis-6379";  // Example container ID
    let delete_container = false;
    docker.stop_container(container_id, delete_container)?;
    println!("Container {} stopped successfully", container_id);
    Ok(())
}
Source

pub fn pull_container_image( &self, container_id: &str, image: &str, platform: Option<&str>, ) -> Result<(), DockerError>

Pulls a container image from a registry.

This method pulls a container image from a specified registry using the docker pull command.

§Arguments
  • container_id - The ID of the container to start.
  • image - The container image with tag.
  • platform - Optional platform tag, such as linux/amd64.
§Returns
  • Result<(), DockerError> - Returns Ok(()) if the image is pulled successfully, or an Err containing the error if it fails.
§Example
use docker_utils::DockerUtil;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let docker = DockerUtil::new()?;

    // Pull image for specific platform
    docker.pull_container_image(
        "nginx-container",
        "nginx:latest",
        Some("linux/amd64")
    )?;

    // Pull image without platform specification
    docker.pull_container_image(
        "redis-container",
        "redis:latest",
        None
    )?;

    Ok(())
}
§Errors

Returns a DockerError if there is an error pulling the container image.

Source

pub fn prune_all_containers(&mut self) -> Result<(), DockerError>

Prunes all stopped containers and their associated volumes and networks.

This method executes the docker system prune command with the --all and --force options to remove all stopped containers, their associated volumes, and networks.

§Returns
  • Result<(), DockerError> - Returns Ok(()) if the containers are pruned successfully, or an Err containing the error if it fails.
§Example
use docker_utils::DockerUtil;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut docker = DockerUtil::new()?;

    // Clean up all stopped containers and their resources
    docker.prune_all_containers()?;
    println!("Successfully pruned all stopped containers");
    Ok(())
}
§Errors

Returns a DockerError if there is an error executing the docker system prune command.

Source§

impl DockerUtil

Source

pub fn check_running(&self, container_id: &str) -> Result<bool, DockerError>

Check if a container is running

§Arguments
  • container_id - The ID of the container to check
§Returns

Returns Ok(true) if the container is running, Ok(false) if it is not, or an Err if an error occurred

Trait Implementations§

Source§

impl Clone for DockerUtil

Source§

fn clone(&self) -> DockerUtil

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DockerUtil

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DockerUtil

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Ord for DockerUtil

Source§

fn cmp(&self, other: &DockerUtil) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DockerUtil

Source§

fn eq(&self, other: &DockerUtil) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for DockerUtil

Source§

fn partial_cmp(&self, other: &DockerUtil) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Copy for DockerUtil

Source§

impl Eq for DockerUtil

Source§

impl StructuralPartialEq for DockerUtil

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more