/
helper.go
1551 lines (1316 loc) · 62.7 KB
/
helper.go
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
// Copyright 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helper
import (
"errors"
"fmt"
"slices"
"strconv"
"strings"
"time"
"github.com/Masterminds/semver/v3"
corev1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/utils/ptr"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
versionutils "github.com/gardener/gardener/pkg/utils/version"
)
// IsControllerInstallationSuccessful returns true if a ControllerInstallation has been marked as "successfully"
// installed.
func IsControllerInstallationSuccessful(controllerInstallation gardencorev1beta1.ControllerInstallation) bool {
var (
installed bool
healthy bool
notProgressing bool
)
for _, condition := range controllerInstallation.Status.Conditions {
if condition.Type == gardencorev1beta1.ControllerInstallationInstalled && condition.Status == gardencorev1beta1.ConditionTrue {
installed = true
}
if condition.Type == gardencorev1beta1.ControllerInstallationHealthy && condition.Status == gardencorev1beta1.ConditionTrue {
healthy = true
}
if condition.Type == gardencorev1beta1.ControllerInstallationProgressing && condition.Status == gardencorev1beta1.ConditionFalse {
notProgressing = true
}
}
return installed && healthy && notProgressing
}
// IsControllerInstallationRequired returns true if a ControllerInstallation has been marked as "required".
func IsControllerInstallationRequired(controllerInstallation gardencorev1beta1.ControllerInstallation) bool {
for _, condition := range controllerInstallation.Status.Conditions {
if condition.Type == gardencorev1beta1.ControllerInstallationRequired && condition.Status == gardencorev1beta1.ConditionTrue {
return true
}
}
return false
}
// ComputeOperationType checks the <lastOperation> and determines whether it is Create, Delete, Reconcile, Migrate or Restore operation
func ComputeOperationType(meta metav1.ObjectMeta, lastOperation *gardencorev1beta1.LastOperation) gardencorev1beta1.LastOperationType {
switch {
case meta.Annotations[v1beta1constants.GardenerOperation] == v1beta1constants.GardenerOperationMigrate:
return gardencorev1beta1.LastOperationTypeMigrate
case meta.DeletionTimestamp != nil:
return gardencorev1beta1.LastOperationTypeDelete
case meta.Annotations[v1beta1constants.GardenerOperation] == v1beta1constants.GardenerOperationRestore:
return gardencorev1beta1.LastOperationTypeRestore
case lastOperation == nil:
return gardencorev1beta1.LastOperationTypeCreate
case lastOperation.Type == gardencorev1beta1.LastOperationTypeCreate && lastOperation.State != gardencorev1beta1.LastOperationStateSucceeded:
return gardencorev1beta1.LastOperationTypeCreate
case lastOperation.Type == gardencorev1beta1.LastOperationTypeMigrate && lastOperation.State != gardencorev1beta1.LastOperationStateSucceeded:
return gardencorev1beta1.LastOperationTypeMigrate
case lastOperation.Type == gardencorev1beta1.LastOperationTypeRestore && lastOperation.State != gardencorev1beta1.LastOperationStateSucceeded:
return gardencorev1beta1.LastOperationTypeRestore
}
return gardencorev1beta1.LastOperationTypeReconcile
}
// HasOperationAnnotation returns true if the operation annotation is present and its value is "reconcile", "restore, or "migrate".
func HasOperationAnnotation(annotations map[string]string) bool {
return annotations[v1beta1constants.GardenerOperation] == v1beta1constants.GardenerOperationReconcile ||
annotations[v1beta1constants.GardenerOperation] == v1beta1constants.GardenerOperationRestore ||
annotations[v1beta1constants.GardenerOperation] == v1beta1constants.GardenerOperationMigrate
}
// TaintsHave returns true if the given key is part of the taints list.
func TaintsHave(taints []gardencorev1beta1.SeedTaint, key string) bool {
for _, taint := range taints {
if taint.Key == key {
return true
}
}
return false
}
// TaintsAreTolerated returns true when all the given taints are tolerated by the given tolerations.
func TaintsAreTolerated(taints []gardencorev1beta1.SeedTaint, tolerations []gardencorev1beta1.Toleration) bool {
if len(taints) == 0 {
return true
}
if len(taints) > len(tolerations) {
return false
}
tolerationKeyValues := make(map[string]string, len(tolerations))
for _, toleration := range tolerations {
v := ""
if toleration.Value != nil {
v = *toleration.Value
}
tolerationKeyValues[toleration.Key] = v
}
for _, taint := range taints {
tolerationValue, ok := tolerationKeyValues[taint.Key]
if !ok {
return false
}
if taint.Value != nil && *taint.Value != tolerationValue {
return false
}
}
return true
}
// ManagedSeedAPIServer contains the configuration of a ManagedSeed API server.
type ManagedSeedAPIServer struct {
Replicas *int32
Autoscaler *ManagedSeedAPIServerAutoscaler
}
// ManagedSeedAPIServerAutoscaler contains the configuration of a ManagedSeed API server autoscaler.
type ManagedSeedAPIServerAutoscaler struct {
MinReplicas *int32
MaxReplicas int32
}
func parseInt32(s string) (int32, error) {
i64, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return 0, err
}
return int32(i64), nil
}
func getFlagsAndSettings(annotation string) (map[string]struct{}, map[string]string) {
var (
flags = make(map[string]struct{})
settings = make(map[string]string)
)
for _, fragment := range strings.Split(annotation, ",") {
parts := strings.SplitN(fragment, "=", 2)
if len(parts) == 1 {
flags[fragment] = struct{}{}
continue
}
settings[parts[0]] = parts[1]
}
return flags, settings
}
func parseManagedSeedAPIServer(settings map[string]string) (*ManagedSeedAPIServer, error) {
apiServerAutoscaler, err := parseManagedSeedAPIServerAutoscaler(settings)
if err != nil {
return nil, err
}
replicasString, ok := settings["apiServer.replicas"]
if !ok && apiServerAutoscaler == nil {
return nil, nil
}
var apiServer ManagedSeedAPIServer
apiServer.Autoscaler = apiServerAutoscaler
if ok {
replicas, err := parseInt32(replicasString)
if err != nil {
return nil, err
}
apiServer.Replicas = &replicas
}
return &apiServer, nil
}
func parseManagedSeedAPIServerAutoscaler(settings map[string]string) (*ManagedSeedAPIServerAutoscaler, error) {
minReplicasString, ok1 := settings["apiServer.autoscaler.minReplicas"]
maxReplicasString, ok2 := settings["apiServer.autoscaler.maxReplicas"]
if !ok1 && !ok2 {
return nil, nil
}
if !ok2 {
return nil, errors.New("apiSrvMaxReplicas has to be specified for ManagedSeed API server autoscaler")
}
var apiServerAutoscaler ManagedSeedAPIServerAutoscaler
if ok1 {
minReplicas, err := parseInt32(minReplicasString)
if err != nil {
return nil, err
}
apiServerAutoscaler.MinReplicas = &minReplicas
}
maxReplicas, err := parseInt32(maxReplicasString)
if err != nil {
return nil, err
}
apiServerAutoscaler.MaxReplicas = maxReplicas
return &apiServerAutoscaler, nil
}
func validateManagedSeedAPIServer(apiServer *ManagedSeedAPIServer, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if apiServer.Replicas != nil && *apiServer.Replicas < 1 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("replicas"), *apiServer.Replicas, "must be greater than 0"))
}
if apiServer.Autoscaler != nil {
allErrs = append(allErrs, validateManagedSeedAPIServerAutoscaler(apiServer.Autoscaler, fldPath.Child("autoscaler"))...)
}
return allErrs
}
func validateManagedSeedAPIServerAutoscaler(autoscaler *ManagedSeedAPIServerAutoscaler, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("minReplicas"), *autoscaler.MinReplicas, "must be greater than 0"))
}
if autoscaler.MaxReplicas < 1 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, "must be greater than 0"))
}
if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas {
allErrs = append(allErrs, field.Invalid(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, "must be greater than or equal to `minReplicas`"))
}
return allErrs
}
func setDefaults_ManagedSeedAPIServer(apiServer *ManagedSeedAPIServer) {
if apiServer.Replicas == nil {
three := int32(3)
apiServer.Replicas = &three
}
if apiServer.Autoscaler == nil {
apiServer.Autoscaler = &ManagedSeedAPIServerAutoscaler{
MaxReplicas: 3,
}
}
setDefaults_ManagedSeedAPIServerAutoscaler(apiServer.Autoscaler)
}
func minInt32(a int32, b int32) int32 {
if a < b {
return a
}
return b
}
func setDefaults_ManagedSeedAPIServerAutoscaler(autoscaler *ManagedSeedAPIServerAutoscaler) {
if autoscaler.MinReplicas == nil {
minReplicas := minInt32(3, autoscaler.MaxReplicas)
autoscaler.MinReplicas = &minReplicas
}
}
// ReadManagedSeedAPIServer reads the managed seed API server settings from the corresponding annotation.
func ReadManagedSeedAPIServer(shoot *gardencorev1beta1.Shoot) (*ManagedSeedAPIServer, error) {
if shoot.Namespace != v1beta1constants.GardenNamespace || shoot.Annotations == nil {
return nil, nil
}
val, ok := shoot.Annotations[v1beta1constants.AnnotationManagedSeedAPIServer]
if !ok {
return nil, nil
}
_, settings := getFlagsAndSettings(val)
apiServer, err := parseManagedSeedAPIServer(settings)
if err != nil {
return nil, err
}
if apiServer == nil {
return nil, nil
}
setDefaults_ManagedSeedAPIServer(apiServer)
if errs := validateManagedSeedAPIServer(apiServer, nil); len(errs) > 0 {
return nil, errs.ToAggregate()
}
return apiServer, nil
}
// HibernationIsEnabled checks if the given shoot's desired state is hibernated.
func HibernationIsEnabled(shoot *gardencorev1beta1.Shoot) bool {
return shoot.Spec.Hibernation != nil && shoot.Spec.Hibernation.Enabled != nil && *shoot.Spec.Hibernation.Enabled
}
// ShootWantsClusterAutoscaler checks if the given Shoot needs a cluster autoscaler.
// This is determined by checking whether one of the Shoot workers has a different
// Maximum than Minimum.
func ShootWantsClusterAutoscaler(shoot *gardencorev1beta1.Shoot) (bool, error) {
for _, worker := range shoot.Spec.Provider.Workers {
if worker.Maximum > worker.Minimum {
return true, nil
}
}
return false, nil
}
// ShootWantsVerticalPodAutoscaler checks if the given Shoot needs a VPA.
func ShootWantsVerticalPodAutoscaler(shoot *gardencorev1beta1.Shoot) bool {
return shoot.Spec.Kubernetes.VerticalPodAutoscaler != nil && shoot.Spec.Kubernetes.VerticalPodAutoscaler.Enabled
}
// ShootIgnoresAlerts checks if the alerts for the annotated shoot cluster should be ignored.
func ShootIgnoresAlerts(shoot *gardencorev1beta1.Shoot) bool {
ignore := false
if value, ok := shoot.Annotations[v1beta1constants.AnnotationShootIgnoreAlerts]; ok {
ignore, _ = strconv.ParseBool(value)
}
return ignore
}
// ShootWantsAlertManager checks if the given shoot specification requires an alert manager.
func ShootWantsAlertManager(shoot *gardencorev1beta1.Shoot) bool {
return !ShootIgnoresAlerts(shoot) && shoot.Spec.Monitoring != nil && shoot.Spec.Monitoring.Alerting != nil && len(shoot.Spec.Monitoring.Alerting.EmailReceivers) > 0
}
// ShootUsesUnmanagedDNS returns true if the shoot's DNS section is marked as 'unmanaged'.
func ShootUsesUnmanagedDNS(shoot *gardencorev1beta1.Shoot) bool {
return shoot.Spec.DNS != nil && len(shoot.Spec.DNS.Providers) > 0 && shoot.Spec.DNS.Providers[0].Type != nil && *shoot.Spec.DNS.Providers[0].Type == "unmanaged"
}
// ShootNeedsForceDeletion determines whether a Shoot should be force deleted or not.
func ShootNeedsForceDeletion(shoot *gardencorev1beta1.Shoot) bool {
if shoot == nil {
return false
}
value, ok := shoot.Annotations[v1beta1constants.AnnotationConfirmationForceDeletion]
if !ok {
return false
}
forceDelete, _ := strconv.ParseBool(value)
return forceDelete
}
// ShootSchedulingProfile returns the scheduling profile of the given Shoot.
func ShootSchedulingProfile(shoot *gardencorev1beta1.Shoot) *gardencorev1beta1.SchedulingProfile {
if shoot.Spec.Kubernetes.KubeScheduler != nil {
return shoot.Spec.Kubernetes.KubeScheduler.Profile
}
return nil
}
// ShootConfinesSpecUpdateRollout returns a bool.
func ShootConfinesSpecUpdateRollout(maintenance *gardencorev1beta1.Maintenance) bool {
return maintenance != nil && maintenance.ConfineSpecUpdateRollout != nil && *maintenance.ConfineSpecUpdateRollout
}
// SeedSettingExcessCapacityReservationEnabled returns true if the 'excess capacity reservation' setting is enabled.
func SeedSettingExcessCapacityReservationEnabled(settings *gardencorev1beta1.SeedSettings) bool {
return settings == nil || settings.ExcessCapacityReservation == nil || ptr.Deref(settings.ExcessCapacityReservation.Enabled, true)
}
// SeedSettingVerticalPodAutoscalerEnabled returns true if the 'verticalPodAutoscaler' setting is enabled.
func SeedSettingVerticalPodAutoscalerEnabled(settings *gardencorev1beta1.SeedSettings) bool {
return settings == nil || settings.VerticalPodAutoscaler == nil || settings.VerticalPodAutoscaler.Enabled
}
// SeedSettingDependencyWatchdogWeederEnabled returns true if the dependency-watchdog-weeder is enabled.
func SeedSettingDependencyWatchdogWeederEnabled(settings *gardencorev1beta1.SeedSettings) bool {
return settings == nil || settings.DependencyWatchdog == nil || settings.DependencyWatchdog.Weeder == nil || settings.DependencyWatchdog.Weeder.Enabled
}
// SeedSettingDependencyWatchdogProberEnabled returns true if the dependency-watchdog-prober is enabled.
func SeedSettingDependencyWatchdogProberEnabled(settings *gardencorev1beta1.SeedSettings) bool {
return settings == nil || settings.DependencyWatchdog == nil || settings.DependencyWatchdog.Prober == nil || settings.DependencyWatchdog.Prober.Enabled
}
// SeedSettingTopologyAwareRoutingEnabled returns true if the topology-aware routing is enabled.
func SeedSettingTopologyAwareRoutingEnabled(settings *gardencorev1beta1.SeedSettings) bool {
return settings != nil && settings.TopologyAwareRouting != nil && settings.TopologyAwareRouting.Enabled
}
// DetermineMachineImageForName finds the cloud specific machine images in the <cloudProfile> for the given <name> and
// region. In case it does not find the machine image with the <name>, it returns false. Otherwise, true and the
// cloud-specific machine image will be returned.
func DetermineMachineImageForName(cloudProfile *gardencorev1beta1.CloudProfile, name string) (bool, gardencorev1beta1.MachineImage) {
for _, image := range cloudProfile.Spec.MachineImages {
if strings.EqualFold(image.Name, name) {
return true, image
}
}
return false, gardencorev1beta1.MachineImage{}
}
// FindMachineImageVersion finds the machine image version in the <cloudProfile> for the given <name> and <version>.
// In case no machine image version can be found with the given <name> or <version>, false is being returned.
func FindMachineImageVersion(machineImages []gardencorev1beta1.MachineImage, name, version string) (gardencorev1beta1.MachineImageVersion, bool) {
for _, image := range machineImages {
if image.Name == name {
for _, imageVersion := range image.Versions {
if imageVersion.Version == version {
return imageVersion, true
}
}
}
}
return gardencorev1beta1.MachineImageVersion{}, false
}
// ShootMachineImageVersionExists checks if the shoot machine image (name, version) exists in the machine image constraint and returns true if yes and the index in the versions slice
func ShootMachineImageVersionExists(constraint gardencorev1beta1.MachineImage, image gardencorev1beta1.ShootMachineImage) (bool, int) {
if constraint.Name != image.Name {
return false, 0
}
for index, v := range constraint.Versions {
if image.Version != nil && v.Version == *image.Version {
return true, index
}
}
return false, 0
}
// ToExpirableVersions returns the expirable versions from the given machine image versions.
func ToExpirableVersions(versions []gardencorev1beta1.MachineImageVersion) []gardencorev1beta1.ExpirableVersion {
expVersions := []gardencorev1beta1.ExpirableVersion{}
for _, version := range versions {
expVersions = append(expVersions, version.ExpirableVersion)
}
return expVersions
}
// FindMachineTypeByName tries to find the machine type details with the given name. If it cannot be found it returns nil.
func FindMachineTypeByName(machines []gardencorev1beta1.MachineType, name string) *gardencorev1beta1.MachineType {
for _, m := range machines {
if m.Name == name {
return &m
}
}
return nil
}
// SystemComponentsAllowed checks if the given worker allows system components to be scheduled onto it
func SystemComponentsAllowed(worker *gardencorev1beta1.Worker) bool {
return worker.SystemComponents == nil || worker.SystemComponents.Allow
}
// KubernetesVersionExistsInCloudProfile checks if the given Kubernetes version exists in the CloudProfile
func KubernetesVersionExistsInCloudProfile(cloudProfile *gardencorev1beta1.CloudProfile, currentVersion string) (bool, gardencorev1beta1.ExpirableVersion, error) {
for _, version := range cloudProfile.Spec.Kubernetes.Versions {
ok, err := versionutils.CompareVersions(version.Version, "=", currentVersion)
if err != nil {
return false, gardencorev1beta1.ExpirableVersion{}, err
}
if ok {
return true, version, nil
}
}
return false, gardencorev1beta1.ExpirableVersion{}, nil
}
// SetMachineImageVersionsToMachineImage sets imageVersions to the matching imageName in the machineImages.
func SetMachineImageVersionsToMachineImage(machineImages []gardencorev1beta1.MachineImage, imageName string, imageVersions []gardencorev1beta1.MachineImageVersion) ([]gardencorev1beta1.MachineImage, error) {
for index, image := range machineImages {
if strings.EqualFold(image.Name, imageName) {
machineImages[index].Versions = imageVersions
return machineImages, nil
}
}
return nil, fmt.Errorf("machine image with name '%s' could not be found", imageName)
}
// GetDefaultMachineImageFromCloudProfile gets the first MachineImage from the CloudProfile
func GetDefaultMachineImageFromCloudProfile(profile gardencorev1beta1.CloudProfile) *gardencorev1beta1.MachineImage {
if len(profile.Spec.MachineImages) == 0 {
return nil
}
return &profile.Spec.MachineImages[0]
}
// WrapWithLastError is wrapper function for gardencorev1beta1.LastError
func WrapWithLastError(err error, lastError *gardencorev1beta1.LastError) error {
if err == nil || lastError == nil {
return err
}
return fmt.Errorf("last error: %w: %s", err, lastError.Description)
}
// FindPrimaryDNSProvider finds the primary provider among the given `providers`.
// It returns the first provider if multiple candidates are found.
func FindPrimaryDNSProvider(providers []gardencorev1beta1.DNSProvider) *gardencorev1beta1.DNSProvider {
for _, provider := range providers {
if provider.Primary != nil && *provider.Primary {
primaryProvider := provider
return &primaryProvider
}
}
return nil
}
// VersionPredicate is a function that evaluates a condition on the given versions.
type VersionPredicate func(expirableVersion gardencorev1beta1.ExpirableVersion, version *semver.Version) (bool, error)
// GetLatestVersionForPatchAutoUpdate finds the latest patch version for a given <currentVersion> for the current minor version from a given slice of versions.
// The current version, preview and expired versions do not qualify.
// In case no newer patch version is found, returns false and an empty string. Otherwise, returns true and the found version.
func GetLatestVersionForPatchAutoUpdate(versions []gardencorev1beta1.ExpirableVersion, currentVersion string) (bool, string, error) {
currentSemVerVersion, err := semver.NewVersion(currentVersion)
if err != nil {
return false, "", err
}
predicates := []VersionPredicate{FilterDifferentMajorMinorVersionAndLowerPatchVersionsOfSameMinor(*currentSemVerVersion)}
return getVersionForAutoUpdate(versions, currentSemVerVersion, predicates)
}
// GetLatestVersionForMinorAutoUpdate finds the latest minor with the latest patch version higher than a given <currentVersion> for the current major version from a given slice of versions.
// Returns the highest patch version for the current minor in case the current version is not the highest patch version yet.
// The current version, preview and expired versions do not qualify.
// In case no newer version is found, returns false and an empty string. Otherwise, returns true and the found version.
func GetLatestVersionForMinorAutoUpdate(versions []gardencorev1beta1.ExpirableVersion, currentVersion string) (bool, string, error) {
// always first check if there is a higher patch version available
found, version, err := GetLatestVersionForPatchAutoUpdate(versions, currentVersion)
if found {
return found, version, nil
}
if err != nil {
return false, version, err
}
currentSemVerVersion, err := semver.NewVersion(currentVersion)
if err != nil {
return false, "", err
}
predicates := []VersionPredicate{FilterDifferentMajorVersion(*currentSemVerVersion)}
return getVersionForAutoUpdate(versions, currentSemVerVersion, predicates)
}
// GetOverallLatestVersionForAutoUpdate finds the overall latest version higher than a given <currentVersion> for the current major version from a given slice of versions.
// Returns the highest patch version for the current minor in case the current version is not the highest patch version yet.
// The current, preview and expired versions do not qualify.
// In case no newer version is found, returns false and an empty string. Otherwise, returns true and the found version.
func GetOverallLatestVersionForAutoUpdate(versions []gardencorev1beta1.ExpirableVersion, currentVersion string) (bool, string, error) {
// always first check if there is a higher patch version available to update to
found, version, err := GetLatestVersionForPatchAutoUpdate(versions, currentVersion)
if found {
return found, version, nil
}
if err != nil {
return false, version, err
}
currentSemVerVersion, err := semver.NewVersion(currentVersion)
if err != nil {
return false, "", err
}
// if there is no higher patch version available, get the overall latest
return getVersionForAutoUpdate(versions, currentSemVerVersion, []VersionPredicate{})
}
// getVersionForAutoUpdate finds the latest eligible version higher than a given <currentVersion> from a slice of versions.
// Versions <= the current version, preview and expired versions do not qualify for patch updates.
// First tries to find a non-deprecated version.
// In case no newer patch version is found, returns false and an empty string. Otherwise, returns true and the found version.
func getVersionForAutoUpdate(versions []gardencorev1beta1.ExpirableVersion, currentSemVerVersion *semver.Version, predicates []VersionPredicate) (bool, string, error) {
versionPredicates := append([]VersionPredicate{FilterExpiredVersion(), FilterSameVersion(*currentSemVerVersion), FilterLowerVersion(*currentSemVerVersion)}, predicates...)
// Try to find non-deprecated version first
qualifyingVersionFound, latestNonDeprecatedImageVersion, err := GetLatestQualifyingVersion(versions, append(versionPredicates, FilterDeprecatedVersion())...)
if err != nil {
return false, "", err
}
if qualifyingVersionFound {
return true, latestNonDeprecatedImageVersion.Version, nil
}
// otherwise, also consider deprecated versions
qualifyingVersionFound, latestVersion, err := GetLatestQualifyingVersion(versions, versionPredicates...)
if err != nil {
return false, "", err
}
// latest version cannot be found. Do not return an error, but allow for forceful upgrade if Shoot's version is expired.
if !qualifyingVersionFound {
return false, "", nil
}
return true, latestVersion.Version, nil
}
// GetVersionForForcefulUpdateToConsecutiveMinor finds a version from a slice of expirable versions that qualifies for a minor level update given a <currentVersion>.
// A qualifying version is a non-preview version having the minor version increased by exactly one version (required for Kubernetes version upgrades).
// In case the consecutive minor version has only expired versions, picks the latest expired version (will try another update during the next maintenance time).
// If a version can be found, returns true and the qualifying patch version of the next minor version.
// In case it does not find a version, it returns false and an empty string.
func GetVersionForForcefulUpdateToConsecutiveMinor(versions []gardencorev1beta1.ExpirableVersion, currentVersion string) (bool, string, error) {
currentSemVerVersion, err := semver.NewVersion(currentVersion)
if err != nil {
return false, "", err
}
// filters out any version that does not have minor version +1
predicates := []VersionPredicate{FilterDifferentMajorVersion(*currentSemVerVersion), FilterNonConsecutiveMinorVersion(*currentSemVerVersion)}
qualifyingVersionFound, latestVersion, err := GetLatestQualifyingVersion(versions, append(predicates, FilterExpiredVersion())...)
if err != nil {
return false, "", err
}
// if no qualifying version is found, allow force update to an expired version
if !qualifyingVersionFound {
qualifyingVersionFound, latestVersion, err = GetLatestQualifyingVersion(versions, predicates...)
if err != nil {
return false, "", err
}
if !qualifyingVersionFound {
return false, "", nil
}
}
return true, latestVersion.Version, nil
}
// GetVersionForForcefulUpdateToNextHigherMinor finds a version from a slice of expirable versions that qualifies for a minor level update given a <currentVersion>.
// A qualifying version is the highest non-preview version with the next higher minor version from the given slice of versions.
// In case the consecutive minor version has only expired versions, picks the latest expired version (will try another update during the next maintenance time).
// If a version can be found, returns true and the qualifying version.
// In case it does not find a version, it returns false and an empty string.
func GetVersionForForcefulUpdateToNextHigherMinor(versions []gardencorev1beta1.ExpirableVersion, currentVersion string) (bool, string, error) {
currentSemVerVersion, err := semver.NewVersion(currentVersion)
if err != nil {
return false, "", err
}
predicates := []VersionPredicate{FilterDifferentMajorVersion(*currentSemVerVersion), FilterEqualAndSmallerMinorVersion(*currentSemVerVersion)}
// prefer non-expired version
return getVersionForMachineImageForceUpdate(versions, func(v semver.Version) int64 { return int64(v.Minor()) }, currentSemVerVersion, predicates)
}
// GetVersionForForcefulUpdateToNextHigherMajor finds a version from a slice of expirable versions that qualifies for a major level update given a <currentVersion>.
// A qualifying version is a non-preview version with the next (as defined in the CloudProfile for the image) higher major version.
// In case the next major version has only expired versions, picks the latest expired version (will try another update during the next maintenance time).
// If a version can be found, returns true and the qualifying version of the next major version.
// In case it does not find a version, it returns false and an empty string.
func GetVersionForForcefulUpdateToNextHigherMajor(versions []gardencorev1beta1.ExpirableVersion, currentVersion string) (bool, string, error) {
currentSemVerVersion, err := semver.NewVersion(currentVersion)
if err != nil {
return false, "", err
}
predicates := []VersionPredicate{FilterEqualAndSmallerMajorVersion(*currentSemVerVersion)}
// prefer non-expired version
return getVersionForMachineImageForceUpdate(versions, func(v semver.Version) int64 { return int64(v.Major()) }, currentSemVerVersion, predicates)
}
// getVersionForMachineImageForceUpdate finds a version from a slice of expirable versions that qualifies for an update given a <currentVersion>.
// In contrast to determining a version for an auto-update, also allows update to an expired version in case a not-expired version cannot be determined.
// Used only for machine image updates, as finds a qualifying version from the next higher minor version, which is not necessarily consecutive (n+1).
func getVersionForMachineImageForceUpdate(versions []gardencorev1beta1.ExpirableVersion, getMajorOrMinor GetMajorOrMinor, currentSemVerVersion *semver.Version, predicates []VersionPredicate) (bool, string, error) {
foundVersion, qualifyingVersion, nextMinorOrMajorVersion, err := GetQualifyingVersionForNextHigher(versions, getMajorOrMinor, currentSemVerVersion, append(predicates, FilterExpiredVersion())...)
if err != nil {
return false, "", err
}
skippedNextMajorMinor := false
if foundVersion {
parse, err := semver.NewVersion(qualifyingVersion.Version)
if err != nil {
return false, "", err
}
skippedNextMajorMinor = getMajorOrMinor(*parse) > nextMinorOrMajorVersion
}
// Two options when allowing updates to expired versions
// 1) No higher non-expired qualifying version could be found at all
// 2) Found a qualifying non-expired version, but we skipped the next minor/major.
// Potentially skipped expired versions in the next minor/major that qualify.
// Prefer update to expired version in next minor/major instead of skipping over minor/major altogether.
// Example: current version: 1.1.0, qualifying version : 1.4.1, next minor: 2. We skipped over the next minor which might have qualifying expired versions.
if !foundVersion || skippedNextMajorMinor {
foundVersion, qualifyingVersion, _, err = GetQualifyingVersionForNextHigher(versions, getMajorOrMinor, currentSemVerVersion, predicates...)
if err != nil {
return false, "", err
}
if !foundVersion {
return false, "", nil
}
}
return true, qualifyingVersion.Version, nil
}
// GetLatestQualifyingVersion returns the latest expirable version from a set of expirable versions.
// A version qualifies if its classification is not preview and the optional predicate does not filter out the version.
// If the predicate returns true, the version is not considered for the latest qualifying version.
func GetLatestQualifyingVersion(versions []gardencorev1beta1.ExpirableVersion, predicate ...VersionPredicate) (qualifyingVersionFound bool, latest *gardencorev1beta1.ExpirableVersion, err error) {
var (
latestSemanticVersion = &semver.Version{}
latestVersion *gardencorev1beta1.ExpirableVersion
)
OUTER:
for _, v := range versions {
if v.Classification != nil && *v.Classification == gardencorev1beta1.ClassificationPreview {
continue
}
semver, err := semver.NewVersion(v.Version)
if err != nil {
return false, nil, fmt.Errorf("error while parsing version '%s': %s", v.Version, err.Error())
}
for _, p := range predicate {
if p == nil {
continue
}
shouldFilter, err := p(v, semver)
if err != nil {
return false, nil, fmt.Errorf("error while evaluation predicate: '%s'", err.Error())
}
if shouldFilter {
continue OUTER
}
}
if semver.GreaterThan(latestSemanticVersion) {
latestSemanticVersion = semver
// avoid DeepCopy
latest := v
latestVersion = &latest
}
}
// unable to find qualified versions
if latestVersion == nil {
return false, nil, nil
}
return true, latestVersion, nil
}
// GetMajorOrMinor returns either the major or the minor version from a semVer version.
type GetMajorOrMinor func(v semver.Version) int64
// GetQualifyingVersionForNextHigher returns the latest expirable version for the next higher {minor/major} (not necessarily consecutive n+1) version from a set of expirable versions.
// A version qualifies if its classification is not preview and the optional predicate does not filter out the version.
// If the predicate returns true, the version is not considered for the latest qualifying version.
func GetQualifyingVersionForNextHigher(versions []gardencorev1beta1.ExpirableVersion, majorOrMinor GetMajorOrMinor, currentSemVerVersion *semver.Version, predicates ...VersionPredicate) (qualifyingVersionFound bool, qualifyingVersion *gardencorev1beta1.ExpirableVersion, nextMinorOrMajor int64, err error) {
// How to find the highest version with the next higher (not necessarily consecutive n+1) minor version (if the next higher minor version has no qualifying version, skip it to avoid consecutive updates)
// 1) Sort the versions in ascending order
// 2) Loop over the sorted array until the minor version changes (select all versions for the next higher minor)
// - predicates filter out version with minor/major <= current_minor/major
// 3) Then select the last version in the array (that's the highest)
slices.SortFunc(versions, func(a, b gardencorev1beta1.ExpirableVersion) int {
return semver.MustParse(a.Version).Compare(semver.MustParse(b.Version))
})
var (
highestVersionNextHigherMinorOrMajor *semver.Version
nextMajorOrMinorVersion int64 = -1
expirableVersionNextHigherMinorOrMajor = gardencorev1beta1.ExpirableVersion{}
)
OUTER:
for _, v := range versions {
parse, err := semver.NewVersion(v.Version)
if err != nil {
return false, nil, 0, err
}
// Determine the next higher minor/major version, even though all versions from that minor/major might be filtered (e.g, all expired)
// That's required so that the caller can determine if the next minor/major version has been skipped or not.
if majorOrMinor(*parse) > majorOrMinor(*currentSemVerVersion) && (majorOrMinor(*parse) < nextMajorOrMinorVersion || nextMajorOrMinorVersion == -1) {
nextMajorOrMinorVersion = majorOrMinor(*parse)
}
// never update to preview versions
if v.Classification != nil && *v.Classification == gardencorev1beta1.ClassificationPreview {
continue
}
for _, p := range predicates {
if p == nil {
continue
}
shouldFilter, err := p(v, parse)
if err != nil {
return false, nil, nextMajorOrMinorVersion, fmt.Errorf("error while evaluation predicate: %w", err)
}
if shouldFilter {
continue OUTER
}
}
// last version is the highest version for next larger minor/major
if highestVersionNextHigherMinorOrMajor != nil && majorOrMinor(*parse) > majorOrMinor(*highestVersionNextHigherMinorOrMajor) {
break
}
highestVersionNextHigherMinorOrMajor = parse
expirableVersionNextHigherMinorOrMajor = v
}
// unable to find qualified versions
if highestVersionNextHigherMinorOrMajor == nil {
return false, nil, nextMajorOrMinorVersion, nil
}
return true, &expirableVersionNextHigherMinorOrMajor, nextMajorOrMinorVersion, nil
}
// FilterDifferentMajorMinorVersionAndLowerPatchVersionsOfSameMinor returns a VersionPredicate(closure) that returns true if a given version v
// - has a different major.minor version compared to the currentSemVerVersion
// - has a lower patch version (acts as >= relational operator)
//
// Uses the tilde range operator.
func FilterDifferentMajorMinorVersionAndLowerPatchVersionsOfSameMinor(currentSemVerVersion semver.Version) VersionPredicate {
return func(_ gardencorev1beta1.ExpirableVersion, v *semver.Version) (bool, error) {
isWithinRange, err := versionutils.CompareVersions(v.String(), "~", currentSemVerVersion.String())
if err != nil {
return true, err
}
return !isWithinRange, nil
}
}
// FilterNonConsecutiveMinorVersion returns a VersionPredicate(closure) that evaluates whether a given version v has a consecutive minor version compared to the currentSemVerVersion
// - implicitly, therefore also versions cannot be smaller than the current version
//
// returns true if v does not have a consecutive minor version.
func FilterNonConsecutiveMinorVersion(currentSemVerVersion semver.Version) VersionPredicate {
return func(_ gardencorev1beta1.ExpirableVersion, v *semver.Version) (bool, error) {
if v.Major() != currentSemVerVersion.Major() {
return true, nil
}
hasIncorrectMinor := currentSemVerVersion.Minor()+1 != v.Minor()
return hasIncorrectMinor, nil
}
}
// FilterDifferentMajorVersion returns a VersionPredicate(closure) that evaluates whether a given version v has the same major version compared to the currentSemVerVersion.
// Returns true if v does not have the same major version.
func FilterDifferentMajorVersion(currentSemVerVersion semver.Version) VersionPredicate {
return func(_ gardencorev1beta1.ExpirableVersion, v *semver.Version) (bool, error) {
return v.Major() != currentSemVerVersion.Major(), nil
}
}
// FilterEqualAndSmallerMajorVersion returns a VersionPredicate(closure) that evaluates whether a given version v has a smaller major version compared to the currentSemVerVersion.
// Returns true if v has a smaller or equal major version.
func FilterEqualAndSmallerMajorVersion(currentSemVerVersion semver.Version) VersionPredicate {
return func(_ gardencorev1beta1.ExpirableVersion, v *semver.Version) (bool, error) {
return v.Major() <= currentSemVerVersion.Major(), nil
}
}
// FilterEqualAndSmallerMinorVersion returns a VersionPredicate(closure) that evaluates whether a given version v has a smaller or equal minor version compared to the currentSemVerVersion.
// Returns true if v has a smaller or equal minor version.
func FilterEqualAndSmallerMinorVersion(currentSemVerVersion semver.Version) VersionPredicate {
return func(_ gardencorev1beta1.ExpirableVersion, v *semver.Version) (bool, error) {
return v.Minor() <= currentSemVerVersion.Minor(), nil
}
}
// FilterSameVersion returns a VersionPredicate(closure) that evaluates whether a given version v is equal to the currentSemVerVersion.
// returns true if it is equal.
func FilterSameVersion(currentSemVerVersion semver.Version) VersionPredicate {
return func(_ gardencorev1beta1.ExpirableVersion, v *semver.Version) (bool, error) {
return v.Equal(¤tSemVerVersion), nil
}
}
// FilterLowerVersion returns a VersionPredicate(closure) that evaluates whether a given version v is lower than the currentSemVerVersion
// returns true if it is lower
func FilterLowerVersion(currentSemVerVersion semver.Version) VersionPredicate {
return func(_ gardencorev1beta1.ExpirableVersion, v *semver.Version) (bool, error) {
return v.LessThan(¤tSemVerVersion), nil
}
}
// FilterExpiredVersion returns a closure that evaluates whether a given expirable version is expired
// returns true if it is expired
func FilterExpiredVersion() func(expirableVersion gardencorev1beta1.ExpirableVersion, version *semver.Version) (bool, error) {
return func(expirableVersion gardencorev1beta1.ExpirableVersion, _ *semver.Version) (bool, error) {
return expirableVersion.ExpirationDate != nil && (time.Now().UTC().After(expirableVersion.ExpirationDate.UTC()) || time.Now().UTC().Equal(expirableVersion.ExpirationDate.UTC())), nil
}
}
// FilterDeprecatedVersion returns a closure that evaluates whether a given expirable version is deprecated
// returns true if it is deprecated
func FilterDeprecatedVersion() func(expirableVersion gardencorev1beta1.ExpirableVersion, version *semver.Version) (bool, error) {
return func(expirableVersion gardencorev1beta1.ExpirableVersion, _ *semver.Version) (bool, error) {
return expirableVersion.Classification != nil && *expirableVersion.Classification == gardencorev1beta1.ClassificationDeprecated, nil
}
}
// GetResourceByName returns the NamedResourceReference with the given name in the given slice, or nil if not found.
func GetResourceByName(resources []gardencorev1beta1.NamedResourceReference, name string) *gardencorev1beta1.NamedResourceReference {
for _, resource := range resources {
if resource.Name == name {
return &resource
}
}
return nil
}
// UpsertLastError adds a 'last error' to the given list of existing 'last errors' if it does not exist yet. Otherwise,
// it updates it.
func UpsertLastError(lastErrors []gardencorev1beta1.LastError, lastError gardencorev1beta1.LastError) []gardencorev1beta1.LastError {
var (
out []gardencorev1beta1.LastError
found bool
)
for _, lastErr := range lastErrors {
if lastErr.TaskID != nil && lastError.TaskID != nil && *lastErr.TaskID == *lastError.TaskID {
out = append(out, lastError)
found = true
} else {
out = append(out, lastErr)
}
}
if !found {
out = append(out, lastError)
}
return out
}
// DeleteLastErrorByTaskID removes the 'last error' with the given task ID from the given 'last error' list.
func DeleteLastErrorByTaskID(lastErrors []gardencorev1beta1.LastError, taskID string) []gardencorev1beta1.LastError {
var out []gardencorev1beta1.LastError
for _, lastErr := range lastErrors {
if lastErr.TaskID == nil || taskID != *lastErr.TaskID {
out = append(out, lastErr)
}
}
return out
}
// ShootItems provides helper functions with ShootLists
type ShootItems gardencorev1beta1.ShootList
// Union returns a set of Shoots that presents either in s or shootList
func (s *ShootItems) Union(shootItems *ShootItems) []gardencorev1beta1.Shoot {
unionedShoots := make(map[string]gardencorev1beta1.Shoot)
for _, s := range s.Items {
unionedShoots[objectKey(s.Namespace, s.Name)] = s
}
for _, s := range shootItems.Items {
unionedShoots[objectKey(s.Namespace, s.Name)] = s
}
shoots := make([]gardencorev1beta1.Shoot, 0, len(unionedShoots))
for _, v := range unionedShoots {
shoots = append(shoots, v)