komodo_client 2.3.1

Client for the Komodo build and deployment system
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
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
use anyhow::Context;
use bson::{Document, doc};
use derive_builder::Builder;
use derive_default_builder::DefaultBuilder;
use partial_derive2::Partial;
use serde::{Deserialize, Serialize};
use strum::{AsRefStr, Display, EnumDiscriminants, EnumString};
use typeshare::typeshare;

use crate::{
  deserializers::*,
  entities::{
    EnvironmentVar, ImageDigest, environment_vars_from_str,
    optional_str,
  },
  parsers::parse_key_value_list,
};

use super::{
  TerminationSignal, Version,
  docker::container::ContainerStateStatusEnum,
  resource::{Resource, ResourceListItem, ResourceQuery},
};

#[cfg(feature = "utoipa")]
#[derive(utoipa::ToSchema)]
#[schema(as = Deployment)]
pub struct DeploymentSchema(
  #[schema(inline)]
  pub  Resource<DeploymentConfig, crate::entities::NoData>,
);

#[typeshare]
pub type Deployment = Resource<DeploymentConfig, DeploymentInfo>;

impl Deployment {
  /// Configured custom container / service name,
  /// falling back to deployment name.
  /// This is the name the next deploy will use.
  pub fn custom_name(&self) -> &str {
    optional_str(self.config.custom_name.trim())
      .unwrap_or(self.name.trim())
  }

  /// The name of the currently deployed container / service,
  /// falling back to [Deployment::custom_name].
  /// May be different than custom_name if the name configuration
  /// changed since the last deploy. Use this to match the Deployment
  /// against the existing container / service.
  pub fn deployed_name(&self) -> &str {
    let trimmed = self.info.deployed_name.trim();
    if !trimmed.is_empty() {
      trimmed
    } else {
      self.custom_name()
    }
  }
}

#[typeshare]
pub type DeploymentListItem =
  ResourceListItem<DeploymentListItemInfo>;

impl DeploymentListItem {
  /// Configured custom container / service name,
  /// falling back to deployment name.
  pub fn custom_name(&self) -> &str {
    optional_str(self.info.custom_name.trim())
      .unwrap_or(self.name.trim())
  }
}

#[typeshare]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct DeploymentListItemInfo {
  /// The state of the deployment / underlying docker container.
  pub state: DeploymentState,
  /// The status of the docker container (eg. up 12 hours, exited 5 minutes ago.)
  pub status: Option<String>,
  /// The container / service name, if different than
  /// the deployment name. Uses the currently deployed name
  /// if deployed, else the configured custom name.
  pub custom_name: String,
  /// The image attached to the deployment.
  pub image: String,
  /// Whether there is a newer image available at the same tag.
  pub update_available: bool,
  /// The swarm that deployment is deployed on, when in Swarm mode.
  pub swarm_id: String,
  /// The name of the swarm that deployment is deployed on, when in Swarm mode.
  #[serde(default)]
  pub swarm_name: String,
  /// The server that deployment is deployed on, when in Server mode.
  pub server_id: String,
  /// The name of the server that deployment is deployed on, when in Server mode.
  #[serde(default)]
  pub server_name: String,
  /// An attached Komodo Build, if it exists.
  pub build_id: Option<String>,
}

#[typeshare]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct DeploymentInfo {
  /// Store the latest associated image digest.
  /// This includes both the image name / tag, and the specific digest hash.
  #[serde(default)]
  pub latest_image_digest: ImageDigest,
  /// The container / service name used at the time of the last deploy.
  /// Kept to match the Deployment to its container / service
  /// even if the name configuration changes before the next deploy.
  #[serde(default)]
  pub deployed_name: String,
}

#[typeshare(serialized_as = "Partial<DeploymentConfig>")]
pub type _PartialDeploymentConfig = PartialDeploymentConfig;

#[typeshare]
#[derive(Serialize, Deserialize, Debug, Clone, Builder, Partial)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[partial_derive(Serialize, Deserialize, Debug, Clone, Default)]
#[cfg_attr(
  feature = "schemars",
  partial_derive(schemars::JsonSchema)
)]
#[diff_derive(Serialize, Deserialize, Debug, Clone, Default)]
#[partial(skip_serializing_none, from, diff)]
pub struct DeploymentConfig {
  /// The Swarm to deploy the Deployment on (as a Swarm Service), setting the Deployment into Swarm mode.
  ///
  /// Note. If both swarm_id and server_id are set,
  /// swarm_id overrides server_id and the Deployment will be in Swarm mode.
  #[serde(default, alias = "swarm")]
  #[partial_attr(serde(alias = "swarm"))]
  #[cfg_attr(
    feature = "schemars",
    partial_attr(schemars(rename = "swarm"))
  )]
  #[builder(default)]
  pub swarm_id: String,

  /// The Server to deploy the Deployment on, setting the Deployment into Container mode.
  ///
  /// Note. If both swarm_id and server_id are set,
  /// swarm_id overrides server_id and the Deployment will be in Swarm mode.
  #[serde(default, alias = "server")]
  #[partial_attr(serde(alias = "server"))]
  #[cfg_attr(
    feature = "schemars",
    partial_attr(schemars(rename = "server"))
  )]
  #[builder(default)]
  pub server_id: String,

  /// Specify a custom container / service name,
  /// if different from Deployment name.
  #[serde(default)]
  #[builder(default)]
  pub custom_name: String,

  /// The image which the deployment deploys.
  /// Can either be a user inputted image, or a Komodo Build.
  #[serde(default)]
  #[builder(default)]
  pub image: DeploymentImage,

  /// Configure the account used to pull the image from the registry.
  /// Used with `docker login`.
  ///
  ///  - If the field is empty string, will use the same account config as the build, or none at all if using image.
  ///  - If the field contains an account, a token for the account must be available.
  ///  - Will get the registry domain from the build / image
  #[serde(default)]
  #[builder(default)]
  pub image_registry_account: String,

  /// Whether to skip secret interpolation into the deployment environment variables.
  #[serde(default)]
  #[builder(default)]
  pub skip_secret_interp: bool,

  /// Whether to redeploy the deployment whenever the attached build finishes.
  #[serde(default)]
  #[builder(default)]
  pub redeploy_on_build: bool,

  /// Whether to poll for any updates to the image.
  #[serde(default)]
  #[builder(default)]
  pub poll_for_updates: bool,

  /// Whether to automatically redeploy when
  /// newer a image is found. Will implicitly
  /// enable `poll_for_updates`, you don't need to
  /// enable both.
  #[serde(default)]
  #[builder(default)]
  pub auto_update: bool,

  /// Whether to send ContainerStateChange alerts for this deployment.
  #[serde(default = "default_send_alerts")]
  #[builder(default = "default_send_alerts()")]
  #[partial_default(default_send_alerts())]
  pub send_alerts: bool,

  /// Configure quick links that are displayed in the resource header
  #[serde(default)]
  #[builder(default)]
  pub links: Vec<String>,

  /// The network attached to the container.
  /// Default is `host`.
  #[serde(default = "default_network")]
  #[builder(default = "default_network()")]
  #[partial_default(default_network())]
  pub network: String,

  /// The restart mode given to the container.
  #[serde(default)]
  #[builder(default)]
  pub restart: RestartMode,

  /// This is interpolated at the end of the `docker run` command,
  /// which means they are either passed to the containers inner process,
  /// or replaces the container command, depending on use of ENTRYPOINT or CMD in dockerfile.
  /// Empty is no command.
  #[serde(default)]
  #[builder(default)]
  pub command: String,

  /// The number of replicas for the Service.
  ///
  /// Note. Only used in Swarm mode.
  #[serde(default = "default_replicas")]
  #[builder(default = "default_replicas()")]
  #[partial_default(default_replicas())]
  pub replicas: i32,

  /// The default termination signal to use to stop the deployment. Defaults to SigTerm (default docker signal).
  #[serde(default)]
  #[builder(default)]
  pub termination_signal: TerminationSignal,

  /// The termination timeout.
  #[serde(default = "default_termination_timeout")]
  #[builder(default = "default_termination_timeout()")]
  #[partial_default(default_termination_timeout())]
  pub termination_timeout: i32,

  /// Extra args which are interpolated into the
  /// `docker run` / `docker service create` command,
  /// and affect the container configuration.
  ///
  /// - Container ref: https://docs.docker.com/reference/cli/docker/container/run/#options
  /// - Swarm Service ref: https://docs.docker.com/reference/cli/docker/service/create/#options
  #[serde(default, deserialize_with = "string_list_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_string_list_deserializer"
  ))]
  #[builder(default)]
  pub extra_args: Vec<String>,

  /// Labels attached to various termination signal options.
  /// Used to specify different shutdown functionality depending
  /// on the termination signal.
  #[serde(default, deserialize_with = "term_labels_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_term_labels_deserializer"
  ))]
  #[builder(default)]
  pub term_signal_labels: String,

  /// The container port mapping.
  /// Irrelevant if container network is `host`.
  /// Maps ports on host to ports on container.
  #[serde(default, deserialize_with = "conversions_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_conversions_deserializer"
  ))]
  #[builder(default)]
  pub ports: String,

  /// The container volume mapping.
  /// Maps files / folders on host to files / folders in container.
  #[serde(default, deserialize_with = "conversions_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_conversions_deserializer"
  ))]
  #[builder(default)]
  pub volumes: String,

  /// The environment variables passed to the container / service.
  #[serde(default, deserialize_with = "env_vars_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_env_vars_deserializer"
  ))]
  #[builder(default)]
  pub environment: String,

  /// The docker labels given to the container.
  #[serde(default, deserialize_with = "labels_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_labels_deserializer"
  ))]
  #[builder(default)]
  pub labels: String,
}

impl DeploymentConfig {
  pub fn builder() -> DeploymentConfigBuilder {
    DeploymentConfigBuilder::default()
  }

  pub fn env_vars(&self) -> anyhow::Result<Vec<EnvironmentVar>> {
    environment_vars_from_str(&self.environment)
      .context("Invalid environment")
  }
}

fn default_replicas() -> i32 {
  1
}

fn default_send_alerts() -> bool {
  true
}

fn default_termination_timeout() -> i32 {
  10
}

fn default_network() -> String {
  String::from("host")
}

impl Default for DeploymentConfig {
  fn default() -> Self {
    Self {
      swarm_id: Default::default(),
      server_id: Default::default(),
      custom_name: Default::default(),
      image: Default::default(),
      image_registry_account: Default::default(),
      skip_secret_interp: Default::default(),
      redeploy_on_build: Default::default(),
      poll_for_updates: Default::default(),
      auto_update: Default::default(),
      send_alerts: default_send_alerts(),
      links: Default::default(),
      network: default_network(),
      restart: Default::default(),
      command: Default::default(),
      replicas: default_replicas(),
      termination_signal: Default::default(),
      termination_timeout: default_termination_timeout(),
      extra_args: Default::default(),
      term_signal_labels: Default::default(),
      ports: Default::default(),
      volumes: Default::default(),
      environment: Default::default(),
      labels: Default::default(),
    }
  }
}

#[cfg(feature = "utoipa")]
impl utoipa::PartialSchema for PartialDeploymentConfig {
  fn schema()
  -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
    utoipa::schema!(#[inline] std::collections::HashMap<String, serde_json::Value>).into()
  }
}

#[cfg(feature = "utoipa")]
impl utoipa::ToSchema for PartialDeploymentConfig {}

#[typeshare]
#[derive(
  Serialize, Deserialize, Debug, Clone, PartialEq, EnumDiscriminants,
)]
#[strum_discriminants(name(DeploymentImageVariant))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(
  not(feature = "utoipa"),
  strum_discriminants(derive(
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    Display,
    EnumString,
    AsRefStr
  ))
)]
#[cfg_attr(
  feature = "utoipa",
  strum_discriminants(derive(
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    Display,
    EnumString,
    AsRefStr,
    utoipa::ToSchema
  ))
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(tag = "type", content = "params")]
pub enum DeploymentImage {
  /// Deploy any external image.
  Image {
    /// The docker image, can be from any registry that works with docker and that the host server can reach.
    #[serde(default)]
    image: String,
  },

  /// Deploy a Komodo Build.
  Build {
    /// The id of the Build
    #[serde(default, alias = "build")]
    #[cfg_attr(feature = "schemars", schemars(rename = "build"))]
    build_id: String,
    /// Use a custom / older version of the image produced by the build.
    /// if version is 0.0.0, this means `latest` image.
    #[serde(default)]
    version: Version,
  },
}

impl Default for DeploymentImage {
  fn default() -> Self {
    Self::Image {
      image: Default::default(),
    }
  }
}

impl DeploymentImage {
  pub fn as_image(&self) -> Option<&str> {
    let Self::Image { image } = self else {
      return None;
    };
    optional_str(image)
  }
}

#[typeshare]
#[derive(
  Debug, Clone, Default, PartialEq, Serialize, Deserialize,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct Conversion {
  /// reference on the server.
  pub local: String,
  /// reference in the container.
  pub container: String,
}

pub fn conversions_from_str(
  input: &str,
) -> anyhow::Result<Vec<Conversion>> {
  parse_key_value_list(input).map(|conversions| {
    conversions
      .into_iter()
      .map(|(local, container)| Conversion { local, container })
      .collect()
  })
}

/// Variants de/serialized from/to snake_case.
///
/// Eg.
/// - NotDeployed -> not_deployed
/// - Restarting -> restarting
/// - Running -> running.
#[typeshare]
#[derive(
  Debug,
  Clone,
  Copy,
  PartialEq,
  Eq,
  Hash,
  PartialOrd,
  Ord,
  Default,
  Display,
  EnumString,
  Serialize,
  Deserialize,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DeploymentState {
  /// The deployment is currently re/deploying
  Deploying,
  /// Container / Service is running
  Running,
  /// Server mode only. Container is created but not running.
  Created,
  /// Server mode only. Container is in restart loop
  Restarting,
  /// Server mode only. Container is in the process of stopping
  Stopping,
  /// Server mode only. Container is being removed
  Removing,
  /// Server mode only. Container is paused
  Paused,
  /// Server mode only. Container is exited
  Exited,
  /// Server mode only. Container is dead
  Dead,
  /// Swarm mode only. Some tasks don't match their desired state.
  Unhealthy,
  /// The deployment is not deployed (no matching Container / Service)
  NotDeployed,
  /// Server / Swarm not reachable for status
  #[default]
  Unknown,
}

impl From<ContainerStateStatusEnum> for DeploymentState {
  fn from(value: ContainerStateStatusEnum) -> Self {
    match value {
      ContainerStateStatusEnum::Empty => DeploymentState::Unknown,
      ContainerStateStatusEnum::Created => DeploymentState::Created,
      ContainerStateStatusEnum::Running => DeploymentState::Running,
      ContainerStateStatusEnum::Paused => DeploymentState::Paused,
      ContainerStateStatusEnum::Restarting => {
        DeploymentState::Restarting
      }
      ContainerStateStatusEnum::Stopping => DeploymentState::Stopping,
      ContainerStateStatusEnum::Removing => DeploymentState::Removing,
      ContainerStateStatusEnum::Exited => DeploymentState::Exited,
      ContainerStateStatusEnum::Dead => DeploymentState::Dead,
    }
  }
}

#[typeshare]
#[derive(
  Serialize,
  Deserialize,
  Debug,
  PartialEq,
  Hash,
  Eq,
  Clone,
  Copy,
  Default,
  Display,
  EnumString,
  AsRefStr,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum RestartMode {
  #[default]
  #[serde(rename = "no")]
  #[strum(serialize = "no")]
  NoRestart,
  #[serde(rename = "on-failure")]
  #[strum(serialize = "on-failure")]
  OnFailure,
  #[serde(rename = "always")]
  #[strum(serialize = "always")]
  Always,
  #[serde(rename = "unless-stopped")]
  #[strum(serialize = "unless-stopped")]
  UnlessStopped,
}

#[typeshare]
#[derive(
  Serialize,
  Deserialize,
  Debug,
  Clone,
  Default,
  PartialEq,
  Eq,
  Builder,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct TerminationSignalLabel {
  #[builder(default)]
  pub signal: TerminationSignal,
  #[builder(default)]
  pub label: String,
}

pub fn term_signal_labels_from_str(
  input: &str,
) -> anyhow::Result<Vec<TerminationSignalLabel>> {
  parse_key_value_list(input).and_then(|list| {
    list
      .into_iter()
      .map(|(signal, label)| {
        anyhow::Ok(TerminationSignalLabel {
          signal: signal.parse()?,
          label,
        })
      })
      .collect()
  })
}

#[typeshare]
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct DeploymentActionState {
  pub pulling: bool,
  pub deploying: bool,
  pub updating: bool,
  pub starting: bool,
  pub restarting: bool,
  pub pausing: bool,
  pub unpausing: bool,
  pub stopping: bool,
  pub destroying: bool,
  pub renaming: bool,
}

#[typeshare]
pub type DeploymentQuery = ResourceQuery<DeploymentQuerySpecifics>;

#[typeshare]
#[derive(
  Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum DeploymentSortBy {
  /// Sort by name. Default.
  #[default]
  Name,
  /// Sort by image.
  Image,
  /// Sort by host Server / Swarm name.
  Host,
  /// Sort by state.
  State,
}

#[typeshare]
#[derive(
  Debug, Clone, Default, Serialize, Deserialize, DefaultBuilder,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct DeploymentQuerySpecifics {
  /// Query only for Deployments on these Servers.
  /// If empty, does not filter by Server.
  /// Only accepts Server id (not name).
  #[serde(default)]
  pub server_ids: Vec<String>,

  /// Query only for Deployments on these Swarms.
  /// If empty, does not filter by Swarm.
  /// Only accepts Swarm id (not name).
  #[serde(default)]
  pub swarm_ids: Vec<String>,

  /// Query only for Deployments with these Builds attached.
  /// If empty, does not filter by Build.
  /// Only accepts Build id (not name).
  #[serde(default)]
  pub build_ids: Vec<String>,

  /// Query only for Deployments with available image updates.
  #[serde(default)]
  pub update_available: bool,

  /// Query only for Deployments matching these states.
  /// If empty, does not filter by state.
  #[serde(default)]
  pub states: Vec<DeploymentState>,
}

impl super::resource::AddFilters for DeploymentQuerySpecifics {
  fn add_filters(&self, filters: &mut Document) {
    if !self.server_ids.is_empty() {
      filters
        .insert("config.server_id", doc! { "$in": &self.server_ids });
    }
    if !self.swarm_ids.is_empty() {
      filters
        .insert("config.swarm_id", doc! { "$in": &self.swarm_ids });
    }
    if !self.build_ids.is_empty() {
      filters.insert("config.image.type", "Build");
      filters.insert(
        "config.image.params.build_id",
        doc! { "$in": &self.build_ids },
      );
    }
  }
}

pub fn extract_registry_domain(
  image_name: &str,
) -> anyhow::Result<String> {
  let mut split = image_name.split('/');
  let maybe_domain =
    split.next().context("image name cannot be empty string")?;
  if maybe_domain.contains('.') {
    Ok(maybe_domain.to_string())
  } else {
    Ok(String::from("docker.io"))
  }
}