csm-rs 0.89.2

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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
use crate::{
  bos::{self, template::http_client::v2::types::BosSessionTemplate},
  cfs::{
    self, component::http_client::v2::types::Component,
    configuration::http_client::v2::types::cfs_configuration_response::CfsConfigurationResponse,
    session::http_client::v2::types::CfsSessionGetResponse,
  },
  common::{self, gitea},
  error::Error,
  hsm,
  ims::{self, image::http_client::types::Image},
};

use chrono::NaiveDateTime;
use globset::Glob;
use serde_json::Value;

use super::http_client::{
  v2::types::cfs_configuration_request::CfsConfigurationRequest,
  v3::types::{
    cfs_configuration::LayerDetails, cfs_configuration_response::Layer,
  },
};

pub async fn create_new_configuration(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  configuration: &CfsConfigurationRequest,
  configuration_name: &str,
  overwrite: bool,
) -> Result<CfsConfigurationResponse, Error> {
  // Check if CFS configuration already exists
  log::info!("Check CFS configuration '{}' exists", configuration_name);

  let cfs_configuration_vec = crate::cfs::configuration::http_client::v2::get(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    Some(configuration_name),
  )
  .await
  .map_err(|e| Error::Message(e.to_string()))
  .unwrap_or_default();

  // Check if CFS configuration already exists and throw an error is that is the case
  if !cfs_configuration_vec.is_empty() {
    if overwrite {
      log::info!(
          "CFS configuration '{}' already exists but 'overwrite' has been enabled",
          configuration_name
        );
    } else {
      log::warn!(
        "CFS configuration '{}' already exists, cancel the process",
        configuration_name
      );
      return Err(Error::ConfigurationAlreadyExists(
        configuration_name.to_string(),
      ));
    }
  }

  log::info!(
    "CFS configuration '{}' does not exists, creating new CFS configuration",
    configuration_name
  );

  crate::cfs::configuration::http_client::v2::put(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &configuration.clone().into(),
    configuration_name,
  )
  .await
  .map(|config| config.into())
  .map_err(|e| Error::Message(e.to_string()))
}

/* pub fn filter_3(
  cfs_configuration_vec: &mut Vec<CfsConfigurationResponse>,
  configuration_name_pattern_opt: Option<&str>,
  limit_number_opt: Option<&u8>,
  since_opt: Option<NaiveDateTime>,
  until_opt: Option<NaiveDateTime>,
) -> Result<Vec<CfsConfigurationResponse>, Error> {
  log::info!("Filter CFS configurations");

  // Filter CFS configurations based on user input (date range or configuration name)
  if let (Some(since), Some(until)) = (since_opt, until_opt) {
    cfs_configuration_vec.retain(|cfs_configuration| {
      let date =
        chrono::DateTime::parse_from_rfc3339(&cfs_configuration.last_updated)
          .unwrap()
          .naive_utc();

      since <= date && date < until
    });
  }

  // Filter CFS configurations based on pattern matching
  if let Some(configuration_name_pattern) = configuration_name_pattern_opt {
    let glob = Glob::new(configuration_name_pattern)
      .unwrap()
      .compile_matcher();
    cfs_configuration_vec.retain(|cfs_configuration| {
      glob.is_match(cfs_configuration.name.clone())
    });
  }

  // Sort by last updated date in ASC order
  cfs_configuration_vec.sort_by(|cfs_configuration_1, cfs_configuration_2| {
    cfs_configuration_1
      .last_updated
      .cmp(&cfs_configuration_2.last_updated)
  });

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

  Ok(cfs_configuration_vec.to_vec())
} */

/// Filter the list of CFS configurations provided. This operation is very expensive since it is
/// filtering by HSM group which means it needs to link CFS configurations with CFS sessions and
/// BOS sessiontemplate. Aditionally, it will also fetch CFS components to find CFS sessions and
/// BOS sessiontemplates linked to specific xnames that also belongs to the HSM group the user is
/// filtering from.
pub fn filter(
  cfs_configuration_vec: &mut Vec<CfsConfigurationResponse>,
  xname_from_groups_vec: &[&str],
  cfs_session_vec: &mut Vec<CfsSessionGetResponse>,
  bos_sessiontemplate_vec: &mut Vec<BosSessionTemplate>,
  cfs_component_vec: &Vec<Component>,
  configuration_name_pattern_opt: Option<&str>,
  hsm_group_name_vec: &[&str],
  since_opt: Option<NaiveDateTime>,
  until_opt: Option<NaiveDateTime>,
  limit_number_opt: Option<&u8>,
  keep_generic_sessions: bool,
) -> Result<Vec<CfsConfigurationResponse>, Error> {
  log::info!("Filter CFS configurations");

  // Filter BOS sessiontemplates based on HSM groups
  bos::template::utils::filter(
    bos_sessiontemplate_vec,
    configuration_name_pattern_opt,
    hsm_group_name_vec,
    &xname_from_groups_vec,
    None,
  );

  // Filter CFS sessions based on HSM groups
  cfs::session::utils::filter(
    cfs_session_vec,
    configuration_name_pattern_opt,
    hsm_group_name_vec,
    xname_from_groups_vec,
    None,
    None,
    keep_generic_sessions,
  )?;

  // Get boot image id and desired configuration from BOS sessiontemplates
  let image_id_cfs_configuration_target_from_bos_sessiontemplate: Vec<(
    String,
    String,
    Vec<String>,
  )> = bos::template::utils::get_image_id_cfs_configuration_target_tuple_vec(
    bos_sessiontemplate_vec,
  );

  // Get image id, configuration and targets from CFS sessions
  let image_id_cfs_configuration_target_from_cfs_session: Vec<(
    String,
    String,
    Vec<String>,
  )> = cfs::session::utils::get_image_id_cfs_configuration_target_tuple_vec(
    cfs_session_vec,
  );

  // Get desired configuration from CFS components
  let desired_config_vec: Vec<String> = cfs_component_vec
    .into_iter()
    .map(|cfs_component| cfs_component.desired_config.clone().unwrap())
    .collect();

  // Merge CFS configurations in list of filtered CFS sessions and BOS sessiontemplates and
  // desired configurations in CFS components
  let cfs_configuration_in_cfs_session_and_bos_sessiontemplate: Vec<String> = [
    image_id_cfs_configuration_target_from_bos_sessiontemplate
      .into_iter()
      .map(|(_, config, _)| config)
      .collect(),
    image_id_cfs_configuration_target_from_cfs_session
      .into_iter()
      .map(|(_, config, _)| config)
      .collect(),
    desired_config_vec,
  ]
  .concat();

  // Filter CFS configurations
  //
  // Filter CFS configurations based on HSM group names
  cfs_configuration_vec.retain(|cfs_configuration| {
    hsm_group_name_vec
      .iter()
      .any(|hsm_group| cfs_configuration.name.contains(hsm_group))
      || cfs_configuration_in_cfs_session_and_bos_sessiontemplate
        .contains(&cfs_configuration.name)
  });

  // Filter CFS configurations based on user input (date range or configuration name)
  if let (Some(since), Some(until)) = (since_opt, until_opt) {
    cfs_configuration_vec.retain(|cfs_configuration| {
      let date =
        chrono::DateTime::parse_from_rfc3339(&cfs_configuration.last_updated)
          .unwrap()
          .naive_utc();

      since <= date && date < until
    });
  }

  // Sort by last updated date in ASC order
  cfs_configuration_vec.sort_by(|cfs_configuration_1, cfs_configuration_2| {
    cfs_configuration_1
      .last_updated
      .cmp(&cfs_configuration_2.last_updated)
  });

  // Filter CFS configurations based on mattern matching
  if let Some(configuration_name_pattern) = configuration_name_pattern_opt {
    let glob = Glob::new(configuration_name_pattern)
      .unwrap()
      .compile_matcher();
    cfs_configuration_vec.retain(|cfs_configuration| {
      glob.is_match(cfs_configuration.name.clone())
    });
  }

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

  Ok(cfs_configuration_vec.to_vec())
}

/* /// Filter the list of CFS configurations provided. This operation is very expensive since it is
/// filtering by HSM group which means it needs to link CFS configurations with CFS sessions and
/// BOS sessiontemplate. Aditionally, it will also fetch CFS components to find CFS sessions and
/// BOS sessiontemplates linked to specific xnames that also belongs to the HSM group the user is
/// filtering from.
#[deprecated(note = "please use `filter_2` instead")]
pub async fn filter(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  cfs_configuration_vec: &mut Vec<CfsConfigurationResponse>,
  configuration_name_pattern_opt: Option<&str>,
  hsm_group_name_vec: &[String],
  since_opt: Option<NaiveDateTime>,
  until_opt: Option<NaiveDateTime>,
  limit_number_opt: Option<&u8>,
) -> Result<Vec<CfsConfigurationResponse>, Error> {
  log::info!("Filter CFS configurations");

  // COLLECT SITE WIDE DATA FOR VALIDATION
  //
  let xname_from_groups_vec =
    hsm::group::utils::get_member_vec_from_hsm_name_vec(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      hsm_group_name_vec,
    )
    .await?;

  let (mut cfs_session_vec, mut bos_sessiontemplate_vec, cfs_component_vec) = tokio::try_join!(
    cfs::session::http_client::v2::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
    ),
    bos::template::http_client::v2::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
    ),
    cfs::component::http_client::v2::get_parallel(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      &xname_from_groups_vec,
    ),
  )?;

  // Filter BOS sessiontemplates based on HSM groups
  bos::template::utils::filter(
    &mut bos_sessiontemplate_vec,
    hsm_group_name_vec,
    &xname_from_groups_vec,
    None,
  );

  // Filter CFS sessions based on HSM groups
  cfs::session::utils::filter_by_hsm(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &mut cfs_session_vec,
    hsm_group_name_vec,
    None,
    true,
  )
  .await?;

  // Get boot image id and desired configuration from BOS sessiontemplates
  let image_id_cfs_configuration_target_from_bos_sessiontemplate: Vec<(
    String,
    String,
    Vec<String>,
  )> = bos::template::utils::get_image_id_cfs_configuration_target_tuple_vec(
    bos_sessiontemplate_vec,
  );

  // Get image id, configuration and targets from CFS sessions
  let image_id_cfs_configuration_target_from_cfs_session: Vec<(
    String,
    String,
    Vec<String>,
  )> = cfs::session::utils::get_image_id_cfs_configuration_target_tuple_vec(
    cfs_session_vec,
  );

  // Get desired configuration from CFS components
  let desired_config_vec: Vec<String> = cfs_component_vec
    .into_iter()
    .map(|cfs_component| cfs_component.desired_config.unwrap())
    .collect();

  // Merge CFS configurations in list of filtered CFS sessions and BOS sessiontemplates and
  // desired configurations in CFS components
  let cfs_configuration_in_cfs_session_and_bos_sessiontemplate: Vec<String> = [
    image_id_cfs_configuration_target_from_bos_sessiontemplate
      .into_iter()
      .map(|(_, config, _)| config)
      .collect(),
    image_id_cfs_configuration_target_from_cfs_session
      .into_iter()
      .map(|(_, config, _)| config)
      .collect(),
    desired_config_vec,
  ]
  .concat();

  // Filter CFS configurations
  //
  // Filter CFS configurations based on HSM group names
  cfs_configuration_vec.retain(|cfs_configuration| {
    hsm_group_name_vec
      .iter()
      .any(|hsm_group| cfs_configuration.name.contains(hsm_group))
      || cfs_configuration_in_cfs_session_and_bos_sessiontemplate
        .contains(&cfs_configuration.name)
  });

  // Filter CFS configurations based on user input (date range or configuration name)
  if let (Some(since), Some(until)) = (since_opt, until_opt) {
    cfs_configuration_vec.retain(|cfs_configuration| {
      let date =
        chrono::DateTime::parse_from_rfc3339(&cfs_configuration.last_updated)
          .unwrap()
          .naive_utc();

      since <= date && date < until
    });
  }

  // Sort by last updated date in ASC order
  cfs_configuration_vec.sort_by(|cfs_configuration_1, cfs_configuration_2| {
    cfs_configuration_1
      .last_updated
      .cmp(&cfs_configuration_2.last_updated)
  });

  // Filter CFS configurations based on mattern matching
  if let Some(configuration_name_pattern) = configuration_name_pattern_opt {
    let glob = Glob::new(configuration_name_pattern)
      .unwrap()
      .compile_matcher();
    cfs_configuration_vec.retain(|cfs_configuration| {
      glob.is_match(cfs_configuration.name.clone())
    });
  }

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

  Ok(cfs_configuration_vec.to_vec())
} */

/* /// Filter the list of CFS configurations provided. This operation is very expensive since it is
/// filtering by HSM group which means it needs to link CFS configurations with CFS sessions and
/// BOS sessiontemplate. Aditionally, it will also fetch CFS components to find CFS sessions and
/// BOS sessiontemplates linked to specific xnames that also belongs to the HSM group the user is
/// filtering from.
pub async fn filter(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  cfs_configuration_vec: &mut Vec<CfsConfigurationResponse>,
  configuration_name_pattern_opt: Option<&str>,
  hsm_group_name_vec: &[String],
  limit_number_opt: Option<&u8>,
) -> Result<Vec<CfsConfigurationResponse>, Error> {
  log::info!("Filter CFS configurations");
  // Get HSM Group members the user has access to
  let hsm_group_members_vec =
    hsm::group::utils::get_member_vec_from_hsm_name_vec(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      hsm_group_name_vec,
    )
    .await?;

  // Get CFS components the user has access to, all CFS sessions, BOS session template
  // Fetch "CFS components" the user has access to (filter by HSM group members)
  // Note: nodes can be configured calling the "CFS Component API" directly (bypassing BOS
  // session API)
  let (cfs_component_vec, mut cfs_session_vec, mut bos_sessiontemplate_vec) = tokio::try_join!(
    cfs::component::http_client::v2::get_parallel(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      &hsm_group_members_vec,
    ),
    crate::cfs::session::http_client::v2::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert
    ),
    crate::bos::template::http_client::v2::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert
    )
  )?;

  // Filter BOS sessiontemplates based on HSM groups
  bos::template::utils::filter(
    &mut bos_sessiontemplate_vec,
    hsm_group_name_vec,
    &hsm_group_members_vec,
    None,
  );

  // Filter CFS sessions based on HSM groups
  cfs::session::utils::filter_by_hsm(
    shasta_token,
    shasta_base_url,
    shasta_root_cert,
    &mut cfs_session_vec,
    hsm_group_name_vec,
    None,
    true,
  )
  .await?;

  // Get boot image id and desired configuration from BOS sessiontemplates
  let image_id_cfs_configuration_target_from_bos_sessiontemplate: Vec<(
    String,
    String,
    Vec<String>,
  )> = bos::template::utils::get_image_id_cfs_configuration_target_tuple_vec(
    bos_sessiontemplate_vec,
  );

  // Get image id, configuration and targets from CFS sessions
  let image_id_cfs_configuration_target_from_cfs_session: Vec<(
    String,
    String,
    Vec<String>,
  )> = cfs::session::utils::get_image_id_cfs_configuration_target_tuple_vec(
    cfs_session_vec,
  );

  // Get desired configuration from CFS components
  let desired_config_vec: Vec<String> = cfs_component_vec
    .into_iter()
    .map(|cfs_component| cfs_component.desired_config.unwrap())
    .collect();

  // Merge CFS configurations in list of filtered CFS sessions and BOS sessiontemplates and
  // desired configurations in CFS components
  let cfs_configuration_in_cfs_session_and_bos_sessiontemplate: Vec<String> = [
    image_id_cfs_configuration_target_from_bos_sessiontemplate
      .into_iter()
      .map(|(_, config, _)| config)
      .collect(),
    image_id_cfs_configuration_target_from_cfs_session
      .into_iter()
      .map(|(_, config, _)| config)
      .collect(),
    desired_config_vec,
  ]
  .concat();

  // Filter CFS configurations
  //
  // Filter CFS configurations based on HSM group names
  cfs_configuration_vec.retain(|cfs_configuration| {
    hsm_group_name_vec
      .iter()
      .any(|hsm_group| cfs_configuration.name.contains(hsm_group))
      || cfs_configuration_in_cfs_session_and_bos_sessiontemplate
        .contains(&cfs_configuration.name)
  });

  // Sort by last updated date in ASC order
  cfs_configuration_vec.sort_by(|cfs_configuration_1, cfs_configuration_2| {
    cfs_configuration_1
      .last_updated
      .cmp(&cfs_configuration_2.last_updated)
  });

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

  // Filter CFS configurations based on mattern matching
  if let Some(configuration_name_pattern) = configuration_name_pattern_opt {
    let glob = Glob::new(configuration_name_pattern)
      .unwrap()
      .compile_matcher();
    cfs_configuration_vec.retain(|cfs_configuration| {
      glob.is_match(cfs_configuration.name.clone())
    });
  }

  Ok(cfs_configuration_vec.to_vec())
} */

/// If filtering by HSM group, then configuration name must include HSM group name (It assumms each configuration
/// is built for a specific cluster based on ansible vars used by the CFS session). The reason
/// for this is because CSCS staff deletes all CFS sessions every now and then...
pub async fn get_and_filter(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  configuration_name: Option<&str>,
  configuration_name_pattern: Option<&str>,
  hsm_group_name_vec: &[&str],
  since_opt: Option<NaiveDateTime>,
  until_opt: Option<NaiveDateTime>,
  limit_number_opt: Option<&u8>,
) -> Result<Vec<CfsConfigurationResponse>, Error> {
  // Get list of configurations.
  // Returns list with only one element if "configuration name" provided

  // COLLECT SITE WIDE DATA FOR VALIDATION
  //
  let xname_from_groups_vec =
    hsm::group::utils::get_member_vec_from_hsm_name_vec(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      hsm_group_name_vec,
    )
    .await?;

  let (
    mut cfs_configuration_vec,
    mut cfs_session_vec,
    mut bos_sessiontemplate_vec,
    cfs_component_vec,
  ) = tokio::try_join!(
    cfs::configuration::http_client::v2::get(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      configuration_name,
    ),
    cfs::session::http_client::v2::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
    ),
    bos::template::http_client::v2::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
    ),
    cfs::component::http_client::v2::get_parallel(
      shasta_token,
      shasta_base_url,
      shasta_root_cert,
      &xname_from_groups_vec,
    ),
  )?;

  let keep_generic_sessions = common::jwt_ops::is_user_admin(shasta_token);

  // Filter CFS configurations if user is not admin
  cfs::configuration::utils::filter(
    &mut cfs_configuration_vec,
    &xname_from_groups_vec
      .iter()
      .map(|x| x.as_str())
      .collect::<Vec<&str>>(),
    &mut cfs_session_vec,
    &mut bos_sessiontemplate_vec,
    &cfs_component_vec,
    configuration_name_pattern,
    hsm_group_name_vec,
    since_opt,
    until_opt,
    limit_number_opt,
    keep_generic_sessions,
  )?;

  Ok(cfs_configuration_vec)
}

// Get all CFS sessions, IMS images and BOS sessiontemplates related to a CFS configuration
pub async fn get_derivatives(
  shasta_token: &str,
  shasta_base_url: &str,
  shasta_root_cert: &[u8],
  configuration_name: &str,
) -> Result<
  (
    Option<Vec<CfsSessionGetResponse>>,
    Option<Vec<BosSessionTemplate>>,
    Option<Vec<Image>>,
  ),
  Error,
> {
  // List of image ids from CFS sessions and BOS sessiontemplates related to CFS configuration
  let mut image_id_vec: Vec<&str> = Vec::new();

  let (mut cfs_session_vec, mut bos_sessiontemplate_vec, mut ims_image_vec) = tokio::try_join!(
    cfs::session::http_client::v2::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert
    ),
    bos::template::http_client::v2::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert
    ),
    ims::image::http_client::get_all(
      shasta_token,
      shasta_base_url,
      shasta_root_cert
    )
  )?;

  // Filter CFS sessions
  cfs::session::utils::filter_by_cofiguration(
    &mut cfs_session_vec,
    configuration_name,
  );

  // Filter BOS sessiontemplate
  bos_sessiontemplate_vec.retain(|bos_sessiontemplate| {
    bos_sessiontemplate
      .images_id()
      .any(|image_id_aux| image_id_vec.contains(&image_id_aux))
      || bos_sessiontemplate.get_configuration().unwrap_or_default()
        == configuration_name
  });

  // Add all image ids in CFS sessions into image_id_vec
  image_id_vec.extend(
    cfs_session_vec
      .iter()
      .flat_map(|cfs_session| cfs_session.results_id()),
  );

  // Add boot images from BOS sessiontemplate to image_id_vec
  image_id_vec.extend(
    bos_sessiontemplate_vec
      .iter()
      .flat_map(|bos_sessiontemplate| bos_sessiontemplate.images_id()),
  );

  // Filter images
  ims_image_vec.retain(|image| {
    image_id_vec.contains(&image.id.as_deref().unwrap_or_default())
  });

  Ok((
    Some(cfs_session_vec),
    Some(bos_sessiontemplate_vec),
    Some(ims_image_vec),
  ))
}

pub async fn get_configuration_layer_details(
  shasta_root_cert: &[u8],
  gitea_base_url: &str,
  gitea_token: &str,
  layer: Layer,
  site_name: &str,
) -> Result<LayerDetails, Error> {
  let commit_id: String =
    layer.commit.clone().unwrap_or("Not defined".to_string());
  // let branch_name_opt: Option<&str> = layer.branch.as_deref();
  // let mut most_recent_commit: bool = false;
  let mut branch_name_vec: Vec<String> = Vec::new();
  let mut tag_name_vec: Vec<String> = Vec::new();
  let commit_sha;

  let repo_ref_vec_rslt = gitea::http_client::get_all_refs_from_repo_url(
    gitea_base_url,
    gitea_token,
    &layer.clone_url,
    shasta_root_cert,
  )
  .await;

  let repo_ref_vec = match repo_ref_vec_rslt {
    Ok(value) => value,
    Err(error) => {
      log::warn!(
        "Could not fetch repo '{}' refs. Reason:\n{:#?}",
        layer.clone_url,
        error
      );
      vec![]
    }
  };

  let mut ref_value_vec: Vec<&Value> = repo_ref_vec
    .iter()
    .filter(|repo_ref| {
      repo_ref
        .pointer("/object/sha")
        .unwrap()
        .as_str()
        .unwrap()
        .eq(&commit_id)
    })
    .collect();

  // Check if ref filtering returns an annotated tag, if so, then get the SHA of its
  // commit because it will be needed in case there are branches related to the
  // annotated tag
  if ref_value_vec.len() == 1 {
    // Potentially an annotated tag
    let ref_value = ref_value_vec.first().unwrap();
    log::debug!("Found ref in remote git repo:\n{:#?}", ref_value);

    let ref_type: &str =
      ref_value.pointer("/object/type").unwrap().as_str().unwrap();

    let mut r#ref = ref_value["ref"].as_str().unwrap().split("/").skip(1);

    let _ref_1 = r#ref.next();
    let ref_2 = r#ref.next();

    if ref_type == "tag" {
      // Yes, we are processing an annotated tag
      let tag_name = ref_2.unwrap();

      let commit_sha_value = gitea::http_client::get_commit_from_tag(
        ref_value["url"].as_str().unwrap(),
        &tag_name,
        gitea_token,
        shasta_root_cert,
        site_name,
      )
      .await?;

      commit_sha = commit_sha_value
        .pointer("/commit/sha")
        .unwrap()
        .as_str()
        .unwrap();

      let annotated_tag_commit_sha =
        [commit_id.clone(), commit_sha.to_string()];

      ref_value_vec = repo_ref_vec
        .iter()
        .filter(|repo_ref| {
          let ref_sha: String = repo_ref
            .pointer("/object/sha")
            .unwrap()
            .as_str()
            .unwrap()
            .to_string();

          annotated_tag_commit_sha.contains(&ref_sha)
        })
        .collect();
    }
  }

  for ref_value in ref_value_vec {
    log::debug!("Found ref in remote git repo:\n{:#?}", ref_value);
    let ref_type: &str =
      ref_value.pointer("/object/type").unwrap().as_str().unwrap();
    let mut r#ref = ref_value["ref"].as_str().unwrap().split("/").skip(1);

    let ref_1 = r#ref.next();
    let ref_2 = r#ref.collect::<Vec<_>>().join("/");

    if ref_type == "commit" {
      // either branch or lightweight tag
      if let (Some("heads"), branch_name_aux) = (ref_1, ref_2.clone()) {
        // branch
        branch_name_vec.push(branch_name_aux);
      } else if let (Some("tags"), tag_name_aux) = (ref_1, ref_2) {
        // lightweight tag
        tag_name_vec.push(tag_name_aux);
      }
    } else {
      // annotated tag
      tag_name_vec.push(ref_2);
    }
  }

  if let Some(cfs_config_layer_branch) = &layer.branch {
    branch_name_vec.push(cfs_config_layer_branch.to_string());
  }

  let commit_id_opt = layer.commit.as_ref();

  let gitea_commit_details: serde_json::Value =
    if let Some(commit_id) = commit_id_opt {
      let repo_name = layer
        .clone_url
        .trim_start_matches("https://api-gw-service-nmn.local/vcs/")
        .trim_end_matches(".git");

      gitea::http_client::get_commit_details_from_external_url(
        repo_name,
        commit_id,
        gitea_token,
        shasta_root_cert,
        site_name,
      )
      .await?
    } else {
      serde_json::json!({})
    };

  Ok(LayerDetails::new(
    &layer.name,
    layer
      .clone_url
      .trim_start_matches(
        format!("https://api.cmn.{}.cscs.ch", site_name).as_str(),
      )
      .trim_end_matches(".git"),
    &commit_id,
    gitea_commit_details
      .pointer("/commit/committer/name")
      .unwrap_or(&serde_json::json!("Not defined"))
      .as_str()
      .unwrap(),
    gitea_commit_details
      .pointer("/commit/committer/date")
      .unwrap_or(&serde_json::json!("Not defined"))
      .as_str()
      .unwrap(),
    &branch_name_vec.join(","),
    &tag_name_vec.join(","),
    &layer.playbook,
  ))
}