eksup 0.14.0

A CLI to aid in upgrading Amazon EKS clusters
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
use std::collections::HashMap;

use anyhow::Result;
use aws_sdk_autoscaling::types::AutoScalingGroup;
use aws_sdk_eks::types::{Addon, AmiTypes, Cluster, Nodegroup};
use serde::{Deserialize, Serialize};
use tabled::{
  Table, Tabled,
  settings::{Margin, Style},
};

use crate::{
  eks::resources,
  finding::{self, Code, Finding, Findings, Remediation},
  output::tabled_vec_to_string,
};

/// Cluster health issue data
///
/// Nearly identical to the SDK's `ClusterIssue` but allows us to serialize/deserialize
#[derive(Debug, Serialize, Deserialize, Tabled)]
pub struct ClusterHealthIssue {
  #[tabled(inline)]
  pub finding: finding::Finding,
  pub code: String,
  pub message: String,
  #[tabled(display = "tabled_vec_to_string")]
  pub resource_ids: Vec<String>,
}

// Manual impl (not using impl_findings! macro) because the markdown table
// intentionally keeps the CHECK column visible, unlike all other finding types.
impl Findings for Vec<ClusterHealthIssue> {
  fn to_markdown_table(&self, leading_whitespace: &str) -> Result<String> {
    if self.is_empty() {
      return Ok(format!(
        "{leading_whitespace}✅ - There are no reported health issues on the cluster control plane"
      ));
    }

    let mut table = Table::new(self);
    table
      .with(Margin::new(1, 0, 0, 0).fill('\t', 'x', 'x', 'x'))
      .with(Style::markdown());

    Ok(format!("{table}\n"))
  }

  fn to_stdout_table(&self) -> Result<String> {
    if self.is_empty() {
      return Ok("".to_owned());
    }

    let mut table = Table::new(self);
    table.with(Style::sharp());

    Ok(format!("{table}\n"))
  }
}

/// Check for any reported health issues on the cluster control plane
pub(crate) fn cluster_health(cluster: &Cluster) -> Result<Vec<ClusterHealthIssue>> {
  let health = cluster.health();

  match health {
    Some(health) => Ok(
      health
        .issues()
        .iter()
        .filter_map(|issue| {
          issue.code.as_ref().map(|code| ClusterHealthIssue {
            finding: Finding::new(Code::EKS002, Remediation::Required),
            code: code.as_str().to_string(),
            message: issue.message().unwrap_or_default().to_string(),
            resource_ids: issue.resource_ids().to_owned(),
          })
        })
        .collect(),
    ),
    None => Ok(vec![]),
  }
}

/// Subnet details that can affect upgrade behavior
#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct InsufficientSubnetIps {
  #[tabled(inline)]
  pub finding: finding::Finding,
  pub id: String,
  pub available_ips: i32,
}

finding::impl_findings!(
  InsufficientSubnetIps,
  "✅ - There is sufficient IP space in the subnets provided"
);

pub(crate) fn control_plane_ips(subnet_ips: &[resources::VpcSubnet]) -> Vec<InsufficientSubnetIps> {
  let mut az_ips: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
  for subnet in subnet_ips {
    *az_ips.entry(subnet.availability_zone_id.clone()).or_default() += subnet.available_ips;
  }
  let mut availability_zone_ips: Vec<(String, i32)> = az_ips.into_iter().collect();
  availability_zone_ips.sort_by(|a, b| a.0.cmp(&b.0));

  // There are at least 2 different availability zones with 5 or more IPs; no finding
  if availability_zone_ips.iter().filter(|(_az, ips)| ips >= &5).count() >= 2 {
    return vec![];
  }

  let finding = Finding::new(Code::EKS001, Remediation::Required);

  availability_zone_ips
    .iter()
    .map(|(az, ips)| InsufficientSubnetIps {
      finding: finding.clone(),
      id: az.clone(),
      available_ips: *ips,
    })
    .collect()
}

/// Check if the subnets used by the pods will support an upgrade
///
/// This checks for the `ENIConfig` custom resource that is used to configure
/// the AWS VPC CNI for custom networking. The subnet listed for each ENIConfig
/// is queried for its relevant data used to report on the available IPs
pub(crate) fn pod_ips(
  subnet_ips: &[resources::VpcSubnet],
  required_ips: i32,
  recommended_ips: i32,
) -> Vec<InsufficientSubnetIps> {
  if subnet_ips.is_empty() {
    return vec![];
  }

  let available_ips: i32 = subnet_ips.iter().map(|subnet| subnet.available_ips).sum();

  if available_ips >= recommended_ips {
    return vec![];
  }

  let remediation = if available_ips < required_ips {
    Remediation::Required
  } else {
    Remediation::Recommended
  };

  let finding = Finding::new(Code::AWS002, remediation);

  let mut az_ips: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
  for subnet in subnet_ips {
    *az_ips.entry(subnet.availability_zone_id.clone()).or_default() += subnet.available_ips;
  }

  let mut sorted_ips: Vec<(String, i32)> = az_ips.into_iter().collect();
  sorted_ips.sort_by(|a, b| a.0.cmp(&b.0));

  sorted_ips
    .into_iter()
    .map(|(az, ips)| InsufficientSubnetIps {
      finding: finding.clone(),
      id: az,
      available_ips: ips,
    })
    .collect()
}

/// Check available IPs in data plane subnets (nodegroup or Fargate profile subnets)
///
/// During an upgrade, the rolling-update/surge process requires additional IPs.
/// If the subnets used by a nodegroup or Fargate profile are running low,
/// the upgrade may fail or be unable to launch replacement nodes/pods.
pub(crate) fn data_plane_ips(
  subnet_ips: &[resources::VpcSubnet],
  required_ips: i32,
  recommended_ips: i32,
) -> Vec<InsufficientSubnetIps> {
  if subnet_ips.is_empty() {
    return vec![];
  }

  let available_ips: i32 = subnet_ips.iter().map(|s| s.available_ips).sum();

  if available_ips >= recommended_ips {
    return vec![];
  }

  let remediation = if available_ips < required_ips {
    Remediation::Required
  } else {
    Remediation::Recommended
  };

  let finding = Finding::new(Code::AWS001, remediation);

  let mut az_ips: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
  for subnet in subnet_ips {
    *az_ips.entry(subnet.availability_zone_id.clone()).or_default() += subnet.available_ips;
  }

  let mut sorted_ips: Vec<(String, i32)> = az_ips.into_iter().collect();
  sorted_ips.sort_by(|a, b| a.0.cmp(&b.0));

  sorted_ips
    .into_iter()
    .map(|(az, ips)| InsufficientSubnetIps {
      finding: finding.clone(),
      id: az,
      available_ips: ips,
    })
    .collect()
}

/// Details of the addon as viewed from an upgrade perspective
///
/// Contains the associated version information to compare the current version
/// of the addon relative to the current "desired" version, as well as
/// relative to the target Kubernetes version "desired" version. It
/// also contains any potential health issues as reported by the EKS API.
/// The intended goal is to be able to plot a path of what steps a user either
/// needs to take to upgrade the cluster, or should consider taking in terms
/// of a recommendation to update to the latest supported version.
#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct AddonVersionCompatibility {
  #[tabled(inline)]
  pub finding: finding::Finding,
  pub name: String,
  /// The current version of the add-on
  #[tabled(rename = "CURRENT")]
  pub version: String,
  /// The default and latest add-on versions for the current Kubernetes version
  #[tabled(skip)]
  pub current_kubernetes_version: resources::AddonVersion,
  /// The default and latest add-on versions for the target Kubernetes version
  #[tabled(inline)]
  pub target_kubernetes_version: resources::AddonVersion,
}

finding::impl_findings!(
  AddonVersionCompatibility,
  "✅ - There are no reported addon version compatibility issues."
);

/// Check for any version compatibility issues for the EKS addons enabled
pub(crate) fn addon_version_compatibility(
  addons: &[Addon],
  current_versions: &HashMap<String, resources::AddonVersion>,
  target_versions: &HashMap<String, resources::AddonVersion>,
) -> Vec<AddonVersionCompatibility> {
  let mut addon_findings = Vec::new();

  for addon in addons {
    let name = addon.addon_name().unwrap_or_default().to_owned();
    let version = addon.addon_version().unwrap_or_default().to_owned();

    let current_kubernetes_version = match current_versions.get(&name) {
      Some(v) => v.clone(),
      None => continue,
    };
    let target_kubernetes_version = match target_versions.get(&name) {
      Some(v) => v.clone(),
      None => continue,
    };

    let remediation = if !target_kubernetes_version.supported_versions.contains(&version)
      || !current_kubernetes_version.supported_versions.contains(&version)
    {
      Some(Remediation::Required)
    } else if current_kubernetes_version.latest != version {
      Some(Remediation::Recommended)
    } else {
      None
    };

    if let Some(remediation) = remediation {
      addon_findings.push(AddonVersionCompatibility {
        finding: Finding::new(Code::EKS005, remediation),
        name,
        version,
        current_kubernetes_version,
        target_kubernetes_version,
      })
    }
  }

  addon_findings
}

/// Addon health issue data
///
/// Nearly identical to the SDK's `AddonIssue` but allows us to serialize/deserialize
#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct AddonHealthIssue {
  #[tabled(inline)]
  pub finding: finding::Finding,
  pub name: String,
  pub code: String,
  pub message: String,
  #[tabled(display = "tabled_vec_to_string")]
  pub resource_ids: Vec<String>,
}

finding::impl_findings!(AddonHealthIssue, "✅ - There are no reported addon health issues.");

pub(crate) fn addon_health(addons: &[Addon]) -> Result<Vec<AddonHealthIssue>> {
  let health_issues = addons
    .iter()
    .flat_map(|addon| {
      let name = addon.addon_name().unwrap_or_default();

      match addon.health() {
        Some(health) => health
          .issues()
          .iter()
          .filter_map(|issue| {
            issue.code.as_ref().map(|code| AddonHealthIssue {
              finding: Finding::new(Code::EKS004, Remediation::Required),
              name: name.to_owned(),
              code: code.as_str().to_string(),
              message: issue.message().unwrap_or_default().to_owned(),
              resource_ids: issue.resource_ids().to_owned(),
            })
          })
          .collect::<Vec<AddonHealthIssue>>(),
        None => vec![],
      }
    })
    .collect();

  Ok(health_issues)
}

/// Nodegroup health issue data
///
/// Nearly similar to the SDK's `NodegroupHealth` but flattened
/// and without `Option()`s to make it a bit more ergonomic here
#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct NodegroupHealthIssue {
  #[tabled(inline)]
  pub finding: finding::Finding,
  pub name: String,
  pub code: String,
  pub message: String,
}

finding::impl_findings!(
  NodegroupHealthIssue,
  "✅ - There are no reported nodegroup health issues."
);

/// Check for any reported health issues on EKS managed node groups
pub(crate) fn eks_managed_nodegroup_health(nodegroups: &[Nodegroup]) -> Result<Vec<NodegroupHealthIssue>> {
  let health_issues = nodegroups
    .iter()
    .flat_map(|nodegroup| {
      let name = nodegroup.nodegroup_name().unwrap_or_default();

      match nodegroup.health() {
        Some(health) => health
          .issues()
          .iter()
          .filter_map(|issue| {
            issue.code.as_ref().map(|code| NodegroupHealthIssue {
              finding: Finding::new(Code::EKS003, Remediation::Required),
              name: name.to_owned(),
              code: code.as_str().to_string(),
              message: issue.message().unwrap_or_default().to_owned(),
            })
          })
          .collect::<Vec<NodegroupHealthIssue>>(),
        None => vec![],
      }
    })
    .collect();

  Ok(health_issues)
}

#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct ManagedNodeGroupUpdate {
  #[tabled(inline)]
  pub finding: finding::Finding,
  /// EKS managed node group name
  #[tabled(rename = "MANAGED NODEGROUP")]
  pub name: String,
  /// Name of the autoscaling group associated to the EKS managed node group
  #[tabled(skip)]
  pub autoscaling_group_name: String,
  /// Launch template controlled by users that influences the autoscaling group
  ///
  /// This distinction is important because we only consider the launch templates
  /// provided by users and not provided by EKS managed node group(s)
  #[tabled(inline)]
  pub launch_template: resources::LaunchTemplate,
}

finding::impl_findings!(
  ManagedNodeGroupUpdate,
  "✅ - There are no pending updates for the EKS managed nodegroup(s)"
);

pub(crate) fn eks_managed_nodegroup_update(
  nodegroup: &Nodegroup,
  launch_template: Option<&resources::LaunchTemplate>,
) -> Vec<ManagedNodeGroupUpdate> {
  let launch_template = match launch_template {
    Some(lt) => lt,
    None => return vec![],
  };

  match nodegroup.resources() {
    Some(resources) => resources
      .auto_scaling_groups()
      .iter()
      .map(|asg| ManagedNodeGroupUpdate {
        finding: Finding::new(Code::EKS006, Remediation::Recommended),
        name: nodegroup.nodegroup_name().unwrap_or_default().to_owned(),
        autoscaling_group_name: asg.name().unwrap_or_default().to_owned(),
        launch_template: launch_template.to_owned(),
      })
      .filter(|asg| asg.launch_template.current_version != asg.launch_template.latest_version)
      .collect(),
    None => vec![],
  }
}

#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct AutoscalingGroupUpdate {
  #[tabled(inline)]
  pub finding: finding::Finding,
  /// Autoscaling group name
  #[tabled(rename = "AUTOSCALING GROUP")]
  pub name: String,
  /// Launch template used by the autoscaling group
  #[tabled(inline)]
  pub launch_template: resources::LaunchTemplate,
}

finding::impl_findings!(
  AutoscalingGroupUpdate,
  "✅ - There are no pending updates for the self-managed nodegroup(s)"
);

/// Returns the autoscaling groups that are not using the latest launch template version
///
/// If there are pending changes, users do not necessarily need to make any changes prior to upgrading.
/// They should, however, be aware of the version currently in use and any changes that may be
/// deployed when updating the launch template for the new Kubernetes version. For example, if the
/// current launch template version is 3 and the latest version is 5, the user should be aware that
/// there may, or may not, be additional changes that were introduced in version 4 and 5 that might be
/// deployed when the launch template is updated to version 6 for the Kubernetes version upgrade. Ideally,
/// users should be on the latest version of the launch template prior to upgrading to avoid any surprises
/// or unexpected changes.
pub(crate) fn self_managed_nodegroup_update(
  asg: &AutoScalingGroup,
  launch_template: &resources::LaunchTemplate,
) -> Option<AutoscalingGroupUpdate> {
  let name = asg.auto_scaling_group_name().unwrap_or_default().to_owned();

  if launch_template.current_version != launch_template.latest_version {
    Some(AutoscalingGroupUpdate {
      finding: Finding::new(Code::EKS007, Remediation::Recommended),
      name,
      launch_template: launch_template.to_owned(),
    })
  } else {
    None
  }
}

#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct Al2AmiDeprecation {
  #[tabled(inline)]
  pub finding: finding::Finding,
  pub name: String,
  #[tabled(rename = "AMI TYPE")]
  pub ami_type: String,
}

finding::impl_findings!(
  Al2AmiDeprecation,
  "✅ - No EKS managed nodegroups are using deprecated AL2 AMI types"
);

/// Check for EKS managed nodegroups using AL2 AMI types which are deprecated in 1.32 and
/// no longer supported starting in 1.33
pub(crate) fn al2_ami_deprecation(nodegroups: &[Nodegroup], target_minor: i32) -> Result<Vec<Al2AmiDeprecation>> {
  if target_minor < 32 {
    return Ok(vec![]);
  }

  let remediation = if target_minor >= 33 {
    Remediation::Required
  } else {
    Remediation::Recommended
  };

  let mut findings = Vec::new();
  for nodegroup in nodegroups {
    let ami_type = match nodegroup.ami_type() {
      Some(ami) => ami,
      None => continue,
    };

    let is_al2 = matches!(
      ami_type,
      AmiTypes::Al2X8664 | AmiTypes::Al2Arm64 | AmiTypes::Al2X8664Gpu
    );
    if is_al2 {
      findings.push(Al2AmiDeprecation {
        finding: Finding::new(Code::EKS008, remediation.clone()),
        name: nodegroup.nodegroup_name().unwrap_or_default().to_owned(),
        ami_type: ami_type.as_str().to_string(),
      });
    }
  }

  Ok(findings)
}

#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct ServiceLimitFinding {
  #[tabled(inline)]
  pub finding: finding::Finding,
  #[tabled(rename = "QUOTA")]
  pub quota_name: String,
  #[tabled(rename = "CURRENT")]
  pub current_usage: String,
  #[tabled(rename = "LIMIT")]
  pub limit: String,
  #[tabled(rename = "USAGE %")]
  pub usage_pct: String,
}

finding::impl_findings!(
  ServiceLimitFinding,
  "✅ - Service limits have sufficient headroom for the upgrade"
);

/// Check if a service quota usage is approaching or exceeding the limit
pub(crate) fn service_limit(
  code: Code,
  quota_name: &str,
  current: f64,
  limit: f64,
  unit: &str,
) -> Option<ServiceLimitFinding> {
  if limit <= 0.0 {
    return None;
  }

  let pct = (current / limit) * 100.0;

  if pct < 80.0 {
    return None;
  }

  let remediation = if pct >= 90.0 {
    Remediation::Required
  } else {
    Remediation::Recommended
  };

  Some(ServiceLimitFinding {
    finding: Finding::new(code, remediation),
    quota_name: quota_name.to_string(),
    current_usage: format!("{current:.1} {unit}"),
    limit: format!("{limit:.1} {unit}"),
    usage_pct: format!("{pct:.0}%"),
  })
}

#[derive(Debug, Serialize, Deserialize, Tabled)]
#[tabled(rename_all = "UpperCase")]
pub struct InsightFinding {
  #[tabled(inline)]
  pub finding: finding::Finding,
  #[tabled(rename = "INSIGHT")]
  pub name: String,
  #[tabled(rename = "STATUS")]
  pub status: String,
  #[tabled(rename = "VERSION")]
  pub kubernetes_version: String,
  #[tabled(rename = "DESCRIPTION")]
  pub description: String,
  #[tabled(rename = "RECOMMENDATION")]
  pub recommendation: String,
}

finding::impl_findings!(InsightFinding, "✅ - No cluster insight issues found");

/// Map raw EKS cluster insights to findings, partitioned by category
///
/// Returns (upgrade_readiness, misconfiguration) tuples.
/// PASSING insights are pre-filtered by the API call; this function
/// maps ERROR → Required and WARNING/UNKNOWN → Recommended.
pub(crate) fn cluster_insights(insights: &[resources::ClusterInsight]) -> (Vec<InsightFinding>, Vec<InsightFinding>) {
  let mut upgrade_readiness = Vec::new();
  let mut misconfiguration = Vec::new();

  for insight in insights {
    let remediation = match insight.status.as_str() {
      "ERROR" => Remediation::Required,
      "WARNING" | "UNKNOWN" => Remediation::Recommended,
      _ => continue,
    };

    let code = if insight.category == "UPGRADE_READINESS" {
      Code::EKS009
    } else {
      Code::EKS010
    };

    let finding = InsightFinding {
      finding: Finding::new(code, remediation),
      name: insight.name.clone(),
      status: insight.status.clone(),
      kubernetes_version: insight.kubernetes_version.clone(),
      description: insight.description.clone(),
      recommendation: insight.recommendation.clone(),
    };

    if insight.category == "UPGRADE_READINESS" {
      upgrade_readiness.push(finding);
    } else {
      misconfiguration.push(finding);
    }
  }

  (upgrade_readiness, misconfiguration)
}

#[cfg(test)]
mod tests {
  use aws_sdk_eks::types::{
    Addon, AddonHealth, AddonIssue, AddonIssueCode, AmiTypes, Cluster, ClusterHealth, ClusterIssue, ClusterIssueCode,
    Issue, Nodegroup, NodegroupHealth, NodegroupIssueCode,
  };

  use super::*;

  // ---------- cluster_health ----------

  #[test]
  fn cluster_health_no_issues() {
    let cluster = Cluster::builder().health(ClusterHealth::builder().build()).build();

    let result = cluster_health(&cluster).unwrap();
    assert!(result.is_empty());
  }

  #[test]
  fn cluster_health_none_health() {
    // Cluster with no health field set at all
    let cluster = Cluster::builder().build();

    let result = cluster_health(&cluster).unwrap();
    assert!(result.is_empty());
  }

  #[test]
  fn cluster_health_has_issues() {
    let issue = ClusterIssue::builder()
      .code(ClusterIssueCode::Ec2SubnetNotFound)
      .message("Subnet not found")
      .resource_ids("subnet-12345")
      .build();

    let cluster = Cluster::builder()
      .health(ClusterHealth::builder().issues(issue).build())
      .build();

    let result = cluster_health(&cluster).unwrap();
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].code, "Ec2SubnetNotFound");
    assert_eq!(result[0].message, "Subnet not found");
    assert_eq!(result[0].resource_ids, vec!["subnet-12345"]);
  }

  // ---------- addon_health ----------

  #[test]
  fn addon_health_no_issues() {
    let addon = Addon::builder()
      .addon_name("vpc-cni")
      .health(AddonHealth::builder().build())
      .build();

    let result = addon_health(&[addon]).unwrap();
    assert!(result.is_empty());
  }

  #[test]
  fn addon_health_has_issues() {
    let issue = AddonIssue::builder()
      .code(AddonIssueCode::AccessDenied)
      .message("Access denied")
      .resource_ids("arn:aws:iam::123456789012:role/test")
      .build();

    let addon = Addon::builder()
      .addon_name("vpc-cni")
      .health(AddonHealth::builder().issues(issue).build())
      .build();

    let result = addon_health(&[addon]).unwrap();
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].name, "vpc-cni");
    assert_eq!(result[0].code, "AccessDenied");
    assert_eq!(result[0].message, "Access denied");
    assert_eq!(result[0].resource_ids, vec!["arn:aws:iam::123456789012:role/test"]);
  }

  #[test]
  fn addon_health_none_health() {
    let addon = Addon::builder().addon_name("coredns").build();

    let result = addon_health(&[addon]).unwrap();
    assert!(result.is_empty());
  }

  #[test]
  fn addon_health_empty_addons() {
    let result = addon_health(&[]).unwrap();
    assert!(result.is_empty());
  }

  // ---------- eks_managed_nodegroup_health ----------

  #[test]
  fn nodegroup_health_no_issues() {
    let ng = Nodegroup::builder()
      .nodegroup_name("test-ng")
      .health(NodegroupHealth::builder().build())
      .build();

    let result = eks_managed_nodegroup_health(&[ng]).unwrap();
    assert!(result.is_empty());
  }

  #[test]
  fn nodegroup_health_has_issues() {
    let issue = Issue::builder()
      .code(NodegroupIssueCode::AccessDenied)
      .message("Access denied to node group")
      .build();

    let ng = Nodegroup::builder()
      .nodegroup_name("test-ng")
      .health(NodegroupHealth::builder().issues(issue).build())
      .build();

    let result = eks_managed_nodegroup_health(&[ng]).unwrap();
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].name, "test-ng");
    assert_eq!(result[0].code, "AccessDenied");
    assert_eq!(result[0].message, "Access denied to node group");
  }

  #[test]
  fn nodegroup_health_none_health() {
    let ng = Nodegroup::builder().nodegroup_name("test-ng").build();

    let result = eks_managed_nodegroup_health(&[ng]).unwrap();
    assert!(result.is_empty());
  }

  // ---------- al2_ami_deprecation ----------

  #[test]
  fn al2_ami_deprecation_target_below_32() {
    let ng = Nodegroup::builder()
      .nodegroup_name("test-ng")
      .ami_type(AmiTypes::Al2X8664)
      .build();

    let result = al2_ami_deprecation(&[ng], 31).unwrap();
    assert!(result.is_empty());
  }

  #[test]
  fn al2_ami_deprecation_target_32_recommended() {
    let ng = Nodegroup::builder()
      .nodegroup_name("test-ng")
      .ami_type(AmiTypes::Al2X8664)
      .build();

    let result = al2_ami_deprecation(&[ng], 32).unwrap();
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].name, "test-ng");
    assert_eq!(result[0].ami_type, "AL2_x86_64");
    assert!(matches!(result[0].finding.remediation, Remediation::Recommended));
  }

  #[test]
  fn al2_ami_deprecation_target_33_required() {
    let ng = Nodegroup::builder()
      .nodegroup_name("test-ng")
      .ami_type(AmiTypes::Al2X8664)
      .build();

    let result = al2_ami_deprecation(&[ng], 33).unwrap();
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].name, "test-ng");
    assert!(matches!(result[0].finding.remediation, Remediation::Required));
  }

  #[test]
  fn al2_ami_deprecation_non_al2_ami_type() {
    let ng = Nodegroup::builder()
      .nodegroup_name("test-ng")
      .ami_type(AmiTypes::Al2023X8664Standard)
      .build();

    let result = al2_ami_deprecation(&[ng], 33).unwrap();
    assert!(result.is_empty());
  }

  #[test]
  fn al2_ami_deprecation_no_ami_type() {
    let ng = Nodegroup::builder().nodegroup_name("test-ng").build();

    let result = al2_ami_deprecation(&[ng], 33).unwrap();
    assert!(result.is_empty());
  }

  #[test]
  fn al2_ami_deprecation_mixed_ami_types() {
    let al2_ng = Nodegroup::builder()
      .nodegroup_name("al2-ng")
      .ami_type(AmiTypes::Al2X8664)
      .build();

    let al2_arm_ng = Nodegroup::builder()
      .nodegroup_name("al2-arm-ng")
      .ami_type(AmiTypes::Al2Arm64)
      .build();

    let al2023_ng = Nodegroup::builder()
      .nodegroup_name("al2023-ng")
      .ami_type(AmiTypes::Al2023X8664Standard)
      .build();

    let bottlerocket_ng = Nodegroup::builder()
      .nodegroup_name("br-ng")
      .ami_type(AmiTypes::BottlerocketX8664)
      .build();

    let result = al2_ami_deprecation(&[al2_ng, al2_arm_ng, al2023_ng, bottlerocket_ng], 32).unwrap();
    // Only the two AL2 nodegroups should produce findings
    assert_eq!(result.len(), 2);
    assert_eq!(result[0].name, "al2-ng");
    assert_eq!(result[1].name, "al2-arm-ng");
    assert!(
      result
        .iter()
        .all(|f| matches!(f.finding.remediation, Remediation::Recommended))
    );
  }

  use crate::eks::resources::VpcSubnet;

  // ---------- control_plane_ips ----------

  #[test]
  fn control_plane_ips_empty_subnets() {
    let result = control_plane_ips(&[]);
    assert!(result.is_empty());
  }

  #[test]
  fn control_plane_ips_two_azs_sufficient() {
    let subnets = vec![
      VpcSubnet {
        id: "subnet-1".into(),
        available_ips: 10,
        availability_zone_id: "use1-az1".into(),
      },
      VpcSubnet {
        id: "subnet-2".into(),
        available_ips: 8,
        availability_zone_id: "use1-az2".into(),
      },
    ];
    let result = control_plane_ips(&subnets);
    assert!(result.is_empty(), "2 AZs with >= 5 IPs should produce no findings");
  }

  #[test]
  fn control_plane_ips_one_az_insufficient() {
    let subnets = vec![
      VpcSubnet {
        id: "subnet-1".into(),
        available_ips: 10,
        availability_zone_id: "use1-az1".into(),
      },
      VpcSubnet {
        id: "subnet-2".into(),
        available_ips: 3,
        availability_zone_id: "use1-az2".into(),
      },
    ];
    let result = control_plane_ips(&subnets);
    assert!(!result.is_empty(), "only 1 AZ with >= 5 IPs should produce findings");
    assert!(
      result
        .iter()
        .all(|f| matches!(f.finding.remediation, Remediation::Required))
    );
  }

  #[test]
  fn control_plane_ips_boundary_exactly_5() {
    let subnets = vec![
      VpcSubnet {
        id: "subnet-1".into(),
        available_ips: 5,
        availability_zone_id: "use1-az1".into(),
      },
      VpcSubnet {
        id: "subnet-2".into(),
        available_ips: 5,
        availability_zone_id: "use1-az2".into(),
      },
    ];
    let result = control_plane_ips(&subnets);
    assert!(result.is_empty(), "exactly 5 IPs in 2 AZs should pass");
  }

  #[test]
  fn control_plane_ips_aggregates_across_subnets_in_same_az() {
    let subnets = vec![
      VpcSubnet {
        id: "subnet-1a".into(),
        available_ips: 3,
        availability_zone_id: "use1-az1".into(),
      },
      VpcSubnet {
        id: "subnet-1b".into(),
        available_ips: 3,
        availability_zone_id: "use1-az1".into(),
      },
      VpcSubnet {
        id: "subnet-2".into(),
        available_ips: 6,
        availability_zone_id: "use1-az2".into(),
      },
    ];
    let result = control_plane_ips(&subnets);
    assert!(result.is_empty(), "3+3=6 in az1 and 6 in az2 should pass");
  }

  // ---------- pod_ips ----------

  #[test]
  fn pod_ips_empty_subnets() {
    let result = pod_ips(&[], 16, 256);
    assert!(result.is_empty(), "no subnets means no custom networking, no findings");
  }

  #[test]
  fn pod_ips_above_recommended() {
    let subnets = vec![
      VpcSubnet {
        id: "subnet-1".into(),
        available_ips: 200,
        availability_zone_id: "use1-az1".into(),
      },
      VpcSubnet {
        id: "subnet-2".into(),
        available_ips: 100,
        availability_zone_id: "use1-az2".into(),
      },
    ];
    let result = pod_ips(&subnets, 16, 256);
    assert!(result.is_empty(), "300 IPs >= 256 recommended threshold");
  }

  #[test]
  fn pod_ips_between_required_and_recommended() {
    let subnets = vec![VpcSubnet {
      id: "subnet-1".into(),
      available_ips: 100,
      availability_zone_id: "use1-az1".into(),
    }];
    let result = pod_ips(&subnets, 16, 256);
    assert!(!result.is_empty());
    assert!(
      result
        .iter()
        .all(|f| matches!(f.finding.remediation, Remediation::Recommended))
    );
  }

  #[test]
  fn pod_ips_below_required() {
    let subnets = vec![VpcSubnet {
      id: "subnet-1".into(),
      available_ips: 10,
      availability_zone_id: "use1-az1".into(),
    }];
    let result = pod_ips(&subnets, 16, 256);
    assert!(!result.is_empty());
    assert!(
      result
        .iter()
        .all(|f| matches!(f.finding.remediation, Remediation::Required))
    );
  }

  // ---------- data_plane_ips ----------

  #[test]
  fn data_plane_ips_empty_subnets() {
    let result = data_plane_ips(&[], 30, 100);
    assert!(result.is_empty());
  }

  #[test]
  fn data_plane_ips_above_recommended() {
    let subnets = vec![
      VpcSubnet {
        id: "subnet-1".into(),
        available_ips: 80,
        availability_zone_id: "use1-az1".into(),
      },
      VpcSubnet {
        id: "subnet-2".into(),
        available_ips: 80,
        availability_zone_id: "use1-az2".into(),
      },
    ];
    let result = data_plane_ips(&subnets, 30, 100);
    assert!(result.is_empty());
  }

  #[test]
  fn data_plane_ips_between_required_and_recommended() {
    let subnets = vec![VpcSubnet {
      id: "subnet-1".into(),
      available_ips: 40,
      availability_zone_id: "use1-az1".into(),
    }];
    let result = data_plane_ips(&subnets, 30, 100);
    assert!(!result.is_empty());
    assert!(
      result
        .iter()
        .all(|f| matches!(f.finding.remediation, Remediation::Recommended))
    );
  }

  #[test]
  fn data_plane_ips_below_required() {
    let subnets = vec![VpcSubnet {
      id: "subnet-1".into(),
      available_ips: 10,
      availability_zone_id: "use1-az1".into(),
    }];
    let result = data_plane_ips(&subnets, 30, 100);
    assert!(!result.is_empty());
    assert!(
      result
        .iter()
        .all(|f| matches!(f.finding.remediation, Remediation::Required))
    );
  }

  // ---------- addon_version_compatibility ----------

  use std::collections::{HashMap as StdHashMap, HashSet};

  use crate::eks::resources::AddonVersion;

  #[test]
  fn addon_version_compat_all_supported() {
    let addon = Addon::builder().addon_name("vpc-cni").addon_version("v1.15.0").build();

    let current = StdHashMap::from([(
      "vpc-cni".into(),
      AddonVersion {
        latest: "v1.15.0".into(),
        default: "v1.14.0".into(),
        supported_versions: HashSet::from(["v1.15.0".into(), "v1.14.0".into()]),
      },
    )]);
    let target = StdHashMap::from([(
      "vpc-cni".into(),
      AddonVersion {
        latest: "v1.16.0".into(),
        default: "v1.15.0".into(),
        supported_versions: HashSet::from(["v1.16.0".into(), "v1.15.0".into()]),
      },
    )]);

    let result = addon_version_compatibility(&[addon], &current, &target);
    assert!(
      result.is_empty(),
      "version supported in both should produce no findings"
    );
  }

  #[test]
  fn addon_version_compat_not_latest_recommended() {
    let addon = Addon::builder().addon_name("vpc-cni").addon_version("v1.14.0").build();

    let current = StdHashMap::from([(
      "vpc-cni".into(),
      AddonVersion {
        latest: "v1.15.0".into(),
        default: "v1.14.0".into(),
        supported_versions: HashSet::from(["v1.15.0".into(), "v1.14.0".into()]),
      },
    )]);
    let target = StdHashMap::from([(
      "vpc-cni".into(),
      AddonVersion {
        latest: "v1.16.0".into(),
        default: "v1.15.0".into(),
        supported_versions: HashSet::from(["v1.16.0".into(), "v1.15.0".into(), "v1.14.0".into()]),
      },
    )]);

    let result = addon_version_compatibility(&[addon], &current, &target);
    assert_eq!(result.len(), 1);
    assert!(matches!(result[0].finding.remediation, Remediation::Recommended));
  }

  #[test]
  fn addon_version_compat_unsupported_on_target_required() {
    let addon = Addon::builder().addon_name("vpc-cni").addon_version("v1.12.0").build();

    let current = StdHashMap::from([(
      "vpc-cni".into(),
      AddonVersion {
        latest: "v1.15.0".into(),
        default: "v1.14.0".into(),
        supported_versions: HashSet::from(["v1.15.0".into(), "v1.14.0".into(), "v1.12.0".into()]),
      },
    )]);
    let target = StdHashMap::from([(
      "vpc-cni".into(),
      AddonVersion {
        latest: "v1.16.0".into(),
        default: "v1.15.0".into(),
        supported_versions: HashSet::from(["v1.16.0".into(), "v1.15.0".into()]),
      },
    )]);

    let result = addon_version_compatibility(&[addon], &current, &target);
    assert_eq!(result.len(), 1);
    assert!(matches!(result[0].finding.remediation, Remediation::Required));
  }

  // ---------- eks_managed_nodegroup_update ----------

  use aws_sdk_eks::types::{AutoScalingGroup as EksAutoScalingGroup, NodegroupResources};

  use crate::eks::resources::LaunchTemplate;

  #[test]
  fn mng_update_no_launch_template() {
    let ng = Nodegroup::builder().nodegroup_name("test").build();
    let result = eks_managed_nodegroup_update(&ng, None);
    assert!(result.is_empty());
  }

  #[test]
  fn mng_update_current_equals_latest() {
    let ng = Nodegroup::builder()
      .nodegroup_name("test")
      .resources(
        NodegroupResources::builder()
          .auto_scaling_groups(EksAutoScalingGroup::builder().name("asg-1").build())
          .build(),
      )
      .build();
    let lt = LaunchTemplate {
      name: "lt-1".into(),
      id: "lt-abc".into(),
      current_version: "3".into(),
      latest_version: "3".into(),
    };
    let result = eks_managed_nodegroup_update(&ng, Some(&lt));
    assert!(result.is_empty(), "current == latest should produce no findings");
  }

  #[test]
  fn mng_update_current_behind_latest() {
    let ng = Nodegroup::builder()
      .nodegroup_name("test")
      .resources(
        NodegroupResources::builder()
          .auto_scaling_groups(EksAutoScalingGroup::builder().name("asg-1").build())
          .build(),
      )
      .build();
    let lt = LaunchTemplate {
      name: "lt-1".into(),
      id: "lt-abc".into(),
      current_version: "2".into(),
      latest_version: "5".into(),
    };
    let result = eks_managed_nodegroup_update(&ng, Some(&lt));
    assert_eq!(result.len(), 1);
    assert!(matches!(result[0].finding.remediation, Remediation::Recommended));
  }

  // ---------- self_managed_nodegroup_update ----------

  #[test]
  fn smng_update_current_equals_latest() {
    let asg = AutoScalingGroup::builder().auto_scaling_group_name("asg-1").build();
    let lt = LaunchTemplate {
      name: "lt-1".into(),
      id: "lt-abc".into(),
      current_version: "3".into(),
      latest_version: "3".into(),
    };
    let result = self_managed_nodegroup_update(&asg, &lt);
    assert!(result.is_none());
  }

  #[test]
  fn smng_update_current_behind_latest() {
    let asg = AutoScalingGroup::builder().auto_scaling_group_name("asg-1").build();
    let lt = LaunchTemplate {
      name: "lt-1".into(),
      id: "lt-abc".into(),
      current_version: "1".into(),
      latest_version: "3".into(),
    };
    let result = self_managed_nodegroup_update(&asg, &lt);
    assert!(result.is_some());
    assert!(matches!(result.unwrap().finding.remediation, Remediation::Recommended));
  }

  // ---------- service_limit ----------

  #[test]
  fn service_limit_below_80_pct() {
    let result = service_limit(Code::AWS003, "EC2 vCPUs", 50.0, 100.0, "vCPUs");
    assert!(result.is_none());
  }

  #[test]
  fn service_limit_between_80_and_90_pct() {
    let result = service_limit(Code::AWS003, "EC2 vCPUs", 85.0, 100.0, "vCPUs");
    assert!(result.is_some());
    assert!(matches!(result.unwrap().finding.remediation, Remediation::Recommended));
  }

  #[test]
  fn service_limit_above_90_pct() {
    let result = service_limit(Code::AWS003, "EC2 vCPUs", 95.0, 100.0, "vCPUs");
    assert!(result.is_some());
    assert!(matches!(result.unwrap().finding.remediation, Remediation::Required));
  }

  #[test]
  fn service_limit_at_100_pct() {
    let result = service_limit(Code::AWS003, "EC2 vCPUs", 100.0, 100.0, "vCPUs");
    assert!(result.is_some());
    assert!(matches!(result.unwrap().finding.remediation, Remediation::Required));
  }

  #[test]
  fn service_limit_zero_limit() {
    let result = service_limit(Code::AWS003, "EC2 vCPUs", 10.0, 0.0, "vCPUs");
    assert!(result.is_none());
  }

  use crate::eks::resources::ClusterInsight;

  fn make_test_insight(category: &str, status: &str) -> ClusterInsight {
    ClusterInsight {
      id: "test-id".into(),
      name: "Test Insight".into(),
      category: category.into(),
      status: status.into(),
      status_reason: String::new(),
      kubernetes_version: "1.31".into(),
      description: "Test description".into(),
      recommendation: "Test recommendation".into(),
    }
  }

  // ---------- cluster_insights ----------

  #[test]
  fn cluster_insights_empty() {
    let (upgrade, misconfig) = cluster_insights(&[]);
    assert!(upgrade.is_empty());
    assert!(misconfig.is_empty());
  }

  #[test]
  fn cluster_insights_error_is_required() {
    let insight = make_test_insight("UPGRADE_READINESS", "ERROR");
    let (upgrade, _) = cluster_insights(&[insight]);
    assert_eq!(upgrade.len(), 1);
    assert!(matches!(upgrade[0].finding.remediation, Remediation::Required));
  }

  #[test]
  fn cluster_insights_warning_is_recommended() {
    let insight = make_test_insight("UPGRADE_READINESS", "WARNING");
    let (upgrade, _) = cluster_insights(&[insight]);
    assert_eq!(upgrade.len(), 1);
    assert!(matches!(upgrade[0].finding.remediation, Remediation::Recommended));
  }

  #[test]
  fn cluster_insights_unknown_is_recommended() {
    let insight = make_test_insight("MISCONFIGURATION", "UNKNOWN");
    let (_, misconfig) = cluster_insights(&[insight]);
    assert_eq!(misconfig.len(), 1);
    assert!(matches!(misconfig[0].finding.remediation, Remediation::Recommended));
  }

  #[test]
  fn cluster_insights_passing_skipped() {
    let insight = make_test_insight("UPGRADE_READINESS", "PASSING");
    let (upgrade, misconfig) = cluster_insights(&[insight]);
    assert!(upgrade.is_empty());
    assert!(misconfig.is_empty());
  }

  #[test]
  fn cluster_insights_partitions_by_category() {
    let insights = vec![
      make_test_insight("UPGRADE_READINESS", "ERROR"),
      make_test_insight("MISCONFIGURATION", "WARNING"),
      make_test_insight("UPGRADE_READINESS", "WARNING"),
    ];
    let (upgrade, misconfig) = cluster_insights(&insights);
    assert_eq!(upgrade.len(), 2);
    assert_eq!(misconfig.len(), 1);
  }

  #[test]
  fn cluster_insights_code_mapping() {
    let insights = vec![
      make_test_insight("UPGRADE_READINESS", "ERROR"),
      make_test_insight("MISCONFIGURATION", "ERROR"),
    ];
    let (upgrade, misconfig) = cluster_insights(&insights);
    assert_eq!(upgrade[0].finding.code.to_string(), "EKS009");
    assert_eq!(misconfig[0].finding.code.to_string(), "EKS010");
  }
}