/
merger.go
461 lines (378 loc) · 16.4 KB
/
merger.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
// Copyright 2019 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 managedresource
import (
"fmt"
"strings"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes/scheme"
resourcesv1alpha1 "github.com/gardener/gardener/pkg/apis/resources/v1alpha1"
"github.com/gardener/gardener/pkg/resourcemanager/controller/garbagecollector/references"
)
const (
descriptionAnnotation = "resources.gardener.cloud/description"
descriptionAnnotationText = `DO NOT EDIT - This resource is managed by gardener-resource-manager.
Any modifications are discarded and the resource is returned to the original state.`
)
// merge merges the values of the `desired` object into the `current` object while preserving `current`'s important
// metadata (like resourceVersion and finalizers), status and selected spec fields of the respective kind (e.g.
// .spec.selector of a Job).
func merge(origin string, desired, current *unstructured.Unstructured, forceOverwriteLabels bool, existingLabels map[string]string, forceOverwriteAnnotations bool, existingAnnotations map[string]string, preserveReplicas, preserveResources bool) error {
// save copy of current object before merging
oldObject := current.DeepCopy()
// copy desired state into new object
newObject := current
desired.DeepCopyInto(newObject)
// keep metadata information of old object to avoid unnecessary update calls
if oldMetadataInterface, ok := oldObject.Object["metadata"]; ok {
// cast to map to be able to check if metadata is empty
if oldMetadataMap, ok := oldMetadataInterface.(map[string]interface{}); ok {
if len(oldMetadataMap) > 0 {
newObject.Object["metadata"] = oldMetadataMap
}
}
}
if forceOverwriteLabels {
newObject.SetLabels(desired.GetLabels())
} else {
newObject.SetLabels(mergeMapsBasedOnOldMap(desired.GetLabels(), oldObject.GetLabels(), existingLabels))
}
var ann map[string]string
if forceOverwriteAnnotations {
ann = desired.GetAnnotations()
} else {
// Here, we drop the 'reference' annotations from `oldObject` which are used by the garbage collector controller.
// Typically, all annotations which were previously added to the desired state of a resource are preserved in the
// `status` of the respective `ManagedResource`. This way, in subsequent reconciliations the controller can know
// whether found annotations were earlier managed by us and have to be dropped or kept.
// However, when an object has existing 'reference' annotations which were are not found in the `status` of the
// `ManagedResource` (this can happen when resources are migrated from one `ManagedResource` to another) then
// they would be kept.
// Since the correct 'reference' annotations must be part of the `desired` object anyways, there is anyways no
// point in potentially keeping old 'reference' annotations from `oldObject`, so we can always drop them here.
ann = mergeMapsBasedOnOldMap(desired.GetAnnotations(), dropReferenceAnnotations(oldObject.GetAnnotations()), existingAnnotations)
}
if ann == nil {
ann = map[string]string{}
}
ann[descriptionAnnotation] = descriptionAnnotationText
ann[resourcesv1alpha1.OriginAnnotation] = origin
newObject.SetAnnotations(ann)
// keep status of old object if it is set and not empty
var oldStatus map[string]interface{}
if oldStatusInterface, containsStatus := oldObject.Object["status"]; containsStatus {
// cast to map to be able to check if status is empty
if oldStatusMap, ok := oldStatusInterface.(map[string]interface{}); ok {
oldStatus = oldStatusMap
}
}
if len(oldStatus) > 0 {
newObject.Object["status"] = oldStatus
} else {
delete(newObject.Object, "status")
}
annotations := desired.GetAnnotations()
if annotations[resourcesv1alpha1.PreserveReplicas] == "true" {
preserveReplicas = true
}
if annotations[resourcesv1alpha1.PreserveResources] == "true" {
preserveResources = true
}
switch newObject.GroupVersionKind().GroupKind() {
case appsv1.SchemeGroupVersion.WithKind("Deployment").GroupKind(), extensionsv1beta1.SchemeGroupVersion.WithKind("Deployment").GroupKind():
return mergeDeployment(scheme.Scheme, oldObject, newObject, preserveReplicas, preserveResources)
case batchv1.SchemeGroupVersion.WithKind("Job").GroupKind():
return mergeJob(scheme.Scheme, oldObject, newObject, preserveResources)
case batchv1.SchemeGroupVersion.WithKind("CronJob").GroupKind():
return mergeCronJob(scheme.Scheme, oldObject, newObject, preserveResources)
case appsv1.SchemeGroupVersion.WithKind("StatefulSet").GroupKind(), extensionsv1beta1.SchemeGroupVersion.WithKind("StatefulSet").GroupKind():
return mergeStatefulSet(scheme.Scheme, oldObject, newObject, preserveReplicas, preserveResources)
case appsv1.SchemeGroupVersion.WithKind("DaemonSet").GroupKind():
return mergeDaemonSet(scheme.Scheme, oldObject, newObject, preserveResources)
case corev1.SchemeGroupVersion.WithKind("Service").GroupKind():
return mergeService(scheme.Scheme, oldObject, newObject)
case corev1.SchemeGroupVersion.WithKind("ServiceAccount").GroupKind():
return mergeServiceAccount(scheme.Scheme, oldObject, newObject)
}
return nil
}
func mergeDeployment(scheme *runtime.Scheme, oldObj, newObj runtime.Object, preserveReplicas, preserveResources bool) error {
oldDeployment := &appsv1.Deployment{}
if err := scheme.Convert(oldObj, oldDeployment, nil); err != nil {
return err
}
newDeployment := &appsv1.Deployment{}
if err := scheme.Convert(newObj, newDeployment, nil); err != nil {
return err
}
// Do not overwrite a Deployment's '.spec.replicas' if the new Deployment's '.spec.replicas'
// field is unset or the Deployment is scaled by either an HPA or HVPA.
if newDeployment.Spec.Replicas == nil || preserveReplicas {
newDeployment.Spec.Replicas = oldDeployment.Spec.Replicas
}
mergePodTemplate(&oldDeployment.Spec.Template, &newDeployment.Spec.Template, preserveResources)
return scheme.Convert(newDeployment, newObj, nil)
}
func mergePodTemplate(oldPod, newPod *corev1.PodTemplateSpec, preserveResources bool) {
if !preserveResources {
return
}
// Do not overwrite a PodTemplate's resource requests / limits if it is scaled by an HVPA
for i, newContainer := range newPod.Spec.Containers {
for j, oldContainer := range oldPod.Spec.Containers {
if newContainer.Name == oldContainer.Name {
mergeContainer(&oldPod.Spec.Containers[j], &newPod.Spec.Containers[i], preserveResources)
break
}
}
}
}
func mergeContainer(oldContainer, newContainer *corev1.Container, preserveResources bool) {
if !preserveResources {
return
}
for resourceName, oldRequests := range oldContainer.Resources.Requests {
switch resourceName {
case corev1.ResourceCPU, corev1.ResourceMemory:
if newContainer.Resources.Requests == nil {
newContainer.Resources.Requests = corev1.ResourceList{}
}
newContainer.Resources.Requests[resourceName] = oldRequests
}
}
for resourceName, oldLimits := range oldContainer.Resources.Limits {
switch resourceName {
case corev1.ResourceCPU, corev1.ResourceMemory:
if newContainer.Resources.Limits == nil {
newContainer.Resources.Limits = corev1.ResourceList{}
}
newContainer.Resources.Limits[resourceName] = oldLimits
}
}
}
func mergeJob(scheme *runtime.Scheme, oldObj, newObj runtime.Object, preserveResources bool) error {
oldJob := &batchv1.Job{}
if err := scheme.Convert(oldObj, oldJob, nil); err != nil {
return err
}
newJob := &batchv1.Job{}
if err := scheme.Convert(newObj, newJob, nil); err != nil {
return err
}
// Do not overwrite a Job's '.spec.selector' since it is immutable.
newJob.Spec.Selector = oldJob.Spec.Selector
// Do not overwrite Job managed labels as 'controller-uid' and 'job-name'. '.spec.template' is immutable.
newJob.Spec.Template.Labels = labels.Merge(oldJob.Spec.Template.Labels, newJob.Spec.Template.Labels)
mergePodTemplate(&oldJob.Spec.Template, &newJob.Spec.Template, preserveResources)
return scheme.Convert(newJob, newObj, nil)
}
func mergeCronJob(scheme *runtime.Scheme, oldObj, newObj runtime.Object, preserveResources bool) error {
switch newObj.GetObjectKind().GroupVersionKind().Version {
case batchv1beta1.SchemeGroupVersion.Version:
return mergeV1beta1CronJob(scheme, oldObj, newObj, preserveResources)
case batchv1.SchemeGroupVersion.Version:
return mergeV1CronJob(scheme, oldObj, newObj, preserveResources)
default:
return fmt.Errorf("cannot merge objects with gvk: %s", newObj.GetObjectKind().GroupVersionKind().String())
}
}
func mergeV1beta1CronJob(scheme *runtime.Scheme, oldObj, newObj runtime.Object, preserveResources bool) error {
oldCronJob := &batchv1beta1.CronJob{}
if err := scheme.Convert(oldObj, oldCronJob, nil); err != nil {
return err
}
newCronJob := &batchv1beta1.CronJob{}
if err := scheme.Convert(newObj, newCronJob, nil); err != nil {
return err
}
mergePodTemplate(&oldCronJob.Spec.JobTemplate.Spec.Template, &newCronJob.Spec.JobTemplate.Spec.Template, preserveResources)
return scheme.Convert(newCronJob, newObj, nil)
}
func mergeV1CronJob(scheme *runtime.Scheme, oldObj, newObj runtime.Object, preserveResources bool) error {
oldCronJob := &batchv1.CronJob{}
if err := scheme.Convert(oldObj, oldCronJob, nil); err != nil {
return err
}
newCronJob := &batchv1.CronJob{}
if err := scheme.Convert(newObj, newCronJob, nil); err != nil {
return err
}
mergePodTemplate(&oldCronJob.Spec.JobTemplate.Spec.Template, &newCronJob.Spec.JobTemplate.Spec.Template, preserveResources)
return scheme.Convert(newCronJob, newObj, nil)
}
func mergeStatefulSet(scheme *runtime.Scheme, oldObj, newObj runtime.Object, preserveReplicas, preserveResources bool) error {
oldStatefulSet := &appsv1.StatefulSet{}
if err := scheme.Convert(oldObj, oldStatefulSet, nil); err != nil {
return err
}
newStatefulSet := &appsv1.StatefulSet{}
if err := scheme.Convert(newObj, newStatefulSet, nil); err != nil {
return err
}
// Do not overwrite a StatefulSet's '.spec.replicas' if the new StatefulSet's `.spec.replicas'
// field is unset or the Deployment is scaled by either an HPA or HVPA.
if newStatefulSet.Spec.Replicas == nil || preserveReplicas {
newStatefulSet.Spec.Replicas = oldStatefulSet.Spec.Replicas
}
// Do not overwrite a StatefulSet's '.spec.volumeClaimTemplates' field once the StatefulSet has been created as it is immutable
if !oldStatefulSet.CreationTimestamp.IsZero() {
newStatefulSet.Spec.VolumeClaimTemplates = oldStatefulSet.Spec.VolumeClaimTemplates
}
mergePodTemplate(&oldStatefulSet.Spec.Template, &newStatefulSet.Spec.Template, preserveResources)
return scheme.Convert(newStatefulSet, newObj, nil)
}
func mergeDaemonSet(scheme *runtime.Scheme, oldObj, newObj runtime.Object, preserveResources bool) error {
oldDaemonSet := &appsv1.DaemonSet{}
if err := scheme.Convert(oldObj, oldDaemonSet, nil); err != nil {
return err
}
newDaemonSet := &appsv1.DaemonSet{}
if err := scheme.Convert(newObj, newDaemonSet, nil); err != nil {
return err
}
mergePodTemplate(&oldDaemonSet.Spec.Template, &newDaemonSet.Spec.Template, preserveResources)
return scheme.Convert(newDaemonSet, newObj, nil)
}
// mergeService merges new service into old service
func mergeService(scheme *runtime.Scheme, oldObj, newObj runtime.Object) error {
oldService := &corev1.Service{}
if err := scheme.Convert(oldObj, oldService, nil); err != nil {
return err
}
if oldService.Spec.Type == "" {
oldService.Spec.Type = corev1.ServiceTypeClusterIP
}
newService := &corev1.Service{}
if err := scheme.Convert(newObj, newService, nil); err != nil {
return err
}
if newService.Spec.Type == "" {
newService.Spec.Type = corev1.ServiceTypeClusterIP
}
if len(oldService.Annotations) > 0 {
mergedAnnotations := map[string]string{}
for annotation, value := range oldService.Annotations {
for _, keepAnnotation := range keepServiceAnnotations() {
if strings.HasPrefix(annotation, keepAnnotation) {
mergedAnnotations[annotation] = value
}
}
}
if len(newService.Annotations) > 0 {
for annotation, value := range newService.Annotations {
mergedAnnotations[annotation] = value
}
}
newService.Annotations = mergedAnnotations
}
switch newService.Spec.Type {
case corev1.ServiceTypeLoadBalancer, corev1.ServiceTypeNodePort:
// do not override ports
var ports []corev1.ServicePort
for _, np := range newService.Spec.Ports {
p := np
for _, op := range oldService.Spec.Ports {
if (np.Port == op.Port || np.Name == op.Name) && np.NodePort == 0 {
p.NodePort = op.NodePort
}
}
ports = append(ports, p)
}
newService.Spec.Ports = ports
// do not override loadbalancer IP
if newService.Spec.LoadBalancerIP == "" && oldService.Spec.LoadBalancerIP != "" {
newService.Spec.LoadBalancerIP = oldService.Spec.LoadBalancerIP
}
case corev1.ServiceTypeExternalName:
// there is no ClusterIP in this case
return scheme.Convert(newService, newObj, nil)
}
// ClusterIP is immutable unless we want to transform the service into headless
// where ClusterIP = None or if the previous type of the service was ExternalName
// and the user wants to explicitly set an ClusterIP.
if newService.Spec.ClusterIP != corev1.ClusterIPNone &&
oldService.Spec.Type != corev1.ServiceTypeExternalName {
newService.Spec.ClusterIP = oldService.Spec.ClusterIP
}
if oldService.Spec.Type == corev1.ServiceTypeLoadBalancer &&
newService.Spec.Type == corev1.ServiceTypeLoadBalancer &&
newService.Spec.ExternalTrafficPolicy == corev1.ServiceExternalTrafficPolicyTypeLocal &&
oldService.Spec.ExternalTrafficPolicy == corev1.ServiceExternalTrafficPolicyTypeLocal &&
newService.Spec.HealthCheckNodePort == 0 {
newService.Spec.HealthCheckNodePort = oldService.Spec.HealthCheckNodePort
}
return scheme.Convert(newService, newObj, nil)
}
func mergeServiceAccount(scheme *runtime.Scheme, oldObj, newObj runtime.Object) error {
oldServiceAccount := &corev1.ServiceAccount{}
if err := scheme.Convert(oldObj, oldServiceAccount, nil); err != nil {
return err
}
newServiceAccount := &corev1.ServiceAccount{}
if err := scheme.Convert(newObj, newServiceAccount, nil); err != nil {
return err
}
// Do not overwrite a ServiceAccount's '.secrets[]' list or '.imagePullSecrets[]'.
newServiceAccount.Secrets = oldServiceAccount.Secrets
newServiceAccount.ImagePullSecrets = oldServiceAccount.ImagePullSecrets
return scheme.Convert(newServiceAccount, newObj, nil)
}
// mergeMapsBasedOnOldMap merges the values of the desired map into the current map.
// It takes an optional map of old desired values and removes any keys/values from the resulting map
// that were once desired (part of `old`) but are not desired anymore.
func mergeMapsBasedOnOldMap(desired, current, old map[string]string) map[string]string {
out := make(map[string]string, len(current))
// use current as base
for k, v := range current {
out[k] = v
}
// overwrite desired values
for k, v := range desired {
out[k] = v
}
// check if we should remove values which were once desired but are not desired anymore
for k, oldValue := range old {
currentValue, isInCurrent := current[k]
if !isInCurrent || currentValue != oldValue {
// is not part of the current map anymore or has been changed by the enduser -> don't remove
continue
}
if _, isDesired := desired[k]; !isDesired {
delete(out, k)
}
}
if len(out) == 0 {
return nil
}
return out
}
func dropReferenceAnnotations(annotations map[string]string) map[string]string {
out := make(map[string]string, len(annotations))
for k, v := range annotations {
if !strings.HasPrefix(k, references.AnnotationKeyPrefix) {
out[k] = v
}
}
return out
}
func keepServiceAnnotations() []string {
return []string{"loadbalancer.openstack.org"}
}