lmrc-docker 0.3.16

Docker client library for the LMRC Stack - ergonomic fluent APIs for containers, images, networks, volumes, and registry management
Documentation
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Container builder for ergonomic container creation.

use crate::DockerClient;
use crate::containers::ContainerRef;
use crate::error::{DockerError, Result};
use bollard::container::*;
use bollard::models::{
    ContainerCreateBody, EndpointSettings, HostConfig, NetworkingConfig, PortBinding,
};
use std::collections::HashMap;
use tracing::info;

/// Builder for creating containers with a fluent API.
pub struct ContainerBuilder<'a> {
    client: &'a DockerClient,
    image: String,
    name: Option<String>,
    config: ContainerCreateBody,
    host_config: HostConfig,
}

impl<'a> ContainerBuilder<'a> {
    pub(crate) fn new(client: &'a DockerClient, image: impl Into<String>) -> Self {
        let image = image.into();
        Self {
            client,
            config: ContainerCreateBody {
                image: Some(image.clone()),
                ..Default::default()
            },
            host_config: HostConfig::default(),
            name: None,
            image,
        }
    }

    /// Set the container name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Add an environment variable.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use lmrc_docker::DockerClient;
    /// # async fn example(client: &DockerClient) -> Result<(), Box<dyn std::error::Error>> {
    /// client.containers()
    ///     .create("nginx:latest")
    ///     .env("ENV", "production")
    ///     .env("DEBUG", "false")
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let env_var = format!("{}={}", key.into(), value.into());
        if let Some(ref mut env) = self.config.env {
            env.push(env_var);
        } else {
            self.config.env = Some(vec![env_var]);
        }
        self
    }

    /// Map a port from host to container.
    ///
    /// # Arguments
    ///
    /// * `host_port` - Port on the host
    /// * `container_port` - Port in the container
    /// * `protocol` - Protocol ("tcp" or "udp")
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use lmrc_docker::DockerClient;
    /// # async fn example(client: &DockerClient) -> Result<(), Box<dyn std::error::Error>> {
    /// client.containers()
    ///     .create("nginx:latest")
    ///     .port(8080, 80, "tcp")
    ///     .port(8443, 443, "tcp")
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn port(mut self, host_port: u16, container_port: u16, protocol: &str) -> Self {
        // Add exposed port
        let port_key = format!("{}/{}", container_port, protocol);
        if let Some(ref mut exposed_ports) = self.config.exposed_ports {
            exposed_ports.insert(port_key.clone(), HashMap::new());
        } else {
            let mut exposed = HashMap::new();
            exposed.insert(port_key.clone(), HashMap::new());
            self.config.exposed_ports = Some(exposed);
        }

        // Add port binding
        let binding = vec![PortBinding {
            host_ip: Some("0.0.0.0".to_string()),
            host_port: Some(host_port.to_string()),
        }];

        if let Some(ref mut port_bindings) = self.host_config.port_bindings {
            port_bindings.insert(port_key, Some(binding));
        } else {
            let mut bindings = HashMap::new();
            bindings.insert(port_key, Some(binding));
            self.host_config.port_bindings = Some(bindings);
        }

        self
    }

    /// Mount a volume.
    ///
    /// # Arguments
    ///
    /// * `host_path` - Path on the host
    /// * `container_path` - Path in the container
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use lmrc_docker::DockerClient;
    /// # async fn example(client: &DockerClient) -> Result<(), Box<dyn std::error::Error>> {
    /// client.containers()
    ///     .create("nginx:latest")
    ///     .volume("/host/data", "/app/data")
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn volume(
        mut self,
        host_path: impl Into<String>,
        container_path: impl Into<String>,
    ) -> Self {
        let binding = format!("{}:{}", host_path.into(), container_path.into());
        if let Some(ref mut binds) = self.host_config.binds {
            binds.push(binding);
        } else {
            self.host_config.binds = Some(vec![binding]);
        }
        self
    }

    /// Connect to a network.
    pub fn network(mut self, network: impl Into<String>) -> Self {
        let network = network.into();
        let endpoint_config = EndpointSettings::default();

        let mut endpoints = HashMap::new();
        endpoints.insert(network, endpoint_config);

        if let Some(ref mut networking_config) = self.config.networking_config {
            if let Some(ref mut endpoints_config) = networking_config.endpoints_config {
                endpoints_config.extend(endpoints);
            } else {
                networking_config.endpoints_config = Some(endpoints);
            }
        } else {
            self.config.networking_config = Some(NetworkingConfig {
                endpoints_config: Some(endpoints),
            });
        }

        self
    }

    /// Set the command to run in the container.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use lmrc_docker::DockerClient;
    /// # async fn example(client: &DockerClient) -> Result<(), Box<dyn std::error::Error>> {
    /// client.containers()
    ///     .create("alpine:latest")
    ///     .cmd(vec!["echo", "hello"])
    ///     .build()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn cmd(mut self, cmd: Vec<impl Into<String>>) -> Self {
        self.config.cmd = Some(cmd.into_iter().map(|s| s.into()).collect());
        self
    }

    /// Set the entrypoint.
    pub fn entrypoint(mut self, entrypoint: Vec<impl Into<String>>) -> Self {
        self.config.entrypoint = Some(entrypoint.into_iter().map(|s| s.into()).collect());
        self
    }

    /// Set the working directory.
    pub fn working_dir(mut self, dir: impl Into<String>) -> Self {
        self.config.working_dir = Some(dir.into());
        self
    }

    /// Set the restart policy to "always".
    pub fn restart_always(mut self) -> Self {
        self.host_config.restart_policy = Some(bollard::models::RestartPolicy {
            name: Some(bollard::models::RestartPolicyNameEnum::ALWAYS),
            maximum_retry_count: None,
        });
        self
    }

    /// Set the restart policy to "unless-stopped".
    pub fn restart_unless_stopped(mut self) -> Self {
        self.host_config.restart_policy = Some(bollard::models::RestartPolicy {
            name: Some(bollard::models::RestartPolicyNameEnum::UNLESS_STOPPED),
            maximum_retry_count: None,
        });
        self
    }

    /// Set the restart policy to "on-failure" with optional retry count.
    pub fn restart_on_failure(mut self, max_retries: Option<i64>) -> Self {
        self.host_config.restart_policy = Some(bollard::models::RestartPolicy {
            name: Some(bollard::models::RestartPolicyNameEnum::ON_FAILURE),
            maximum_retry_count: max_retries,
        });
        self
    }

    /// Set memory limit in bytes.
    pub fn memory(mut self, bytes: i64) -> Self {
        self.host_config.memory = Some(bytes);
        self
    }

    /// Set CPU shares (relative weight).
    pub fn cpu_shares(mut self, shares: i64) -> Self {
        self.host_config.cpu_shares = Some(shares);
        self
    }

    /// Add a label.
    pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        if self.config.labels.is_none() {
            self.config.labels = Some(HashMap::new());
        }
        if let Some(ref mut labels) = self.config.labels {
            labels.insert(key.into(), value.into());
        }
        self
    }

    /// Enable auto-remove (container is deleted when it stops).
    pub fn auto_remove(mut self, enable: bool) -> Self {
        self.host_config.auto_remove = Some(enable);
        self
    }

    /// Enable privileged mode.
    pub fn privileged(mut self, enable: bool) -> Self {
        self.host_config.privileged = Some(enable);
        self
    }

    /// Build and create the container.
    ///
    /// Returns a [`ContainerRef`] that can be used to interact with the container.
    pub async fn build(self) -> Result<ContainerRef<'a>> {
        info!("Creating container from image: {}", self.image);

        let options = CreateContainerOptions {
            name: self.name.as_deref().unwrap_or(""),
            platform: None,
        };

        let config = ContainerCreateBody {
            host_config: Some(self.host_config),
            ..self.config
        };

        let response = self
            .client
            .docker
            .create_container(Some(options), config)
            .await
            .map_err(|e| {
                DockerError::ContainerOperationFailed(format!("Failed to create: {}", e))
            })?;

        info!("Container created with ID: {}", response.id);

        Ok(ContainerRef::new(self.client, response.id))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_env() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest")
            .env("KEY1", "value1")
            .env("KEY2", "value2");

        assert_eq!(builder.config.env.as_ref().unwrap().len(), 2);
        assert!(
            builder
                .config
                .env
                .as_ref()
                .unwrap()
                .contains(&"KEY1=value1".to_string())
        );
        assert!(
            builder
                .config
                .env
                .as_ref()
                .unwrap()
                .contains(&"KEY2=value2".to_string())
        );
    }

    #[test]
    fn test_builder_name() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest").name("test-container");

        assert_eq!(builder.name, Some("test-container".to_string()));
    }

    #[test]
    fn test_builder_port() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "nginx:latest").port(8080, 80, "tcp");

        assert!(builder.config.exposed_ports.is_some());
        assert!(builder.host_config.port_bindings.is_some());

        let bindings = builder.host_config.port_bindings.as_ref().unwrap();
        assert!(bindings.contains_key("80/tcp"));
    }

    #[test]
    fn test_builder_volume() {
        let client = DockerClient::new().unwrap();
        let builder =
            ContainerBuilder::new(&client, "alpine:latest").volume("/host/path", "/container/path");

        assert!(builder.host_config.binds.is_some());
        let binds = builder.host_config.binds.as_ref().unwrap();
        assert_eq!(binds.len(), 1);
        assert_eq!(binds[0], "/host/path:/container/path");
    }

    #[test]
    fn test_builder_cmd() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest").cmd(vec!["echo", "hello"]);

        assert!(builder.config.cmd.is_some());
        let cmd = builder.config.cmd.as_ref().unwrap();
        assert_eq!(cmd.len(), 2);
        assert_eq!(cmd[0], "echo");
        assert_eq!(cmd[1], "hello");
    }

    #[test]
    fn test_builder_working_dir() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest").working_dir("/app");

        assert_eq!(builder.config.working_dir, Some("/app".to_string()));
    }

    #[test]
    fn test_builder_restart_policies() {
        let client = DockerClient::new().unwrap();

        let builder_always = ContainerBuilder::new(&client, "alpine:latest").restart_always();
        assert!(builder_always.host_config.restart_policy.is_some());

        let builder_unless =
            ContainerBuilder::new(&client, "alpine:latest").restart_unless_stopped();
        assert!(builder_unless.host_config.restart_policy.is_some());

        let builder_failure =
            ContainerBuilder::new(&client, "alpine:latest").restart_on_failure(Some(5));
        assert!(builder_failure.host_config.restart_policy.is_some());
        assert_eq!(
            builder_failure
                .host_config
                .restart_policy
                .as_ref()
                .unwrap()
                .maximum_retry_count,
            Some(5)
        );
    }

    #[test]
    fn test_builder_memory() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest").memory(512 * 1024 * 1024);

        assert_eq!(builder.host_config.memory, Some(512 * 1024 * 1024));
    }

    #[test]
    fn test_builder_cpu_shares() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest").cpu_shares(512);

        assert_eq!(builder.host_config.cpu_shares, Some(512));
    }

    #[test]
    fn test_builder_labels() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest")
            .label("env", "test")
            .label("version", "1.0");

        assert!(builder.config.labels.is_some());
        let labels = builder.config.labels.as_ref().unwrap();
        assert_eq!(labels.get("env"), Some(&"test".to_string()));
        assert_eq!(labels.get("version"), Some(&"1.0".to_string()));
    }

    #[test]
    fn test_builder_auto_remove() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest").auto_remove(true);

        assert_eq!(builder.host_config.auto_remove, Some(true));
    }

    #[test]
    fn test_builder_privileged() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "alpine:latest").privileged(true);

        assert_eq!(builder.host_config.privileged, Some(true));
    }

    #[test]
    fn test_builder_chaining() {
        let client = DockerClient::new().unwrap();
        let builder = ContainerBuilder::new(&client, "nginx:latest")
            .name("web-server")
            .env("ENV", "production")
            .port(8080, 80, "tcp")
            .volume("/data", "/app/data")
            .memory(512 * 1024 * 1024)
            .restart_always()
            .label("app", "web");

        assert_eq!(builder.name, Some("web-server".to_string()));
        assert!(builder.config.env.is_some());
        assert!(builder.config.exposed_ports.is_some());
        assert!(builder.host_config.binds.is_some());
        assert!(builder.host_config.memory.is_some());
        assert!(builder.host_config.restart_policy.is_some());
        assert!(builder.config.labels.is_some());
    }
}