docker-wrapper 0.11.1

A Docker CLI wrapper for Rust
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Docker update command implementation.
//!
//! This module provides the `docker update` command for updating container configurations.

use super::{CommandExecutor, CommandOutput, DockerCommand};
use crate::error::Result;
use async_trait::async_trait;

/// Docker update command builder
///
/// Update configuration of one or more containers.
///
/// # Example
///
/// ```no_run
/// use docker_wrapper::UpdateCommand;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Update memory limit
/// let result = UpdateCommand::new("my-container")
///     .memory("512m")
///     .run()
///     .await?;
///
/// if result.success() {
///     println!("Container updated successfully");
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct UpdateCommand {
    /// Container names or IDs to update
    containers: Vec<String>,
    /// Memory limit
    memory: Option<String>,
    /// Memory reservation (soft limit)
    memory_reservation: Option<String>,
    /// Memory swap limit
    memory_swap: Option<String>,
    /// CPU shares (relative weight)
    cpu_shares: Option<u64>,
    /// CPU period
    cpu_period: Option<u64>,
    /// CPU quota
    cpu_quota: Option<i64>,
    /// CPUs (number of CPUs)
    cpus: Option<String>,
    /// CPU set
    cpuset_cpus: Option<String>,
    /// Memory nodes
    cpuset_mems: Option<String>,
    /// Block IO weight
    blkio_weight: Option<u16>,
    /// Kernel memory limit
    kernel_memory: Option<String>,
    /// Restart policy
    restart: Option<String>,
    /// PID limit
    pids_limit: Option<i64>,
    /// Command executor
    pub executor: CommandExecutor,
}

impl UpdateCommand {
    /// Create a new update command for a single container
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container");
    /// ```
    #[must_use]
    pub fn new(container: impl Into<String>) -> Self {
        Self {
            containers: vec![container.into()],
            memory: None,
            memory_reservation: None,
            memory_swap: None,
            cpu_shares: None,
            cpu_period: None,
            cpu_quota: None,
            cpus: None,
            cpuset_cpus: None,
            cpuset_mems: None,
            blkio_weight: None,
            kernel_memory: None,
            restart: None,
            pids_limit: None,
            executor: CommandExecutor::new(),
        }
    }

    /// Create a new update command for multiple containers
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new_multiple(vec!["web", "db", "cache"]);
    /// ```
    #[must_use]
    pub fn new_multiple(containers: Vec<impl Into<String>>) -> Self {
        Self {
            containers: containers.into_iter().map(Into::into).collect(),
            memory: None,
            memory_reservation: None,
            memory_swap: None,
            cpu_shares: None,
            cpu_period: None,
            cpu_quota: None,
            cpus: None,
            cpuset_cpus: None,
            cpuset_mems: None,
            blkio_weight: None,
            kernel_memory: None,
            restart: None,
            pids_limit: None,
            executor: CommandExecutor::new(),
        }
    }

    /// Add another container to update
    #[must_use]
    pub fn container(mut self, container: impl Into<String>) -> Self {
        self.containers.push(container.into());
        self
    }

    /// Set memory limit
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .memory("512m");
    /// ```
    #[must_use]
    pub fn memory(mut self, memory: impl Into<String>) -> Self {
        self.memory = Some(memory.into());
        self
    }

    /// Set memory reservation (soft limit)
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .memory_reservation("256m");
    /// ```
    #[must_use]
    pub fn memory_reservation(mut self, memory_reservation: impl Into<String>) -> Self {
        self.memory_reservation = Some(memory_reservation.into());
        self
    }

    /// Set memory swap limit
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .memory_swap("1g");
    /// ```
    #[must_use]
    pub fn memory_swap(mut self, memory_swap: impl Into<String>) -> Self {
        self.memory_swap = Some(memory_swap.into());
        self
    }

    /// Set CPU shares (relative weight)
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .cpu_shares(512);
    /// ```
    #[must_use]
    pub fn cpu_shares(mut self, cpu_shares: u64) -> Self {
        self.cpu_shares = Some(cpu_shares);
        self
    }

    /// Set CPU period
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .cpu_period(100_000);
    /// ```
    #[must_use]
    pub fn cpu_period(mut self, cpu_period: u64) -> Self {
        self.cpu_period = Some(cpu_period);
        self
    }

    /// Set CPU quota
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .cpu_quota(50000);
    /// ```
    #[must_use]
    pub fn cpu_quota(mut self, cpu_quota: i64) -> Self {
        self.cpu_quota = Some(cpu_quota);
        self
    }

    /// Set number of CPUs
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .cpus("1.5");
    /// ```
    #[must_use]
    pub fn cpus(mut self, cpus: impl Into<String>) -> Self {
        self.cpus = Some(cpus.into());
        self
    }

    /// Set CPU set
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .cpuset_cpus("0,1");
    /// ```
    #[must_use]
    pub fn cpuset_cpus(mut self, cpuset_cpus: impl Into<String>) -> Self {
        self.cpuset_cpus = Some(cpuset_cpus.into());
        self
    }

    /// Set memory nodes
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .cpuset_mems("0");
    /// ```
    #[must_use]
    pub fn cpuset_mems(mut self, cpuset_mems: impl Into<String>) -> Self {
        self.cpuset_mems = Some(cpuset_mems.into());
        self
    }

    /// Set block IO weight
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .blkio_weight(500);
    /// ```
    #[must_use]
    pub fn blkio_weight(mut self, blkio_weight: u16) -> Self {
        self.blkio_weight = Some(blkio_weight);
        self
    }

    /// Set kernel memory limit
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .kernel_memory("128m");
    /// ```
    #[must_use]
    pub fn kernel_memory(mut self, kernel_memory: impl Into<String>) -> Self {
        self.kernel_memory = Some(kernel_memory.into());
        self
    }

    /// Set restart policy
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .restart("unless-stopped");
    /// ```
    #[must_use]
    pub fn restart(mut self, restart: impl Into<String>) -> Self {
        self.restart = Some(restart.into());
        self
    }

    /// Set PID limit
    ///
    /// # Example
    ///
    /// ```
    /// use docker_wrapper::UpdateCommand;
    ///
    /// let cmd = UpdateCommand::new("my-container")
    ///     .pids_limit(100);
    /// ```
    #[must_use]
    pub fn pids_limit(mut self, pids_limit: i64) -> Self {
        self.pids_limit = Some(pids_limit);
        self
    }

    /// Execute the update command
    ///
    /// # Errors
    /// Returns an error if:
    /// - The Docker daemon is not running
    /// - Any of the specified containers don't exist
    /// - Invalid resource limits are specified
    ///
    /// # Example
    ///
    /// ```no_run
    /// use docker_wrapper::UpdateCommand;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let result = UpdateCommand::new("my-container")
    ///     .memory("1g")
    ///     .cpu_shares(512)
    ///     .run()
    ///     .await?;
    ///
    /// if result.success() {
    ///     println!("Updated containers: {:?}", result.containers());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run(&self) -> Result<UpdateResult> {
        let output = self.execute().await?;

        Ok(UpdateResult {
            output,
            containers: self.containers.clone(),
        })
    }
}

#[async_trait]
impl DockerCommand for UpdateCommand {
    type Output = CommandOutput;

    fn build_command_args(&self) -> Vec<String> {
        let mut args = vec!["update".to_string()];

        if let Some(ref memory) = self.memory {
            args.push("--memory".to_string());
            args.push(memory.clone());
        }

        if let Some(ref memory_reservation) = self.memory_reservation {
            args.push("--memory-reservation".to_string());
            args.push(memory_reservation.clone());
        }

        if let Some(ref memory_swap) = self.memory_swap {
            args.push("--memory-swap".to_string());
            args.push(memory_swap.clone());
        }

        if let Some(cpu_shares) = self.cpu_shares {
            args.push("--cpu-shares".to_string());
            args.push(cpu_shares.to_string());
        }

        if let Some(cpu_period) = self.cpu_period {
            args.push("--cpu-period".to_string());
            args.push(cpu_period.to_string());
        }

        if let Some(cpu_quota) = self.cpu_quota {
            args.push("--cpu-quota".to_string());
            args.push(cpu_quota.to_string());
        }

        if let Some(ref cpus) = self.cpus {
            args.push("--cpus".to_string());
            args.push(cpus.clone());
        }

        if let Some(ref cpuset_cpus) = self.cpuset_cpus {
            args.push("--cpuset-cpus".to_string());
            args.push(cpuset_cpus.clone());
        }

        if let Some(ref cpuset_mems) = self.cpuset_mems {
            args.push("--cpuset-mems".to_string());
            args.push(cpuset_mems.clone());
        }

        if let Some(blkio_weight) = self.blkio_weight {
            args.push("--blkio-weight".to_string());
            args.push(blkio_weight.to_string());
        }

        if let Some(ref kernel_memory) = self.kernel_memory {
            args.push("--kernel-memory".to_string());
            args.push(kernel_memory.clone());
        }

        if let Some(ref restart) = self.restart {
            args.push("--restart".to_string());
            args.push(restart.clone());
        }

        if let Some(pids_limit) = self.pids_limit {
            args.push("--pids-limit".to_string());
            args.push(pids_limit.to_string());
        }

        args.extend(self.containers.clone());
        args.extend(self.executor.raw_args.clone());
        args
    }

    fn get_executor(&self) -> &CommandExecutor {
        &self.executor
    }

    fn get_executor_mut(&mut self) -> &mut CommandExecutor {
        &mut self.executor
    }

    async fn execute(&self) -> Result<Self::Output> {
        if self.containers.is_empty() {
            return Err(crate::error::Error::invalid_config(
                "No containers specified for update",
            ));
        }

        let args = self.build_command_args();
        let command_name = args[0].clone();
        let command_args = args[1..].to_vec();
        self.executor
            .execute_command(&command_name, command_args)
            .await
    }
}

/// Result from the update command
#[derive(Debug, Clone)]
pub struct UpdateResult {
    /// Raw command output
    pub output: CommandOutput,
    /// Containers that were updated
    pub containers: Vec<String>,
}

impl UpdateResult {
    /// Check if the update was successful
    #[must_use]
    pub fn success(&self) -> bool {
        self.output.success
    }

    /// Get the updated container names
    #[must_use]
    pub fn containers(&self) -> &[String] {
        &self.containers
    }

    /// Get the raw command output
    #[must_use]
    pub fn output(&self) -> &CommandOutput {
        &self.output
    }

    /// Get container count
    #[must_use]
    pub fn container_count(&self) -> usize {
        self.containers.len()
    }
}

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

    #[test]
    fn test_update_single_container() {
        let cmd = UpdateCommand::new("test-container");
        let args = cmd.build_command_args();
        assert_eq!(args, vec!["update", "test-container"]);
    }

    #[test]
    fn test_update_multiple_containers() {
        let cmd = UpdateCommand::new_multiple(vec!["web", "db", "cache"]);
        let args = cmd.build_command_args();
        assert_eq!(args, vec!["update", "web", "db", "cache"]);
    }

    #[test]
    fn test_update_add_container() {
        let cmd = UpdateCommand::new("web").container("db").container("cache");
        let args = cmd.build_command_args();
        assert_eq!(args, vec!["update", "web", "db", "cache"]);
    }

    #[test]
    fn test_update_memory_options() {
        let cmd = UpdateCommand::new("test-container")
            .memory("512m")
            .memory_reservation("256m")
            .memory_swap("1g");
        let args = cmd.build_command_args();
        assert_eq!(
            args,
            vec![
                "update",
                "--memory",
                "512m",
                "--memory-reservation",
                "256m",
                "--memory-swap",
                "1g",
                "test-container"
            ]
        );
    }

    #[test]
    fn test_update_cpu_options() {
        let cmd = UpdateCommand::new("test-container")
            .cpu_shares(512)
            .cpu_period(100_000)
            .cpu_quota(50000)
            .cpus("1.5")
            .cpuset_cpus("0,1")
            .cpuset_mems("0");
        let args = cmd.build_command_args();
        assert_eq!(
            args,
            vec![
                "update",
                "--cpu-shares",
                "512",
                "--cpu-period",
                "100000",
                "--cpu-quota",
                "50000",
                "--cpus",
                "1.5",
                "--cpuset-cpus",
                "0,1",
                "--cpuset-mems",
                "0",
                "test-container"
            ]
        );
    }

    #[test]
    fn test_update_all_options() {
        let cmd = UpdateCommand::new("test-container")
            .memory("1g")
            .cpu_shares(1024)
            .blkio_weight(500)
            .kernel_memory("128m")
            .restart("unless-stopped")
            .pids_limit(100);
        let args = cmd.build_command_args();
        assert_eq!(
            args,
            vec![
                "update",
                "--memory",
                "1g",
                "--cpu-shares",
                "1024",
                "--blkio-weight",
                "500",
                "--kernel-memory",
                "128m",
                "--restart",
                "unless-stopped",
                "--pids-limit",
                "100",
                "test-container"
            ]
        );
    }

    #[test]
    fn test_update_result() {
        let result = UpdateResult {
            output: CommandOutput {
                stdout: "test-container".to_string(),
                stderr: String::new(),
                exit_code: 0,
                success: true,
            },
            containers: vec!["test-container".to_string()],
        };

        assert!(result.success());
        assert_eq!(result.containers(), &["test-container"]);
        assert_eq!(result.container_count(), 1);
    }
}