dragonfly-client-config 1.3.4

Configuration for the dragonfly client
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
/*
 *     Copyright 2024 The Dragonfly Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use crate::dfdaemon::default_proxy_server_port;
use dragonfly_client_core::error::{ErrorType, OrErr};
use dragonfly_client_core::Result;
use serde::{ser::SerializeStruct, Deserialize, Serialize};
use std::fs;
use std::net::Ipv4Addr;
use std::path::PathBuf;
use tracing::{info, instrument};
use validator::Validate;

/// NAME is the name of dfinit.
pub const NAME: &str = "dfinit";

/// default_dfinit_config_path is the default config path for dfinit.
#[inline]
pub fn default_dfinit_config_path() -> PathBuf {
    crate::default_config_dir().join("dfinit.yaml")
}

/// default_container_runtime_containerd_config_path is the default containerd configuration path.
#[inline]
fn default_container_runtime_containerd_config_path() -> PathBuf {
    PathBuf::from("/etc/containerd/config.toml")
}

/// default_container_runtime_docker_config_path is the default docker configuration path.
#[inline]
fn default_container_runtime_docker_config_path() -> PathBuf {
    PathBuf::from("/etc/docker/daemon.json")
}

/// default_container_runtime_crio_config_path is the default cri-o configuration path.
#[inline]
fn default_container_runtime_crio_config_path() -> PathBuf {
    PathBuf::from("/etc/containers/registries.conf")
}

/// default_container_runtime_podman_config_path is the default podman configuration path.
#[inline]
fn default_container_runtime_podman_config_path() -> PathBuf {
    PathBuf::from("/etc/containers/registries.conf")
}

/// default_container_runtime_crio_unqualified_search_registries is the default unqualified search registries of cri-o,
/// refer to https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#global-settings.
#[inline]
fn default_container_runtime_crio_unqualified_search_registries() -> Vec<String> {
    vec![
        "registry.fedoraproject.org".to_string(),
        "registry.access.redhat.com".to_string(),
        "docker.io".to_string(),
    ]
}

/// default_container_runtime_podman_unqualified_search_registries is the default unqualified search registries of cri-o,
/// refer to https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#global-settings.
#[inline]
fn default_container_runtime_podman_unqualified_search_registries() -> Vec<String> {
    vec![
        "registry.fedoraproject.org".to_string(),
        "registry.access.redhat.com".to_string(),
        "docker.io".to_string(),
    ]
}

/// default_proxy_addr is the default proxy address of dfdaemon.
#[inline]
fn default_proxy_addr() -> String {
    format!(
        "http://{}:{}",
        Ipv4Addr::LOCALHOST,
        default_proxy_server_port()
    )
}

/// default_container_runtime_containerd_registry_host_capabilities is the default
/// capabilities of the containerd registry.
#[inline]
fn default_container_runtime_containerd_registry_capabilities() -> Vec<String> {
    vec!["pull".to_string(), "resolve".to_string()]
}

/// Registry is the registry configuration for containerd.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ContainerdRegistry {
    /// host_namespace is the location where container images and artifacts are sourced,
    /// refer to https://github.com/containerd/containerd/blob/main/docs/hosts.md#registry-host-namespace.
    /// The registry host namespace portion is [registry_host_name|IP address][:port], such as
    /// docker.io, ghcr.io, gcr.io, etc.
    pub host_namespace: String,

    /// server_addr specifies the default server for this registry host namespace, refer to
    /// https://github.com/containerd/containerd/blob/main/docs/hosts.md#server-field.
    pub server_addr: String,

    /// capabilities is the list of capabilities in containerd configuration, refer to
    /// https://github.com/containerd/containerd/blob/main/docs/hosts.md#capabilities-field.
    #[serde(default = "default_container_runtime_containerd_registry_capabilities")]
    pub capabilities: Vec<String>,

    /// skip_verify is the flag to skip verifying the server's certificate, refer to
    /// https://github.com/containerd/containerd/blob/main/docs/hosts.md#bypass-tls-verification-example.
    pub skip_verify: Option<bool>,

    /// ca (Certificate Authority Certification) can be set to a path or an array of paths each pointing
    /// to a ca file for use in authenticating with the registry namespace, refer to
    /// https://github.com/containerd/containerd/blob/main/docs/hosts.md#ca-field.
    pub ca: Option<Vec<String>>,
}

/// Containerd is the containerd configuration for dfinit.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Containerd {
    /// config_path is the path of containerd configuration file.
    #[serde(default = "default_container_runtime_containerd_config_path")]
    pub config_path: PathBuf,

    /// registries is the list of containerd registries.
    pub registries: Vec<ContainerdRegistry>,
}

/// CRIORegistry is the registry configuration for cri-o.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize, PartialEq, Eq)]
#[serde(default, rename_all = "camelCase")]
pub struct CRIORegistry {
    /// prefix is the prefix of the user-specified image name, refer to
    /// https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#choosing-a-registry-toml-table.
    pub prefix: String,

    /// location accepts the same format as the prefix field, and specifies the physical location of the prefix-rooted namespace,
    /// refer to https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#remapping-and-mirroring-registries.
    pub location: String,
}

/// CRIO is the cri-o configuration for dfinit.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CRIO {
    /// config_path is the path of cri-o registries's configuration file.
    #[serde(default = "default_container_runtime_crio_config_path")]
    pub config_path: PathBuf,

    /// unqualified_search_registries is an array of host[:port] registries to try when pulling an unqualified image, in order.
    /// Refer to https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#global-settings.
    #[serde(default = "default_container_runtime_crio_unqualified_search_registries")]
    pub unqualified_search_registries: Vec<String>,

    /// registries is the list of cri-o registries, refer to
    /// https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#namespaced-registry-settings.
    pub registries: Vec<CRIORegistry>,
}

/// PodmanRegistry is the registry configuration for podman.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize, PartialEq, Eq)]
#[serde(default, rename_all = "camelCase")]
pub struct PodmanRegistry {
    /// prefix is the prefix of the user-specified image name, refer to
    /// https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#choosing-a-registry-toml-table.
    pub prefix: String,

    /// location accepts the same format as the prefix field, and specifies the physical location of the prefix-rooted namespace,
    /// refer to https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#remapping-and-mirroring-registries.
    pub location: String,
}

/// Podman is the podman configuration for dfinit.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Podman {
    /// config_path is the path of cri-o registries's configuration file.
    #[serde(default = "default_container_runtime_podman_config_path")]
    pub config_path: PathBuf,

    /// unqualified_search_registries is an array of host[:port] registries to try when pulling an unqualified image, in order.
    /// Refer to https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#global-settings.
    #[serde(default = "default_container_runtime_podman_unqualified_search_registries")]
    pub unqualified_search_registries: Vec<String>,

    /// registries is the list of cri-o registries, refer to
    /// https://github.com/containers/image/blob/main/docs/containers-registries.conf.5.md#namespaced-registry-settings.
    pub registries: Vec<PodmanRegistry>,
}

/// Docker is the docker configuration for dfinit.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Docker {
    /// config_path is the path of docker configuration file.
    #[serde(default = "default_container_runtime_docker_config_path")]
    pub config_path: PathBuf,
}

/// ContainerRuntime is the container runtime configuration for dfinit.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ContainerRuntime {
    #[serde(flatten)]
    pub config: Option<ContainerRuntimeConfig>,
}

/// ContainerRuntimeConfig is the container runtime configuration for dfinit.
#[derive(Debug, Clone)]
pub enum ContainerRuntimeConfig {
    Containerd(Containerd),
    Docker(Docker),
    CRIO(CRIO),
    Podman(Podman),
}

/// Serialize is the implementation of the Serialize trait for ContainerRuntimeConfig.
impl Serialize for ContainerRuntimeConfig {
    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match *self {
            ContainerRuntimeConfig::Containerd(ref cfg) => {
                let mut state = serializer.serialize_struct("containerd", 1)?;
                state.serialize_field("containerd", &cfg)?;
                state.end()
            }
            ContainerRuntimeConfig::Docker(ref cfg) => {
                let mut state = serializer.serialize_struct("docker", 1)?;
                state.serialize_field("docker", &cfg)?;
                state.end()
            }
            ContainerRuntimeConfig::CRIO(ref cfg) => {
                let mut state = serializer.serialize_struct("crio", 1)?;
                state.serialize_field("crio", &cfg)?;
                state.end()
            }
            ContainerRuntimeConfig::Podman(ref cfg) => {
                let mut state = serializer.serialize_struct("podman", 1)?;
                state.serialize_field("podman", &cfg)?;
                state.end()
            }
        }
    }
}

/// Deserialize is the implementation of the Deserialize trait for ContainerRuntimeConfig.
impl<'de> Deserialize<'de> for ContainerRuntimeConfig {
    fn deserialize<D>(deserializer: D) -> std::prelude::v1::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct ContainerRuntimeHelper {
            containerd: Option<Containerd>,
            docker: Option<Docker>,
            crio: Option<CRIO>,
            podman: Option<Podman>,
        }

        let helper = ContainerRuntimeHelper::deserialize(deserializer)?;
        match helper {
            ContainerRuntimeHelper {
                containerd: Some(containerd),
                ..
            } => Ok(ContainerRuntimeConfig::Containerd(containerd)),
            ContainerRuntimeHelper {
                docker: Some(docker),
                ..
            } => Ok(ContainerRuntimeConfig::Docker(docker)),
            ContainerRuntimeHelper {
                crio: Some(crio), ..
            } => Ok(ContainerRuntimeConfig::CRIO(crio)),
            ContainerRuntimeHelper {
                podman: Some(podman),
                ..
            } => Ok(ContainerRuntimeConfig::Podman(podman)),
            _ => {
                use serde::de::Error;
                Err(D::Error::custom(
                    "expected containerd or docker or crio or podman",
                ))
            }
        }
    }
}

/// Proxy is the proxy server configuration for dfdaemon.
#[derive(Debug, Clone, Validate, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Proxy {
    // addr is the proxy server address of dfdaemon.
    #[serde(default = "default_proxy_addr")]
    pub addr: String,
}

/// Proxy implements Default.
impl Default for Proxy {
    fn default() -> Self {
        Self {
            addr: default_proxy_addr(),
        }
    }
}

/// Config is the configuration for dfinit.
#[derive(Debug, Clone, Default, Validate, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Config {
    /// proxy is the configuration of the dfdaemon's HTTP/HTTPS proxy.
    #[validate]
    pub proxy: Proxy,

    /// container_runtime is the container runtime configuration.
    #[validate]
    pub container_runtime: ContainerRuntime,
}

/// Config implements the config operation of dfinit.
impl Config {
    /// load loads configuration from file.
    #[instrument(skip_all)]
    pub fn load(path: &PathBuf) -> Result<Config> {
        // Load configuration from file.
        let content = fs::read_to_string(path)?;
        let config: Config = serde_yaml::from_str(&content).or_err(ErrorType::ConfigError)?;
        info!("load config from {}", path.display());

        // Validate configuration.
        config.validate().or_err(ErrorType::ValidationError)?;
        Ok(config)
    }
}

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

    #[test]
    fn test_default_dfinit_config_path() {
        let expected = crate::default_config_dir().join("dfinit.yaml");
        assert_eq!(default_dfinit_config_path(), expected);
    }

    #[test]
    fn test_container_runtime_default_paths() {
        assert_eq!(
            default_container_runtime_containerd_config_path(),
            Path::new("/etc/containerd/config.toml")
        );
        assert_eq!(
            default_container_runtime_docker_config_path(),
            Path::new("/etc/docker/daemon.json")
        );
        assert_eq!(
            default_container_runtime_crio_config_path(),
            Path::new("/etc/containers/registries.conf")
        );
        assert_eq!(
            default_container_runtime_podman_config_path(),
            Path::new("/etc/containers/registries.conf")
        );
    }

    #[test]
    fn test_default_unqualified_search_registries() {
        let crio_registries = default_container_runtime_crio_unqualified_search_registries();
        assert_eq!(
            crio_registries,
            vec![
                "registry.fedoraproject.org",
                "registry.access.redhat.com",
                "docker.io"
            ]
        );

        let podman_registries = default_container_runtime_podman_unqualified_search_registries();
        assert_eq!(
            podman_registries,
            vec![
                "registry.fedoraproject.org",
                "registry.access.redhat.com",
                "docker.io"
            ]
        );
    }

    #[test]
    fn serialize_container_runtime() {
        let cfg = ContainerRuntimeConfig::Containerd(Containerd {
            ..Default::default()
        });
        let res = serde_yaml::to_string(&cfg).unwrap();
        let expected = r#"
containerd:
  configPath: ''
  registries: []"#;
        assert_eq!(expected.trim(), res.trim());

        let runtime_cfg = ContainerRuntimeConfig::Docker(Docker {
            config_path: PathBuf::from("/root/.dragonfly/config/dfinit/yaml"),
        });
        let cfg = Config {
            container_runtime: ContainerRuntime {
                config: Some(runtime_cfg),
            },
            proxy: Proxy {
                addr: String::from("hello"),
            },
        };

        let res = serde_yaml::to_string(&cfg).unwrap();
        let expected = r#"
proxy:
  addr: hello
containerRuntime:
  docker:
    configPath: /root/.dragonfly/config/dfinit/yaml"#;
        assert_eq!(expected.trim(), res.trim());

        let runtime_cfg = ContainerRuntimeConfig::Containerd(Containerd {
            config_path: PathBuf::from("/root/.dragonfly/config/dfinit/yaml"),
            ..Default::default()
        });
        let cfg = Config {
            container_runtime: ContainerRuntime {
                config: Some(runtime_cfg),
            },
            proxy: Proxy {
                addr: String::from("hello"),
            },
        };
        let res = serde_yaml::to_string(&cfg).unwrap();
        let expected = r#"
proxy:
  addr: hello
containerRuntime:
  containerd:
    configPath: /root/.dragonfly/config/dfinit/yaml
    registries: []"#;
        assert_eq!(expected.trim(), res.trim());
    }

    #[test]
    fn deserialize_container_runtime_correctly() {
        let raw_data = r#"
            proxy: 
                addr: "hello"
        "#;
        let cfg: Config = serde_yaml::from_str(raw_data).expect("failed to deserialize");
        assert!(cfg.container_runtime.config.is_none());
        assert_eq!("hello".to_string(), cfg.proxy.addr);

        let raw_data = r#"
            proxy: 
                addr: "hello"
            containerRuntime:
                containerd:
                    configPath: "test_path"
        "#;
        let cfg: Config = serde_yaml::from_str(raw_data).expect("failed to deserialize");
        assert_eq!("hello".to_string(), cfg.proxy.addr);
        if let Some(ContainerRuntimeConfig::Containerd(c)) = cfg.container_runtime.config {
            assert_eq!(PathBuf::from("test_path"), c.config_path);
        } else {
            panic!("failed to deserialize");
        }
    }

    #[test]
    fn deserialize_container_runtime_crio_correctly() {
        let raw_data = r#"
            proxy: 
                addr: "hello"
            containerRuntime:
                crio:
                    configPath: "test_path"
                    unqualifiedSearchRegistries:
                        - "reg1"
                        - "reg2"
                    registries:
                        - prefix: "prefix1"
                          location: "location1"
                        - prefix: "prefix2"
                          location: "location2"
        "#;
        let cfg: Config = serde_yaml::from_str(raw_data).expect("failed to deserialize");
        if let Some(ContainerRuntimeConfig::CRIO(c)) = cfg.container_runtime.config {
            assert_eq!(PathBuf::from("test_path"), c.config_path);
            assert_eq!(vec!["reg1", "reg2"], c.unqualified_search_registries);
            assert_eq!(
                vec![
                    CRIORegistry {
                        location: "location1".to_string(),
                        prefix: "prefix1".to_string()
                    },
                    CRIORegistry {
                        location: "location2".to_string(),
                        prefix: "prefix2".to_string()
                    },
                ],
                c.registries
            );
        } else {
            panic!("failed to deserialize");
        }
    }

    #[test]
    fn deserialize_container_runtime_podman_correctly() {
        let raw_data = r#"
            proxy: 
                addr: "hello"
            containerRuntime:
                podman:
                    configPath: "test_path"
                    unqualifiedSearchRegistries:
                        - "reg1"
                        - "reg2"
                    registries:
                        - prefix: "prefix1"
                          location: "location1"
                        - prefix: "prefix2"
                          location: "location2"
        "#;
        let cfg: Config = serde_yaml::from_str(raw_data).expect("failed to deserialize");
        if let Some(ContainerRuntimeConfig::Podman(c)) = cfg.container_runtime.config {
            assert_eq!(PathBuf::from("test_path"), c.config_path);
            assert_eq!(vec!["reg1", "reg2"], c.unqualified_search_registries);
            assert_eq!(
                vec![
                    PodmanRegistry {
                        location: "location1".to_string(),
                        prefix: "prefix1".to_string()
                    },
                    PodmanRegistry {
                        location: "location2".to_string(),
                        prefix: "prefix2".to_string()
                    },
                ],
                c.registries
            );
        } else {
            panic!("failed to deserialize");
        }
    }
}