/
utils.go
783 lines (666 loc) · 27.6 KB
/
utils.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
// Copyright (c) 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 common
import (
"context"
"errors"
"fmt"
"math/big"
"net"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
gardencorelisters "github.com/gardener/gardener/pkg/client/core/listers/core/v1beta1"
"github.com/gardener/gardener/pkg/client/kubernetes"
"github.com/gardener/gardener/pkg/utils"
kutil "github.com/gardener/gardener/pkg/utils/kubernetes"
"github.com/gardener/gardener/pkg/version"
jsoniter "github.com/json-iterator/go"
appsv1 "k8s.io/api/apps/v1"
autoscalingv2beta1 "k8s.io/api/autoscaling/v2beta1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
rbacv1 "k8s.io/api/rbac/v1"
schedulingv1beta1 "k8s.io/api/scheduling/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/client"
)
var (
json = jsoniter.ConfigFastest
// TimeNow returns the current time. Exposed for testing.
TimeNow = time.Now
)
// GetSecretKeysWithPrefix returns a list of keys of the given map <m> which are prefixed with <kind>.
func GetSecretKeysWithPrefix(kind string, m map[string]*corev1.Secret) []string {
result := []string{}
for key := range m {
if strings.HasPrefix(key, kind) {
result = append(result, key)
}
}
return result
}
// ComputeOffsetIP parses the provided <subnet> and offsets with the value of <offset>.
// For example, <subnet> = 100.64.0.0/11 and <offset> = 10 the result would be 100.64.0.10
// IPv6 and IPv4 is supported.
func ComputeOffsetIP(subnet *net.IPNet, offset int64) (net.IP, error) {
if subnet == nil {
return nil, fmt.Errorf("subnet is nil")
}
isIPv6 := false
bytes := subnet.IP.To4()
if bytes == nil {
isIPv6 = true
bytes = subnet.IP.To16()
}
ip := net.IP(big.NewInt(0).Add(big.NewInt(0).SetBytes(bytes), big.NewInt(offset)).Bytes())
if !subnet.Contains(ip) {
return nil, fmt.Errorf("cannot compute IP with offset %d - subnet %q too small", offset, subnet)
}
// there is no broadcast address on IPv6
if isIPv6 {
return ip, nil
}
for i := range ip {
// IP address is not the same, so it's not the broadcast ip.
if ip[i] != ip[i]|^subnet.Mask[i] {
return ip.To4(), nil
}
}
return nil, fmt.Errorf("computed IPv4 address %q is broadcast for subnet %q", ip, subnet)
}
// GenerateAddonConfig returns the provided <values> in case <enabled> is true. Otherwise, nil is
// being returned.
func GenerateAddonConfig(values map[string]interface{}, enabled bool) map[string]interface{} {
v := map[string]interface{}{
"enabled": enabled,
}
if enabled {
for key, value := range values {
v[key] = value
}
}
return v
}
// GenerateBackupEntryName returns BackupEntry resource name created from provided <seedNamespace> and <shootUID>.
func GenerateBackupEntryName(seedNamespace string, shootUID types.UID) string {
return fmt.Sprintf("%s--%s", seedNamespace, shootUID)
}
// ExtractShootDetailsFromBackupEntryName returns Shoot resource technicalID its UID from provided <backupEntryName>.
func ExtractShootDetailsFromBackupEntryName(backupEntryName string) (shootTechnicalID, shootUID string) {
tokens := strings.Split(backupEntryName, "--")
shootUID = tokens[len(tokens)-1]
shootTechnicalID = strings.TrimSuffix(backupEntryName, shootUID)
shootTechnicalID = strings.TrimSuffix(shootTechnicalID, "--")
return shootTechnicalID, shootUID
}
// IsFollowingNewNamingConvention determines whether the new naming convention followed for shoot resources.
// TODO: Remove this and use only "--" as separator, once we have all shoots deployed as per new naming conventions.
func IsFollowingNewNamingConvention(seedNamespace string) bool {
return len(strings.Split(seedNamespace, "--")) > 2
}
// ReplaceCloudProviderConfigKey replaces a key with the new value in the given cloud provider config.
func ReplaceCloudProviderConfigKey(cloudProviderConfig, separator, key, value string) string {
keyValueRegexp := regexp.MustCompile(fmt.Sprintf(`(\Q%s\E%s)([^\n]*)`, key, separator))
return keyValueRegexp.ReplaceAllString(cloudProviderConfig, fmt.Sprintf(`${1}%q`, strings.Replace(value, `$`, `$$`, -1)))
}
// ProjectForNamespace returns the project object responsible for a given <namespace>. It tries to identify the project object by looking for the namespace
// name in the project statuses.
func ProjectForNamespace(projectLister gardencorelisters.ProjectLister, namespaceName string) (*gardencorev1beta1.Project, error) {
projectList, err := projectLister.List(labels.Everything())
if err != nil {
return nil, err
}
for _, project := range projectList {
if project.Spec.Namespace != nil && *project.Spec.Namespace == namespaceName {
return project, nil
}
}
return nil, apierrors.NewNotFound(gardencorev1beta1.Resource("Project"), fmt.Sprintf("for namespace %s", namespaceName))
}
// ProjectNameForNamespace determines the project name for a given <namespace>. It tries to identify it first per the namespace's ownerReferences.
// If it doesn't help then it will check whether the project name is a label on the namespace object. If it doesn't help then the name can be inferred
// from the namespace name in case it is prefixed with the project prefix. If none of those approaches the namespace name itself is returned as project
// name.
func ProjectNameForNamespace(namespace *corev1.Namespace) string {
for _, ownerReference := range namespace.OwnerReferences {
if ownerReference.Kind == "Project" {
return ownerReference.Name
}
}
if name, ok := namespace.Labels[ProjectName]; ok {
return name
}
if nameSplit := strings.Split(namespace.Name, ProjectPrefix); len(nameSplit) > 1 {
return nameSplit[1]
}
return namespace.Name
}
// MergeOwnerReferences merges the newReferences with the list of existing references.
func MergeOwnerReferences(references []metav1.OwnerReference, newReferences ...metav1.OwnerReference) []metav1.OwnerReference {
uids := make(map[types.UID]struct{})
for _, reference := range references {
uids[reference.UID] = struct{}{}
}
for _, newReference := range newReferences {
if _, ok := uids[newReference.UID]; !ok {
references = append(references, newReference)
}
}
return references
}
// ReadLeaderElectionRecord returns the leader election record for a given lock type and a namespace/name combination.
func ReadLeaderElectionRecord(k8sClient kubernetes.Interface, lock, namespace, name string) (*resourcelock.LeaderElectionRecord, error) {
var (
leaderElectionRecord resourcelock.LeaderElectionRecord
annotations map[string]string
)
switch lock {
case resourcelock.EndpointsResourceLock:
endpoint, err := k8sClient.Kubernetes().CoreV1().Endpoints(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return nil, err
}
annotations = endpoint.Annotations
case resourcelock.ConfigMapsResourceLock:
configmap, err := k8sClient.Kubernetes().CoreV1().ConfigMaps(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return nil, err
}
annotations = configmap.Annotations
default:
return nil, fmt.Errorf("unknown lock type: %s", lock)
}
leaderElection, ok := annotations[resourcelock.LeaderElectionRecordAnnotationKey]
if !ok {
return nil, fmt.Errorf("could not find key %s in annotations", resourcelock.LeaderElectionRecordAnnotationKey)
}
if err := json.Unmarshal([]byte(leaderElection), &leaderElectionRecord); err != nil {
return nil, fmt.Errorf("failed to unmarshal leader election record: %+v", err)
}
return &leaderElectionRecord, nil
}
// GardenerDeletionGracePeriod is the default grace period for Gardener's force deletion methods.
var GardenerDeletionGracePeriod = 5 * time.Minute
// ShouldObjectBeRemoved determines whether the given object should be gone now.
// This is calculated by first checking the deletion timestamp of an object: If the deletion timestamp
// is unset, the object should not be removed - i.e. this returns false.
// Otherwise, it is checked whether the deletionTimestamp is before the current time minus the
// grace period.
func ShouldObjectBeRemoved(obj metav1.Object, gracePeriod time.Duration) bool {
deletionTimestamp := obj.GetDeletionTimestamp()
if deletionTimestamp == nil {
return false
}
return deletionTimestamp.Time.Before(time.Now().Add(-gracePeriod))
}
// ComputeSecretCheckSum computes the sha256 checksum of secret data.
func ComputeSecretCheckSum(m map[string][]byte) string {
var (
hash string
keys []string
)
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
hash += utils.ComputeSHA256Hex(m[k])
}
return utils.ComputeSHA256Hex([]byte(hash))
}
// DeleteHvpa delete all resources required for the HVPA in the given namespace.
func DeleteHvpa(k8sClient kubernetes.Interface, namespace string) error {
if k8sClient == nil {
return fmt.Errorf("require kubernetes client")
}
listOptions := metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=%s", v1beta1constants.GardenRole, GardenRoleHvpa),
}
// Delete all CRDs with label "gardener.cloud/role=hvpa"
// Workaround: Due to https://github.com/gardener/gardener/issues/2257, we first list the HVPA CRDs and then remove
// them one by one.
crdList, err := k8sClient.APIExtension().ApiextensionsV1beta1().CustomResourceDefinitions().List(listOptions)
if err != nil {
return err
}
for _, crd := range crdList.Items {
if err := k8sClient.APIExtension().ApiextensionsV1beta1().CustomResourceDefinitions().Delete(crd.Name, &metav1.DeleteOptions{}); client.IgnoreNotFound(err) != nil {
return err
}
}
// Delete all Deployments with label "gardener.cloud/role=hvpa"
deletePropagation := metav1.DeletePropagationForeground
if err := k8sClient.Kubernetes().AppsV1().Deployments(namespace).DeleteCollection(&metav1.DeleteOptions{PropagationPolicy: &deletePropagation}, listOptions); client.IgnoreNotFound(err) != nil {
return err
}
// Delete all ClusterRoles with label "gardener.cloud/role=hvpa"
if err := k8sClient.Kubernetes().RbacV1().ClusterRoles().DeleteCollection(&metav1.DeleteOptions{}, listOptions); client.IgnoreNotFound(err) != nil {
return err
}
// Delete all ClusterRoleBindings with label "gardener.cloud/role=hvpa"
if err := k8sClient.Kubernetes().RbacV1().ClusterRoleBindings().DeleteCollection(&metav1.DeleteOptions{}, listOptions); client.IgnoreNotFound(err) != nil {
return err
}
// Delete all ServiceAccounts with label "gardener.cloud/role=hvpa"
if err := k8sClient.Kubernetes().CoreV1().ServiceAccounts(namespace).DeleteCollection(&metav1.DeleteOptions{}, listOptions); client.IgnoreNotFound(err) != nil {
return err
}
return nil
}
// DeleteLoggingStack deletes all resource of the EFK logging stack in the given namespace.
func DeleteLoggingStack(ctx context.Context, k8sClient client.Client, namespace string) error {
if k8sClient == nil {
return errors.New("must provide non-nil kubernetes client to common.DeleteLoggingStack")
}
// Delete the resources below that match "garden.sapcloud.io/role=logging"
lists := []runtime.Object{
&corev1.ConfigMapList{},
&batchv1beta1.CronJobList{},
&rbacv1.ClusterRoleList{},
&rbacv1.ClusterRoleBindingList{},
&rbacv1.RoleList{},
&rbacv1.RoleBindingList{},
&appsv1.DaemonSetList{},
&appsv1.DeploymentList{},
&autoscalingv2beta1.HorizontalPodAutoscalerList{},
&extensionsv1beta1.IngressList{},
&corev1.SecretList{},
&corev1.ServiceAccountList{},
&corev1.ServiceList{},
&appsv1.StatefulSetList{},
}
for _, list := range lists {
if err := k8sClient.List(ctx, list,
client.InNamespace(namespace),
client.MatchingLabels(map[string]string{v1beta1constants.DeprecatedGardenRole: v1beta1constants.GardenRoleLogging})); err != nil {
return err
}
if err := meta.EachListItem(list, func(obj runtime.Object) error {
return client.IgnoreNotFound(k8sClient.Delete(ctx, obj, kubernetes.DefaultDeleteOptions...))
}); err != nil {
return err
}
}
pvc := &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: "elasticsearch-logging-elasticsearch-logging-0",
Namespace: namespace,
},
}
if err := k8sClient.Delete(ctx, pvc); client.IgnoreNotFound(err) != nil && !meta.IsNoMatchError(err) {
return err
}
return nil
}
// DeleteReserveExcessCapacity deletes the deployment and priority class for excess capacity
func DeleteReserveExcessCapacity(ctx context.Context, k8sClient client.Client) error {
if k8sClient == nil {
return errors.New("must provide non-nil kubernetes client to common.DeleteReserveExcessCapacity")
}
deploy := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "reserve-excess-capacity",
Namespace: v1beta1constants.GardenNamespace,
},
}
if err := k8sClient.Delete(ctx, deploy); client.IgnoreNotFound(err) != nil {
return err
}
priorityClass := &schedulingv1beta1.PriorityClass{
ObjectMeta: metav1.ObjectMeta{
Name: "gardener-reserve-excess-capacity",
},
}
return client.IgnoreNotFound(k8sClient.Delete(ctx, priorityClass))
}
// DeleteAlertmanager deletes all resources of the Alertmanager in a given namespace.
func DeleteAlertmanager(ctx context.Context, k8sClient client.Client, namespace string) error {
objs := []runtime.Object{
&appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{
Name: v1beta1constants.StatefulSetNameAlertManager,
Namespace: namespace,
},
},
&extensionsv1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "alertmanager",
Namespace: namespace,
},
},
&corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "alertmanager-client",
Namespace: namespace,
},
},
&corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "alertmanager",
Namespace: namespace,
},
},
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "alertmanager-basic-auth",
Namespace: namespace,
},
},
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: AlertManagerTLS,
Namespace: namespace,
},
},
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "alertmanager-config",
Namespace: namespace,
},
},
&corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: "alertmanager-db-alertmanager-0",
Namespace: namespace,
},
},
}
for _, obj := range objs {
if err := k8sClient.Delete(ctx, obj, kubernetes.DefaultDeleteOptions...); client.IgnoreNotFound(err) != nil {
return err
}
}
return nil
}
// DeleteGrafanaByRole deletes the monitoring stack for the shoot owner.
func DeleteGrafanaByRole(k8sClient kubernetes.Interface, namespace, role string) error {
if k8sClient == nil {
return fmt.Errorf("require kubernetes client")
}
listOptions := metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=%s,%s=%s", "component", "grafana", "role", role),
}
deletePropagation := metav1.DeletePropagationForeground
if err := k8sClient.Kubernetes().AppsV1().Deployments(namespace).DeleteCollection(
&metav1.DeleteOptions{
PropagationPolicy: &deletePropagation,
}, listOptions); err != nil && !apierrors.IsNotFound(err) {
return err
}
if err := k8sClient.Kubernetes().CoreV1().ConfigMaps(namespace).DeleteCollection(
&metav1.DeleteOptions{}, listOptions); err != nil && !apierrors.IsNotFound(err) {
return err
}
if err := k8sClient.Kubernetes().ExtensionsV1beta1().Ingresses(namespace).DeleteCollection(
&metav1.DeleteOptions{}, listOptions); err != nil && !apierrors.IsNotFound(err) {
return err
}
if err := k8sClient.Kubernetes().CoreV1().Secrets(namespace).DeleteCollection(
&metav1.DeleteOptions{}, listOptions); err != nil && !apierrors.IsNotFound(err) {
return err
}
if err := k8sClient.Kubernetes().CoreV1().Services(namespace).Delete(fmt.Sprintf("grafana-%s", role),
&metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) {
return err
}
return nil
}
// GetDomainInfoFromAnnotations returns the provider and the domain that is specified in the give annotations.
func GetDomainInfoFromAnnotations(annotations map[string]string) (provider string, domain string, includeZones, excludeZones []string, err error) {
if annotations == nil {
return "", "", nil, nil, fmt.Errorf("domain secret has no annotations")
}
if providerAnnotation, ok := annotations[DNSProviderDeprecated]; ok {
provider = providerAnnotation
}
if providerAnnotation, ok := annotations[DNSProvider]; ok {
provider = providerAnnotation
}
if domainAnnotation, ok := annotations[DNSDomainDeprecated]; ok {
domain = domainAnnotation
}
if domainAnnotation, ok := annotations[DNSDomain]; ok {
domain = domainAnnotation
}
if includeZonesAnnotation, ok := annotations[DNSIncludeZones]; ok {
includeZones = strings.Split(includeZonesAnnotation, ",")
}
if excludeZonesAnnotation, ok := annotations[DNSExcludeZones]; ok {
excludeZones = strings.Split(excludeZonesAnnotation, ",")
}
if len(domain) == 0 {
return "", "", nil, nil, fmt.Errorf("missing dns domain annotation on domain secret")
}
if len(provider) == 0 {
return "", "", nil, nil, fmt.Errorf("missing dns provider annotation on domain secret")
}
return
}
// CurrentReplicaCount returns the current replicaCount for the given deployment.
func CurrentReplicaCount(client client.Client, namespace, deploymentName string) (int32, error) {
deployment := &appsv1.Deployment{}
if err := client.Get(context.TODO(), kutil.Key(namespace, deploymentName), deployment); err != nil && !apierrors.IsNotFound(err) {
return 0, err
}
if deployment.Spec.Replicas == nil {
return 0, nil
}
return *deployment.Spec.Replicas, nil
}
// RespectShootSyncPeriodOverwrite checks whether to respect the sync period overwrite of a Shoot or not.
func RespectShootSyncPeriodOverwrite(respectSyncPeriodOverwrite bool, shoot *gardencorev1beta1.Shoot) bool {
return respectSyncPeriodOverwrite || shoot.Namespace == v1beta1constants.GardenNamespace
}
// ShouldIgnoreShoot determines whether a Shoot should be ignored or not.
func ShouldIgnoreShoot(respectSyncPeriodOverwrite bool, shoot *gardencorev1beta1.Shoot) bool {
if !RespectShootSyncPeriodOverwrite(respectSyncPeriodOverwrite, shoot) {
return false
}
value, ok := GetShootIgnoreAnnotation(shoot.Annotations)
if !ok {
return false
}
ignore, _ := strconv.ParseBool(value)
return ignore
}
// IsShootFailed checks if a Shoot is failed.
func IsShootFailed(shoot *gardencorev1beta1.Shoot) bool {
lastOperation := shoot.Status.LastOperation
return lastOperation != nil && lastOperation.State == gardencorev1beta1.LastOperationStateFailed &&
shoot.Generation == shoot.Status.ObservedGeneration &&
shoot.Status.Gardener.Version == version.Get().GitVersion
}
// IsNowInEffectiveShootMaintenanceTimeWindow checks if the current time is in the effective
// maintenance time window of the Shoot.
func IsNowInEffectiveShootMaintenanceTimeWindow(shoot *gardencorev1beta1.Shoot) bool {
return EffectiveShootMaintenanceTimeWindow(shoot).Contains(time.Now())
}
// IsObservedAtLatestGenerationAndSucceeded checks whether the Shoot's generation has changed or if the LastOperation status
// is Succeeded.
func IsObservedAtLatestGenerationAndSucceeded(shoot *gardencorev1beta1.Shoot) bool {
lastOperation := shoot.Status.LastOperation
return shoot.Generation == shoot.Status.ObservedGeneration &&
(lastOperation != nil && lastOperation.State == gardencorev1beta1.LastOperationStateSucceeded)
}
// SyncPeriodOfShoot determines the sync period of the given shoot.
//
// If no overwrite is allowed, the defaultMinSyncPeriod is returned.
// Otherwise, the overwrite is parsed. If an error occurs or it is smaller than the defaultMinSyncPeriod,
// the defaultMinSyncPeriod is returned. Otherwise, the overwrite is returned.
func SyncPeriodOfShoot(respectSyncPeriodOverwrite bool, defaultMinSyncPeriod time.Duration, shoot *gardencorev1beta1.Shoot) time.Duration {
if !RespectShootSyncPeriodOverwrite(respectSyncPeriodOverwrite, shoot) {
return defaultMinSyncPeriod
}
syncPeriodOverwrite, ok := GetShootSyncPeriodAnnotation(shoot.Annotations)
if !ok {
return defaultMinSyncPeriod
}
syncPeriod, err := time.ParseDuration(syncPeriodOverwrite)
if err != nil {
return defaultMinSyncPeriod
}
if syncPeriod < defaultMinSyncPeriod {
return defaultMinSyncPeriod
}
return syncPeriod
}
// EffectiveMaintenanceTimeWindow cuts a maintenance time window at the end with a guess of 15 minutes. It is subtracted from the end
// of a maintenance time window to use a best-effort kind of finishing the operation before the end.
// Generally, we can't make sure that the maintenance operation is done by the end of the time window anyway (considering large
// clusters with hundreds of nodes, a rolling update will take several hours).
func EffectiveMaintenanceTimeWindow(timeWindow *utils.MaintenanceTimeWindow) *utils.MaintenanceTimeWindow {
return timeWindow.WithEnd(timeWindow.End().Add(0, -15, 0))
}
// EffectiveShootMaintenanceTimeWindow returns the effective MaintenanceTimeWindow of the given Shoot.
func EffectiveShootMaintenanceTimeWindow(shoot *gardencorev1beta1.Shoot) *utils.MaintenanceTimeWindow {
maintenance := shoot.Spec.Maintenance
if maintenance == nil || maintenance.TimeWindow == nil {
return utils.AlwaysTimeWindow
}
timeWindow, err := utils.ParseMaintenanceTimeWindow(maintenance.TimeWindow.Begin, maintenance.TimeWindow.End)
if err != nil {
return utils.AlwaysTimeWindow
}
return EffectiveMaintenanceTimeWindow(timeWindow)
}
// GardenEtcdEncryptionSecretName returns the name to the 'backup' of the etcd encryption secret in the Garden cluster.
func GardenEtcdEncryptionSecretName(shootName string) string {
return fmt.Sprintf("%s.%s", shootName, EtcdEncryptionSecretName)
}
// ReadServiceAccountSigningKeySecret reads the signing key secret to extract the signing key.
// It errors if there is no value at ServiceAccountSigningKeySecretDataKey.
func ReadServiceAccountSigningKeySecret(secret *corev1.Secret) (string, error) {
data, ok := secret.Data[ServiceAccountSigningKeySecretDataKey]
if !ok {
return "", fmt.Errorf("no signing key secret in secret %s/%s at .Data.%s", secret.Namespace, secret.Name, ServiceAccountSigningKeySecretDataKey)
}
return string(data), nil
}
// GetServiceAccountSigningKeySecret gets the signing key from the secret with the given name and namespace.
func GetServiceAccountSigningKeySecret(ctx context.Context, c client.Client, shootNamespace, secretName string) (string, error) {
secret := &corev1.Secret{}
if err := c.Get(ctx, kutil.Key(shootNamespace, secretName), secret); err != nil {
return "", err
}
return ReadServiceAccountSigningKeySecret(secret)
}
// GetAPIServerDomain returns the fully qualified domain name of for the api-server for the Shoot cluster. The
// end result is 'api.<domain>'.
func GetAPIServerDomain(domain string) string {
return fmt.Sprintf("%s.%s", APIServerPrefix, domain)
}
// GetSecretFromSecretRef gets the Secret object from <secretRef>.
func GetSecretFromSecretRef(ctx context.Context, c client.Client, secretRef *corev1.SecretReference) (*corev1.Secret, error) {
secret := &corev1.Secret{}
if err := c.Get(ctx, kutil.Key(secretRef.Namespace, secretRef.Name), secret); err != nil {
return nil, err
}
return secret, nil
}
// GetConfirmationDeletionAnnotation fetches the value for ConfirmationDeletion annotation.
// If not present, it fallbacks to ConfirmationDeletionDeprecated.
func GetConfirmationDeletionAnnotation(annotations map[string]string) (string, bool) {
return getDeprecatedAnnotation(annotations, ConfirmationDeletion, ConfirmationDeletionDeprecated)
}
// GetShootExpirationTimestampAnnotation fetches the value for ShootExpirationTimestamp annotation.
// If not present, it fallbacks to ShootExpirationTimestampDeprecated.
func GetShootExpirationTimestampAnnotation(annotations map[string]string) (string, bool) {
return getDeprecatedAnnotation(annotations, ShootExpirationTimestamp, ShootExpirationTimestampDeprecated)
}
// GetShootOperationAnnotation fetches the value for v1beta1constants.GardenerOperation annotation.
// If not present, it fallbacks to ShootOperationDeprecated.
func GetShootOperationAnnotation(annotations map[string]string) (string, bool) {
return getDeprecatedAnnotation(annotations, v1beta1constants.GardenerOperation, ShootOperationDeprecated)
}
// GetShootSyncPeriodAnnotation fetches the value for ShootSyncPeriod annotation.
// If not present, it fallbacks to ShootSyncPeriodDeprecated.
func GetShootSyncPeriodAnnotation(annotations map[string]string) (string, bool) {
return getDeprecatedAnnotation(annotations, ShootSyncPeriod, ShootSyncPeriodDeprecated)
}
// GetShootIgnoreAnnotation fetches the value for ShootIgnore annotation.
// If not present, it fallbacks to ShootIgnoreDeprecated.
func GetShootIgnoreAnnotation(annotations map[string]string) (string, bool) {
return getDeprecatedAnnotation(annotations, ShootIgnore, ShootIgnoreDeprecated)
}
// GetTasksAnnotation fetches the value for ShootTasks annotation.
// If not present, it falls back to ShootTasksDeprecated.
func GetTasksAnnotation(annotations map[string]string) (string, bool) {
return getDeprecatedAnnotation(annotations, ShootTasks, ShootTasksDeprecated)
}
func getDeprecatedAnnotation(annotations map[string]string, annotationKey, deprecatedAnnotationKey string) (string, bool) {
val, ok := annotations[annotationKey]
if !ok {
val, ok = annotations[deprecatedAnnotationKey]
}
return val, ok
}
// CheckIfDeletionIsConfirmed returns whether the deletion of an object is confirmed or not.
func CheckIfDeletionIsConfirmed(obj metav1.Object) error {
annotations := obj.GetAnnotations()
if annotations == nil {
return annotationRequiredError()
}
value, _ := GetConfirmationDeletionAnnotation(annotations)
if true, err := strconv.ParseBool(value); err != nil || !true {
return annotationRequiredError()
}
return nil
}
func annotationRequiredError() error {
return fmt.Errorf("must have a %q annotation to delete", ConfirmationDeletion)
}
// ConfirmDeletion adds Gardener's deletion confirmation annotation to the given object and sends an UPDATE request.
func ConfirmDeletion(ctx context.Context, c client.Client, obj runtime.Object) error {
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
key, err := client.ObjectKeyFromObject(obj)
if err != nil {
return err
}
if err := c.Get(ctx, key, obj); err != nil {
if !apierrors.IsNotFound(err) {
return err
}
return nil
}
existing := obj.DeepCopyObject()
acc, err := meta.Accessor(obj)
if err != nil {
return err
}
kutil.SetMetaDataAnnotation(acc, ConfirmationDeletion, "true")
kutil.SetMetaDataAnnotation(acc, v1beta1constants.GardenerTimestamp, TimeNow().UTC().String())
if reflect.DeepEqual(existing, obj) {
return nil
}
return c.Update(ctx, obj)
})
}
// ExtensionID returns an identifier for the given extension kind/type.
func ExtensionID(extensionKind, extensionType string) string {
return fmt.Sprintf("%s/%s", extensionKind, extensionType)
}