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
//! Prerequisites module for Docker detection and validation.
//!
//! This module provides functionality to detect Docker installation,
//! validate version compatibility, and ensure the Docker daemon is running.

use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;
use tracing::{debug, info, warn};
use which::which;

/// Default timeout for prerequisite checks (30 seconds)
pub const DEFAULT_PREREQ_TIMEOUT: Duration = Duration::from_secs(30);

/// Docker version information
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DockerVersion {
    /// Full version string (e.g., "24.0.7")
    pub version: String,
    /// Major version number
    pub major: u32,
    /// Minor version number
    pub minor: u32,
    /// Patch version number
    pub patch: u32,
}

impl DockerVersion {
    /// Parse a Docker version string
    ///
    /// # Errors
    /// Returns `Error::ParseError` if the version string is invalid
    pub fn parse(version_str: &str) -> Result<Self> {
        let clean_version = version_str.trim().trim_start_matches('v');
        let parts: Vec<&str> = clean_version.split('.').collect();

        if parts.len() < 3 {
            return Err(Error::parse_error(format!(
                "Invalid version format: {version_str}"
            )));
        }

        let major = parts[0]
            .parse()
            .map_err(|_| Error::parse_error(format!("Invalid major version: {}", parts[0])))?;

        let minor = parts[1]
            .parse()
            .map_err(|_| Error::parse_error(format!("Invalid minor version: {}", parts[1])))?;

        let patch = parts[2]
            .parse()
            .map_err(|_| Error::parse_error(format!("Invalid patch version: {}", parts[2])))?;

        Ok(Self {
            version: clean_version.to_string(),
            major,
            minor,
            patch,
        })
    }

    /// Check if this version meets the minimum requirement
    #[must_use]
    pub fn meets_minimum(&self, minimum: &DockerVersion) -> bool {
        if self.major > minimum.major {
            return true;
        }
        if self.major == minimum.major {
            if self.minor > minimum.minor {
                return true;
            }
            if self.minor == minimum.minor && self.patch >= minimum.patch {
                return true;
            }
        }
        false
    }
}

/// Docker system information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DockerInfo {
    /// Docker version
    pub version: DockerVersion,
    /// Docker binary path
    pub binary_path: String,
    /// Whether Docker daemon is running
    pub daemon_running: bool,
    /// Docker server version (if daemon is running)
    pub server_version: Option<DockerVersion>,
    /// Operating system
    pub os: String,
    /// Architecture
    pub architecture: String,
}

/// Main prerequisites checker
pub struct DockerPrerequisites {
    /// Minimum required Docker version
    pub minimum_version: DockerVersion,
    /// Timeout for prerequisite checks
    pub timeout: Option<Duration>,
}

impl Default for DockerPrerequisites {
    fn default() -> Self {
        Self {
            minimum_version: DockerVersion {
                version: "20.10.0".to_string(),
                major: 20,
                minor: 10,
                patch: 0,
            },
            timeout: None,
        }
    }
}

impl DockerPrerequisites {
    /// Create a new prerequisites checker with custom minimum version
    #[must_use]
    pub fn new(minimum_version: DockerVersion) -> Self {
        Self {
            minimum_version,
            timeout: None,
        }
    }

    /// Set a timeout for prerequisite checks
    ///
    /// If any check takes longer than the specified duration, it will be
    /// terminated and an `Error::Timeout` will be returned.
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set a timeout in seconds for prerequisite checks
    #[must_use]
    pub fn with_timeout_secs(mut self, seconds: u64) -> Self {
        self.timeout = Some(Duration::from_secs(seconds));
        self
    }

    /// Check all Docker prerequisites
    ///
    /// # Errors
    /// Returns various `Error` variants if Docker is not found,
    /// daemon is not running, version requirements are not met, or the check times out
    pub async fn check(&self) -> Result<DockerInfo> {
        if let Some(timeout_duration) = self.timeout {
            match timeout(timeout_duration, self.check_internal()).await {
                Ok(result) => result,
                Err(_) => Err(Error::timeout(timeout_duration.as_secs())),
            }
        } else {
            self.check_internal().await
        }
    }

    /// Internal check implementation without timeout wrapper
    async fn check_internal(&self) -> Result<DockerInfo> {
        info!("Checking Docker prerequisites...");

        // Find Docker binary
        let binary_path = Self::find_docker_binary()?;
        debug!("Found Docker binary at: {}", binary_path);

        // Get Docker version
        let version = self.get_docker_version(&binary_path).await?;
        info!("Found Docker version: {}", version.version);

        // Check version compatibility
        if !version.meets_minimum(&self.minimum_version) {
            return Err(Error::UnsupportedVersion {
                found: version.version.clone(),
                minimum: self.minimum_version.version.clone(),
            });
        }

        // Check if daemon is running
        let (daemon_running, server_version) = self.check_daemon(&binary_path).await;

        if daemon_running {
            info!("Docker daemon is running");
        } else {
            warn!("Docker daemon is not running");
        }

        // Get system info
        let (os, architecture) = Self::get_system_info();

        Ok(DockerInfo {
            version,
            binary_path,
            daemon_running,
            server_version,
            os,
            architecture,
        })
    }

    /// Find Docker binary in PATH
    ///
    /// Uses the `which` crate for cross-platform binary lookup,
    /// working on both Unix and Windows systems.
    fn find_docker_binary() -> Result<String> {
        let path = which("docker").map_err(|_| Error::DockerNotFound)?;
        Ok(path.to_string_lossy().to_string())
    }

    /// Get Docker client version
    async fn get_docker_version(&self, binary_path: &str) -> Result<DockerVersion> {
        let output = Command::new(binary_path)
            .args(["--version"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .await
            .map_err(|e| Error::custom(format!("Failed to run 'docker --version': {e}")))?;

        if !output.status.success() {
            return Err(Error::command_failed(
                "docker --version",
                output.status.code().unwrap_or(-1),
                String::from_utf8_lossy(&output.stdout).to_string(),
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        let version_output = String::from_utf8_lossy(&output.stdout);
        debug!("Docker version output: {}", version_output);

        // Parse "Docker version 24.0.7, build afdd53b" format
        let version_str = version_output
            .split_whitespace()
            .nth(2)
            .and_then(|v| v.split(',').next())
            .ok_or_else(|| {
                Error::parse_error(format!("Could not parse version from: {version_output}"))
            })?;

        DockerVersion::parse(version_str)
    }

    /// Check if Docker daemon is running and get server version
    async fn check_daemon(&self, binary_path: &str) -> (bool, Option<DockerVersion>) {
        let output = Command::new(binary_path)
            .args(["version", "--format", "{{.Server.Version}}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .await;

        match output {
            Ok(output) if output.status.success() => {
                let server_version_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if server_version_str.is_empty() {
                    (false, None)
                } else {
                    match DockerVersion::parse(&server_version_str) {
                        Ok(version) => (true, Some(version)),
                        Err(_) => (true, None),
                    }
                }
            }
            _ => (false, None),
        }
    }

    /// Get system information
    fn get_system_info() -> (String, String) {
        let os = std::env::consts::OS.to_string();
        let arch = std::env::consts::ARCH.to_string();
        (os, arch)
    }
}

/// Convenience function to check Docker prerequisites with default settings
///
/// # Errors
/// Returns various `Error` variants if Docker is not available
/// or does not meet minimum requirements
pub async fn ensure_docker() -> Result<DockerInfo> {
    let checker = DockerPrerequisites::default();
    checker.check().await
}

/// Convenience function to check Docker prerequisites with a timeout
///
/// # Errors
/// Returns various `Error` variants if Docker is not available,
/// does not meet minimum requirements, or the check times out
pub async fn ensure_docker_with_timeout(timeout: Duration) -> Result<DockerInfo> {
    let checker = DockerPrerequisites::default().with_timeout(timeout);
    checker.check().await
}

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

    #[test]
    fn test_docker_version_parse() {
        let version = DockerVersion::parse("24.0.7").unwrap();
        assert_eq!(version.major, 24);
        assert_eq!(version.minor, 0);
        assert_eq!(version.patch, 7);
        assert_eq!(version.version, "24.0.7");
    }

    #[test]
    fn test_docker_version_parse_with_v_prefix() {
        let version = DockerVersion::parse("v20.10.21").unwrap();
        assert_eq!(version.major, 20);
        assert_eq!(version.minor, 10);
        assert_eq!(version.patch, 21);
        assert_eq!(version.version, "20.10.21");
    }

    #[test]
    fn test_docker_version_parse_invalid() {
        assert!(DockerVersion::parse("invalid").is_err());
        assert!(DockerVersion::parse("1.2").is_err());
        assert!(DockerVersion::parse("a.b.c").is_err());
    }

    #[test]
    fn test_version_meets_minimum() {
        let current = DockerVersion::parse("24.0.7").unwrap();
        let minimum = DockerVersion::parse("20.10.0").unwrap();
        let too_high = DockerVersion::parse("25.0.0").unwrap();

        assert!(current.meets_minimum(&minimum));
        assert!(!current.meets_minimum(&too_high));

        // Test exact match
        let exact = DockerVersion::parse("20.10.0").unwrap();
        assert!(exact.meets_minimum(&minimum));

        // Test minor version differences
        let newer_minor = DockerVersion::parse("20.11.0").unwrap();
        let older_minor = DockerVersion::parse("20.9.0").unwrap();
        assert!(newer_minor.meets_minimum(&minimum));
        assert!(!older_minor.meets_minimum(&minimum));

        // Test patch version differences
        let newer_patch = DockerVersion::parse("20.10.1").unwrap();
        let older_patch = DockerVersion::parse("20.10.0").unwrap();
        assert!(newer_patch.meets_minimum(&minimum));
        assert!(older_patch.meets_minimum(&minimum)); // Equal should pass
    }

    #[test]
    fn test_prerequisites_default() {
        let prereqs = DockerPrerequisites::default();
        assert_eq!(prereqs.minimum_version.version, "20.10.0");
    }

    #[test]
    fn test_prerequisites_custom_minimum() {
        let custom_version = DockerVersion::parse("25.0.0").unwrap();
        let prereqs = DockerPrerequisites::new(custom_version.clone());
        assert_eq!(prereqs.minimum_version, custom_version);
    }

    #[test]
    fn test_prerequisites_timeout() {
        let prereqs = DockerPrerequisites::default();
        assert!(prereqs.timeout.is_none());

        let prereqs_with_timeout =
            DockerPrerequisites::default().with_timeout(Duration::from_secs(10));
        assert_eq!(prereqs_with_timeout.timeout, Some(Duration::from_secs(10)));

        let prereqs_with_secs = DockerPrerequisites::default().with_timeout_secs(30);
        assert_eq!(prereqs_with_secs.timeout, Some(Duration::from_secs(30)));
    }

    #[tokio::test]
    async fn test_ensure_docker_integration() {
        // This is an integration test that requires Docker to be installed
        // It will be skipped in environments without Docker
        let result = ensure_docker().await;

        match result {
            Ok(info) => {
                assert!(!info.binary_path.is_empty());
                assert!(!info.version.version.is_empty());
                assert!(info.version.major >= 20);
                println!(
                    "Docker found: {} at {}",
                    info.version.version, info.binary_path
                );

                if info.daemon_running {
                    println!("Docker daemon is running");
                    if let Some(server_version) = info.server_version {
                        println!("Server version: {}", server_version.version);
                    }
                } else {
                    println!("Docker daemon is not running");
                }
            }
            Err(Error::DockerNotFound) => {
                println!("Docker not found - skipping integration test");
            }
            Err(e) => {
                println!("Prerequisites check failed: {e}");
            }
        }
    }
}