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
//! Image management operations.

use crate::DockerClient;
use crate::error::{DockerError, Result};
use bollard::auth::DockerCredentials;
use bollard::image::*;
use bollard::models::*;
use futures_util::StreamExt;
use std::collections::HashMap;
use tracing::{debug, info, warn};

mod builder;
pub use builder::*;

/// Image operations manager.
pub struct Images<'a> {
    client: &'a DockerClient,
}

impl<'a> Images<'a> {
    pub(crate) fn new(client: &'a DockerClient) -> Self {
        Self { client }
    }

    /// Create a new image builder for building images.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lmrc_docker::DockerClient;
    /// use std::path::Path;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = DockerClient::new()?;
    ///
    ///     client.images()
    ///         .build("my-app:latest")
    ///         .dockerfile("Dockerfile")
    ///         .context(Path::new("."))
    ///         .build_arg("RUNTIME_IMAGE", "alpine:latest")
    ///         .execute()
    ///         .await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn build(&self, tag: impl Into<String>) -> ImageBuilder<'a> {
        ImageBuilder::new(self.client, tag)
    }

    /// Get a reference to a specific image.
    pub fn get(&self, name_or_id: impl Into<String>) -> ImageRef<'a> {
        ImageRef::new(self.client, name_or_id.into())
    }

    /// List all images.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lmrc_docker::DockerClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = DockerClient::new()?;
    ///     let images = client.images().list(true).await?;
    ///     for image in images {
    ///         println!("{:?}", image.repo_tags);
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn list(&self, all: bool) -> Result<Vec<ImageSummary>> {
        let options = Some(ListImagesOptions::<String> {
            all,
            ..Default::default()
        });

        self.client
            .docker
            .list_images(options)
            .await
            .map_err(|e| DockerError::Other(format!("Failed to list images: {}", e)))
    }

    /// Pull an image from a registry.
    ///
    /// # Arguments
    ///
    /// * `image` - Image name with optional tag (e.g., "nginx:latest")
    /// * `credentials` - Optional Docker registry credentials
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lmrc_docker::DockerClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = DockerClient::new()?;
    ///     client.images().pull("nginx:latest", None).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn pull(
        &self,
        image: impl Into<String>,
        credentials: Option<DockerCredentials>,
    ) -> Result<()> {
        let image = image.into();
        info!("Pulling image: {}", image);

        let options = Some(CreateImageOptions::<String> {
            from_image: image.clone(),
            ..Default::default()
        });

        let mut stream = self.client.docker.create_image(options, None, credentials);

        while let Some(result) = stream.next().await {
            match result {
                Ok(info) => {
                    if let Some(status) = info.status {
                        debug!("Pull status: {}", status);
                    }
                    if let Some(error) = info.error {
                        return Err(DockerError::PullFailed(error));
                    }
                }
                Err(e) => {
                    return Err(DockerError::PullFailed(e.to_string()));
                }
            }
        }

        info!("Successfully pulled image: {}", image);
        Ok(())
    }

    /// Search for images in a registry.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lmrc_docker::DockerClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = DockerClient::new()?;
    ///     let results = client.images().search("nginx", None).await?;
    ///     for result in results {
    ///         println!("{}: {}", result.name.unwrap_or_default(), result.description.unwrap_or_default());
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn search(
        &self,
        term: impl Into<String>,
        limit: Option<i64>,
    ) -> Result<Vec<ImageSearchResponseItem>> {
        let options = SearchImagesOptions {
            term: term.into(),
            limit: limit.map(|l| l as u64),
            ..Default::default()
        };

        self.client
            .docker
            .search_images(options)
            .await
            .map_err(|e| DockerError::Other(format!("Failed to search images: {}", e)))
    }

    /// Prune unused images.
    ///
    /// # Arguments
    ///
    /// * `dangling_only` - If true, only remove dangling images (untagged)
    pub async fn prune(&self, dangling_only: bool) -> Result<ImagePruneResponse> {
        info!("Pruning unused images...");
        let mut filters = HashMap::new();
        if dangling_only {
            filters.insert("dangling", vec!["true"]);
        }

        let options = Some(PruneImagesOptions { filters });

        self.client
            .docker
            .prune_images(options)
            .await
            .map_err(|e| DockerError::Other(format!("Failed to prune images: {}", e)))
    }
}

/// Reference to a specific image.
pub struct ImageRef<'a> {
    client: &'a DockerClient,
    name: String,
}

impl<'a> ImageRef<'a> {
    pub(crate) fn new(client: &'a DockerClient, name: String) -> Self {
        Self { client, name }
    }

    /// Get the image name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Inspect the image to get detailed information.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lmrc_docker::DockerClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = DockerClient::new()?;
    ///     let info = client.images().get("nginx:latest").inspect().await?;
    ///     println!("Image ID: {:?}", info.id);
    ///     Ok(())
    /// }
    /// ```
    pub async fn inspect(&self) -> Result<ImageInspect> {
        debug!("Inspecting image: {}", self.name);
        self.client
            .docker
            .inspect_image(&self.name)
            .await
            .map_err(|e| DockerError::ImageNotFound(format!("{}: {}", self.name, e)))
    }

    /// Get the history of the image (layer information).
    pub async fn history(&self) -> Result<Vec<HistoryResponseItem>> {
        debug!("Getting history for image: {}", self.name);
        self.client
            .docker
            .image_history(&self.name)
            .await
            .map_err(|e| DockerError::ImageNotFound(format!("{}: {}", self.name, e)))
    }

    /// Tag the image with a new name/tag.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lmrc_docker::DockerClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = DockerClient::new()?;
    ///     client.images()
    ///         .get("nginx:latest")
    ///         .tag("my-nginx:v1.0")
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn tag(&self, new_tag: impl Into<String>) -> Result<()> {
        let new_tag = new_tag.into();
        info!("Tagging image {} as {}", self.name, new_tag);

        // Parse the new tag to extract repo and tag
        let parts: Vec<&str> = new_tag.rsplitn(2, ':').collect();
        let (repo, tag) = if parts.len() == 2 {
            (parts[1], Some(parts[0]))
        } else {
            (new_tag.as_str(), None)
        };

        let options = TagImageOptions {
            repo,
            tag: tag.unwrap_or("latest"),
        };

        self.client
            .docker
            .tag_image(&self.name, Some(options))
            .await
            .map_err(|e| DockerError::Other(format!("Failed to tag image: {}", e)))
    }

    /// Push the image to a registry.
    ///
    /// # Arguments
    ///
    /// * `credentials` - Optional Docker registry credentials
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lmrc_docker::DockerClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = DockerClient::new()?;
    ///     client.images()
    ///         .get("myregistry.com/my-app:v1.0")
    ///         .push(None)
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn push(&self, credentials: Option<DockerCredentials>) -> Result<()> {
        info!("Pushing image: {}", self.name);

        // Parse tag from image name
        let tag = self.name.split(':').nth(1).unwrap_or("latest");

        let options = Some(PushImageOptions { tag });

        let mut stream = self
            .client
            .docker
            .push_image(&self.name, options, credentials);

        while let Some(result) = stream.next().await {
            match result {
                Ok(info) => {
                    if let Some(status) = info.status {
                        if status.contains("error") || status.contains("Error") {
                            warn!("Push error: {}", status);
                        } else {
                            debug!("Push status: {}", status);
                        }
                    }
                    if let Some(error) = info.error {
                        return Err(DockerError::PushFailed(error));
                    }
                }
                Err(e) => {
                    return Err(DockerError::PushFailed(e.to_string()));
                }
            }
        }

        info!("Successfully pushed image: {}", self.name);
        Ok(())
    }

    /// Remove the image.
    ///
    /// # Arguments
    ///
    /// * `force` - Force removal even if image is in use
    /// * `noprune` - Do not delete untagged parent images
    pub async fn remove(&self, force: bool, noprune: bool) -> Result<Vec<ImageDeleteResponseItem>> {
        info!("Removing image: {}", self.name);

        let options = Some(RemoveImageOptions { force, noprune });

        self.client
            .docker
            .remove_image(&self.name, options, None)
            .await
            .map_err(|e| DockerError::Other(format!("Failed to remove image: {}", e)))
    }

    /// Export the image as a tar archive.
    pub async fn export(&self) -> Result<Vec<u8>> {
        info!("Exporting image: {}", self.name);

        let mut stream = self.client.docker.export_image(&self.name);
        let mut data = Vec::new();

        while let Some(chunk) = stream.next().await {
            match chunk {
                Ok(bytes) => data.extend_from_slice(&bytes),
                Err(e) => {
                    return Err(DockerError::Other(format!("Failed to export image: {}", e)));
                }
            }
        }

        Ok(data)
    }
}

impl DockerClient {
    /// Access image operations.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lmrc_docker::DockerClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = DockerClient::new()?;
    ///     let images = client.images().list(false).await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn images(&self) -> Images<'_> {
        Images::new(self)
    }
}