-
Notifications
You must be signed in to change notification settings - Fork 455
/
handler.go
519 lines (449 loc) · 17.4 KB
/
handler.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
// Copyright 2022 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 highavailabilityconfig
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
hvpav1alpha1 "github.com/gardener/hvpa-controller/api/v1alpha1"
"github.com/go-logr/logr"
admissionv1 "k8s.io/api/admission/v1"
appsv1 "k8s.io/api/apps/v1"
autoscalingv2 "k8s.io/api/autoscaling/v2"
autoscalingv2beta1 "k8s.io/api/autoscaling/v2beta1"
corev1 "k8s.io/api/core/v1"
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/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
resourcesv1alpha1 "github.com/gardener/gardener/pkg/apis/resources/v1alpha1"
"github.com/gardener/gardener/pkg/resourcemanager/apis/config"
kubernetesutils "github.com/gardener/gardener/pkg/utils/kubernetes"
)
// Handler handles admission requests and sets the following fields based on the failure tolerance type and the
// component type:
// - `.spec.replicas`
// - `.spec.template.spec.affinity`
// - `.spec.template.spec.topologySpreadConstraints`
type Handler struct {
Logger logr.Logger
TargetClient client.Reader
Config config.HighAvailabilityConfigWebhookConfig
Decoder *admission.Decoder
}
// Handle defaults the high availability settings of the provided resource.
func (h *Handler) Handle(ctx context.Context, req admission.Request) admission.Response {
var (
requestGK = schema.GroupKind{Group: req.Kind.Group, Kind: req.Kind.Kind}
obj runtime.Object
err error
)
namespace := &corev1.Namespace{}
if err := h.TargetClient.Get(ctx, client.ObjectKey{Name: req.Namespace}, namespace); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
var (
failureToleranceType *gardencorev1beta1.FailureToleranceType
zones []string
isZonePinningEnabled bool
)
if v, ok := namespace.Annotations[resourcesv1alpha1.HighAvailabilityConfigFailureToleranceType]; ok {
value := gardencorev1beta1.FailureToleranceType(v)
failureToleranceType = &value
}
if v, ok := namespace.Annotations[resourcesv1alpha1.HighAvailabilityConfigZones]; ok {
zones = sets.List(sets.New(strings.Split(v, ",")...).Delete(""))
}
if v, err := strconv.ParseBool(namespace.Annotations[resourcesv1alpha1.HighAvailabilityConfigZonePinning]); err == nil {
isZonePinningEnabled = v
}
isHorizontallyScaled, maxReplicas, err := h.isHorizontallyScaled(ctx, req.Namespace, schema.GroupVersion{Group: req.Kind.Group, Version: req.Kind.Version}.String(), req.Kind.Kind, req.Name)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
switch requestGK {
case appsv1.SchemeGroupVersion.WithKind("Deployment").GroupKind():
obj, err = h.handleDeployment(req, failureToleranceType, zones, isHorizontallyScaled, maxReplicas, isZonePinningEnabled)
case appsv1.SchemeGroupVersion.WithKind("StatefulSet").GroupKind():
obj, err = h.handleStatefulSet(req, failureToleranceType, zones, isHorizontallyScaled, maxReplicas, isZonePinningEnabled)
case autoscalingv2.SchemeGroupVersion.WithKind("HorizontalPodAutoscaler").GroupKind():
obj, err = h.handleHorizontalPodAutoscaler(req, failureToleranceType)
case hvpav1alpha1.SchemeGroupVersionHvpa.WithKind("Hvpa").GroupKind():
obj, err = h.handleHvpa(req, failureToleranceType)
default:
return admission.Allowed(fmt.Sprintf("unexpected resource: %s", requestGK))
}
if err != nil {
var apiStatus apierrors.APIStatus
if errors.As(err, &apiStatus) {
result := apiStatus.Status()
return admission.Response{AdmissionResponse: admissionv1.AdmissionResponse{Allowed: false, Result: &result}}
}
return admission.Denied(err.Error())
}
marshalled, err := json.Marshal(obj)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, marshalled)
}
func (h *Handler) handleDeployment(
req admission.Request,
failureToleranceType *gardencorev1beta1.FailureToleranceType,
zones []string,
isHorizontallyScaled bool,
maxReplicas int32,
isZonePinningEnabled bool,
) (
runtime.Object,
error,
) {
deployment := &appsv1.Deployment{}
if err := h.Decoder.Decode(req, deployment); err != nil {
return nil, err
}
log := h.Logger.WithValues("deployment", kubernetesutils.ObjectKeyForCreateWebhooks(deployment, req))
if err := mutateReplicas(
log,
failureToleranceType,
isHorizontallyScaled,
deployment,
deployment.Spec.Replicas,
func(replicas *int32) { deployment.Spec.Replicas = replicas },
); err != nil {
return nil, err
}
h.mutateNodeAffinity(
// TODO(ScheererJ): Remove "failureToleranceType != nil" after the shoot namespaces have been annotated with
// "zone-pinning=enabled" as well (today, only the istio-ingress namespaces have this annotation).
failureToleranceType != nil || isZonePinningEnabled,
zones,
&deployment.Spec.Template,
)
h.mutateTopologySpreadConstraints(
failureToleranceType,
zones,
isHorizontallyScaled,
deployment.Spec.Replicas,
maxReplicas,
&deployment.Spec.Template,
)
h.mutatePodTolerationSeconds(
&deployment.Spec.Template,
)
return deployment, nil
}
func (h *Handler) handleStatefulSet(
req admission.Request,
failureToleranceType *gardencorev1beta1.FailureToleranceType,
zones []string,
isHorizontallyScaled bool,
maxReplicas int32,
isZonePinningEnabled bool,
) (
runtime.Object,
error,
) {
statefulSet := &appsv1.StatefulSet{}
if err := h.Decoder.Decode(req, statefulSet); err != nil {
return nil, err
}
log := h.Logger.WithValues("statefulSet", kubernetesutils.ObjectKeyForCreateWebhooks(statefulSet, req))
if err := mutateReplicas(
log,
failureToleranceType,
isHorizontallyScaled,
statefulSet,
statefulSet.Spec.Replicas,
func(replicas *int32) { statefulSet.Spec.Replicas = replicas },
); err != nil {
return nil, err
}
h.mutateNodeAffinity(
// TODO(ScheererJ): Remove "failureToleranceType != nil" after the shoot namespaces have been annotated with
// "zone-pinning=enabled" as well (today, only the istio-ingress namespaces have this annotation).
failureToleranceType != nil || isZonePinningEnabled,
zones,
&statefulSet.Spec.Template,
)
h.mutateTopologySpreadConstraints(
failureToleranceType,
zones,
isHorizontallyScaled,
statefulSet.Spec.Replicas,
maxReplicas,
&statefulSet.Spec.Template,
)
h.mutatePodTolerationSeconds(
&statefulSet.Spec.Template,
)
return statefulSet, nil
}
func (h *Handler) handleHvpa(req admission.Request, failureToleranceType *gardencorev1beta1.FailureToleranceType) (runtime.Object, error) {
hvpa := &hvpav1alpha1.Hvpa{}
if err := h.Decoder.Decode(req, hvpa); err != nil {
return nil, err
}
log := h.Logger.WithValues("hvpa", kubernetesutils.ObjectKeyForCreateWebhooks(hvpa, req))
if err := mutateAutoscalingReplicas(
log,
failureToleranceType,
hvpa,
func() *int32 { return hvpa.Spec.Hpa.Template.Spec.MinReplicas },
func(n *int32) { hvpa.Spec.Hpa.Template.Spec.MinReplicas = n },
func() int32 { return hvpa.Spec.Hpa.Template.Spec.MaxReplicas },
func(n int32) { hvpa.Spec.Hpa.Template.Spec.MaxReplicas = n },
); err != nil {
return nil, err
}
return hvpa, nil
}
func (h *Handler) handleHorizontalPodAutoscaler(req admission.Request, failureToleranceType *gardencorev1beta1.FailureToleranceType) (runtime.Object, error) {
switch req.Kind.Version {
case autoscalingv2beta1.SchemeGroupVersion.Version:
hpa := &autoscalingv2beta1.HorizontalPodAutoscaler{}
if err := h.Decoder.Decode(req, hpa); err != nil {
return nil, err
}
log := h.Logger.WithValues("hpa", kubernetesutils.ObjectKeyForCreateWebhooks(hpa, req))
if err := mutateAutoscalingReplicas(
log,
failureToleranceType,
hpa,
func() *int32 { return hpa.Spec.MinReplicas },
func(n *int32) { hpa.Spec.MinReplicas = n },
func() int32 { return hpa.Spec.MaxReplicas },
func(n int32) { hpa.Spec.MaxReplicas = n },
); err != nil {
return nil, err
}
return hpa, nil
case autoscalingv2.SchemeGroupVersion.Version:
hpa := &autoscalingv2.HorizontalPodAutoscaler{}
if err := h.Decoder.Decode(req, hpa); err != nil {
return nil, err
}
log := h.Logger.WithValues("hpa", kubernetesutils.ObjectKeyForCreateWebhooks(hpa, req))
if err := mutateAutoscalingReplicas(
log,
failureToleranceType,
hpa,
func() *int32 { return hpa.Spec.MinReplicas },
func(n *int32) { hpa.Spec.MinReplicas = n },
func() int32 { return hpa.Spec.MaxReplicas },
func(n int32) { hpa.Spec.MaxReplicas = n },
); err != nil {
return nil, err
}
return hpa, nil
default:
return nil, fmt.Errorf("autoscaling version %q in request is not supported", req.Kind.Version)
}
}
func mutateReplicas(
log logr.Logger,
failureToleranceType *gardencorev1beta1.FailureToleranceType,
isHorizontallyScaled bool,
obj client.Object,
currentReplicas *int32,
setReplicas func(*int32),
) error {
replicas, err := getReplicaCount(obj, currentReplicas, failureToleranceType)
if err != nil {
return err
}
if replicas == nil {
return nil
}
// only mutate replicas if object is not horizontally scaled or if current replica count is lower than what we have
// computed
if !isHorizontallyScaled || pointer.Int32Deref(currentReplicas, 0) < *replicas {
log.Info("Mutating replicas", "replicas", *replicas)
setReplicas(replicas)
}
return nil
}
func getReplicaCount(obj client.Object, currentOrMinReplicas *int32, failureToleranceType *gardencorev1beta1.FailureToleranceType) (*int32, error) {
// do not mutate replicas if they are set to 0 (hibernation case or HPA disabled)
if pointer.Int32Deref(currentOrMinReplicas, 0) == 0 {
return nil, nil
}
replicas := kubernetesutils.GetReplicaCount(failureToleranceType, obj.GetLabels()[resourcesv1alpha1.HighAvailabilityConfigType])
if replicas == nil {
return nil, nil
}
// check if custom replica overwrite is desired
if replicasOverwrite := obj.GetAnnotations()[resourcesv1alpha1.HighAvailabilityConfigReplicas]; replicasOverwrite != "" {
v, err := strconv.Atoi(replicasOverwrite)
if err != nil {
return nil, err
}
replicas = pointer.Int32(int32(v))
}
return replicas, nil
}
func (h *Handler) isHorizontallyScaled(ctx context.Context, namespace, targetAPIVersion, targetKind, targetName string) (bool, int32, error) {
hpaList := &autoscalingv2.HorizontalPodAutoscalerList{}
if err := h.TargetClient.List(ctx, hpaList, client.InNamespace(namespace)); err != nil {
return false, 0, fmt.Errorf("failed to list all HPAs: %w", err)
}
for _, hpa := range hpaList.Items {
if targetRef := hpa.Spec.ScaleTargetRef; targetRef.APIVersion == targetAPIVersion &&
targetRef.Kind == targetKind && targetRef.Name == targetName {
return true, hpa.Spec.MaxReplicas, nil
}
}
hvpaList := &hvpav1alpha1.HvpaList{}
if err := h.TargetClient.List(ctx, hvpaList); err != nil && !meta.IsNoMatchError(err) {
return false, 0, fmt.Errorf("failed to list all HVPAs: %w", err)
}
for _, hvpa := range hvpaList.Items {
if targetRef := hvpa.Spec.TargetRef; targetRef != nil && targetRef.APIVersion == targetAPIVersion &&
targetRef.Kind == targetKind && targetRef.Name == targetName && hvpa.Spec.Hpa.Deploy {
return true, hvpa.Spec.Hpa.Template.Spec.MaxReplicas, nil
}
}
return false, 0, nil
}
func (h *Handler) mutateNodeAffinity(
isZonePinningEnabled bool,
zones []string,
podTemplateSpec *corev1.PodTemplateSpec,
) {
if nodeSelectorRequirement := kubernetesutils.GetNodeSelectorRequirementForZones(isZonePinningEnabled, zones); nodeSelectorRequirement != nil {
if podTemplateSpec.Spec.Affinity == nil {
podTemplateSpec.Spec.Affinity = &corev1.Affinity{}
}
if podTemplateSpec.Spec.Affinity.NodeAffinity == nil {
podTemplateSpec.Spec.Affinity.NodeAffinity = &corev1.NodeAffinity{}
}
if podTemplateSpec.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {
podTemplateSpec.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution = &corev1.NodeSelector{}
}
if len(podTemplateSpec.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms) == 0 {
podTemplateSpec.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms = []corev1.NodeSelectorTerm{{}}
}
for i, term := range podTemplateSpec.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms {
filteredExpressions := make([]corev1.NodeSelectorRequirement, 0, len(term.MatchExpressions))
// Remove existing expressions for `topology.kubernetes.io/zone` to
// - avoid duplicates for the same key
// - remove expressions that prevent zone pinning
for _, expr := range term.MatchExpressions {
if expr.Key != corev1.LabelTopologyZone {
filteredExpressions = append(filteredExpressions, expr)
}
}
// Add remaining expressions with intended zone expression.
podTemplateSpec.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms[i].MatchExpressions = append(filteredExpressions, *nodeSelectorRequirement)
}
}
}
func (h *Handler) mutateTopologySpreadConstraints(
failureToleranceType *gardencorev1beta1.FailureToleranceType,
zones []string,
isHorizontallyScaled bool,
currentReplicas *int32,
maxReplicas int32,
podTemplateSpec *corev1.PodTemplateSpec,
) {
replicas := pointer.Int32Deref(currentReplicas, 0)
// Set maxReplicas to replicas if component is not scaled horizontally or of the replica count is higher than maxReplicas
// which can happen if the involved H(V)PA object is not mutated yet.
if !isHorizontallyScaled || replicas > maxReplicas {
maxReplicas = replicas
}
if constraints := kubernetesutils.GetTopologySpreadConstraints(replicas, maxReplicas, metav1.LabelSelector{MatchLabels: podTemplateSpec.Labels}, int32(len(zones)), failureToleranceType); constraints != nil {
// Filter existing constraints with the same topology key to prevent that we are trying to add a constraint with
// the same key multiple times.
var filteredConstraints []corev1.TopologySpreadConstraint
for _, constraint := range podTemplateSpec.Spec.TopologySpreadConstraints {
if constraint.TopologyKey != corev1.LabelHostname && constraint.TopologyKey != corev1.LabelTopologyZone {
filteredConstraints = append(filteredConstraints, constraint)
}
}
podTemplateSpec.Spec.TopologySpreadConstraints = append(filteredConstraints, constraints...)
}
}
func (h *Handler) mutatePodTolerationSeconds(podTemplateSpec *corev1.PodTemplateSpec) {
var (
toleratesNodeNotReady bool
toleratesNodeUnreachable bool
)
// Check if toleration is already specific in podTemplate.
for _, toleration := range podTemplateSpec.Spec.Tolerations {
if len(toleration.Effect) > 0 && toleration.Effect != corev1.TaintEffectNoExecute {
continue
}
switch toleration.Key {
case corev1.TaintNodeNotReady:
toleratesNodeNotReady = true
case corev1.TaintNodeUnreachable:
toleratesNodeUnreachable = true
}
}
if !toleratesNodeNotReady && h.Config.DefaultNotReadyTolerationSeconds != nil {
podTemplateSpec.Spec.Tolerations = append(podTemplateSpec.Spec.Tolerations, corev1.Toleration{
Key: corev1.TaintNodeNotReady,
Operator: corev1.TolerationOpExists,
Effect: corev1.TaintEffectNoExecute,
TolerationSeconds: h.Config.DefaultNotReadyTolerationSeconds,
})
}
if !toleratesNodeUnreachable && h.Config.DefaultUnreachableTolerationSeconds != nil {
podTemplateSpec.Spec.Tolerations = append(podTemplateSpec.Spec.Tolerations, corev1.Toleration{
Key: corev1.TaintNodeUnreachable,
Operator: corev1.TolerationOpExists,
Effect: corev1.TaintEffectNoExecute,
TolerationSeconds: h.Config.DefaultUnreachableTolerationSeconds,
})
}
}
func mutateAutoscalingReplicas(
log logr.Logger,
failureToleranceType *gardencorev1beta1.FailureToleranceType,
obj client.Object,
getMinReplicas func() *int32,
setMinReplicas func(*int32),
getMaxReplicas func() int32,
setMaxReplicas func(int32),
) error {
replicas, err := getReplicaCount(obj, getMinReplicas(), failureToleranceType)
if err != nil {
return err
}
if replicas == nil {
return nil
}
// For compatibility reasons, only overwrite minReplicas if the current count is lower than the calculated count.
// TODO(timuthy): Reconsider if this should be removed in a future version.
if pointer.Int32Deref(getMinReplicas(), 0) < *replicas {
log.Info("Mutating minReplicas", "minReplicas", replicas)
setMinReplicas(replicas)
}
if getMaxReplicas() < pointer.Int32Deref(getMinReplicas(), 0) {
log.Info("Mutating maxReplicas", "maxReplicas", replicas)
setMaxReplicas(*replicas)
}
return nil
}