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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
use crate::api::{ContainerStatus, Filter, ImageName, Labels};

use std::{
    collections::HashMap,
    hash::Hash,
    iter::Peekable,
    str::{self, FromStr},
    string::ToString,
    time::Duration,
};

use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};

use crate::{Error, Result};

pub enum Health {
    Starting,
    Healthy,
    Unhealthy,
    None,
}

impl AsRef<str> for Health {
    fn as_ref(&self) -> &str {
        match &self {
            Health::Starting => "starting",
            Health::Healthy => "healthy",
            Health::Unhealthy => "unhealthy",
            Health::None => "none",
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Isolation {
    Default,
    Process,
    HyperV,
}

impl AsRef<str> for Isolation {
    fn as_ref(&self) -> &str {
        match &self {
            Isolation::Default => "default",
            Isolation::Process => "process",
            Isolation::HyperV => "hyperv",
        }
    }
}

/// Filter Opts for container listings
pub enum ContainerFilter {
    Ancestor(ImageName),
    /// Container ID or name.
    Before(String),
    /// Containers with the specified exit code.
    ExitCode(u64),
    Health(Health),
    /// The container's ID.
    Id(String),
    /// Applies only to Windows daemon.
    Isolation(Isolation),
    IsTask(bool),
    /// Label in the form of `label=key`.
    LabelKey(String),
    /// Label in the form of `label=key=val`.
    Label(String, String),
    /// The container's name.
    Name(String),
    Publish(PublishPort),
    /// Network ID or name.
    Network(String),
    /// Container ID or name.
    Since(String),
    Status(ContainerStatus),
    /// Volume name or mount point destination.
    Volume(String),
}

impl Filter for ContainerFilter {
    fn query_key_val(&self) -> (&'static str, String) {
        use ContainerFilter::*;
        match &self {
            Ancestor(name) => ("ancestor", name.to_string()),
            Before(before) => ("before", before.to_owned()),
            ExitCode(c) => ("exit", c.to_string()),
            Health(health) => ("health", health.as_ref().to_string()),
            Id(id) => ("id", id.to_owned()),
            Isolation(isolation) => ("isolation", isolation.as_ref().to_string()),
            IsTask(is_task) => ("is-task", is_task.to_string()),
            LabelKey(key) => ("label", key.to_owned()),
            Label(key, val) => ("label", format!("{}={}", key, val)),
            Name(name) => ("name", name.to_owned()),
            Publish(port) => ("publsh", port.to_string()),
            Network(net) => ("net", net.to_owned()),
            Since(since) => ("since", since.to_owned()),
            Status(s) => ("status", s.as_ref().to_string()),
            Volume(vol) => ("volume", vol.to_owned()),
        }
    }
}

impl_opts_builder!(url => ContainerList);

impl ContainerListOptsBuilder {
    impl_filter_func!(
        /// Filter the list of containers by one of the enum variants.
        ContainerFilter
    );

    impl_url_bool_field!(
        /// If set to true all containers will be returned
        all => "all"
    );

    impl_url_str_field!(since: S => "since");

    impl_url_str_field!(before: B => "before");

    impl_url_bool_field!(
        /// If set to true the sizes of the containers will be returned
        sized => "size"
    );
}

/// Interface for building a new docker container from an existing image
#[derive(Serialize, Debug)]
pub struct ContainerCreateOpts {
    pub name: Option<String>,
    params: HashMap<&'static str, Value>,
}

/// Function to insert a JSON value into a tree where the desired
/// location of the value is given as a path of JSON keys.
fn insert<'a, I, V>(key_path: &mut Peekable<I>, value: &V, parent_node: &mut Value)
where
    V: Serialize,
    I: Iterator<Item = &'a str>,
{
    if let Some(local_key) = key_path.next() {
        if key_path.peek().is_some() {
            if let Some(node) = parent_node.as_object_mut() {
                let node = node
                    .entry(local_key.to_string())
                    .or_insert(Value::Object(Map::new()));

                insert(key_path, value, node);
            }
        } else if let Some(node) = parent_node.as_object_mut() {
            node.insert(
                local_key.to_string(),
                serde_json::to_value(value).unwrap_or_default(),
            );
        }
    }
}

impl ContainerCreateOpts {
    /// Returns a builder for creating a new container.
    pub fn builder<N>(name: N) -> ContainerOptsBuilder
    where
        N: AsRef<str>,
    {
        ContainerOptsBuilder::new(name.as_ref())
    }

    /// Serialize options as a JSON string.
    pub fn serialize(&self) -> Result<String> {
        serde_json::to_string(&self.to_json()).map_err(Error::from)
    }

    fn to_json(&self) -> Value {
        let mut body_members = Map::new();
        // The HostConfig element gets initialized to an empty object,
        // for backward compatibility.
        body_members.insert("HostConfig".to_string(), Value::Object(Map::new()));
        let mut body = Value::Object(body_members);
        self.parse_from(&self.params, &mut body);
        body
    }

    fn parse_from<'a, K, V>(&self, params: &'a HashMap<K, V>, body: &mut Value)
    where
        &'a HashMap<K, V>: IntoIterator,
        K: ToString + Eq + Hash,
        V: Serialize,
    {
        for (k, v) in params.iter() {
            let key_string = k.to_string();
            insert(&mut key_string.split('.').peekable(), v, body)
        }
    }
}

#[derive(Default)]
pub struct ContainerOptsBuilder {
    name: Option<String>,
    params: HashMap<&'static str, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
/// Network protocol on which a port can be exposed.
pub enum Protocol {
    Tcp,
    Udp,
    Sctp,
}

impl AsRef<str> for Protocol {
    fn as_ref(&self) -> &str {
        match &self {
            Self::Tcp => "tcp",
            Self::Udp => "udp",
            Self::Sctp => "sctp",
        }
    }
}

impl FromStr for Protocol {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "tcp" => Ok(Protocol::Tcp),
            "udp" => Ok(Protocol::Udp),
            "sctp" => Ok(Protocol::Sctp),
            proto => Err(Error::InvalidProtocol(proto.into())),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
/// Structure used to expose a port on a container with [`expose`](ContainerOptsBuilder::expose) or
/// [`publish`](ContainerOptsBuilder::publish).
pub struct PublishPort {
    port: u32,
    protocol: Protocol,
}

impl PublishPort {
    /// Expose a TCP port.
    pub fn tcp(port: u32) -> Self {
        Self {
            port,
            protocol: Protocol::Tcp,
        }
    }

    /// Expose a UDP port.
    pub fn udp(port: u32) -> Self {
        Self {
            port,
            protocol: Protocol::Udp,
        }
    }

    // Expose a SCTP port.
    pub fn sctp(port: u32) -> Self {
        Self {
            port,
            protocol: Protocol::Sctp,
        }
    }
}

impl FromStr for PublishPort {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        let mut elems = s.split('/');
        let port = elems
            .next()
            .ok_or_else(|| Error::InvalidPort("missing port number".into()))
            .and_then(|port| {
                port.parse::<u32>()
                    .map_err(|e| Error::InvalidPort(format!("expected port number - {}", e)))
            })?;

        let protocol = elems
            .next()
            .ok_or_else(|| Error::InvalidPort("missing protocol".into()))
            .and_then(Protocol::from_str)?;

        Ok(PublishPort { port, protocol })
    }
}

impl ToString for PublishPort {
    fn to_string(&self) -> String {
        format!("{}/{}", self.port, self.protocol.as_ref())
    }
}

impl ContainerOptsBuilder {
    pub(crate) fn new(image: &str) -> Self {
        let mut params = HashMap::new();

        params.insert("Image", Value::String(image.to_owned()));
        ContainerOptsBuilder { name: None, params }
    }

    /// Set the name of the container.
    pub fn name<N>(&mut self, name: N) -> &mut Self
    where
        N: Into<String>,
    {
        self.name = Some(name.into());
        self
    }

    /// enable all exposed ports on the container to be mapped to random, available, ports on the host
    pub fn publish_all_ports(&mut self) -> &mut Self {
        self.params
            .insert("HostConfig.PublishAllPorts", Value::Bool(true));
        self
    }

    pub fn expose(&mut self, srcport: PublishPort, hostport: u32) -> &mut Self {
        let mut exposedport: HashMap<String, String> = HashMap::new();
        exposedport.insert("HostPort".to_string(), hostport.to_string());

        // The idea here is to go thought the 'old' port binds and to apply them to the local
        // 'port_bindings' variable, add the bind we want and replace the 'old' value
        let mut port_bindings: HashMap<String, Value> = HashMap::new();
        for (key, val) in self
            .params
            .get("HostConfig.PortBindings")
            .unwrap_or(&json!(null))
            .as_object()
            .unwrap_or(&Map::new())
            .iter()
        {
            port_bindings.insert(key.to_string(), json!(val));
        }
        port_bindings.insert(srcport.to_string(), json!(vec![exposedport]));

        self.params
            .insert("HostConfig.PortBindings", json!(port_bindings));

        // Replicate the port bindings over to the exposed ports config
        let mut exposed_ports: HashMap<String, Value> = HashMap::new();
        let empty_config: HashMap<String, Value> = HashMap::new();
        for key in port_bindings.keys() {
            exposed_ports.insert(key.to_string(), json!(empty_config));
        }

        self.params.insert("ExposedPorts", json!(exposed_ports));

        self
    }

    /// Publish a port in the container without assigning a port on the host
    pub fn publish(&mut self, port: PublishPort) -> &mut Self {
        /* The idea here is to go thought the 'old' port binds
         * and to apply them to the local 'exposedport_bindings' variable,
         * add the bind we want and replace the 'old' value */
        let mut exposed_port_bindings: HashMap<String, Value> = HashMap::new();
        for (key, val) in self
            .params
            .get("ExposedPorts")
            .unwrap_or(&json!(null))
            .as_object()
            .unwrap_or(&Map::new())
            .iter()
        {
            exposed_port_bindings.insert(key.to_string(), json!(val));
        }
        exposed_port_bindings.insert(port.to_string(), json!({}));

        // Replicate the port bindings over to the exposed ports config
        let mut exposed_ports: HashMap<String, Value> = HashMap::new();
        let empty_config: HashMap<String, Value> = HashMap::new();
        for key in exposed_port_bindings.keys() {
            exposed_ports.insert(key.to_string(), json!(empty_config));
        }

        self.params.insert("ExposedPorts", json!(exposed_ports));

        self
    }

    impl_str_field!(
        /// Specify the working dir (corresponds to the `-w` docker cli argument)
        working_dir: W => "WorkingDir"
    );

    impl_vec_field!(
        /// Specify any bind mounts, taking the form of `/some/host/path:/some/container/path`
        volumes: V => "HostConfig.Binds"
    );

    impl_vec_field!(links: L => "HostConfig.Links");

    impl_field!(memory: u64 => "HostConfig.Memory");

    impl_field!(
        /// Total memory limit (memory + swap) in bytes. Set to -1 (default) to enable unlimited swap.
        memory_swap: i64 => "HostConfig.MemorySwap"
    );

    impl_field!(
        /// CPU quota in units of 10<sup>-9</sup> CPUs. Set to 0 (default) for there to be no limit.
        ///
        /// For example, setting `nano_cpus` to `500_000_000` results in the container being allocated
        /// 50% of a single CPU, while `2_000_000_000` results in the container being allocated 2 CPUs.
        nano_cpus: u64 => "HostConfig.NanoCpus"
    );

    /// CPU quota in units of CPUs. This is a wrapper around `nano_cpus` to do the unit conversion.
    ///
    /// See [`nano_cpus`](#method.nano_cpus).
    pub fn cpus(&mut self, cpus: f64) -> &mut Self {
        self.nano_cpus((1_000_000_000.0 * cpus) as u64)
    }

    impl_field!(
    /// Sets an integer value representing the container's relative CPU weight versus other containers.
    cpu_shares: u32 => "HostConfig.CpuShares");

    impl_map_field!(json labels: L => "Labels");

    /// Whether to attach to `stdin`.
    pub fn attach_stdin(&mut self, attach: bool) -> &mut Self {
        self.params.insert("AttachStdin", json!(attach));
        self.params.insert("OpenStdin", json!(attach));
        self
    }

    impl_field!(
    /// Whether to attach to `stdout`.
    attach_stdout: bool => "AttachStdout");

    impl_field!(
    /// Whether to attach to `stderr`.
    attach_stderr: bool => "AttachStderr");

    impl_field!(
    /// Whether standard streams should be attached to a TTY.
    tty: bool => "Tty");

    impl_vec_field!(extra_hosts: H => "HostConfig.ExtraHosts");

    impl_vec_field!(volumes_from: V => "HostConfig.VolumesFrom");

    impl_str_field!(network_mode: M => "HostConfig.NetworkMode");

    impl_vec_field!(env: E => "Env");

    impl_vec_field!(cmd: C => "Cmd");

    impl_vec_field!(entrypoint: E => "Entrypoint");

    impl_vec_field!(capabilities: C => "HostConfig.CapAdd");

    pub fn devices(&mut self, devices: Vec<Labels>) -> &mut Self {
        self.params.insert("HostConfig.Devices", json!(devices));
        self
    }

    impl_str_field!(log_driver: L => "HostConfig.LogConfig.Type");

    pub fn restart_policy(&mut self, name: &str, maximum_retry_count: u64) -> &mut Self {
        self.params
            .insert("HostConfig.RestartPolicy.Name", json!(name));
        if name == "on-failure" {
            self.params.insert(
                "HostConfig.RestartPolicy.MaximumRetryCount",
                json!(maximum_retry_count),
            );
        }
        self
    }

    impl_field!(auto_remove: bool => "HostConfig.AutoRemove");

    impl_str_field!(
    /// Signal to stop a container as a string. Default is \"SIGTERM\"
    stop_signal: S => "StopSignal");

    impl_field!(
    /// Signal to stop a container as an integer. Default is 15 (SIGTERM).
    stop_signal_num: u64 => "StopSignal");

    impl_field!(
    /// Timeout to stop a container. Only seconds are counted. Default is 10s
    stop_timeout: Duration => "StopTimeout");

    impl_str_field!(userns_mode: M => "HostConfig.UsernsMode");

    impl_field!(privileged: bool => "HostConfig.Privileged");

    impl_str_field!(user: U => "User");

    pub fn build(&self) -> ContainerCreateOpts {
        ContainerCreateOpts {
            name: self.name.clone(),
            params: self.params.clone(),
        }
    }
}

impl_opts_builder!(url => RmContainer);

impl RmContainerOptsBuilder {
    impl_url_bool_field!(
        /// If the container is running, kill it before removing it.
        force => "force"
    );

    impl_url_bool_field!(
        /// Remove anonymous volumes associated with the container.
        volumes => "v"
    );

    impl_url_bool_field!(
        /// Remove the specified link associated with the container.
        link => "link"
    );
}

impl_opts_builder!(url => ContainerPrune);

pub enum ContainerPruneFilter {
    /// Prune containers created before this timestamp. The <timestamp> can be Unix timestamps,
    /// date formatted timestamps, or Go duration strings (e.g. 10m, 1h30m) computed relative to
    /// the daemon machine’s time.
    Until(String),
    #[cfg(feature = "chrono")]
    #[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
    /// Prune containers created before this timestamp. Same as `Until` but takes a datetime object.
    UntilDate(chrono::DateTime<chrono::Utc>),
    /// Label in the form of `label=key`.
    LabelKey(String),
    /// Label in the form of `label=key=val`.
    Label(String, String),
}

impl Filter for ContainerPruneFilter {
    fn query_key_val(&self) -> (&'static str, String) {
        use ContainerPruneFilter::*;
        match &self {
            Until(until) => ("until", until.to_owned()),
            #[cfg(feature = "chrono")]
            UntilDate(until) => ("until", until.timestamp().to_string()),
            LabelKey(label) => ("label", label.to_owned()),
            Label(key, val) => ("label", format!("{}={}", key, val)),
        }
    }
}

impl ContainerPruneOptsBuilder {
    impl_filter_func!(ContainerPruneFilter);
}

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

    macro_rules! test_case {
        ($opts:expr, $want:expr) => {
            let opts = $opts.build();

            pretty_assertions::assert_eq!($want, opts.serialize().unwrap())
        };
    }

    #[test]
    fn create_container_opts() {
        test_case!(
            ContainerOptsBuilder::new("test_image"),
            r#"{"HostConfig":{},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").env(vec!["foo", "bar"]),
            r#"{"Env":["foo","bar"],"HostConfig":{},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").env(&["foo", "bar", "baz"]),
            r#"{"Env":["foo","bar","baz"],"HostConfig":{},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").env(std::iter::once("test")),
            r#"{"Env":["test"],"HostConfig":{},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").user("alice"),
            r#"{"HostConfig":{},"Image":"test_image","User":"alice"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image")
                .network_mode("host")
                .auto_remove(true)
                .privileged(true),
            r#"{"HostConfig":{"AutoRemove":true,"NetworkMode":"host","Privileged":true},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").expose(PublishPort::tcp(80), 8080),
            r#"{"ExposedPorts":{"80/tcp":{}},"HostConfig":{"PortBindings":{"80/tcp":[{"HostPort":"8080"}]}},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image")
                .expose(PublishPort::udp(80), 8080)
                .expose(PublishPort::sctp(81), 8081),
            r#"{"ExposedPorts":{"80/udp":{},"81/sctp":{}},"HostConfig":{"PortBindings":{"80/udp":[{"HostPort":"8080"}],"81/sctp":[{"HostPort":"8081"}]}},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image")
                .publish(PublishPort::udp(80))
                .publish(PublishPort::sctp(6969))
                .publish(PublishPort::tcp(1337)),
            r#"{"ExposedPorts":{"1337/tcp":{},"6969/sctp":{},"80/udp":{}},"HostConfig":{},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").publish_all_ports(),
            r#"{"HostConfig":{"PublishAllPorts":true},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").log_driver("fluentd"),
            r#"{"HostConfig":{"LogConfig":{"Type":"fluentd"}},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").restart_policy("on-failure", 10),
            r#"{"HostConfig":{"RestartPolicy":{"MaximumRetryCount":10,"Name":"on-failure"}},"Image":"test_image"}"#
        );

        test_case!(
            ContainerOptsBuilder::new("test_image").restart_policy("always", 0),
            r#"{"HostConfig":{"RestartPolicy":{"Name":"always"}},"Image":"test_image"}"#
        );
    }
}