/
mutate.go
355 lines (303 loc) · 11.7 KB
/
mutate.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifests
import (
"errors"
"fmt"
"reflect"
"dario.cat/mergo"
routev1 "github.com/openshift/api/route/v1"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
appsv1 "k8s.io/api/apps/v1"
autoscalingv2 "k8s.io/api/autoscaling/v2"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
policyV1 "k8s.io/api/policy/v1"
rbacv1 "k8s.io/api/rbac/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
var (
ImmutableChangeErr = errors.New("immutable field change attempted")
)
// MutateFuncFor returns a mutate function based on the
// existing resource's concrete type. It supports currently
// only the following types or else panics:
// - ConfigMap
// - Service
// - ServiceAccount
// - ClusterRole
// - ClusterRoleBinding
// - Role
// - RoleBinding
// - Deployment
// - DaemonSet
// - StatefulSet
// - ServiceMonitor
// - Ingress
// - HorizontalPodAutoscaler
// - Route
// - Secret
// In order for the operator to reconcile other types, they must be added here.
// The function returned takes no arguments but instead uses the existing and desired inputs here. Existing is expected
// to be set by the controller-runtime package through a client get call.
func MutateFuncFor(existing, desired client.Object) controllerutil.MutateFn {
return func() error {
// Get the existing annotations and override any conflicts with the desired annotations
// This will preserve any annotations on the existing set.
existingAnnotations := existing.GetAnnotations()
if err := mergeWithOverride(&existingAnnotations, desired.GetAnnotations()); err != nil {
return err
}
existing.SetAnnotations(existingAnnotations)
// Get the existing labels and override any conflicts with the desired labels
// This will preserve any labels on the existing set.
existingLabels := existing.GetLabels()
if err := mergeWithOverride(&existingLabels, desired.GetLabels()); err != nil {
return err
}
existing.SetLabels(existingLabels)
if ownerRefs := desired.GetOwnerReferences(); len(ownerRefs) > 0 {
existing.SetOwnerReferences(ownerRefs)
}
switch existing.(type) {
case *corev1.ConfigMap:
cm := existing.(*corev1.ConfigMap)
wantCm := desired.(*corev1.ConfigMap)
mutateConfigMap(cm, wantCm)
case *corev1.Service:
svc := existing.(*corev1.Service)
wantSvc := desired.(*corev1.Service)
return mutateService(svc, wantSvc)
case *corev1.ServiceAccount:
sa := existing.(*corev1.ServiceAccount)
wantSa := desired.(*corev1.ServiceAccount)
mutateServiceAccount(sa, wantSa)
case *rbacv1.ClusterRole:
cr := existing.(*rbacv1.ClusterRole)
wantCr := desired.(*rbacv1.ClusterRole)
mutateClusterRole(cr, wantCr)
case *rbacv1.ClusterRoleBinding:
crb := existing.(*rbacv1.ClusterRoleBinding)
wantCrb := desired.(*rbacv1.ClusterRoleBinding)
mutateClusterRoleBinding(crb, wantCrb)
case *rbacv1.Role:
r := existing.(*rbacv1.Role)
wantR := desired.(*rbacv1.Role)
mutateRole(r, wantR)
case *rbacv1.RoleBinding:
rb := existing.(*rbacv1.RoleBinding)
wantRb := desired.(*rbacv1.RoleBinding)
mutateRoleBinding(rb, wantRb)
case *appsv1.Deployment:
dpl := existing.(*appsv1.Deployment)
wantDpl := desired.(*appsv1.Deployment)
return mutateDeployment(dpl, wantDpl)
case *appsv1.DaemonSet:
dpl := existing.(*appsv1.DaemonSet)
wantDpl := desired.(*appsv1.DaemonSet)
return mutateDaemonset(dpl, wantDpl)
case *appsv1.StatefulSet:
sts := existing.(*appsv1.StatefulSet)
wantSts := desired.(*appsv1.StatefulSet)
return mutateStatefulSet(sts, wantSts)
case *monitoringv1.ServiceMonitor:
svcMonitor := existing.(*monitoringv1.ServiceMonitor)
wantSvcMonitor := desired.(*monitoringv1.ServiceMonitor)
mutateServiceMonitor(svcMonitor, wantSvcMonitor)
case *monitoringv1.PodMonitor:
podMonitor := existing.(*monitoringv1.PodMonitor)
wantPodMonitor := desired.(*monitoringv1.PodMonitor)
mutatePodMonitor(podMonitor, wantPodMonitor)
case *networkingv1.Ingress:
ing := existing.(*networkingv1.Ingress)
wantIng := desired.(*networkingv1.Ingress)
mutateIngress(ing, wantIng)
case *autoscalingv2.HorizontalPodAutoscaler:
existingHPA := existing.(*autoscalingv2.HorizontalPodAutoscaler)
desiredHPA := desired.(*autoscalingv2.HorizontalPodAutoscaler)
mutateAutoscalingHPA(existingHPA, desiredHPA)
case *policyV1.PodDisruptionBudget:
existingPDB := existing.(*policyV1.PodDisruptionBudget)
desiredPDB := desired.(*policyV1.PodDisruptionBudget)
mutatePolicyV1PDB(existingPDB, desiredPDB)
case *routev1.Route:
rt := existing.(*routev1.Route)
wantRt := desired.(*routev1.Route)
mutateRoute(rt, wantRt)
case *corev1.Secret:
pr := existing.(*corev1.Secret)
wantPr := desired.(*corev1.Secret)
mutateSecret(pr, wantPr)
default:
t := reflect.TypeOf(existing).String()
return fmt.Errorf("missing mutate implementation for resource type: %s", t)
}
return nil
}
}
func mergeWithOverride(dst, src interface{}) error {
return mergo.Merge(dst, src, mergo.WithOverride)
}
func mutateSecret(existing, desired *corev1.Secret) {
existing.Labels = desired.Labels
existing.Annotations = desired.Annotations
existing.Data = desired.Data
}
func mutateConfigMap(existing, desired *corev1.ConfigMap) {
existing.BinaryData = desired.BinaryData
existing.Data = desired.Data
}
func mutateServiceAccount(existing, desired *corev1.ServiceAccount) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
}
func mutateClusterRole(existing, desired *rbacv1.ClusterRole) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Rules = desired.Rules
}
func mutateClusterRoleBinding(existing, desired *rbacv1.ClusterRoleBinding) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Subjects = desired.Subjects
}
func mutateRole(existing, desired *rbacv1.Role) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Rules = desired.Rules
}
func mutateRoleBinding(existing, desired *rbacv1.RoleBinding) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Subjects = desired.Subjects
}
func mutateAutoscalingHPA(existing, desired *autoscalingv2.HorizontalPodAutoscaler) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Spec = desired.Spec
}
func mutatePolicyV1PDB(existing, desired *policyV1.PodDisruptionBudget) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Spec = desired.Spec
}
func mutateIngress(existing, desired *networkingv1.Ingress) {
existing.Labels = desired.Labels
existing.Annotations = desired.Annotations
existing.Spec.DefaultBackend = desired.Spec.DefaultBackend
existing.Spec.Rules = desired.Spec.Rules
existing.Spec.TLS = desired.Spec.TLS
}
func mutateRoute(existing, desired *routev1.Route) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Spec = desired.Spec
}
func mutateServiceMonitor(existing, desired *monitoringv1.ServiceMonitor) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Spec = desired.Spec
}
func mutatePodMonitor(existing, desired *monitoringv1.PodMonitor) {
existing.Annotations = desired.Annotations
existing.Labels = desired.Labels
existing.Spec = desired.Spec
}
func mutateService(existing, desired *corev1.Service) error {
existing.Spec.Ports = desired.Spec.Ports
if err := mergeWithOverride(&existing.Spec.Selector, desired.Spec.Selector); err != nil {
return err
}
return nil
}
func mutateDaemonset(existing, desired *appsv1.DaemonSet) error {
if !existing.CreationTimestamp.IsZero() && !apiequality.Semantic.DeepEqual(desired.Spec.Selector, existing.Spec.Selector) {
return ImmutableChangeErr
}
// Daemonset selector is immutable so we set this value only if
// a new object is going to be created
if existing.CreationTimestamp.IsZero() {
existing.Spec.Selector = desired.Spec.Selector
}
if err := mergeWithOverride(&existing.Spec, desired.Spec); err != nil {
return err
}
return nil
}
func mutateDeployment(existing, desired *appsv1.Deployment) error {
if !existing.CreationTimestamp.IsZero() && !apiequality.Semantic.DeepEqual(desired.Spec.Selector, existing.Spec.Selector) {
return ImmutableChangeErr
}
// Deployment selector is immutable so we set this value only if
// a new object is going to be created
if existing.CreationTimestamp.IsZero() {
existing.Spec.Selector = desired.Spec.Selector
}
existing.Spec.Replicas = desired.Spec.Replicas
if err := mergeWithOverride(&existing.Spec.Template, desired.Spec.Template); err != nil {
return err
}
if err := mergeWithOverride(&existing.Spec.Strategy, desired.Spec.Strategy); err != nil {
return err
}
return nil
}
func mutateStatefulSet(existing, desired *appsv1.StatefulSet) error {
if hasChange, field := hasImmutableFieldChange(existing, desired); hasChange {
return fmt.Errorf("%s is being changed, %w", field, ImmutableChangeErr)
}
// StatefulSet selector is immutable so we set this value only if
// a new object is going to be created
if existing.CreationTimestamp.IsZero() {
existing.Spec.Selector = desired.Spec.Selector
}
existing.Spec.PodManagementPolicy = desired.Spec.PodManagementPolicy
existing.Spec.Replicas = desired.Spec.Replicas
for i := range existing.Spec.VolumeClaimTemplates {
existing.Spec.VolumeClaimTemplates[i].TypeMeta = desired.Spec.VolumeClaimTemplates[i].TypeMeta
existing.Spec.VolumeClaimTemplates[i].ObjectMeta = desired.Spec.VolumeClaimTemplates[i].ObjectMeta
existing.Spec.VolumeClaimTemplates[i].Spec = desired.Spec.VolumeClaimTemplates[i].Spec
}
if err := mergeWithOverride(&existing.Spec.Template, desired.Spec.Template); err != nil {
return err
}
return nil
}
func hasImmutableFieldChange(existing, desired *appsv1.StatefulSet) (bool, string) {
if existing.CreationTimestamp.IsZero() {
return false, ""
}
if !apiequality.Semantic.DeepEqual(desired.Spec.Selector, existing.Spec.Selector) {
return true, fmt.Sprintf("Spec.Selector: desired: %s existing: %s", desired.Spec.Selector, existing.Spec.Selector)
}
if hasVolumeClaimsTemplatesChanged(existing, desired) {
return true, "Spec.VolumeClaimTemplates"
}
return false, ""
}
// hasVolumeClaimsTemplatesChanged if volume claims template change has been detected.
// We need to do this manually due to some fields being automatically filled by the API server
// and these needs to be excluded from the comparison to prevent false positives.
func hasVolumeClaimsTemplatesChanged(existing, desired *appsv1.StatefulSet) bool {
if len(desired.Spec.VolumeClaimTemplates) != len(existing.Spec.VolumeClaimTemplates) {
return true
}
for i := range desired.Spec.VolumeClaimTemplates {
// VolumeMode is automatically set by the API server, so if it is not set in the CR, assume it's the same as the existing one.
if desired.Spec.VolumeClaimTemplates[i].Spec.VolumeMode == nil || *desired.Spec.VolumeClaimTemplates[i].Spec.VolumeMode == "" {
desired.Spec.VolumeClaimTemplates[i].Spec.VolumeMode = existing.Spec.VolumeClaimTemplates[i].Spec.VolumeMode
}
if desired.Spec.VolumeClaimTemplates[i].Name != existing.Spec.VolumeClaimTemplates[i].Name {
return true
}
if !apiequality.Semantic.DeepEqual(desired.Spec.VolumeClaimTemplates[i].Annotations, existing.Spec.VolumeClaimTemplates[i].Annotations) {
return true
}
if !apiequality.Semantic.DeepEqual(desired.Spec.VolumeClaimTemplates[i].Spec, existing.Spec.VolumeClaimTemplates[i].Spec) {
return true
}
}
return false
}