1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use crate::{Container, Image};
use std::{collections::HashMap, io::Read};

/// Defines the minimum API required for interacting with the Docker daemon.
pub trait Docker
where
    Self: Sized,
{
    fn run<I: Image>(&self, image: I) -> Container<'_, Self, I>;
    fn run_with_args<I: Image>(&self, image: I, run_args: RunArgs) -> Container<'_, Self, I>;
    fn logs(&self, id: &str) -> Logs;
    fn ports(&self, id: &str) -> Ports;
    fn rm(&self, id: &str);
    fn stop(&self, id: &str);
    fn start(&self, id: &str);
}

/// Container run command arguments.
/// `name` - run image instance with the given name (should be explicitly set to be seen by other containers created in the same docker network).
/// `network` - run image instance on the given network.
#[derive(Debug, Clone, Default)]
pub struct RunArgs {
    name: Option<String>,
    network: Option<String>,
}

impl RunArgs {
    pub fn with_name<T: ToString>(self, name: T) -> Self {
        RunArgs {
            name: Some(name.to_string()),
            ..self
        }
    }

    pub fn with_network<T: ToString>(self, network: T) -> Self {
        RunArgs {
            network: Some(network.to_string()),
            ..self
        }
    }

    pub(crate) fn network(&self) -> Option<String> {
        self.network.clone()
    }

    pub(crate) fn name(&self) -> Option<String> {
        self.name.clone()
    }
}

/// The exposed ports of a running container.
#[derive(Debug, PartialEq, Default)]
pub struct Ports {
    mapping: HashMap<u16, u16>,
}

impl Ports {
    /// Registers the mapping of an exposed port.
    pub fn add_mapping(&mut self, internal: u16, host: u16) -> &mut Self {
        log::debug!("Registering port mapping: {} -> {}", internal, host);

        self.mapping.insert(internal, host);

        self
    }

    /// Returns the host port for the given internal port.
    pub fn map_to_host_port(&self, internal_port: u16) -> Option<u16> {
        self.mapping.get(&internal_port).cloned()
    }
}

/// Log streams of running container (stdout & stderr).
#[derive(derivative::Derivative)]
#[derivative(Debug)]
pub struct Logs {
    #[derivative(Debug = "ignore")]
    pub stdout: Box<dyn Read>,
    #[derivative(Debug = "ignore")]
    pub stderr: Box<dyn Read>,
}