manta-cli 2.0.0-beta.64

Another CLI for ALPS
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
//! `manta apply` subcommands — mutating operations that update an
//! existing resource or drive a workflow against the cluster.
//!
//! Leaves and their endpoints:
//!
//! - [`sat_file`] — `manta apply sat-file`: renders a SAT template,
//!   builds an in-memory plan, and POSTs one element at a time to
//!   `/api/v1/sat-file/{configurations,images,session-templates}`. See
//!   that module's docs for the plan/apply pattern.
//! - [`template`] — `manta apply template`: `POST
//!   /api/v1/sessiontemplates/{name}/session` to create a BOS session.
//! - [`boot_node`] / [`boot_group`] — `manta apply boot {nodes,group}`:
//!   `POST /api/v1/boot-config` against an explicit hosts expression
//!   (the `group` leaf resolves group members first).
//! - [`boot_parameters`] — `manta apply boot-parameters`: `PUT
//!   /api/v1/boot-parameters` to update an existing record.
//! - [`hardware_group`] — `manta apply hardware group`: `POST
//!   /api/v1/hardware-clusters/{target}` to pin or unpin
//!   pattern-selected components.
//! - [`kernel_parameters`] — `manta apply kernel-parameters`: full
//!   replace, rebooting affected nodes. See
//!   [`super::add::kernel_parameters`] for the additive variant.
//! - [`redfish_endpoint`] — `manta apply redfish-endpoint`: update an
//!   existing record.
//! - `ephemeral-environment` (handled inline below) — `POST
//!   /api/v1/ephemeral-env` to provision an ephemeral environment for
//!   an image; refuses to run if stdout is not a TTY.
//!
//! Most leaves accept `--dry-run`; whether that flows to the server or
//! short-circuits client-side depends on the endpoint and is
//! documented per-leaf.

pub mod boot_group;
pub mod boot_node;
pub mod boot_parameters;
pub mod runtime_configuration_group;
pub mod runtime_configuration_node;
pub mod hardware_group;
pub mod kernel_parameters;
pub mod redfish_endpoint;
pub mod sat_file;
pub mod template;

use crate::common::app_context::AppContext;
use crate::common::authentication::get_api_token;
use crate::common::clap_ext::ArgMatchesExt;
use crate::http_client::{MantaClient, OpenApiResultExt};
use anyhow::{Context, Error, bail};
use clap::ArgMatches;

/// Dispatch `manta apply` subcommands (hardware, sat-file, boot,
/// boot-parameters, redfish-endpoints, kernel-parameters,
/// ephemeral-environment, template).
///
/// # Errors
///
/// Returns an error when the auth token cannot be obtained, when
/// required clap arguments are missing or malformed (e.g. a non-UUID
/// `--boot-image` or a non-numeric `--ansible-verbosity`), when no
/// subcommand is provided or the name is unknown, when stdin is not a
/// terminal for `ephemeral-environment`, or when the leaf handler
/// returns an error.
pub async fn handle_apply(
  cli_apply: &ArgMatches,
  ctx: &AppContext<'_>,
) -> Result<(), Error> {
  let token = get_api_token(ctx).await?;

  match cli_apply.subcommand() {
    Some(("hardware", m)) => match m.subcommand() {
      Some(("group", m)) => {
        hardware_group::exec(m, ctx, &token).await?;
      }
      Some((other, _)) => bail!("Unknown 'apply hardware' subcommand: {other}"),
      None => bail!("No 'apply hardware' subcommand provided"),
    },

    Some(("sat-file", m)) => {
      let timestamp = chrono::Utc::now().format("%Y%m%d%H%M%S").to_string();

      let cli_value_vec_opt: Option<Vec<String>> =
        m.get_many("values").map(|value_vec| {
          value_vec
            .map(|value: &String| value.replace("__DATE__", &timestamp))
            .collect()
        });

      let cli_values_file_content_opt: Option<String> =
        if let Some(values_file_path) =
          m.get_one::<std::path::PathBuf>("values-file")
        {
          let content = std::fs::read_to_string(values_file_path)
            .with_context(|| {
              format!(
                "Failed to read values file '{}'",
                values_file_path.display()
              )
            })?;
          Some(content.replace("__DATE__", &timestamp))
        } else {
          None
        };

      let sat_template_file = m
        .get_one::<std::path::PathBuf>("sat-template-file")
        .context("SAT template file argument not provided")?;

      let sat_file_content: String = std::fs::read_to_string(sat_template_file)
        .with_context(|| {
          format!(
            "Could not read SAT file template '{}'",
            sat_template_file.display()
          )
        })?;

      let ansible_passthrough_env: Option<String> =
        ctx.settings.get("ansible-passthrough").ok();
      let ansible_passthrough_cli_arg = m.opt_string("ansible-passthrough");
      let ansible_passthrough =
        ansible_passthrough_env.or(ansible_passthrough_cli_arg);
      let ansible_verbosity: Option<u8> = m
        .get_one::<String>("ansible-verbosity")
        .map(|v| {
          v.parse::<u8>().with_context(|| {
            format!(
              "Could not parse ansible-verbosity '{v}' as a number (0-255)"
            )
          })
        })
        .transpose()?;

      let overwrite: bool = m.get_flag("overwrite-configuration");
      let create_bos_session: bool = m.get_flag("create-bos-session");
      let watch_logs: bool = m.get_flag("watch-logs");
      let timestamps: bool = m.get_flag("timestamps");
      let assume_yes: bool = m.get_flag("assume-yes");
      let dry_run: bool = m.get_flag("dry-run");
      let output_opt = m.opt_str("output");

      sat_file::exec::exec(
        ctx,
        &token,
        &sat_file::exec::SatApplyOptions {
          sat_file_content: sat_file_content.as_str(),
          values_file_content_opt: cli_values_file_content_opt.as_deref(),
          values_cli_opt: cli_value_vec_opt.as_deref(),
          ansible_verbosity_opt: ansible_verbosity,
          ansible_passthrough_opt: ansible_passthrough.as_deref(),
          create_bos_session,
          watch_logs,
          timestamps,
          prehook_opt: m.opt_str("pre-hook"),
          posthook_opt: m.opt_str("post-hook"),
          image_only: m.get_flag("image-only"),
          session_template_only: m.get_flag("sessiontemplate-only"),
          overwrite,
          dry_run,
          assume_yes,
          output_opt,
        },
      )
      .await?;
    }

    Some(("template", m)) => {
      let bos_session_name_opt = m.opt_str("name");
      let bos_sessiontemplate_name = m.req_str("template")?;
      let limit = m.req_str("limit")?;
      let bos_session_operation = m.req_str("operation")?;
      let include_disabled: bool = *m
        .get_one("include-disabled")
        .context("'include-disabled' must have a value")?;
      template::exec(
        ctx,
        &token,
        template::ExecParams {
          session_name: bos_session_name_opt,
          template_name: bos_sessiontemplate_name,
          operation: bos_session_operation,
          limit,
          include_disabled,
          dry_run: m.get_flag("dry-run"),
          output: m.opt_str("output"),
        },
      )
      .await?;
    }

    Some(("ephemeral-environment", m)) => {
      let image_id = m.req_str("image-id")?;
      let dry_run = m.get_flag("dry-run");
      let req = crate::openapi_client::types::CreateEphemeralEnvRequest {
        image_id: image_id.to_string(),
      };

      if dry_run {
        return crate::output::action_result::preview_request(
          "POST",
          "/ephemeral-env",
          &req,
          m.opt_str("output"),
        );
      }

      if !std::io::IsTerminal::is_terminal(&std::io::stdout()) {
        bail!("This command needs to run in interactive mode");
      }

      let client = MantaClient::from_app_ctx(ctx, Some(&token))?;
      let response = client
        .openapi
        .create_ephemeral_env(client.site_name(), &req)
        .await
        .into_anyhow().await?;
      println!("{}", response.hostname);
    }

    Some(("boot-parameters", m)) => {
      let hosts = m.req_str("hosts")?;
      let params = m.opt_str("params");
      let kernel = m.opt_str("kernel");
      let initrd = m.opt_str("initrd");
      let output_opt = m.opt_str("output");
      boot_parameters::exec(
        ctx,
        &token,
        boot_parameters::ExecParams {
          xnames: hosts,
          nids: None,
          macs: None,
          boot_params: params,
          kernel,
          initrd,
          output: output_opt,
        },
      )
      .await?;
    }

    Some(("redfish-endpoints", m)) => {
      redfish_endpoint::exec(
        ctx,
        &token,
        redfish_endpoint::ExecParams {
          id: m.req_str("id")?,
          name: m.opt_str("name"),
          hostname: m.opt_str("hostname"),
          domain: m.opt_str("domain"),
          fqdn: m.opt_str("fqdn"),
          enabled: m.get_flag("enabled"),
          user: m.opt_str("user"),
          password: m.opt_str("password"),
          use_ssdp: m.get_flag("use-ssdp"),
          mac_required: m.get_flag("mac-required"),
          mac_addr: m.opt_str("macaddr"),
          ip_address: m.opt_str("ipaddress"),
          rediscover_on_update: m.get_flag("rediscover-on-update"),
          template_id: m.opt_str("template-id"),
          output: m.opt_str("output"),
          dry_run: m.get_flag("dry-run"),
        },
      )
      .await?;
    }

    Some(("kernel-parameters", m)) => {
      let hsm_group_name_arg_opt = m.opt_str("group");
      let nodes_opt = if hsm_group_name_arg_opt.is_none() {
        m.opt_str("nodes")
      } else {
        None
      };
      let dryrun = m.get_flag("dry-run");
      let kernel_parameters_val = m.req_str("VALUE")?;
      let output_opt = m.opt_str("output");
      kernel_parameters::exec(
        ctx,
        &token,
        kernel_parameters::ExecParams {
          kernel_params: kernel_parameters_val,
          hosts_expression: nodes_opt,
          hsm_group: hsm_group_name_arg_opt,
          dry_run: dryrun,
          output: output_opt,
        },
      )
      .await?;
    }

    Some(("boot", m)) => match m.subcommand() {
      Some(("nodes", m)) => {
        let hosts_string = m.req_str("VALUE")?;
        let new_boot_image_id_opt = m.opt_str("boot-image");
        if let Some(new_boot_image_id) = new_boot_image_id_opt
          && uuid::Uuid::parse_str(new_boot_image_id).is_err()
        {
          bail!("Image id is not a UUID");
        }
        boot_node::exec(
          ctx,
          &token,
          boot_node::ExecParams {
            boot_image: new_boot_image_id_opt,
            boot_image_configuration: m.opt_str("boot-image-configuration"),
            kernel_parameters: m.opt_str("kernel-parameters"),
            hosts_expression: hosts_string,
            dry_run: m.get_flag("dry-run"),
            output: m.opt_str("output"),
          },
        )
        .await?;
      }
      Some(("group", m)) => {
        boot_group::exec(
          ctx,
          &token,
          boot_group::ExecParams {
            boot_image: m.opt_str("boot-image"),
            boot_image_configuration: m.opt_str("boot-image-configuration"),
            kernel_parameters: m.opt_str("kernel-parameters"),
            hsm_group_name: m.req_str("GROUP_NAME")?,
            dry_run: m.get_flag("dry-run"),
            output: m.opt_str("output"),
          },
        )
        .await?;
      }
      Some((other, _)) => bail!("Unknown 'apply boot' subcommand: {other}"),
      None => bail!("No 'apply boot' subcommand provided"),
    },

    Some(("runtime-configuration", m)) => match m.subcommand() {
      Some(("nodes", m)) => {
        runtime_configuration_node::exec(
          ctx,
          &token,
          runtime_configuration_node::ExecParams {
            configuration_name: m.req_str("configuration-name")?,
            hosts_expression: m.req_str("VALUE")?,
            disable: m.get_flag("disable"),
            dry_run: m.get_flag("dry-run"),
          },
        )
        .await?;
      }
      Some(("group", m)) => {
        runtime_configuration_group::exec(
          ctx,
          &token,
          runtime_configuration_group::ExecParams {
            configuration_name: m.req_str("configuration-name")?,
            group_name: m.req_str("GROUP_NAME")?,
            disable: m.get_flag("disable"),
            dry_run: m.get_flag("dry-run"),
          },
        )
        .await?;
      }
      Some((other, _)) => {
        bail!("Unknown 'apply runtime-configuration' subcommand: {other}")
      }
      None => bail!("No 'apply runtime-configuration' subcommand provided"),
    },

    Some((other, _)) => bail!("Unknown 'apply' subcommand: {other}"),
    None => bail!("No 'apply' subcommand provided"),
  }
  Ok(())
}

#[cfg(test)]
mod tests {
  /// `--dry-run` parses on `manta apply ephemeral-environment` (long flag).
  #[test]
  fn ephemeral_env_accepts_dry_run() {
    let result = crate::build::build_cli().try_get_matches_from([
      "manta",
      "apply",
      "ephemeral-environment",
      "--image-id",
      "abc-123",
      "--dry-run",
    ]);
    assert!(
      result.is_ok(),
      "expected --dry-run to parse on `apply ephemeral-environment`: {result:?}"
    );
  }

  /// `-d` short alias also parses.
  #[test]
  fn ephemeral_env_accepts_dry_run_short_alias() {
    let result = crate::build::build_cli().try_get_matches_from([
      "manta",
      "apply",
      "ephemeral-environment",
      "--image-id",
      "abc-123",
      "-d",
    ]);
    assert!(
      result.is_ok(),
      "expected -d short alias to parse: {result:?}"
    );
  }

  /// `--dry-run -o json` parses — output flag is honored on the dry-run preview.
  #[test]
  fn ephemeral_env_accepts_dry_run_with_output_json() {
    let result = crate::build::build_cli().try_get_matches_from([
      "manta",
      "apply",
      "ephemeral-environment",
      "--image-id",
      "abc-123",
      "--dry-run",
      "-o",
      "json",
    ]);
    assert!(
      result.is_ok(),
      "expected `--dry-run -o json` to parse on `apply ephemeral-environment`: {result:?}"
    );
  }
}