podman-api 0.1.0

Rust interface to Podman
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
use crate::api::Filter;
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;

impl_opts_builder!(url =>
    /// Adjust how an image is built.
    ImageBuild
);

#[derive(Debug, Clone, PartialEq, Eq)]
/// The networking mode for the run commands during image build.
pub enum NetworkMode {
    /// Limited to containers within a single host, port mapping required for external access.
    Bridge,
    /// No isolation between host and containers on this network.
    Host,
    /// Disable all networking for this container.
    None,
    /// Share networking with given container.
    Container,
    /// Custom network's name.
    Custom(String),
}

impl AsRef<str> for NetworkMode {
    fn as_ref(&self) -> &str {
        match self {
            NetworkMode::Bridge => "bridge",
            NetworkMode::Host => "host",
            NetworkMode::None => "none",
            NetworkMode::Container => "container",
            NetworkMode::Custom(custom) => custom,
        }
    }
}

impl fmt::Display for NetworkMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_ref())
    }
}

#[derive(Debug, Clone, PartialEq)]
/// Used to set the image platform with [`platform`](ImageBuildOptsBuilder::platform).
pub struct Platform {
    os: String,
    arch: Option<String>,
    version: Option<String>,
}

impl Platform {
    pub fn new(os: impl Into<String>) -> Self {
        Self {
            os: os.into(),
            arch: None,
            version: None,
        }
    }

    pub fn arch(mut self, arch: impl Into<String>) -> Self {
        self.arch = Some(arch.into());
        self
    }

    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }
}

impl fmt::Display for Platform {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(arch) = &self.arch {
            if let Some(vers) = &self.version {
                write!(f, "{}/{}/{}", self.os, arch, vers)
            } else {
                write!(f, "{}/{}", self.os, arch)
            }
        } else {
            write!(f, "{}", self.os)
        }
    }
}

impl ImageBuildOptsBuilder {
    impl_map_field!(url
        /// Key-value build time variables.
        build_args => "buildargs"
    );

    /// List of images used to build cache resolution
    pub fn cache_from<I>(mut self, images: impl IntoIterator<Item = I>) -> Self
    where
        I: Into<String>,
    {
        self.params.insert(
            "cachefrom",
            serde_json::to_string(&images.into_iter().map(|i| i.into()).collect::<Vec<_>>())
                .unwrap_or_default(),
        );
        self
    }

    impl_url_field!(
        /// Limits the CPU CFS (Completely Fair Scheduler) period.
        cpu_period: isize => "cpuperiod"
    );

    impl_url_field!(
        /// Limits the CPU CFS (Completely Fair Scheduler) quota.
        cpu_quota: isize => "cpuquota"
    );

    impl_url_field!(
        /// Set CPUs in which to allow execution. Example: `0-1`, `1-3`
        cpu_set_cpus: isize => "cpusetcpus"
    );

    impl_url_field!(
        /// CPU shares - relative weights
        cpu_shares: isize => "cpushares"
    );

    impl_url_str_field!(
        /// Path within the build context to the Dockerfile. This is ignored
        /// if remote is specified and points to an external Dockerfile.
        dockerfile => "Dockerfile"
    );

    impl_url_str_field!(
        /// Extra hosts to add to /etc/hosts.
        extra_hosts => "extrahosts"
    );

    impl_url_bool_field!(
        /// Always remove intermediate containers, even upon failure.
        force_rm => "forcerm"
    );

    impl_url_bool_field!(
        /// Inject http proxy environment variables into container.
        http_proxy => "httpproxy"
    );

    impl_map_field!(url
        /// Key-value pairs to set as labels on the new image.
        labels => "labels"
    );

    impl_url_bool_field!(
        /// Cache intermediate layers during build.
        layers => "layers"
    );

    impl_url_field!(
        /// The upper limit (in bytes) on how much memory running
        /// containers can use.
        memory: usize => "memory"
    );

    impl_url_field!(
        /// Limits the amount of memory and swap together.
        memswap: usize => "memswap"
    );

    impl_url_enum_field!(
        /// Set the networking mode for the run commands during build.
        network_mode: NetworkMode => "networkmode"
    );

    impl_url_bool_field!(
        /// Do not use the cache when building the image.
        no_cache => "nocache"
    );

    impl_url_str_field!(
        /// Output configuration.
        outputs => "outputs"
    );

    pub fn platform(mut self, platform: Platform) -> Self {
        self.params.insert("platform", platform.to_string());
        self
    }

    impl_url_bool_field!(
        /// Attempt to pull the image even if an older image exists locally.
        pull => "pull"
    );

    impl_url_bool_field!(
        /// Suppress verbose build output.
        quiet => "q"
    );

    impl_url_str_field!(
        /// A Git repository URI or HTTP/HTTPS context URI. If the URI points
        /// to a single text file, the file’s contents are placed into a file
        /// called Dockerfile and the image is built from that file. If the URI
        /// points to a tarball, the file is downloaded by the daemon and
        /// the contents therein used as the context for the build. If the URI
        /// points to a tarball and the dockerfile parameter is also specified,
        /// there must be a file with the corresponding path inside the tarball.
        remote => "remote"
    );

    impl_url_bool_field!(
        /// Remove intermediate containers after a successful build.
        remove => "rm"
    );

    impl_url_field!(
        /// Value to use when mounting an shmfs on the container's /dev/shm directory.
        /// Default is 64MB
        shared_mem_size: usize => "shmsize"
    );

    impl_url_bool_field!(
        /// Silently ignored. Squash the resulting images layers into a single layer.
        squash => "squash"
    );

    impl_url_str_field!(
        /// A name and optional tag to apply to the image in the `name:tag` format.
        tag => "t"
    );

    impl_url_str_field!(
        /// Target build stage
        target => "target"
    );
}

impl_opts_builder!(url =>
    /// Adjust how images are listed.
    ImageList
);

#[derive(Debug, Clone)]
/// Used to filter listed images with [`ImagesListFilter`](ImagesListFilter).
pub enum ImageOpt {
    Name(crate::Id),
    Tag(crate::Id, String),
    Digest(crate::Id, String),
}

impl fmt::Display for ImageOpt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ImageOpt::*;
        match self {
            Name(id) => write!(f, "{}", id),
            Tag(id, tag) => write!(f, "{}:{}", id, tag),
            Digest(id, digest) => write!(f, "{}@{}", id, digest),
        }
    }
}

#[derive(Debug)]
/// Used to filter listed images by one of the variants.
pub enum ImageListFilter {
    Before(ImageOpt),
    Dangling(bool),
    /// Image that contains key label.
    LabelKey(String),
    /// Image that contains key-value label.
    LabelKeyVal(String, String),
    /// Image name with optional tag.
    Reference(crate::Id, Option<String>),
    Id(crate::Id),
    Since(ImageOpt),
}

impl Filter for ImageListFilter {
    fn query_key_val(&self) -> (&'static str, String) {
        use ImageListFilter::*;
        match &self {
            Before(image) => ("before", image.to_string()),
            Dangling(dangling) => ("dangling", dangling.to_string()),
            LabelKey(key) => ("label", key.clone()),
            LabelKeyVal(key, val) => ("label", format!("{}={}", key, val)),
            Reference(image, tag) => (
                "reference",
                if let Some(tag) = tag {
                    format!("{}:{}", image, tag)
                } else {
                    image.to_string()
                },
            ),
            Id(id) => ("id", id.to_string()),
            Since(image) => ("since", image.to_string()),
        }
    }
}

impl ImageListOptsBuilder {
    impl_filter_func!(ImageListFilter);

    impl_url_bool_field!(
        /// Show all images. Only images from a final layer (no children) are shown by default.
        all => "all"
    );
}

impl_opts_builder!(url =>
    /// Adjust the way an image is tagged/untagged.
    ImageTag
);

impl ImageTagOptsBuilder {
    impl_url_str_field!(
        /// Set the image repository.
        repo => "repo"
    );

    impl_url_str_field!(
        /// Set the image tag.
        tag => "tag"
    );
}

#[derive(Clone, Serialize, Debug)]
#[serde(untagged)]
pub enum RegistryAuth {
    Password {
        username: String,
        password: String,

        #[serde(skip_serializing_if = "Option::is_none")]
        email: Option<String>,

        #[serde(rename = "serveraddress")]
        #[serde(skip_serializing_if = "Option::is_none")]
        server_address: Option<String>,
    },
    Token {
        #[serde(rename = "identitytoken")]
        identity_token: String,
    },
}

impl RegistryAuth {
    /// return a new instance with token authentication
    pub fn token(token: impl Into<String>) -> RegistryAuth {
        RegistryAuth::Token {
            identity_token: token.into(),
        }
    }

    /// return a new instance of a builder for authentication
    pub fn builder() -> RegistryAuthBuilder {
        RegistryAuthBuilder::default()
    }

    /// serialize authentication as JSON in base64
    pub fn serialize(&self) -> String {
        serde_json::to_string(self)
            .map(|c| base64::encode_config(&c, base64::URL_SAFE))
            .unwrap_or_default()
    }
}

#[derive(Default)]
pub struct RegistryAuthBuilder {
    username: Option<String>,
    password: Option<String>,
    email: Option<String>,
    server_address: Option<String>,
}

impl RegistryAuthBuilder {
    /// The username used for authentication.
    pub fn username(&mut self, username: impl Into<String>) -> &mut Self {
        self.username = Some(username.into());
        self
    }

    /// The password used for authentication.
    pub fn password(&mut self, password: impl Into<String>) -> &mut Self {
        self.password = Some(password.into());
        self
    }

    /// The email addres used for authentication.
    pub fn email(&mut self, email: impl Into<String>) -> &mut Self {
        self.email = Some(email.into());
        self
    }

    /// The server address of registry, should be a domain/IP without a protocol.
    /// Example: `10.92.0.1`, `docker.corp.local`
    pub fn server_address(&mut self, server_address: impl Into<String>) -> &mut Self {
        self.server_address = Some(server_address.into());
        self
    }

    /// Create the final authentication object.
    pub fn build(&self) -> RegistryAuth {
        RegistryAuth::Password {
            username: self.username.clone().unwrap_or_default(),
            password: self.password.clone().unwrap_or_default(),
            email: self.email.clone(),
            server_address: self.server_address.clone(),
        }
    }
}

#[derive(Default, Debug)]
pub struct PullOpts {
    auth: Option<RegistryAuth>,
    params: HashMap<&'static str, String>,
}

impl PullOpts {
    /// return a new instance of a builder for Opts
    pub fn builder() -> PullOptsBuilder {
        PullOptsBuilder::default()
    }

    /// serialize Opts as a string. returns None if no Opts are defined
    pub fn serialize(&self) -> Option<String> {
        if self.params.is_empty() {
            None
        } else {
            Some(crate::util::url::encoded_pairs(
                self.params.iter().map(|(k, v)| (k, v)),
            ))
        }
    }

    pub(crate) fn auth_header(&self) -> Option<String> {
        self.auth.clone().map(|a| a.serialize())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The networking mode for the run commands during image build.
pub enum PullPolicy {
    Always,
    Missing,
    Newer,
    Never,
}

impl AsRef<str> for PullPolicy {
    fn as_ref(&self) -> &str {
        match self {
            PullPolicy::Always => "always",
            PullPolicy::Missing => "missing",
            PullPolicy::Newer => "newer",
            PullPolicy::Never => "never",
        }
    }
}

impl fmt::Display for PullPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_ref())
    }
}

#[derive(Debug, Default)]
pub struct PullOptsBuilder {
    auth: Option<RegistryAuth>,
    params: HashMap<&'static str, String>,
}

impl PullOptsBuilder {
    impl_url_bool_field!(
        /// Pull all tagged images in the repository.
        all_tags => "allTags"
    );

    impl_url_str_field!(
        /// Pull image for the specified architecture.
        arch => "Arch"
    );

    impl_url_str_field!(
        /// username:password for the registry.
        credentials => "credentials"
    );

    impl_url_str_field!(
        /// Pull image for the specified operating system.
        os => "OS"
    );

    impl_url_enum_field!(
        /// Image pull policy.
        policy: PullPolicy => "policy"
    );

    impl_url_bool_field!(
        /// Silences extra stream data on pull.
        quiet => "quiet"
    );

    impl_url_str_field!(
        /// Mandatory reference to the image.
        reference => "referene"
    );

    impl_url_bool_field!(
        /// Require TLS verification.
        tls_verify => "tlsVerify"
    );

    impl_url_str_field!(
        /// Pull image for the specified variant.
        variant => "Variant"
    );

    pub fn auth(&mut self, auth: RegistryAuth) -> &mut Self {
        self.auth = Some(auth);
        self
    }

    pub fn build(&mut self) -> PullOpts {
        PullOpts {
            auth: self.auth.take(),
            params: self.params.clone(),
        }
    }
}

impl_opts_builder!(url =>
    /// Adjust how an image is exported.
    ImageExport
);

impl ImageExportOptsBuilder {
    impl_url_bool_field!(
        /// Use compression on image.
        compress => "compress"
    );

    impl_url_str_field!(
        /// Format for exported image.
        format => "format"
    );
}

impl_opts_builder!(url =>
    /// Adjust how an image is imported.
    ImageImport
);

impl ImageImportOptsBuilder {
    impl_url_vec_field!(
        /// Apply the following possible instructions to the created image: CMD | ENTRYPOINT | ENV | EXPOSE | LABEL | STOPSIGNAL | USER | VOLUME | WORKDIR.
        changes => "changes"
    );

    impl_url_str_field!(
        /// Set commit message for imported image.
        message => "message"
    );

    impl_url_str_field!(
        /// Optional Name[:TAG] for the image.
        reference => "reference"
    );

    impl_url_str_field!(
        /// Load image from the specified URL.
        url => "url"
    );
}