manta-cli 1.59.9-beta.5

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
546
547
548
549
550
551
552
553
554
555
556
557
use std::collections::HashMap;

use comfy_table::{Cell, ContentArrangement, Table};
use csm_rs::node::types::NodeDetails;
use hostlist_parser::parse;
use manta_backend_dispatcher::{
  error::Error, interfaces::hsm::group::GroupTrait, types::Component,
};
use regex::Regex;

use crate::manta_backend_dispatcher::StaticBackendDispatcher;

// Validate and get short nid
pub fn get_short_nid(long_nid: &str) -> Result<usize, Error> {
  // Validate nid has the right length
  if long_nid.len() != 9 {
    return Err(Error::Message(format!(
      "Nid '{}' not valid, Nid does not have 9 characters",
      long_nid
    )));
  }

  long_nid.strip_prefix("nid")
        .ok_or_else(|| Error::Message(format!("Nid '{}' not valid, 'nid' prefix missing", long_nid)))
        .and_then(|nid_number| nid_number.to_string().parse::<usize>()
                            .map_err(|e| Error::Message(format!("Intermediate operation to convert Nid {} from long to short format. Reason:\n{}", nid_number, e.to_string())))
        )
}

pub async fn get_xname_from_nid_hostlist(
  node_vec: &Vec<String>,
  node_metadata_available_vec: &Vec<Component>,
) -> Result<Vec<String>, Error> {
  // Convert long nids to short nids
  // Get xnames from short nids
  let short_nid_vec: Vec<usize> = node_vec
    .clone()
    .iter()
    .map(|nid_long| get_short_nid(nid_long))
    .collect::<Result<Vec<_>, Error>>()?;

  log::debug!("short Nid list expanded: {:?}", short_nid_vec);

  let xname_vec: Vec<String> = node_metadata_available_vec
    .into_iter()
    .filter(|node_metadata_available| {
      short_nid_vec.contains(&node_metadata_available.nid.unwrap())
    })
    .map(|node_metadata_available| node_metadata_available.id.as_ref().unwrap())
    .cloned()
    .collect();

  Ok(xname_vec)
}

pub async fn get_xname_from_xname_hostlist(
  node_vec: &Vec<String>,
  node_metadata_available_vec: &Vec<Component>,
) -> Result<Vec<String>, Error> {
  // If hostlist of XNAMEs, return hostlist expanded xnames
  // Validate XNAMEs
  log::debug!("XNAME format are valid");

  let xname_vec: Vec<String> = node_metadata_available_vec
    .into_iter()
    .filter(|node_metadata_available| {
      node_vec.contains(&node_metadata_available.id.as_ref().unwrap())
    })
    .map(|node_metadata_available| node_metadata_available.id.as_ref().unwrap())
    .cloned()
    .collect();

  Ok(xname_vec)
}

pub async fn get_xname_from_nid_regex(
  regex: &Regex,
  node_metadata_available_vec: &Vec<Component>,
) -> Result<Vec<String>, Error> {
  let xname_vec: Vec<String> = node_metadata_available_vec
    .clone()
    .into_iter()
    .filter(|node_metadata_available: &Component| {
      regex.is_match(&format!("nid{:06}", node_metadata_available.nid.unwrap()))
    })
    .map(|node_metadata_available| node_metadata_available.id.unwrap())
    .collect();

  Ok(xname_vec)
}

pub async fn get_xname_from_xname_regex(
  regex: &Regex,
  node_metadata_available_vec: &Vec<Component>,
) -> Result<Vec<String>, Error> {
  let xname_vec = node_metadata_available_vec
    .clone()
    .into_iter()
    .filter(|node_metadata_available: &Component| {
      regex.is_match(&node_metadata_available.id.as_ref().unwrap())
    })
    .map(|node_metadata_available| node_metadata_available.id.unwrap())
    .collect();

  Ok(xname_vec)
}

/// Translates and filters a 'host expression' into a list of xnames.
/// a host expression is a comma separated list of NIDs or XNAMEs, a regex or a hostlist
/// NOTE: user can provice a host expression and expand the list to all siblings
pub async fn from_hosts_expression_to_xname_vec(
  user_input: &str,
  is_include_siblings: bool,
  node_metadata_available_vec: Vec<Component>,
) -> Result<Vec<String>, Error> {
  // Check if hostlist
  // Expand user input to list of nids
  let hostlist_expanded_vec_rslt =
    parse(user_input).map_err(|e| Error::Message(e.to_string()));

  // Check if regex
  /* let regexexp_rslt =
  Regex::new(user_input).map_err(|e| Error::Message(e.to_string())); */

  let xname_vec = if let Ok(node_vec) = hostlist_expanded_vec_rslt {
    log::debug!("Hostlist format is valid");
    // If hostlist, expand hostlist
    let xname_vec: Vec<String> = if validate_nid_format_vec(node_vec.clone()) {
      // If hostlist of NIDs, convert to xname
      // Validate NIDs
      log::debug!("NID format is valid");
      log::debug!("hostlist Nids: {}", user_input);
      log::debug!("hostlist Nids expanded: {:?}", node_vec);

      get_xname_from_nid_hostlist(&node_vec, &node_metadata_available_vec)
        .await?
    } else if validate_xname_format_vec(node_vec.clone()) {
      // If hostlist of XNAMEs, return hostlist expanded xnames
      // Validate XNAMEs
      log::debug!("NID format is valid");
      log::debug!("hostlist Nids: {}", user_input);
      log::debug!("hostlist Nids expanded: {:?}", node_vec);

      get_xname_from_xname_hostlist(&node_vec, &node_metadata_available_vec)
        .await?
    } else {
      return Err(Error::Message(format!(
        "Could not parse user input as a list of nodes from a hostlist expression.",
      )));
    };

    xname_vec
  /* } else if let Ok(regex) = regexexp_rslt {
  log::debug!("Regex format is valid");
  // If regex, return regex
  // Filter, validate and translate list of regex nids to xnames
  let xname_vec =
    get_xname_from_nid_regex(&regex, &node_metadata_available_vec).await?;

  log::debug!("Regex format: {}", regex);
  log::debug!("NID list from regex: {:?}", xname_vec);

  let xname_vec: Vec<String> = if xname_vec.is_empty() {
    log::debug!("No NIDs found from regex");
    // Filter, validate and translate list of regex xnames to xnames
    get_xname_from_xname_regex(&regex, &node_metadata_available_vec).await?
  } else {
    xname_vec
  };

  xname_vec */
  } else {
    return Err(Error::Message(format!(
      "Could not parse user input as a list of nodes from a hostlist or regex expression.",
    )));
  };

  if xname_vec.is_empty() {
    return Err(Error::Message(format!(
      "Could not parse user input as a list of nodes from a hostlist or regex expression.",
    )));
  }

  // Include siblings if requested
  let xname_vec: Vec<String> = if is_include_siblings {
    log::debug!("Include siblings");
    let xname_blade_vec: Vec<String> = xname_vec
      .iter()
      .map(|xname| xname[0..10].to_string())
      .collect();

    log::debug!("XNAME blades:\n{:?}", xname_blade_vec);

    // Filter xnames to the ones the user has access to
    let xname_vec = node_metadata_available_vec
      .into_iter()
      .filter(|node_metadata_available| {
        xname_blade_vec.iter().any(|xname_blade| {
          node_metadata_available
            .id
            .as_ref()
            .unwrap()
            .starts_with(xname_blade)
        })
      })
      .map(|node_metadata_available| node_metadata_available.id.unwrap())
      .collect();

    xname_vec
  } else {
    xname_vec
  };

  Ok(xname_vec)
}

/// Returns a HashMap with keys HSM group names the user has access to and values a curated list of memembers that matches
/// hostlist
pub async fn get_curated_hsm_group_from_xname_hostlist(
  backend: &StaticBackendDispatcher,
  auth_token: &str,
  xname_vec: &[String],
) -> HashMap<String, Vec<String>> {
  // Create a summary of HSM groups and the list of members filtered by the list of nodes the
  // user is targeting
  let mut hsm_group_summary: HashMap<String, Vec<String>> = HashMap::new();

  /* // Get final list of xnames to operate on
  // Get list of HSM groups available
  // NOTE: HSM available are the ones the user has access to
  // let hsm_group_name_available: Vec<String> = get_hsm_name_available_from_jwt(shasta_token).await;

  // Get all HSM groups in the system
  // FIXME: client should not fetch all info in backend. Create a method in backend to do provide
  // information already filtered to the client:
  // hsm::groups::utils::get_hsm_group_available_vec(shasta_token, shasta_base_url,
  // shasta_root_cert) -> Vec<HsmGroup> to get the list of HSM available to the user and return
  // a Vec of HsmGroups the user has access to
  let hsm_group_vec_all =
      hsm::group::http_client::get_all(shasta_token, shasta_base_url, shasta_root_cert)
          .await
          .expect("Error - fetching HSM groups"); */

  let hsm_name_available_vec =
    backend.get_group_name_available(auth_token).await.unwrap();

  // Get HSM group user has access to
  let hsm_group_available_map = backend
    .get_group_map_and_filter_by_group_vec(
      auth_token,
      &hsm_name_available_vec
        .iter()
        .map(String::as_str)
        .collect::<Vec<&str>>(),
    )
    .await
    .expect("ERROR - could not get HSM group summary");

  // Filter hsm group members
  for (hsm_name, hsm_members) in hsm_group_available_map {
    let xname_filtered: Vec<String> = hsm_members
      .iter()
      .filter(|&xname| xname_vec.contains(&xname))
      .cloned()
      .collect();
    if !xname_filtered.is_empty() {
      hsm_group_summary.insert(hsm_name, xname_filtered);
    }
  }

  hsm_group_summary
}

/// Check if input is a NID
pub fn validate_nid_format_vec(node_vec: Vec<String>) -> bool {
  node_vec.iter().all(|nid| validate_nid_format(nid))
}

/// Check if input is a NID
pub fn validate_nid_format(nid: &str) -> bool {
  nid.to_lowercase().starts_with("nid")
    && nid.len() == 9
    && nid
      .strip_prefix("nid")
      .is_some_and(|nid_number| nid_number.chars().all(char::is_numeric))
}

/// Validate xname is correct (it uses regex taken from HPE Cray CSM docs)
pub fn validate_xname_format_vec(node_vec: Vec<String>) -> bool {
  node_vec.iter().all(|nid| validate_xname_format(nid))
}

/// Validate xname is correct (it uses regex taken from HPE Cray CSM docs)
pub fn validate_xname_format(xname: &str) -> bool {
  let xname_re =
    Regex::new(r"^x\d{4}c[0-7]s([0-9]|[1-5][0-9]|6[0-4])b[0-1]n[0-7]$")
      .unwrap();

  xname_re.is_match(xname)
}

pub fn print_table(nodes_status: Vec<NodeDetails>) {
  let mut table = Table::new();
  table.set_content_arrangement(ContentArrangement::Dynamic);

  table.set_header(vec![
    "XNAME",
    "NID",
    "HSM",
    "Power",
    "Runtime Config",
    "Config Stat",
    "Enabled",
    "# Error",
    "Image ID",
  ]);

  for node_status in nodes_status {
    let mut node_vec: Vec<String> = node_status
      .hsm
      .split(",")
      .map(|xname_str| xname_str.trim().to_string())
      .collect();
    node_vec.sort();

    table.add_row(vec![
      Cell::new(node_status.xname),
      Cell::new(node_status.nid),
      Cell::new(nodes_to_string_format_discrete_columns(Some(&node_vec), 1)),
      Cell::new(node_status.power_status),
      Cell::new(node_status.desired_configuration),
      Cell::new(node_status.configuration_status),
      Cell::new(node_status.enabled),
      Cell::new(node_status.error_count),
      Cell::new(node_status.boot_image_id),
    ]);
  }

  println!("{table}");
}

pub fn print_table_wide(nodes_status: Vec<NodeDetails>) {
  let mut table = Table::new();
  table.set_content_arrangement(ContentArrangement::Dynamic);

  table.set_header(vec![
    "XNAME",
    "NID",
    "HSM",
    "Power",
    "Runtime Config",
    "Config Status",
    "Enabled",
    "Error #",
    "Image ID",
    "Kernel Params",
  ]);

  for node_status in nodes_status {
    let kernel_params_vec: Vec<&str> =
      node_status.kernel_params.split_whitespace().collect();
    let cell_max_width = kernel_params_vec
      .iter()
      .map(|value| value.len())
      .max()
      .unwrap_or(0);

    let mut kernel_params_string: String = kernel_params_vec[0].to_string();
    let mut cell_width = kernel_params_string.len();

    for kernel_param in kernel_params_vec.iter().skip(1) {
      cell_width += kernel_param.len();

      if cell_width + kernel_param.len() >= cell_max_width {
        kernel_params_string.push_str("\n");
        cell_width = 0;
      } else {
        kernel_params_string.push_str(" ");
      }

      kernel_params_string.push_str(kernel_param);
    }

    let mut node_vec: Vec<String> = node_status
      .hsm
      .split(",")
      .map(|xname_str| xname_str.trim().to_string())
      .collect();
    node_vec.sort();

    table.add_row(vec![
      Cell::new(node_status.xname),
      Cell::new(node_status.nid),
      Cell::new(nodes_to_string_format_discrete_columns(Some(&node_vec), 1)),
      Cell::new(node_status.power_status),
      Cell::new(node_status.desired_configuration),
      Cell::new(node_status.configuration_status),
      Cell::new(node_status.enabled),
      Cell::new(node_status.error_count),
      Cell::new(node_status.boot_image_id),
      Cell::new(kernel_params_string),
    ]);
  }

  println!("{table}");
}

pub fn print_summary(node_details_list: Vec<NodeDetails>) {
  let mut power_status_counters: HashMap<String, usize> = HashMap::new();
  let mut boot_configuration_counters: HashMap<String, usize> = HashMap::new();
  let mut runtime_configuration_counters: HashMap<String, usize> =
    HashMap::new();
  let mut boot_image_counters: HashMap<String, usize> = HashMap::new();

  for node in node_details_list {
    power_status_counters
      .entry(node.power_status)
      .and_modify(|power_status_counter| *power_status_counter += 1)
      .or_insert(1);

    boot_configuration_counters
      .entry(node.boot_configuration)
      .and_modify(|power_status_counter| *power_status_counter += 1)
      .or_insert(1);

    runtime_configuration_counters
      .entry(node.desired_configuration)
      .and_modify(|power_status_counter| *power_status_counter += 1)
      .or_insert(1);

    boot_image_counters
      .entry(node.boot_image_id)
      .and_modify(|power_status_counter| *power_status_counter += 1)
      .or_insert(1);
  }

  let mut table = Table::new();

  table.set_header(vec!["Power status", "Num nodes"]);

  for power_status in
    ["FAILED", "ON", "OFF", "READY", "STANDBY", "UNCONFIGURED"]
  {
    table
      .load_preset(comfy_table::presets::ASCII_FULL_CONDENSED)
      .add_row(vec![
        Cell::new(power_status),
        Cell::new(power_status_counters.get(power_status).unwrap_or(&0))
          .set_alignment(comfy_table::CellAlignment::Center),
      ]);
  }

  println!("{table}");

  let mut table = Table::new();

  table.set_header(vec!["Boot configuration name", "Num nodes"]);

  for (config_name, counter) in boot_configuration_counters {
    table
      .load_preset(comfy_table::presets::ASCII_FULL_CONDENSED)
      .add_row(vec![
        Cell::new(config_name),
        Cell::new(counter).set_alignment(comfy_table::CellAlignment::Center),
      ]);
  }

  println!("{table}");

  let mut table = Table::new();

  table.set_header(vec!["Boot image id", "Num nodes"]);

  for (image_id, counter) in boot_image_counters {
    table
      .load_preset(comfy_table::presets::ASCII_FULL_CONDENSED)
      .add_row(vec![
        Cell::new(image_id),
        Cell::new(counter).set_alignment(comfy_table::CellAlignment::Center),
      ]);
  }

  println!("{table}");

  let mut table = Table::new();

  table.set_header(vec!["Runtime configuration name", "Num nodes"]);

  for (config_name, counter) in runtime_configuration_counters {
    table
      .load_preset(comfy_table::presets::ASCII_FULL_CONDENSED)
      .add_row(vec![
        Cell::new(config_name),
        Cell::new(counter).set_alignment(comfy_table::CellAlignment::Center),
      ]);
  }

  println!("{table}");
}

pub fn nodes_to_string_format_discrete_columns(
  nodes: Option<&Vec<String>>,
  num_columns: usize,
) -> String {
  let mut members: String;

  match nodes {
    Some(nodes) if !nodes.is_empty() => {
      members = nodes[0].clone(); // take first element

      for (i, _) in nodes.iter().enumerate().skip(1) {
        // iterate for the rest of the list
        if i % num_columns == 0 {
          // breaking the cell content into multiple lines (only 2 xnames per line)

          members.push_str(",\n");
        } else {
          members.push(',');
        }

        members.push_str(&nodes[i]);
      }
    }
    _ => members = "".to_string(),
  }

  members
}

pub fn string_vec_to_multi_line_string(
  nodes: Option<&Vec<String>>,
  num_columns: usize,
) -> String {
  let mut members: String;

  match nodes {
    Some(nodes) if !nodes.is_empty() => {
      members = nodes.first().unwrap().to_string(); // take first element

      for (i, _) in nodes.iter().enumerate().skip(1) {
        // iterate for the rest of the list
        if i % num_columns == 0 {
          // breaking the cell content into multiple lines (only 2 xnames per line)

          members.push_str(",\n");
        } else {
          members.push(',');
        }

        members.push_str(&nodes[i]);
      }
    }
    _ => members = "".to_string(),
  }

  members
}