ironflow-ops-docker 0.1.16

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
482
483
484
485
486
487
//! Volume operations: create, inspect, list, remove, prune.

use std::collections::HashMap;

use async_trait::async_trait;
use bollard::Docker;
use bollard::models::VolumeCreateRequest;
use bollard::query_parameters::{ListVolumesOptions, PruneVolumesOptions, RemoveVolumeOptions};
use ironflow_core::error::OperationError;
use ironflow_core::operation::{Operation, OperationContext, TypedOperation};
use serde::{Deserialize, Serialize};
use serde_json::Value;

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

// ---------------------------------------------------------------------------
// VolumeCreate
// ---------------------------------------------------------------------------

/// Output of a volume creation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeCreateOutput {
    /// The volume name.
    pub name: String,
    /// The mount point.
    pub mountpoint: String,
}

/// Create a volume.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_docker::volumes::VolumeCreate;
/// use ironflow_ops_docker::DockerClient;
/// use ironflow_core::operation::Operation;
///
/// let client = DockerClient::connect_local().unwrap();
/// let op = VolumeCreate::new(&client, "my-volume");
/// assert_eq!(op.kind(), "docker");
/// ```
pub struct VolumeCreate {
    docker: Docker,
    name: String,
    driver: Option<String>,
    labels: HashMap<String, String>,
}

impl VolumeCreate {
    /// Create a new volume-create operation.
    pub fn new(client: impl Into<DockerRef>, name: impl Into<String>) -> Self {
        Self {
            docker: client.into().0,
            name: name.into(),
            driver: None,
            labels: HashMap::new(),
        }
    }

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

    /// Add a label.
    pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.labels.insert(key.into(), value.into());
        self
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::External`] if the volume cannot be created.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<VolumeCreateOutput, OperationError> {
        let request = VolumeCreateRequest {
            name: Some(self.name.clone()),
            driver: Some(self.driver.clone().unwrap_or_else(|| "local".to_string())),
            labels: Some(self.labels.clone()),
            ..Default::default()
        };
        let response = self
            .docker
            .create_volume(request)
            .await
            .map_err(docker_error)?;
        Ok(VolumeCreateOutput {
            name: response.name,
            mountpoint: response.mountpoint,
        })
    }
}

#[async_trait]
impl Operation for VolumeCreate {
    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": "volume_create",
            "name": self.name,
        }))
    }
}

impl TypedOperation for VolumeCreate {
    type Output = VolumeCreateOutput;
}

// ---------------------------------------------------------------------------
// VolumeInspect
// ---------------------------------------------------------------------------

/// Output of a volume inspection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeInspectOutput {
    /// The volume name.
    pub name: String,
    /// The mount point.
    pub mountpoint: String,
    /// The driver.
    pub driver: String,
}

/// Inspect a volume.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_docker::volumes::VolumeInspect;
/// use ironflow_ops_docker::DockerClient;
/// use ironflow_core::operation::Operation;
///
/// let client = DockerClient::connect_local().unwrap();
/// let op = VolumeInspect::new(&client, "my-volume");
/// assert_eq!(op.kind(), "docker");
/// ```
pub struct VolumeInspect {
    docker: Docker,
    name: String,
}

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

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::External`] if the volume does not exist.
    pub async fn run(
        &self,
        _ctx: &OperationContext,
    ) -> Result<VolumeInspectOutput, OperationError> {
        let response = self
            .docker
            .inspect_volume(&self.name)
            .await
            .map_err(docker_error)?;
        Ok(VolumeInspectOutput {
            name: response.name,
            mountpoint: response.mountpoint,
            driver: response.driver,
        })
    }
}

#[async_trait]
impl Operation for VolumeInspect {
    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": "volume_inspect",
            "name": self.name,
        }))
    }
}

impl TypedOperation for VolumeInspect {
    type Output = VolumeInspectOutput;
}

// ---------------------------------------------------------------------------
// VolumeList
// ---------------------------------------------------------------------------

/// A single entry in the volume list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeListEntry {
    /// Volume name.
    pub name: String,
    /// Volume driver.
    pub driver: String,
    /// Mount point.
    pub mountpoint: String,
}

/// Output of a volume list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeListOutput {
    /// The volumes.
    pub volumes: Vec<VolumeListEntry>,
}

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

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

    /// 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<VolumeListOutput, OperationError> {
        let options = ListVolumesOptions {
            filters: Some(self.filters.clone()),
        };
        let response = self
            .docker
            .list_volumes(Some(options))
            .await
            .map_err(docker_error)?;
        let volumes = response
            .volumes
            .unwrap_or_default()
            .into_iter()
            .map(|v| VolumeListEntry {
                name: v.name,
                driver: v.driver,
                mountpoint: v.mountpoint,
            })
            .collect();
        Ok(VolumeListOutput { volumes })
    }
}

#[async_trait]
impl Operation for VolumeList {
    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": "volume_list",
        }))
    }
}

impl TypedOperation for VolumeList {
    type Output = VolumeListOutput;
}

// ---------------------------------------------------------------------------
// VolumeRemove
// ---------------------------------------------------------------------------

/// Output of a volume removal.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeRemoveOutput {
    /// The removed volume name.
    pub name: String,
}

/// Remove a volume.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_docker::volumes::VolumeRemove;
/// use ironflow_ops_docker::DockerClient;
/// use ironflow_core::operation::Operation;
///
/// let client = DockerClient::connect_local().unwrap();
/// let op = VolumeRemove::new(&client, "my-volume");
/// assert_eq!(op.kind(), "docker");
/// ```
pub struct VolumeRemove {
    docker: Docker,
    name: String,
    force: bool,
}

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

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

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::External`] if the volume does not exist.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<VolumeRemoveOutput, OperationError> {
        self.docker
            .remove_volume(&self.name, Some(RemoveVolumeOptions { force: self.force }))
            .await
            .map_err(docker_error)?;
        Ok(VolumeRemoveOutput {
            name: self.name.clone(),
        })
    }
}

#[async_trait]
impl Operation for VolumeRemove {
    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": "volume_remove",
            "name": self.name,
        }))
    }
}

impl TypedOperation for VolumeRemove {
    type Output = VolumeRemoveOutput;
}

// ---------------------------------------------------------------------------
// VolumePrune
// ---------------------------------------------------------------------------

/// Output of pruning unused volumes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumePruneOutput {
    /// Names of removed volumes.
    pub volumes_deleted: Vec<String>,
    /// Disk space reclaimed in bytes.
    pub space_reclaimed: u64,
}

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

impl VolumePrune {
    /// Create a new volume-prune operation.
    pub fn new(client: impl Into<DockerRef>) -> Self {
        Self {
            docker: client.into().0,
            filters: HashMap::new(),
        }
    }

    /// 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<VolumePruneOutput, OperationError> {
        let options = PruneVolumesOptions {
            filters: Some(self.filters.clone()),
        };
        let response = self
            .docker
            .prune_volumes(Some(options))
            .await
            .map_err(docker_error)?;
        Ok(VolumePruneOutput {
            volumes_deleted: response.volumes_deleted.unwrap_or_default(),
            space_reclaimed: response.space_reclaimed.unwrap_or(0) as u64,
        })
    }
}

#[async_trait]
impl Operation for VolumePrune {
    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": "volume_prune",
        }))
    }
}

impl TypedOperation for VolumePrune {
    type Output = VolumePruneOutput;
}