csm-rs 0.7.1

A library for Shasta
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
use crate::{
  cfs,
  error::Error,
  hsm::{
    self,
    group::{
      hacks::{filter_roles_and_subroles, filter_system_hsm_group_names},
      types::Group,
    },
  },
};
use std::io::{self, Write};

use super::http_client::v2::types::CfsSessionGetResponse;

// Check if a session is related to a group the user has access to
pub fn check_cfs_session_against_groups_available(
  cfs_session: &CfsSessionGetResponse,
  group_available: Vec<Group>,
) -> bool {
  group_available.iter().any(|group| {
    cfs_session
      .get_target_hsm()
      .is_some_and(|group_vec| group_vec.contains(&group.label))
      || cfs_session
        .get_target_xname()
        .is_some_and(|session_xname_vec| {
          session_xname_vec
            .iter()
            .all(|xname| group.get_members().contains(xname))
        })
  })
}

/* /// Checks if a session is "generic". A generic session is a session used to create an
/// image and it is not dedicated to a specific group.
/// Images generated by generic sessions are called generic images and they can be used by
/// any group.
/// For a CFS session to be generic, it must be linked to a HSM group or xname related to a
/// HSM group the user has access to.
/// Generic CFS sessions must belong to one or more of the following roles:
/// - Application
/// - Compute
/// - UAN
/// - UserDefined
/// How to calculate.
/// 1) We extract the HSM groups the CFS session is linked to
/// 2) We substract the roles mentioned above to the list of HSM groups
/// 3) If the list is empty then, we are dealing with a generic CFS session
pub fn is_session_generic(cfs_session: &CfsSessionGetResponse) -> bool {
    if cfs_session
        .get_target_def()
        .is_some_and(|target_def| target_def == "image".to_string())
    {
        let hsm_group_name_vec: Vec<String> = cfs_session
            .get_target_hsm()
            .unwrap_or_default()
            .into_iter()
            .filter(|hsm_group_name| {
                !["Application", "Compute", "UAN", "UserDefined"].contains(&hsm_group_name.as_str())
            })
            .collect();

        hsm_group_name_vec.is_empty()
    } else {
        false
    }
} */

/// Checks if a session is "generic". A generic "session" is a session used to create an
/// image and it is not dedicated to a specific group.
/// Images generated by "generic sessions" are called generic images and they can be used by
/// any group.
/// For a CFS session to be generic, it must be linked to a system wide HSM group or a role or a subrole or xname related to a HSM group the user has access to.
/// Generic CFS sessions must belong to one or more of the following roles:
/// - Application
/// - Compute
/// - UAN
/// - UserDefined
/// - etc
/// How to calculate.
/// 1) We extract the HSM groups the CFS session is linked to
/// 2) We substract the roles mentioned above to the list of HSM groups
/// 3) We substract the system wide HSM groups
/// 4) If the list is empty then, we are dealing with a generic CFS session
pub fn is_session_image_generic(cfs_session: &CfsSessionGetResponse) -> bool {
  let target_group_vec_opt = cfs_session.get_target_hsm();
  let is_image = cfs_session.is_target_def_image();

  if let (Some(mut target_group_vec), true) = (target_group_vec_opt, is_image) {
    // Remove roles and subroles from the list of HSM groups
    target_group_vec = filter_roles_and_subroles(target_group_vec);

    // Remove system wide HSM groups from the list of HSM groups
    target_group_vec = filter_system_hsm_group_names(target_group_vec);

    log::debug!(
      "CFS session {} is generic: {}",
      cfs_session.name.as_ref().unwrap(),
      target_group_vec.is_empty()
    );

    target_group_vec.is_empty()
  } else {
    false
  }
}

/// Filter CFS sessions related to a list of HSM group names, how this works is, it will
/// get the list of nodes within those HSM groups and filter all CFS sessions in the system
/// using either the HSM group names or nodes as target.
/// NOTE: Please make sure the user has access to the HSM groups he is asking for before
/// calling this function
pub async fn filter_by_hsm(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  cfs_session_vec: &mut Vec<CfsSessionGetResponse>,
  hsm_group_name_vec: &[String],
  limit_number_opt: Option<&u8>,
  keep_generic_sessions: bool,
) -> Result<(), Error> {
  log::info!("Filter CFS sessions by groups");
  // Get all xnames in list of HSM groups
  let xname_vec: Vec<String> =
    hsm::group::utils::get_member_vec_from_hsm_name_vec(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      &hsm_group_name_vec,
    )
    .await?;

  filter(
    cfs_session_vec,
    hsm_group_name_vec.to_vec(),
    xname_vec,
    limit_number_opt,
    keep_generic_sessions,
  )
}

pub async fn filter_by_xname(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  cfs_session_vec: &mut Vec<CfsSessionGetResponse>,
  xname_vec: &[&str],
  limit_number_opt: Option<&u8>,
  keep_generic_sessions: bool,
) -> Result<(), Error> {
  log::info!("Filter CFS sessions by xnames");
  let hsm_group_name_from_xnames_vec: Vec<String> =
    hsm::group::utils::get_hsm_group_name_vec_from_xname_vec(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      xname_vec,
    )
    .await;

  log::info!(
    "HSM groups that belongs to xnames {:?} are: {:?}",
    xname_vec,
    hsm_group_name_from_xnames_vec
  );

  filter(
    cfs_session_vec,
    Vec::new(),
    xname_vec
      .iter()
      .map(|xname| xname.to_string())
      .collect::<Vec<String>>(),
    limit_number_opt,
    keep_generic_sessions,
  )
}

pub fn filter(
  cfs_session_vec: &mut Vec<CfsSessionGetResponse>,
  hsm_group_name_available_vec: Vec<String>,
  xname_available_vec: Vec<String>,
  limit_number_opt: Option<&u8>,
  keep_generic_sessions: bool,
) -> Result<(), Error> {
  log::info!("Filter CFS sessions by groups");
  // Checks either target.groups contains hsm_group_name or ansible.limit is a subset of
  // hsm_group.members.ids
  cfs_session_vec.retain(|cfs_session| {
    cfs_session.get_target_hsm().is_some_and(|target_hsm_vec| {
      (keep_generic_sessions && is_session_image_generic(cfs_session))
        || target_hsm_vec.iter().any(|target_hsm| {
          hsm_group_name_available_vec
            .iter()
            .any(|hsm_group_name| hsm_group_name.contains(target_hsm))
        })
    }) || cfs_session
      .get_target_xname()
      .is_some_and(|target_xname_vec| {
        target_xname_vec
          .iter()
          .any(|target_xname| xname_available_vec.contains(target_xname))
      })
  });

  // Sort CFS sessions by start time order ASC
  cfs_session_vec.sort_by(|a, b| {
    a.get_start_time()
      .unwrap()
      .cmp(&b.get_start_time().unwrap())
  });

  if let Some(limit_number) = limit_number_opt {
    // Limiting the number of results to return to client
    *cfs_session_vec = cfs_session_vec
      [cfs_session_vec.len().saturating_sub(*limit_number as usize)..]
      .to_vec();
  }

  Ok(())
}
/// Filter CFS sessions to the ones related to a CFS configuration
pub fn filter_by_cofiguration(
  cfs_session_vec: &mut Vec<CfsSessionGetResponse>,
  cfs_configuration_name: &str,
) {
  log::info!(
    "Filter CFS sessions by configuration name '{}'",
    cfs_configuration_name
  );

  cfs_session_vec.retain(|cfs_session| {
    cfs_session.configuration_namen().as_deref() == Some(cfs_configuration_name)
  });
}

/// Filter CFS sessions related to a list of HSM group names and a list of nodes and filter
/// all CFS sessions in the system using either the HSM group names or nodes as target.
/// NOTE: Please make sure the user has access to the HSM groups and nodes he is asking for before
/// calling this function
pub fn find_cfs_session_related_to_image_id(
  cfs_session_vec: &[CfsSessionGetResponse],
  image_id: &str,
) -> Option<CfsSessionGetResponse> {
  cfs_session_vec
    .iter()
    .find(|cfs_session| {
      cfs_session
        .get_first_result_id()
        .is_some_and(|result_id| result_id == image_id)
    })
    .cloned()
}

pub fn get_cfs_configuration_name(
  cfs_session: &CfsSessionGetResponse,
) -> Option<String> {
  cfs_session
    .configuration
    .as_ref()
    .unwrap()
    .name
    .as_ref()
    .cloned()
}

/// Returns a tuple like (image_id, cfs_configuration_name, target) from a list of CFS
/// sessions
pub fn get_image_id_cfs_configuration_target_tuple_vec(
  cfs_session_vec: Vec<CfsSessionGetResponse>,
) -> Vec<(String, String, Vec<String>)> {
  let mut image_id_cfs_configuration_target_from_cfs_session: Vec<(
    String,
    String,
    Vec<String>,
  )> = Vec::new();

  cfs_session_vec.iter().for_each(|cfs_session| {
    let result_id: &str = cfs_session.first_result_id().unwrap_or_default();

    let target: Vec<String> = cfs_session
      .get_target_hsm()
      .or_else(|| cfs_session.get_target_xname())
      .unwrap_or_default();

    let cfs_configuration = cfs_session.configuration_namen().unwrap();

    image_id_cfs_configuration_target_from_cfs_session.push((
      result_id.to_string(),
      cfs_configuration.to_string(),
      target,
    ));
  });

  image_id_cfs_configuration_target_from_cfs_session
}

/// Returns a tuple like (image_id, cfs_configuration_name, target) from a list of CFS
/// sessions. Only returns values from CFS sessions with an artifact.result_id value
/// (meaning CFS sessions completed and successful of type image)
pub fn get_image_id_cfs_configuration_target_for_existing_images_tuple_vec(
  cfs_session_vec: &[CfsSessionGetResponse],
) -> Vec<(String, String, Vec<String>)> {
  let mut image_id_cfs_configuration_target_from_cfs_session: Vec<(
    String,
    String,
    Vec<String>,
  )> = Vec::new();

  cfs_session_vec.iter().for_each(|cfs_session| {
    if let Some(result_id) = cfs_session.get_first_result_id() {
      let target: Vec<String> = cfs_session
        .get_target_hsm()
        .or_else(|| cfs_session.get_target_xname())
        .unwrap_or_default();

      let cfs_configuration = cfs_session.configuration_namen().unwrap();

      image_id_cfs_configuration_target_from_cfs_session.push((
        result_id.to_string(),
        cfs_configuration.to_string(),
        target,
      ));
    } else {
      image_id_cfs_configuration_target_from_cfs_session.push((
        "".to_string(),
        "".to_string(),
        vec![],
      ));
    }
  });

  image_id_cfs_configuration_target_from_cfs_session
}

/// Return a list of the images ids related with a list of CFS sessions. The result list if
/// filtered to CFS session completed and target def 'image' therefore the length of the
/// resulting list may be smaller than the list of CFS sessions
#[deprecated(note = "Use `images_id_from_cfs_session` instead")]
pub fn get_image_id_from_cfs_session_vec(
  cfs_session_vec: &[CfsSessionGetResponse],
) -> Vec<String> {
  let mut image_id_vec: Vec<String> = cfs_session_vec
    .iter()
    .flat_map(|cfs_session| cfs_session.get_result_id_vec())
    .collect();

  image_id_vec.sort();
  image_id_vec.dedup();

  image_id_vec
}

/// Return a list of the images ids related with a list of CFS sessions. The result list if
/// filtered to CFS session completed and target def 'image' therefore the length of the
/// resulting list may be smaller than the list of CFS sessions
pub fn images_id_from_cfs_session(
  cfs_session_vec: &[CfsSessionGetResponse],
) -> impl Iterator<Item = &str> {
  let mut image_id_vec: Vec<&str> = cfs_session_vec
    .iter()
    .flat_map(|cfs_session| cfs_session.results_id())
    .collect();

  image_id_vec.sort();
  image_id_vec.dedup();

  image_id_vec.into_iter()
}

/// Wait a CFS session to finish
// FIXME: This function prints CFS session logs to stdout which is not a good idea because the
// client may run outside this machine
pub async fn wait_cfs_session_to_finish(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  cfs_session_id: &str,
) -> Result<(), Error> {
  let mut i = 0;
  let max = 3000; // Max ammount of attempts to check if CFS session has ended
  loop {
    let cfs_session_vec = cfs::session::get_and_sort(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      None,
      None,
      None,
      Some(&cfs_session_id.to_string()),
      None,
    )
    .await?;

    let cfs_session = if cfs_session_vec.is_empty() {
      return Err(Error::Message(format!(
        "ERROR - CFS session '{}' missing. Exit",
        cfs_session_id
      )));
    } else {
      cfs_session_vec.first().unwrap().clone()
    };

    log::debug!("CFS session details:\n{:#?}", cfs_session);

    let cfs_session_status =
      cfs_session.status.unwrap().session.unwrap().status.unwrap();

    if cfs_session_status != "complete" && i < max {
      print!("\x1B[2K"); // Clear current line
      io::stdout().flush().unwrap();
      println!(
                "Waiting CFS session '{}' with status '{}'. Checking again in 2 secs. Attempt {} of {}.",
                cfs_session_id, cfs_session_status, i, max
            );
      io::stdout().flush().unwrap();

      tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;

      i += 1;
    } else {
      println!(
        "CFS session '{}' finished with status '{}'",
        cfs_session_id, cfs_session_status
      );
      break Ok(());
    }
  }
}

pub async fn get_list_xnames_related_to_session(
  group_available_vec: Vec<Group>,
  cfs_session: CfsSessionGetResponse,
) -> Result<Vec<String>, Error> {
  let target_group_xname_vec: Vec<String> = if let Some(target_hsm_vec) =
    cfs_session.get_target_hsm()
  {
    group_available_vec
      .into_iter()
      .filter(|group_available| target_hsm_vec.contains(&group_available.label))
      .flat_map(|group_available| group_available.get_members())
      .collect()
  } else {
    vec![]
  };

  let target_xname_vec =
    if let Some(target_xname) = cfs_session.get_target_xname() {
      target_xname
    } else {
      vec![]
    };

  Ok([target_xname_vec, target_group_xname_vec].concat())
}