manta-cli 1.62.0

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
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
use std::collections::HashMap;

use anyhow::{Context, Error, bail};
use manta_backend_dispatcher::{
  interfaces::hsm::group::GroupTrait, types::Group,
};

use crate::{
  cli::commands::hw_cluster_common::utils::{
    calculate_hsm_hw_component_summary, fetch_hsm_hw_inventory,
    print_hsm_group_json, resolve_hw_description_to_xnames,
  },
  common::app_context::AppContext,
};

/// Determines whether the hw cluster operation moves nodes
/// into the target (Pin) or releases them back (Unpin).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HwClusterMode {
  Pin,
  Unpin,
}

/// Execute a hardware cluster pin or unpin operation,
/// moving nodes between target and parent HSM groups.
#[allow(clippy::too_many_arguments)]
pub async fn exec(
  mode: HwClusterMode,
  ctx: &AppContext<'_>,
  shasta_token: &str,
  target_hsm_group_name: &str,
  parent_hsm_group_name: &str,
  pattern: &str,
  dryrun: bool,
  create_target_hsm_group: bool,
  delete_empty_parent_hsm_group: bool,
) -> Result<(), Error> {
  let backend = ctx.infra.backend;

  // Parse user input
  let (user_defined_hw_component_vec, user_defined_hw_component_count_hashmap) =
    parse_hw_pattern_usize(target_hsm_group_name, pattern)?;

  let mem_lcm = super::MEMORY_CAPACITY_LCM;

  // Ensure target group exists (create if requested)
  ensure_target_group_exists(
    backend,
    shasta_token,
    target_hsm_group_name,
    dryrun,
    create_target_hsm_group,
  )
  .await?;

  // Fetch target HSM inventory
  let (
    target_hsm_group_member_vec,
    target_hsm_node_hw_component_count_vec,
    target_hsm_hw_component_summary,
  ) = fetch_hsm_hw_inventory(
    backend,
    shasta_token,
    &user_defined_hw_component_vec,
    target_hsm_group_name,
    mem_lcm,
  )
  .await?;

  log::info!(
    "HSM group '{}' hw component summary: {:?}",
    target_hsm_group_name,
    target_hsm_hw_component_summary
  );

  // Fetch parent HSM inventory
  let (
    parent_hsm_group_member_vec,
    parent_hsm_node_hw_component_count_vec,
    _parent_summary,
  ) = fetch_hsm_hw_inventory(
    backend,
    shasta_token,
    &user_defined_hw_component_vec,
    parent_hsm_group_name,
    mem_lcm,
  )
  .await?;

  // Validate resource sufficiency
  validate_resource_sufficiency(
    &target_hsm_node_hw_component_count_vec,
    &parent_hsm_node_hw_component_count_vec,
    &user_defined_hw_component_count_hashmap,
  )?;

  // Resolve hw description to xname sets
  let (
    target_hsm_node_hw_component_count_vec,
    parent_hsm_node_hw_component_count_vec,
  ) = resolve_hw_description_to_xnames(
    mode,
    target_hsm_node_hw_component_count_vec,
    parent_hsm_node_hw_component_count_vec,
    user_defined_hw_component_count_hashmap,
  )
  .await?;

  let target_hsm_hw_component_summary =
    calculate_hsm_hw_component_summary(&target_hsm_node_hw_component_count_vec);

  let parent_hsm_hw_component_summary =
    calculate_hsm_hw_component_summary(&parent_hsm_node_hw_component_count_vec);

  let target_hsm_node_vec: Vec<String> = target_hsm_node_hw_component_count_vec
    .into_iter()
    .map(|(xname, _)| xname)
    .collect();

  let parent_hsm_node_vec: Vec<String> = parent_hsm_node_hw_component_count_vec
    .into_iter()
    .map(|(xname, _)| xname)
    .collect();

  // Apply changes
  apply_group_updates(
    backend,
    shasta_token,
    target_hsm_group_name,
    parent_hsm_group_name,
    &target_hsm_group_member_vec,
    &parent_hsm_group_member_vec,
    &target_hsm_node_vec,
    &parent_hsm_node_vec,
    dryrun,
    delete_empty_parent_hsm_group,
  )
  .await?;

  // Print results
  log::info!(
    "HSM '{}' hw component summary: {:?}",
    target_hsm_group_name,
    target_hsm_hw_component_summary
  );

  print_hsm_group_json(target_hsm_group_name, &target_hsm_node_vec)?;

  log::info!(
    "HSM '{}' hw component summary: {:?}",
    parent_hsm_group_name,
    parent_hsm_hw_component_summary
  );

  print_hsm_group_json(parent_hsm_group_name, &parent_hsm_node_vec)?;

  Ok(())
}

/// Parse user pattern `"a100:4:epyc:10"` into hw component
/// names and a hashmap of `{component -> count}` as `usize`.
fn parse_hw_pattern_usize(
  target_hsm_group_name: &str,
  pattern: &str,
) -> Result<(Vec<String>, HashMap<String, usize>), Error> {
  let pattern = format!("{}:{}", target_hsm_group_name, pattern);
  log::info!("pattern: {}", pattern);

  let pattern_lowercase = pattern.to_lowercase();

  let (_group_name, pattern_hw_component) =
    pattern_lowercase.split_once(':').context(
      "Invalid pattern format: \
       expected 'group:component:count'",
    )?;

  let pattern_element_vec: Vec<&str> =
    pattern_hw_component.split(':').collect();

  if !pattern_element_vec.len().is_multiple_of(2) {
    bail!(
      "Error in pattern: odd number of elements. \
       Expected pairs of <hw component>:<count>. \
       eg a100:4:epyc:10:instinct:8",
    );
  }

  let mut hw_component_count: HashMap<String, usize> = HashMap::new();

  for chunk in pattern_element_vec.chunks_exact(2) {
    if let Ok(count) = chunk[1].parse::<usize>() {
      hw_component_count.insert(chunk[0].to_string(), count);
    } else {
      bail!(
        "Error in pattern. Please make sure to follow \
         <hsm name>:<hw component>:<counter>:... \
         eg <tasna>:a100:4:epyc:10:instinct:8",
      );
    }
  }

  log::info!(
    "User defined hw components with counters: {:?}",
    hw_component_count
  );

  let mut hw_component_vec: Vec<String> =
    hw_component_count.keys().cloned().collect();
  hw_component_vec.sort();

  Ok((hw_component_vec, hw_component_count))
}

/// Ensure the target HSM group exists, creating it if
/// `create_target_hsm_group` is set.
async fn ensure_target_group_exists(
  backend: &crate::manta_backend_dispatcher::StaticBackendDispatcher,
  shasta_token: &str,
  target_hsm_group_name: &str,
  dryrun: bool,
  create_target_hsm_group: bool,
) -> Result<(), Error> {
  match backend.get_group(shasta_token, target_hsm_group_name).await {
    Ok(_) => {
      log::debug!("Target HSM group '{}' exists, good.", target_hsm_group_name);
      Ok(())
    }
    Err(_) => {
      if !create_target_hsm_group {
        bail!(
          "Target HSM group '{}' does not exist, \
           but the option to create the group was \
           NOT specified, cannot continue.",
          target_hsm_group_name,
        );
      }
      log::info!(
        "Target HSM group '{}' does not exist, \
         but the option to create the group has \
         been selected, creating it now.",
        target_hsm_group_name
      );
      if dryrun {
        bail!(
          "Dryrun selected, cannot create the \
           new group and continue.",
        );
      }
      let group = Group {
        label: target_hsm_group_name.to_string(),
        description: None,
        tags: None,
        members: None,
        exclusive_group: Some("false".to_string()),
      };
      let _ = backend
        .add_group(shasta_token, group)
        .await
        .context("Unable to create new target HSM group")?;
      Ok(())
    }
  }
}

/// Validate that combined target+parent resources can
/// fulfill the user request.
fn validate_resource_sufficiency(
  target_hw: &[(String, HashMap<String, usize>)],
  parent_hw: &[(String, HashMap<String, usize>)],
  requested: &HashMap<String, usize>,
) -> Result<(), Error> {
  let mut combined = parent_hw.to_vec();
  for elem in target_hw {
    if !parent_hw.iter().any(|(xname, _)| xname.eq(&elem.0)) {
      combined.push(elem.clone());
    }
  }

  let combined_summary = calculate_hsm_hw_component_summary(&combined);

  for (hw_component, qty) in requested {
    if combined_summary
      .get(hw_component)
      .is_none_or(|value| value < qty)
    {
      bail!(
        "There are not enough resources \
         to fulfill user request.",
      );
    }
  }

  Ok(())
}

/// Apply group membership updates to both target and parent
/// HSM groups. Optionally deletes the parent group if it
/// becomes empty.
#[allow(clippy::too_many_arguments)]
async fn apply_group_updates(
  backend: &crate::manta_backend_dispatcher::StaticBackendDispatcher,
  shasta_token: &str,
  target_group: &str,
  parent_group: &str,
  old_target_members: &[String],
  old_parent_members: &[String],
  new_target_members: &[String],
  new_parent_members: &[String],
  dryrun: bool,
  delete_empty_parent: bool,
) -> Result<(), Error> {
  // Update target group
  log::info!("Updating target HSM group '{}' members", target_group);
  if dryrun {
    log::info!(
      "Dry run enabled, not modifying the \
       HSM groups on the system."
    );
  } else {
    backend
      .update_group_members(
        shasta_token,
        target_group,
        &old_target_members
          .iter()
          .map(String::as_str)
          .collect::<Vec<&str>>(),
        &new_target_members
          .iter()
          .map(String::as_str)
          .collect::<Vec<&str>>(),
      )
      .await
      .context("Failed to update target HSM group members")?;
  }

  // Update parent group
  log::info!("Updating parent HSM group '{}' members", parent_group);
  if dryrun {
    log::info!(
      "Dry run enabled, not modifying the \
       HSM groups on the system."
    );
  } else {
    let parent_will_be_empty =
      old_target_members.len() == old_parent_members.len();
    backend
      .update_group_members(
        shasta_token,
        parent_group,
        &old_parent_members
          .iter()
          .map(String::as_str)
          .collect::<Vec<&str>>(),
        &new_parent_members
          .iter()
          .map(String::as_str)
          .collect::<Vec<&str>>(),
      )
      .await
      .context("Failed to update parent HSM group members")?;

    if parent_will_be_empty && delete_empty_parent {
      log::info!(
        "Parent HSM group '{}' is now empty and \
         the option to delete empty groups has \
         been selected, removing it.",
        parent_group
      );
      match backend.delete_group(shasta_token, parent_group).await {
        Ok(_) => {
          log::info!("HSM group removed successfully.")
        }
        Err(e) => log::debug!(
          "Error removing the HSM group. \
           This always fails, ignore please. \
           Reported: {}",
          e
        ),
      };
    } else if parent_will_be_empty {
      log::debug!(
        "Parent HSM group '{}' is now empty and \
         the option to delete empty groups has \
         NOT been selected, will not remove it.",
        parent_group
      )
    }
  }

  Ok(())
}

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

  // ---- parse_hw_pattern_usize ----

  #[test]
  fn parse_hw_pattern_usize_valid() {
    let (names, counts) =
      parse_hw_pattern_usize("tasna", "a100:4:epyc:10").unwrap();
    assert_eq!(names, vec!["a100", "epyc"]);
    assert_eq!(counts.get("a100"), Some(&4));
    assert_eq!(counts.get("epyc"), Some(&10));
  }

  #[test]
  fn parse_hw_pattern_usize_single_pair() {
    let (names, counts) =
      parse_hw_pattern_usize("group1", "instinct:8").unwrap();
    assert_eq!(names, vec!["instinct"]);
    assert_eq!(counts.get("instinct"), Some(&8));
  }

  #[test]
  fn parse_hw_pattern_usize_odd_elements_errors() {
    assert!(parse_hw_pattern_usize("g", "a100:4:epyc").is_err());
  }

  #[test]
  fn parse_hw_pattern_usize_non_numeric_count_errors() {
    assert!(parse_hw_pattern_usize("g", "a100:four").is_err());
  }

  #[test]
  fn parse_hw_pattern_usize_negative_count_errors() {
    // usize cannot be negative
    assert!(parse_hw_pattern_usize("g", "a100:-3").is_err());
  }

  #[test]
  fn parse_hw_pattern_usize_sorted_output() {
    let (names, _) =
      parse_hw_pattern_usize("g", "zebra:1:alpha:2:mid:3").unwrap();
    assert_eq!(names, vec!["alpha", "mid", "zebra"]);
  }

  #[test]
  fn parse_hw_pattern_usize_lowercased() {
    // Pattern should be lowercased
    let (names, counts) = parse_hw_pattern_usize("GROUP", "A100:4").unwrap();
    assert_eq!(names, vec!["a100"]);
    assert_eq!(counts.get("a100"), Some(&4));
  }

  // ---- validate_resource_sufficiency ----

  #[test]
  fn validate_sufficiency_passes() {
    let target_hw = vec![(
      "x1000c0s0b0n0".to_string(),
      HashMap::from([("a100".to_string(), 4)]),
    )];
    let parent_hw = vec![(
      "x1000c0s1b0n0".to_string(),
      HashMap::from([("a100".to_string(), 8)]),
    )];
    let requested = HashMap::from([("a100".to_string(), 10)]);
    assert!(
      validate_resource_sufficiency(&target_hw, &parent_hw, &requested,)
        .is_ok()
    );
  }

  #[test]
  fn validate_sufficiency_fails_insufficient() {
    let target_hw: Vec<(String, HashMap<String, usize>)> = vec![];
    let parent_hw = vec![(
      "x1000c0s0b0n0".to_string(),
      HashMap::from([("a100".to_string(), 2)]),
    )];
    let requested = HashMap::from([("a100".to_string(), 10)]);
    assert!(
      validate_resource_sufficiency(&target_hw, &parent_hw, &requested,)
        .is_err()
    );
  }

  #[test]
  fn validate_sufficiency_fails_missing_component() {
    let target_hw: Vec<(String, HashMap<String, usize>)> = vec![];
    let parent_hw = vec![(
      "x1000c0s0b0n0".to_string(),
      HashMap::from([("epyc".to_string(), 10)]),
    )];
    let requested = HashMap::from([("a100".to_string(), 1)]);
    assert!(
      validate_resource_sufficiency(&target_hw, &parent_hw, &requested,)
        .is_err()
    );
  }

  #[test]
  fn validate_sufficiency_exact_match() {
    let target_hw: Vec<(String, HashMap<String, usize>)> = vec![];
    let parent_hw = vec![(
      "x1000c0s0b0n0".to_string(),
      HashMap::from([("a100".to_string(), 4)]),
    )];
    let requested = HashMap::from([("a100".to_string(), 4)]);
    assert!(
      validate_resource_sufficiency(&target_hw, &parent_hw, &requested,)
        .is_ok()
    );
  }

  #[test]
  fn validate_sufficiency_combines_target_and_parent() {
    // Target has a node not in parent — should be combined
    let target_hw = vec![(
      "x1000c0s0b0n0".to_string(),
      HashMap::from([("a100".to_string(), 3)]),
    )];
    let parent_hw = vec![(
      "x1000c0s1b0n0".to_string(),
      HashMap::from([("a100".to_string(), 3)]),
    )];
    let requested = HashMap::from([("a100".to_string(), 6)]);
    assert!(
      validate_resource_sufficiency(&target_hw, &parent_hw, &requested,)
        .is_ok()
    );
  }

  #[test]
  fn validate_sufficiency_no_double_count_overlap() {
    // Target node IS in parent — should NOT be double-counted
    let target_hw = vec![(
      "x1000c0s0b0n0".to_string(),
      HashMap::from([("a100".to_string(), 4)]),
    )];
    let parent_hw = vec![(
      "x1000c0s0b0n0".to_string(),
      HashMap::from([("a100".to_string(), 4)]),
    )];
    // Total available is 4, not 8
    let requested = HashMap::from([("a100".to_string(), 5)]);
    assert!(
      validate_resource_sufficiency(&target_hw, &parent_hw, &requested,)
        .is_err()
    );
  }
}