manta-cli 1.63.1

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
//! Implements the `manta delete hardware` command.

use std::collections::HashMap;

use manta_backend_dispatcher::{error::Error, interfaces::hsm::group::GroupTrait};

use crate::{
  cli::commands::hw_cluster_common::{
    MEMORY_CAPACITY_LCM,
    utils::{
      calculate_hsm_hw_component_summary,
      calculate_hw_component_scarcity_scores, fetch_hsm_hw_inventory,
      parse_hw_pattern, print_hsm_group_json, show_solution_and_confirm,
    },
  },
  common::{
    app_context::AppContext,
    authorization::get_groups_names_available,
  },
};

/// Result of a `delete hw-component` operation.
pub struct DeleteHwResult {
  pub nodes_moved: Vec<String>,
  pub target_nodes: Vec<String>,
  pub parent_nodes: Vec<String>,
}

/// Core logic for removing hardware components from a cluster group.
/// No terminal interaction — suitable for both CLI and HTTP callers.
pub async fn run(
  backend: &crate::manta_backend_dispatcher::StaticBackendDispatcher,
  token: &str,
  target_hsm_group_name: &str,
  parent_hsm_group_name: &str,
  pattern: &str,
  dryrun: bool,
  delete_hsm_group: bool,
) -> Result<DeleteHwResult, Error> {
  use crate::cli::commands::hw_cluster_common::{
    MEMORY_CAPACITY_LCM,
    utils::{
      calculate_hw_component_scarcity_scores,
      fetch_hsm_hw_inventory, parse_hw_pattern,
    },
  };

  match backend.get_group(token, target_hsm_group_name).await {
    Ok(_) => {}
    Err(_) => {
      return Err(Error::NotFound(format!(
        "HSM group {} does not exist, cannot remove hw from it.",
        target_hsm_group_name
      )));
    }
  }

  let pattern_str = format!("{}:{}", target_hsm_group_name, pattern);
  let pattern_lowercase = pattern_str.to_lowercase();
  let mut pattern_element_vec: Vec<&str> =
    pattern_lowercase.split(':').collect();
  let target_name = pattern_element_vec.remove(0);

  let (
    user_defined_delta_hw_component_vec,
    user_defined_delta_hw_component_count_hashmap,
  ) = parse_hw_pattern(&pattern_element_vec)?;

  let mem_lcm = MEMORY_CAPACITY_LCM;
  let (
    target_hsm_group_member_vec,
    mut target_hsm_node_hw_component_count_vec,
    target_hsm_hw_component_summary,
  ) = fetch_hsm_hw_inventory(
    backend,
    token,
    &user_defined_delta_hw_component_vec,
    target_name,
    mem_lcm,
  )
  .await?;

  if target_hsm_node_hw_component_count_vec.is_empty() {
    handle_empty_target(backend, token, target_name, dryrun, delete_hsm_group).await?;
    return Ok(DeleteHwResult {
      nodes_moved: vec![],
      target_nodes: vec![],
      parent_nodes: vec![],
    });
  }

  let (
    parent_hsm_group_member_vec,
    parent_hsm_node_hw_component_count_vec,
    _parent_summary,
  ) = fetch_hsm_hw_inventory(
    backend,
    token,
    &user_defined_delta_hw_component_vec,
    parent_hsm_group_name,
    mem_lcm,
  )
  .await?;

  let combined = [
    target_hsm_node_hw_component_count_vec.clone(),
    parent_hsm_node_hw_component_count_vec.clone(),
  ]
  .concat();
  let scarcity_scores = calculate_hw_component_scarcity_scores(&combined).await;

  let final_target_summary =
    compute_final_summary(&target_hsm_hw_component_summary, &user_defined_delta_hw_component_count_hashmap)?;

  let hw_counters_to_move =
    crate::cli::commands::apply_hw_cluster_unpin::utils::calculate_target_hsm_unpin(
      &final_target_summary,
      &final_target_summary.keys().cloned().collect::<Vec<String>>(),
      &mut target_hsm_node_hw_component_count_vec,
      &scarcity_scores,
    )?;

  let nodes_to_move: Vec<String> = hw_counters_to_move
    .iter()
    .map(|(xname, _)| xname.clone())
    .collect();

  let mut parent_nodes: Vec<String> = parent_hsm_group_member_vec;
  parent_nodes.extend(nodes_to_move.clone());
  parent_nodes.sort();

  let target_nodes: Vec<String> = target_hsm_node_hw_component_count_vec
    .iter()
    .map(|(xname, _)| xname.clone())
    .collect();

  if !dryrun {
    apply_node_moves(
      backend,
      token,
      target_name,
      parent_hsm_group_name,
      &nodes_to_move,
      target_hsm_group_member_vec.len() == nodes_to_move.len(),
      delete_hsm_group,
    )
    .await?;
  }

  Ok(DeleteHwResult { nodes_moved: nodes_to_move, target_nodes, parent_nodes })
}

/// Remove hardware components from a cluster group.
pub async fn exec(
  ctx: &AppContext<'_>,
  token: &str,
  target_hsm_group_name_arg_opt: Option<&str>,
  parent_hsm_group_name_arg_opt: Option<&str>,
  pattern: &str,
  dryrun: bool,
  delete_hsm_group: bool,
) -> Result<(), Error> {
  let backend = ctx.infra.backend;
  let settings_hsm_group_name_opt = ctx.cli.settings_hsm_group_name_opt;
  let target_hsm_group_vec = get_groups_names_available(
    backend,
    token,
    target_hsm_group_name_arg_opt,
    settings_hsm_group_name_opt,
  )
  .await?;
  let parent_hsm_group_vec = get_groups_names_available(
    backend,
    token,
    parent_hsm_group_name_arg_opt,
    settings_hsm_group_name_opt,
  )
  .await?;

  let target_hsm_group_name = target_hsm_group_vec
    .first()
    .ok_or_else(|| Error::NotFound("Target HSM group vec is empty".to_string()))?;
  let parent_hsm_group_name = parent_hsm_group_vec
    .first()
    .ok_or_else(|| Error::NotFound("Parent HSM group vec is empty".to_string()))?;

  match backend
    .get_group(token, target_hsm_group_name)
    .await
  {
    Ok(_) => {
      tracing::debug!("The HSM group {} exists, good.", target_hsm_group_name)
    }
    Err(_) => {
      return Err(Error::NotFound(format!(
        "HSM group {} does not exist, cannot remove hw \
         from it and cannot continue.",
        target_hsm_group_name
      )));
    }
  }

  // Parse the hardware pattern
  let pattern = format!("{}:{}", target_hsm_group_name, pattern);
  let pattern_lowercase = pattern.to_lowercase();
  let mut pattern_element_vec: Vec<&str> =
    pattern_lowercase.split(':').collect();
  let target_hsm_group_name = pattern_element_vec.remove(0);

  let (
    user_defined_delta_hw_component_vec,
    user_defined_delta_hw_component_count_hashmap,
  ) = parse_hw_pattern(&pattern_element_vec)?;

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

  // Fetch target HSM inventory
  let mem_lcm = MEMORY_CAPACITY_LCM;
  let (
    target_hsm_group_member_vec,
    mut target_hsm_node_hw_component_count_vec,
    target_hsm_hw_component_summary,
  ) = fetch_hsm_hw_inventory(
    backend,
    token,
    &user_defined_delta_hw_component_vec,
    target_hsm_group_name,
    mem_lcm,
  )
  .await?;

  if target_hsm_node_hw_component_count_vec.is_empty() {
    return handle_empty_target(
      backend,
      token,
      target_hsm_group_name,
      dryrun,
      delete_hsm_group,
    )
    .await;
  }

  tracing::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_hsm_hw_component_summary,
  ) = fetch_hsm_hw_inventory(
    backend,
    token,
    &user_defined_delta_hw_component_vec,
    parent_hsm_group_name,
    mem_lcm,
  )
  .await?;

  // Calculate combined scarcity scores
  let combined = [
    target_hsm_node_hw_component_count_vec.clone(),
    parent_hsm_node_hw_component_count_vec.clone(),
  ]
  .concat();

  let scarcity_scores = calculate_hw_component_scarcity_scores(&combined).await;

  // Calculate final target HSM hw component summary
  let final_target_hsm_hw_component_summary = compute_final_summary(
    &target_hsm_hw_component_summary,
    &user_defined_delta_hw_component_count_hashmap,
  )?;

  // Find nodes to move out of target
  let hw_counters_to_move =
    crate::cli::commands::apply_hw_cluster_unpin::utils::calculate_target_hsm_unpin(
      &final_target_hsm_hw_component_summary,
      &final_target_hsm_hw_component_summary
        .keys()
        .cloned()
        .collect::<Vec<String>>(),
      &mut target_hsm_node_hw_component_count_vec,
      &scarcity_scores,
    )?;

  let nodes_to_move: Vec<String> = hw_counters_to_move
    .iter()
    .map(|(xname, _)| xname.clone())
    .collect();

  // Prepare display data
  let mut parent_hsm_node_vec: Vec<String> = parent_hsm_group_member_vec;
  parent_hsm_node_vec.extend(nodes_to_move.clone());
  parent_hsm_node_vec.sort();

  let target_hsm_hw_component_summary =
    calculate_hsm_hw_component_summary(&target_hsm_node_hw_component_count_vec);

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

  // Show solution and confirm
  show_solution_and_confirm(
    target_hsm_group_name,
    &user_defined_delta_hw_component_vec,
    &target_hsm_node_hw_component_count_vec,
    &target_hsm_hw_component_summary,
  )?;

  // Apply changes
  if dryrun {
    tracing::info!(
      "Dry run enabled, not modifying the HSM groups \
       on the system."
    )
  } else {
    apply_node_moves(
      backend,
      token,
      target_hsm_group_name,
      parent_hsm_group_name,
      &nodes_to_move,
      target_hsm_group_member_vec.len() == nodes_to_move.len(),
      delete_hsm_group,
    )
    .await?;
  }

  print_hsm_group_json(target_hsm_group_name, &target_hsm_node_vec)?;
  print_hsm_group_json(parent_hsm_group_name, &parent_hsm_node_vec)?;

  Ok(())
}

/// Handle the case when target HSM group is already empty.
async fn handle_empty_target(
  backend: &crate::manta_backend_dispatcher::StaticBackendDispatcher,
  shasta_token: &str,
  target_hsm_group_name: &str,
  dryrun: bool,
  delete_hsm_group: bool,
) -> Result<(), Error> {
  tracing::info!(
    "The target HSM group {} is already empty, cannot \
     remove hardware from it.",
    target_hsm_group_name
  );

  if dryrun || !delete_hsm_group {
    tracing::info!(
      "The option to delete empty groups has NOT been \
       selected, or the dryrun has been enabled. We \
       are done with this action."
    );
    return Ok(());
  }

  tracing::info!(
    "The option to delete empty groups has been \
     selected, removing it."
  );
  match backend
    .delete_group(shasta_token, target_hsm_group_name)
    .await
  {
    Ok(_) => {
      tracing::info!(
        "HSM group removed successfully, we are \
         done with this action."
      );
    }
    Err(e) => tracing::debug!(
      "Error removing the HSM group. This always \
       fails, ignore please. Reported: {}",
      e
    ),
  };
  Ok(())
}

/// Compute the final target HSM hw component summary after
/// subtracting the user-defined deltas.
fn compute_final_summary(
  current_summary: &HashMap<String, usize>,
  deltas: &HashMap<String, isize>,
) -> Result<HashMap<String, usize>, Error> {
  let mut final_summary: HashMap<String, usize> = HashMap::new();

  for (hw_component, counter) in deltas {
    let current = *current_summary.get(hw_component).ok_or_else(|| {
      Error::NotFound(format!(
        "hw component '{}' not found in target HSM \
           hw component summary",
        hw_component
      ))
    })?;

    final_summary.insert(hw_component.to_string(), current - *counter as usize);
  }

  Ok(final_summary)
}

/// Move nodes between HSM groups: delete from target, add
/// to parent. Optionally delete the target group if empty.
async fn apply_node_moves(
  backend: &crate::manta_backend_dispatcher::StaticBackendDispatcher,
  shasta_token: &str,
  target_group: &str,
  parent_group: &str,
  nodes: &[String],
  target_will_be_empty: bool,
  delete_hsm_group: bool,
) -> Result<(), Error> {
  for xname in nodes {
    backend
      .delete_member_from_group(shasta_token, target_group, xname.as_str())
      .await?;

    backend
      .add_members_to_group(shasta_token, parent_group, &[xname.as_str()])
      .await?;
  }

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

  Ok(())
}