ironflow-ops-docker 0.1.11

Docker operations for Ironflow workflows, powered by bollard
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
//! Image management: list, pull, push, build, inspect, remove.

use std::collections::HashMap;

use async_trait::async_trait;
use bollard::Docker;
use bollard::query_parameters::{
    CreateImageOptions, ListImagesOptions, PushImageOptions, RemoveImageOptions,
};
use ironflow_core::error::OperationError;
use ironflow_core::operation::{Operation, OperationContext, TypedOperation};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio_stream::StreamExt;

use crate::containers::DockerRef;
use crate::helpers::{docker_error, to_value};

// ---------------------------------------------------------------------------
// ImageList
// ---------------------------------------------------------------------------

/// A single entry in the image list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageListEntry {
    /// Image ID.
    pub id: String,
    /// Repository tags.
    pub repo_tags: Vec<String>,
    /// Image size in bytes.
    pub size: i64,
    /// Creation timestamp.
    pub created: i64,
}

/// Output of an image list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageListOutput {
    /// The images.
    pub images: Vec<ImageListEntry>,
}

/// List local images.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_docker::images::ImageList;
/// use ironflow_ops_docker::DockerClient;
/// use ironflow_core::operation::Operation;
///
/// let client = DockerClient::connect_local().unwrap();
/// let op = ImageList::new(&client);
/// assert_eq!(op.kind(), "docker");
/// ```
pub struct ImageList {
    docker: Docker,
    all: bool,
    filters: HashMap<String, Vec<String>>,
}

impl ImageList {
    /// Create a new image-list operation.
    pub fn new(client: impl Into<DockerRef>) -> Self {
        Self {
            docker: client.into().0,
            all: false,
            filters: HashMap::new(),
        }
    }

    /// Include intermediate images.
    pub fn all(mut self) -> Self {
        self.all = true;
        self
    }

    /// Add a filter.
    pub fn filter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.filters
            .entry(key.into())
            .or_default()
            .push(value.into());
        self
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::External`] if the Docker daemon is
    /// unreachable.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<ImageListOutput, OperationError> {
        let options = ListImagesOptions {
            all: self.all,
            filters: Some(self.filters.clone()),
            ..Default::default()
        };
        let images = self
            .docker
            .list_images(Some(options))
            .await
            .map_err(docker_error)?;
        let entries = images
            .into_iter()
            .map(|i| ImageListEntry {
                id: i.id,
                repo_tags: i.repo_tags,
                size: i.size,
                created: i.created,
            })
            .collect();
        Ok(ImageListOutput { images: entries })
    }
}

#[async_trait]
impl Operation for ImageList {
    fn kind(&self) -> &str {
        "docker"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({
            "operation": "image_list",
            "all": self.all,
        }))
    }
}

impl TypedOperation for ImageList {
    type Output = ImageListOutput;
}

// ---------------------------------------------------------------------------
// ImagePull
// ---------------------------------------------------------------------------

/// Output of an image pull.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImagePullOutput {
    /// The pulled image reference.
    pub image: String,
}

/// Pull an image from a registry.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_docker::images::ImagePull;
/// use ironflow_ops_docker::DockerClient;
/// use ironflow_core::operation::Operation;
///
/// let client = DockerClient::connect_local().unwrap();
/// let op = ImagePull::new(&client, "alpine:latest");
/// assert_eq!(op.kind(), "docker");
/// ```
pub struct ImagePull {
    docker: Docker,
    image: String,
}

impl ImagePull {
    /// Create a new image-pull operation.
    pub fn new(client: impl Into<DockerRef>, image: impl Into<String>) -> Self {
        Self {
            docker: client.into().0,
            image: image.into(),
        }
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::External`] if the image cannot be pulled.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<ImagePullOutput, OperationError> {
        let options = CreateImageOptions {
            from_image: Some(self.image.clone()),
            ..Default::default()
        };
        let mut stream = self.docker.create_image(Some(options), None, None);
        while let Some(result) = stream.next().await {
            result.map_err(docker_error)?;
        }
        Ok(ImagePullOutput {
            image: self.image.clone(),
        })
    }
}

#[async_trait]
impl Operation for ImagePull {
    fn kind(&self) -> &str {
        "docker"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({
            "operation": "image_pull",
            "image": self.image,
        }))
    }
}

impl TypedOperation for ImagePull {
    type Output = ImagePullOutput;
}

// ---------------------------------------------------------------------------
// ImagePush
// ---------------------------------------------------------------------------

/// Output of an image push.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImagePushOutput {
    /// The pushed image reference.
    pub image: String,
}

/// Push an image to a registry.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_docker::images::ImagePush;
/// use ironflow_ops_docker::DockerClient;
/// use ironflow_core::operation::Operation;
///
/// let client = DockerClient::connect_local().unwrap();
/// let op = ImagePush::new(&client, "my-image:latest");
/// assert_eq!(op.kind(), "docker");
/// ```
pub struct ImagePush {
    docker: Docker,
    image: String,
    tag: Option<String>,
}

impl ImagePush {
    /// Create a new image-push operation.
    pub fn new(client: impl Into<DockerRef>, image: impl Into<String>) -> Self {
        Self {
            docker: client.into().0,
            image: image.into(),
            tag: None,
        }
    }

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

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::External`] if the push fails.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<ImagePushOutput, OperationError> {
        let options = PushImageOptions {
            tag: Some(self.tag.clone().unwrap_or_else(|| "latest".to_string())),
            platform: None,
        };
        let mut stream = self.docker.push_image(&self.image, Some(options), None);
        while let Some(result) = stream.next().await {
            result.map_err(docker_error)?;
        }
        Ok(ImagePushOutput {
            image: self.image.clone(),
        })
    }
}

#[async_trait]
impl Operation for ImagePush {
    fn kind(&self) -> &str {
        "docker"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({
            "operation": "image_push",
            "image": self.image,
        }))
    }
}

impl TypedOperation for ImagePush {
    type Output = ImagePushOutput;
}

// ---------------------------------------------------------------------------
// ImageInspect
// ---------------------------------------------------------------------------

/// Output of an image inspection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageInspectOutput {
    /// The full inspection response as JSON.
    pub data: Value,
}

/// Inspect an image.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_docker::images::ImageInspect;
/// use ironflow_ops_docker::DockerClient;
/// use ironflow_core::operation::Operation;
///
/// let client = DockerClient::connect_local().unwrap();
/// let op = ImageInspect::new(&client, "alpine:latest");
/// assert_eq!(op.kind(), "docker");
/// ```
pub struct ImageInspect {
    docker: Docker,
    image: String,
}

impl ImageInspect {
    /// Create a new image-inspect operation.
    pub fn new(client: impl Into<DockerRef>, image: impl Into<String>) -> Self {
        Self {
            docker: client.into().0,
            image: image.into(),
        }
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::External`] if the image does not exist.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<ImageInspectOutput, OperationError> {
        let response = self
            .docker
            .inspect_image(&self.image)
            .await
            .map_err(docker_error)?;
        let data = serde_json::to_value(&response).map_err(|e| OperationError::External {
            origin: "docker".to_string(),
            message: e.to_string(),
        })?;
        Ok(ImageInspectOutput { data })
    }
}

#[async_trait]
impl Operation for ImageInspect {
    fn kind(&self) -> &str {
        "docker"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({
            "operation": "image_inspect",
            "image": self.image,
        }))
    }
}

impl TypedOperation for ImageInspect {
    type Output = ImageInspectOutput;
}

// ---------------------------------------------------------------------------
// ImageRemove
// ---------------------------------------------------------------------------

/// Output of an image removal.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageRemoveOutput {
    /// The removed image reference.
    pub image: String,
}

/// Remove an image.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_docker::images::ImageRemove;
/// use ironflow_ops_docker::DockerClient;
/// use ironflow_core::operation::Operation;
///
/// let client = DockerClient::connect_local().unwrap();
/// let op = ImageRemove::new(&client, "alpine:latest");
/// assert_eq!(op.kind(), "docker");
/// ```
pub struct ImageRemove {
    docker: Docker,
    image: String,
    force: bool,
    no_prune: bool,
}

impl ImageRemove {
    /// Create a new image-remove operation.
    pub fn new(client: impl Into<DockerRef>, image: impl Into<String>) -> Self {
        Self {
            docker: client.into().0,
            image: image.into(),
            force: false,
            no_prune: false,
        }
    }

    /// Force-remove the image.
    pub fn force(mut self) -> Self {
        self.force = true;
        self
    }

    /// Do not delete untagged parent images.
    pub fn no_prune(mut self) -> Self {
        self.no_prune = true;
        self
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::External`] if the image does not exist.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<ImageRemoveOutput, OperationError> {
        let options = RemoveImageOptions {
            force: self.force,
            noprune: self.no_prune,
            platforms: None,
        };
        self.docker
            .remove_image(&self.image, Some(options), None)
            .await
            .map_err(docker_error)?;
        Ok(ImageRemoveOutput {
            image: self.image.clone(),
        })
    }
}

#[async_trait]
impl Operation for ImageRemove {
    fn kind(&self) -> &str {
        "docker"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({
            "operation": "image_remove",
            "image": self.image,
        }))
    }
}

impl TypedOperation for ImageRemove {
    type Output = ImageRemoveOutput;
}