depl 2.4.3

Toolkit for a bunch of local and remote CI/CD actions
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
//! Actions module.
//!
//! Action is the main entity of Deployer. Actions as part of pipelines are used to build, install, and deploy processes.

use anyhow::{anyhow, bail};
use colored::Colorize;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};

pub mod observe;
pub mod patch;
pub mod staged;
pub mod storage_add;
pub mod storage_use;
pub mod test;

use crate::actions::staged::{Stage, StagedAction};
use crate::actions::{
  observe::ObserveAction, patch::PatchAction, storage_add::AddToStorageAction, storage_use::UseFromStorageAction,
  test::TestAction,
};
use crate::bset;
use crate::cmd::{CatActionArgs, EditActionArgs, NewActionArgs, RemoveActionArgs};
use crate::entities::info::StrToInfo;
use crate::entities::variables::Variable;
use crate::entities::{
  custom_command::CustomCommand,
  environment::RunEnvironment,
  info::{ActionInfo, ShortName, info2str, str2info},
  requirements::Requirement,
};
use crate::globals::DeployerGlobalConfig;
use crate::pipelines::DescribedPipeline;
use crate::project::DeployerProjectOptions;
use crate::rw::read_checked;

/// Used action.
#[derive(Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct UsedAction {
  /// Description of the action.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub title: Option<String>,
  /// Action defined in the project config.
  pub used: ActionInfo,
  /// Placeholder - variable name pairs for given action.
  #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
  pub with: BTreeMap<String, ShortName>,
}

impl UsedAction {
  /// Finds the definition of an action, if it's used.
  pub fn definition<'project>(
    &'project self,
    definitions: &'project BTreeSet<DefinedAction>,
  ) -> anyhow::Result<&'project DefinedAction> {
    definitions
      .iter()
      .find(|d| d.info.eq(&self.used))
      .ok_or(anyhow::anyhow!(
        "Can't find definition of `{}` action!",
        self.used.to_str()
      ))
  }

  /// Returns mutable slice to all custom commands in this action.
  pub fn commands<'project>(
    &'project self,
    definitions: &'project BTreeSet<DefinedAction>,
  ) -> anyhow::Result<Vec<&'project CustomCommand>> {
    self.definition(definitions)?.commands()
  }
}

/// Defined action.
///
/// Represents common info about an action, some properties such as requirements, and
/// action definition.
#[derive(Deserialize, Serialize, Eq, Clone)]
pub struct DefinedAction {
  /// Short name and version.
  #[serde(serialize_with = "info2str", deserialize_with = "str2info")]
  pub info: ActionInfo,

  /// List of tags (to use with `grep` when searching through `deployer ls actions`).
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub tags: Vec<String>,

  /// Requirements list.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub requirements: Vec<Requirement>,

  /// Flag of execution inside project folder.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub exec_in_project_dir: Option<bool>,

  /// Flag of skipping project folder synchronization with running folder after execution with `exec_in_project_dir = true`.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub skip_sync: Option<bool>,

  /// Action definition.
  pub action: Action,
}

impl PartialEq for DefinedAction {
  fn eq(&self, other: &Self) -> bool {
    self.info.eq(&other.info)
  }
}

impl Ord for DefinedAction {
  fn cmp(&self, other: &Self) -> std::cmp::Ordering {
    self.info.cmp(&other.info)
  }
}

#[allow(clippy::non_canonical_partial_ord_impl)]
impl PartialOrd for DefinedAction {
  fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
    Some(self.info.cmp(&other.info))
  }
}

impl DefinedAction {
  /// Returns mutable slice to all custom commands in this action.
  pub fn commands(&self) -> anyhow::Result<Vec<&CustomCommand>> {
    let cmds = match &self.action {
      Action::Interrupt
      | Action::SyncToRemote { .. }
      | Action::SyncFromRemote { .. }
      | Action::AddToStorage(_)
      | Action::UseFromStorage(_)
      | Action::Patch(_) => vec![],
      Action::Custom(cmd) => vec![cmd],
      Action::Staged(a) => vec![&a.command],
      Action::Test(ta) => vec![&ta.command],
      Action::Observe(oa) => vec![&oa.command],
    };
    Ok(cmds)
  }

  /// Collects all required variables to become a used action.
  pub fn collect_required_variables(&self) -> BTreeSet<String> {
    let mut vars = bset![];

    match &self.action {
      Action::Custom(cmd) => {
        cmd.placeholders.iter().for_each(|item| {
          vars.insert(item.to_owned());
        });
      }
      Action::Staged(a) => {
        a.command.placeholders.iter().for_each(|item| {
          vars.insert(item.to_owned());
        });
      }
      Action::Test(ta) => {
        ta.command.placeholders.iter().for_each(|item| {
          vars.insert(item.to_owned());
        });
      }
      Action::Observe(oa) => {
        oa.command.placeholders.iter().for_each(|item| {
          vars.insert(item.to_owned());
        });
      }
      _ => {}
    }

    vars
  }

  /// Converts defined action to shell commands.
  pub async fn to_shell(
    &self,
    env: &RunEnvironment<'_>,
    vars: &BTreeMap<String, Variable>,
  ) -> anyhow::Result<Vec<String>> {
    match &self.action {
      Action::Interrupt if !env.containered_build => Ok(vec!["read -p \"Press Enter to continue...\"".to_string()]),
      Action::Custom(c) => c.to_shell(env, vars).await,
      Action::Test(c) => c.to_shell(env, vars).await,
      Action::Staged(a) if a.stage() != Stage::Deploy || !env.containered_build => a.to_shell(env, vars).await,
      Action::Observe(c) if !env.containered_build => c.to_shell(env, vars).await,
      Action::Patch(c) => c.to_shell(env).await,
      Action::AddToStorage(c) => c.to_shell(env).await,
      Action::UseFromStorage(c) if !env.containered_build && !env.containered_run => c.to_shell(env).await,

      _ => {
        println!("Skip action during translation into shell script...");
        Ok(vec![])
      }
    }
  }

  /// Converts self to used action.
  pub fn r#use(&self) -> UsedAction {
    UsedAction {
      title: None,
      used: self.info.clone(),
      with: Default::default(),
    }
  }

  /// Tells if action will print command output by default.
  pub fn is_always_piped(&self) -> bool {
    match &self.action {
      Action::Custom(c) => c.show_success_output.is_some_and(|v| v),
      Action::Staged(s) => s.command.show_success_output.is_some_and(|v| v),
      Action::Test(t) => t.command.show_success_output.is_some_and(|v| v),
      Action::Observe(_) => true,
      _ => false,
    }
  }

  /// Tells if action is observer and will not collect any output to the return vector.
  pub fn is_observer(&self) -> bool {
    matches!(&self.action, Action::Observe(_))
  }
}

/// Action types.
///
/// See [DOCS.en.md](/DOCS.en.md) and [DOCS.ru.md](/DOCS.ru.md).
#[derive(Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Clone)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum Action {
  /// Used when the user needs to perform actions independently.
  Interrupt,

  /// Action to synchronize build folder with remote host.
  SyncToRemote {
    /// Remote host shortname.
    remote_host_name: ShortName,
  },
  /// Action to synchronize build folder from remote host.
  SyncFromRemote {
    /// Remote host shortname.
    remote_host_name: ShortName,
  },

  /// Single command.
  Custom(CustomCommand),
  /// Staged action.
  Staged(StagedAction),
  /// Action to run tests.
  Test(TestAction),

  /// Action to run observers (`btop`, `gdb`, some `docker` containers, foreground benchmarks, Jaeger, Prometheus, Grafana, etc.).
  Observe(ObserveAction),

  /// Action to copy content with given info from Deployer's storage.
  UseFromStorage(UseFromStorageAction),
  /// Action to add all available artifacts to Deployer's storage.
  AddToStorage(AddToStorageAction),

  /// Action to apply `smart-patcher` patches
  /// (see [`smart-patcher` repository](https://github.com/impulse-sw/smart-patcher)).
  Patch(PatchAction),
}

impl Action {
  /// Interrupt action.
  pub fn interrupt() -> anyhow::Result<(bool, Vec<String>)> {
    println!();
    inquire_reorder::Confirm::new("The pipeline is interrupted. Hit `Enter` to continue")
      .with_default(true)
      .prompt()?;
    let _ = std::io::read_to_string(std::io::stdin())?;
    Ok((true, vec![]))
  }

  /// Runs the action with given project options and run environment.
  pub async fn run_with(
    &self,
    config: &DeployerProjectOptions,
    pipeline: &DescribedPipeline,
    env: &mut RunEnvironment<'_>,
    with: &BTreeMap<String, ShortName>,
  ) -> anyhow::Result<(bool, Vec<String>)> {
    use crate::pipelines::place_artifacts;
    use crate::remote::{sync_from_remote, sync_to_remote};

    let vars = config.variables_for(with)?;

    let (status, output) = match self {
      Action::SyncToRemote { remote_host_name } => {
        if let Some(remote) = env.remotes.get(remote_host_name) {
          use std::{collections::HashSet, path::PathBuf};

          let mut ignore = HashSet::new();
          config.cache_files.iter().for_each(|i| {
            ignore.insert(i.to_owned());
          });
          config.ignore_files.iter().for_each(|i| {
            ignore.insert(i.to_owned());
          });
          ignore.insert(PathBuf::from("artifacts"));

          if let Err(e) = sync_to_remote(env.run_dir, remote, &ignore) {
            (false, vec![e.to_string()])
          } else {
            (true, vec![])
          }
        } else {
          (
            false,
            vec!["There is no such remote host in Deployer's Registry!".to_string()],
          )
        }
      }
      Action::SyncFromRemote { remote_host_name } => {
        if let Some(remote) = env.remotes.get(remote_host_name) {
          if let Err(e) = sync_from_remote(env.run_dir, remote) {
            (false, vec![e.to_string()])
          } else {
            (true, vec![])
          }
        } else {
          (
            false,
            vec!["There is no such remote host in Deployer's Registry!".to_string()],
          )
        }
      }
      Action::Custom(cmd) => cmd.execute(env, &vars).await?,
      Action::Test(test) => test.execute(env, &vars).await?,
      Action::Staged(a) if a.stage() != Stage::Deploy || !env.containered_build => a.execute(env, &vars).await?,
      Action::Observe(o_action) if !env.containered_build => o_action.execute(env, &vars).await?,
      Action::Patch(patch) => patch.execute(env).await?,
      Action::Interrupt if !env.containered_build => Action::interrupt()?,
      Action::UseFromStorage(use_from_action) if !env.containered_build && !env.containered_run => {
        use_from_action.execute(env).await?
      }
      Action::AddToStorage(rules) if !env.containered_build && !env.containered_run => {
        let placements = pipeline.collect_artifacts_placements(config, env).await?;
        place_artifacts(env, placements, false)?;
        rules.execute(env).await?
      }

      _ => (
        true,
        vec!["Skip this action due to not supporting when running in containers...".to_string()],
      ),
    };

    Ok((status, output))
  }
}

/// Prints all available actions on the screen.
pub fn list_actions(globals: &DeployerGlobalConfig) {
  println!("Available actions in Deployer's Registry:");

  for action in globals.actions_registry.iter() {
    let action_info = action.info.to_str();
    let tags = if action.tags.is_empty() {
      String::new()
    } else {
      format!(" (tags: {})", action.tags.join(", ").as_str().blue().italic())
    };
    println!("• {} {}", action_info.blue().bold(), tags);
  }
}

fn choose_action<'a>(actions_registry: &'a BTreeSet<DefinedAction>, prompt: &str) -> anyhow::Result<&'a DefinedAction> {
  if actions_registry.is_empty() {
    bail!("There is no actions in the Registry.");
  }

  let keys = actions_registry
    .iter()
    .map(|action| action.info.to_str())
    .collect::<Vec<_>>();
  let selected = inquire_reorder::Select::new(prompt, keys).prompt()?;
  actions_registry
    .iter()
    .find(|action| action.info.to_str().eq(&selected))
    .ok_or(anyhow!("No such action!"))
}

/// Removes selected action.
pub fn remove_action(globals: &mut DeployerGlobalConfig, args: RemoveActionArgs) -> anyhow::Result<()> {
  let action = if let Some(info) = args.info {
    let info = info.to_info()?;
    globals
      .actions_registry
      .iter()
      .find(|action| action.info.eq(&info))
      .ok_or(anyhow!("This action is not found in registry!"))?
      .clone()
  } else {
    choose_action(
      &globals.actions_registry,
      "Select action for removing from the registry:",
    )?
    .clone()
  };

  if !args.yes && !inquire_reorder::Confirm::new("Are you sure? (y/n)").prompt()? {
    return Ok(());
  }

  globals.actions_registry.remove(&action);

  Ok(())
}

/// Adds new action.
pub fn new_action(globals: &mut DeployerGlobalConfig, args: &NewActionArgs) -> anyhow::Result<DefinedAction> {
  if let Some(from_file) = &args.from {
    let action = read_checked::<DefinedAction>(from_file)
      .map_err(|e| {
        panic!("Can't read provided Action file due to: {e}");
      })
      .unwrap();
    globals.actions_registry.insert(action.clone());
    return Ok(action);
  }

  let defined_action = DefinedAction::new_from_prompt(Some(globals))?;

  Ok(defined_action)
}

/// Prints action as YAML.
pub fn cat_action(globals: &DeployerGlobalConfig, args: CatActionArgs) -> anyhow::Result<()> {
  let action = if let Some(info) = args.info {
    let info = info.to_info()?;
    globals
      .actions_registry
      .iter()
      .find(|action| action.info.eq(&info))
      .ok_or(anyhow!("This action is not found in registry!"))?
      .clone()
  } else {
    choose_action(&globals.actions_registry, "Select action for displaying:")?.clone()
  };

  let action_ser = serde_pretty_yaml::to_string_pretty(&action)?;
  println!("{action_ser}");

  Ok(())
}

/// Edits the action.
pub async fn edit_action(globals: &mut DeployerGlobalConfig, args: EditActionArgs) -> anyhow::Result<()> {
  let mut action = if let Some(info) = args.info {
    let info = info.to_info()?;
    globals
      .actions_registry
      .iter()
      .find(|action| action.info.eq(&info))
      .ok_or(anyhow!("This action is not found in registry!"))?
      .clone()
  } else {
    choose_action(&globals.actions_registry, "Select action for editing:")?.clone()
  };

  action.edit_action_from_prompt(None).await?;
  globals
    .actions_registry
    .retain(|in_registry| in_registry.info.ne(&action.info));
  globals.actions_registry.insert(action);

  Ok(())
}