-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ownerreference_helpers.go
435 lines (378 loc) · 20.5 KB
/
ownerreference_helpers.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
/*
Copyright 2023 The Kubernetes Authors.
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 framework
import (
"context"
"fmt"
"reflect"
"sort"
"time"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
kerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
bootstrapv1 "sigs.k8s.io/cluster-api/bootstrap/kubeadm/api/v1beta1"
clusterctlcluster "sigs.k8s.io/cluster-api/cmd/clusterctl/client/cluster"
controlplanev1 "sigs.k8s.io/cluster-api/controlplane/kubeadm/api/v1beta1"
addonsv1 "sigs.k8s.io/cluster-api/exp/addons/api/v1beta1"
expv1 "sigs.k8s.io/cluster-api/exp/api/v1beta1"
"sigs.k8s.io/cluster-api/util/patch"
)
// ValidateOwnerReferencesOnUpdate checks that expected owner references are updated to the correct apiVersion.
func ValidateOwnerReferencesOnUpdate(ctx context.Context, proxy ClusterProxy, namespace, clusterName string, assertFuncs ...map[string]func(reference []metav1.OwnerReference) error) {
clusterKey := client.ObjectKey{Namespace: namespace, Name: clusterName}
// Pause the cluster.
setClusterPause(ctx, proxy.GetClient(), clusterKey, true)
// Change the version of the OwnerReferences on each object in the Graph to "v1alpha1"
changeOwnerReferencesAPIVersion(ctx, proxy, namespace)
// Unpause the cluster.
setClusterPause(ctx, proxy.GetClient(), clusterKey, false)
// Force ClusterClass reconciliation. This ensures ClusterClass ownerReferences are re-reconciled before asserting
// the owner reference graph.
forceClusterClassReconcile(ctx, proxy.GetClient(), clusterKey)
// Force ClusterResourceSet reconciliation. This ensures ClusterResourceBinding ownerReferences are re-reconciled before
// asserting the owner reference graph.
forceClusterResourceSetReconcile(ctx, proxy.GetClient(), namespace)
// Check that the ownerReferences have updated their apiVersions to current versions after reconciliation.
AssertOwnerReferences(namespace, proxy.GetKubeconfigPath(), assertFuncs...)
}
// ValidateOwnerReferencesResilience checks that expected owner references are in place, deletes them, and verifies that expect owner references are properly rebuilt.
func ValidateOwnerReferencesResilience(ctx context.Context, proxy ClusterProxy, namespace, clusterName string, assertFuncs ...map[string]func(reference []metav1.OwnerReference) error) {
// Check that the ownerReferences are as expected on the first iteration.
AssertOwnerReferences(namespace, proxy.GetKubeconfigPath(), assertFuncs...)
clusterKey := client.ObjectKey{Namespace: namespace, Name: clusterName}
// Removes all the owner references.
// NOTE: we are testing the worst-case scenario, where all the owner references are removed while the
// reconcilers are not working; this mimics what happens with the current velero backup/restore, which is an
// edge case where an external system intentionally nukes all the owner references in a single operation.
// The assumption is that if the system can recover from this edge case, it can also handle use cases where an owner
// reference is deleted by mistake.
setClusterPause(ctx, proxy.GetClient(), clusterKey, true)
// Once all Clusters are paused remove the OwnerReference from all objects in the graph.
removeOwnerReferences(ctx, proxy, namespace)
// Unpause the cluster.
setClusterPause(ctx, proxy.GetClient(), clusterKey, false)
// Annotate the clusterClass, if one is in use, to speed up reconciliation. This ensures ClusterClass ownerReferences
// are re-reconciled before asserting the owner reference graph.
forceClusterClassReconcile(ctx, proxy.GetClient(), clusterKey)
// Check that the ownerReferences are as expected after additional reconciliations.
AssertOwnerReferences(namespace, proxy.GetKubeconfigPath(), assertFuncs...)
}
func AssertOwnerReferences(namespace, kubeconfigPath string, assertFuncs ...map[string]func(reference []metav1.OwnerReference) error) {
allAssertFuncs := map[string]func(reference []metav1.OwnerReference) error{}
for _, m := range assertFuncs {
for k, v := range m {
allAssertFuncs[k] = v
}
}
Eventually(func() error {
allErrs := []error{}
ctx := context.Background()
graph, err := clusterctlcluster.GetOwnerGraph(ctx, namespace, kubeconfigPath)
Expect(err).ToNot(HaveOccurred())
for _, v := range graph {
if _, ok := allAssertFuncs[v.Object.Kind]; !ok {
allErrs = append(allErrs, fmt.Errorf("kind %s does not have an associated ownerRef assertion function", v.Object.Kind))
continue
}
if err := allAssertFuncs[v.Object.Kind](v.Owners); err != nil {
allErrs = append(allErrs, errors.Wrapf(err, "Unexpected ownerReferences for %s/%s", v.Object.Kind, v.Object.Name))
}
}
return kerrors.NewAggregate(allErrs)
}).WithTimeout(5 * time.Minute).WithPolling(2 * time.Second).Should(Succeed())
}
// Kinds and Owners for types in the core API package.
var (
coreGroupVersion = clusterv1.GroupVersion.String()
extensionConfigKind = "ExtensionConfig"
clusterClassKind = "ClusterClass"
clusterKind = "Cluster"
machineKind = "Machine"
machineSetKind = "MachineSet"
machineDeploymentKind = "MachineDeployment"
machineHealthCheckKind = "MachineHealthCheck"
clusterOwner = metav1.OwnerReference{Kind: clusterKind, APIVersion: coreGroupVersion}
clusterController = metav1.OwnerReference{Kind: clusterKind, APIVersion: coreGroupVersion, Controller: pointer.Bool(true)}
clusterClassOwner = metav1.OwnerReference{Kind: clusterClassKind, APIVersion: coreGroupVersion}
machineDeploymentController = metav1.OwnerReference{Kind: machineDeploymentKind, APIVersion: coreGroupVersion, Controller: pointer.Bool(true)}
machineSetController = metav1.OwnerReference{Kind: machineSetKind, APIVersion: coreGroupVersion, Controller: pointer.Bool(true)}
machineController = metav1.OwnerReference{Kind: machineKind, APIVersion: coreGroupVersion, Controller: pointer.Bool(true)}
)
// CoreOwnerReferenceAssertion maps Cluster API core types to functions which return an error if the passed
// OwnerReferences aren't as expected.
// Note: These relationships are documented in https://github.com/kubernetes-sigs/cluster-api/tree/main/docs/book/src/reference/owner_references.md.
// That document should be updated if these references change.
var CoreOwnerReferenceAssertion = map[string]func([]metav1.OwnerReference) error{
extensionConfigKind: func(owners []metav1.OwnerReference) error {
// ExtensionConfig should have no owners.
return HasExactOwners(owners)
},
clusterClassKind: func(owners []metav1.OwnerReference) error {
// ClusterClass doesn't have ownerReferences (it is a clusterctl move-hierarchy root).
return HasExactOwners(owners)
},
clusterKind: func(owners []metav1.OwnerReference) error {
// Cluster doesn't have ownerReferences (it is a clusterctl move-hierarchy root).
return HasExactOwners(owners)
},
machineDeploymentKind: func(owners []metav1.OwnerReference) error {
// MachineDeployments must be owned by a Cluster.
return HasExactOwners(owners, clusterOwner)
},
machineSetKind: func(owners []metav1.OwnerReference) error {
// MachineSets must be owned and controlled by a MachineDeployment.
return HasExactOwners(owners, machineDeploymentController)
},
machineKind: func(owners []metav1.OwnerReference) error {
// Machines must be owned and controlled by a MachineSet or a KubeadmControlPlane, depending on if this Machine is part of a ControlPlane or not.
return HasOneOfExactOwners(owners, []metav1.OwnerReference{machineSetController}, []metav1.OwnerReference{kubeadmControlPlaneController})
},
machineHealthCheckKind: func(owners []metav1.OwnerReference) error {
// MachineHealthChecks must be owned by the Cluster.
return HasExactOwners(owners, clusterOwner)
},
}
// Kinds and Owners for types in the exp package.
var (
clusterResourceSetKind = "ClusterResourceSet"
clusterResourceSetBindingKind = "ClusterResourceSetBinding"
machinePoolKind = "MachinePool"
machinePoolOwner = metav1.OwnerReference{Kind: machinePoolKind, APIVersion: expv1.GroupVersion.String()}
machinePoolController = metav1.OwnerReference{Kind: machinePoolKind, APIVersion: expv1.GroupVersion.String(), Controller: pointer.Bool(true)}
clusterResourceSetOwner = metav1.OwnerReference{Kind: clusterResourceSetKind, APIVersion: addonsv1.GroupVersion.String()}
)
// ExpOwnerReferenceAssertions maps experimental types to functions which return an error if the passed OwnerReferences
// aren't as expected.
// Note: These relationships are documented in https://github.com/kubernetes-sigs/cluster-api/tree/main/docs/book/src/reference/owner_references.md.
// That document should be updated if these references change.
var ExpOwnerReferenceAssertions = map[string]func([]metav1.OwnerReference) error{
clusterResourceSetKind: func(owners []metav1.OwnerReference) error {
// ClusterResourcesSet doesn't have ownerReferences (it is a clusterctl move-hierarchy root).
return HasExactOwners(owners)
},
// ClusterResourcesSetBinding has ClusterResourceSet set as owners on creation.
clusterResourceSetBindingKind: func(owners []metav1.OwnerReference) error {
return HasOneOfExactOwners(owners, []metav1.OwnerReference{clusterResourceSetOwner}, []metav1.OwnerReference{clusterResourceSetOwner, clusterResourceSetOwner})
},
// MachinePool must be owned by a Cluster.
machinePoolKind: func(owners []metav1.OwnerReference) error {
// MachinePools must be owned by a Cluster.
return HasExactOwners(owners, clusterOwner)
},
}
var (
configMapKind = "ConfigMap"
secretKind = "Secret"
)
// KubernetesReferenceAssertions maps Kubernetes types to functions which return an error if the passed OwnerReferences
// aren't as expected.
// Note: These relationships are documented in https://github.com/kubernetes-sigs/cluster-api/tree/main/docs/book/src/reference/owner_references.md.
// That document should be updated if these references change.
var KubernetesReferenceAssertions = map[string]func([]metav1.OwnerReference) error{
secretKind: func(owners []metav1.OwnerReference) error {
// Secrets for cluster certificates must be owned and controlled by the KubeadmControlPlane. The bootstrap secret should be owned and controlled by a KubeadmControlPlane.
return HasOneOfExactOwners(owners, []metav1.OwnerReference{kubeadmControlPlaneController}, []metav1.OwnerReference{kubeadmConfigController})
},
configMapKind: func(owners []metav1.OwnerReference) error {
// The only configMaps considered here are those owned by a ClusterResourceSet.
return HasExactOwners(owners, clusterResourceSetOwner)
},
}
// Kind and Owners for types in the Kubeadm ControlPlane package.
var (
kubeadmControlPlaneKind = "KubeadmControlPlane"
kubeadmControlPlaneTemplateKind = "KubeadmControlPlaneTemplate"
kubeadmControlPlaneGroupVersion = controlplanev1.GroupVersion.String()
kubeadmControlPlaneController = metav1.OwnerReference{Kind: kubeadmControlPlaneKind, APIVersion: kubeadmControlPlaneGroupVersion, Controller: pointer.Bool(true)}
)
// KubeadmControlPlaneOwnerReferenceAssertions maps Kubeadm control plane types to functions which return an error if the passed
// OwnerReferences aren't as expected.
// Note: These relationships are documented in https://github.com/kubernetes-sigs/cluster-api/tree/main/docs/book/src/reference/owner_references.md.
// That document should be updated if these references change.
var KubeadmControlPlaneOwnerReferenceAssertions = map[string]func([]metav1.OwnerReference) error{
kubeadmControlPlaneKind: func(owners []metav1.OwnerReference) error {
// The KubeadmControlPlane must be owned and controlled by a Cluster.
return HasExactOwners(owners, clusterController)
},
kubeadmControlPlaneTemplateKind: func(owners []metav1.OwnerReference) error {
// The KubeadmControlPlaneTemplate must be owned by a ClusterClass.
return HasExactOwners(owners, clusterClassOwner)
},
}
// Owners and kinds for types in the Kubeadm Bootstrap package.
var (
kubeadmConfigKind = "KubeadmConfig"
kubeadmConfigTemplateKind = "KubeadmConfigTemplate"
kubeadmConfigGroupVersion = bootstrapv1.GroupVersion.String()
kubeadmConfigController = metav1.OwnerReference{Kind: kubeadmConfigKind, APIVersion: kubeadmConfigGroupVersion, Controller: pointer.Bool(true)}
)
// KubeadmBootstrapOwnerReferenceAssertions maps KubeadmBootstrap types to functions which return an error if the passed OwnerReferences
// aren't as expected.
// Note: These relationships are documented in https://github.com/kubernetes-sigs/cluster-api/tree/main/docs/book/src/reference/owner_references.md.
// That document should be updated if these references change.
var KubeadmBootstrapOwnerReferenceAssertions = map[string]func([]metav1.OwnerReference) error{
kubeadmConfigKind: func(owners []metav1.OwnerReference) error {
// The KubeadmConfig must be owned and controlled by a Machine or MachinePool.
return HasOneOfExactOwners(owners, []metav1.OwnerReference{machineController}, []metav1.OwnerReference{machinePoolController})
},
kubeadmConfigTemplateKind: func(owners []metav1.OwnerReference) error {
// The KubeadmConfigTemplate must be owned by a ClusterClass.
return HasOneOfExactOwners(owners, []metav1.OwnerReference{clusterOwner}, []metav1.OwnerReference{clusterClassOwner})
},
}
// Kinds for types in the Docker infrastructure package.
var (
dockerMachineKind = "DockerMachine"
dockerMachineTemplateKind = "DockerMachineTemplate"
dockerMachinePoolKind = "DockerMachinePool"
dockerClusterKind = "DockerCluster"
dockerClusterTemplateKind = "DockerClusterTemplate"
)
// DockerInfraOwnerReferenceAssertions maps Docker Infrastructure types to functions which return an error if the passed
// OwnerReferences aren't as expected.
// Note: These relationships are documented in https://github.com/kubernetes-sigs/cluster-api/tree/main/docs/book/src/reference/owner_references.md.
// That document should be updated if these references change.
var DockerInfraOwnerReferenceAssertions = map[string]func([]metav1.OwnerReference) error{
dockerMachineKind: func(owners []metav1.OwnerReference) error {
// The DockerMachine must be owned and controlled by a Machine.
return HasExactOwners(owners, machineController)
},
dockerMachineTemplateKind: func(owners []metav1.OwnerReference) error {
// Base DockerMachineTemplates referenced in a ClusterClass must be owned by the ClusterClass.
// DockerMachineTemplates created for specific Clusters in the Topology controller must be owned by a Cluster.
return HasOneOfExactOwners(owners, []metav1.OwnerReference{clusterOwner}, []metav1.OwnerReference{clusterClassOwner})
},
dockerClusterKind: func(owners []metav1.OwnerReference) error {
// DockerCluster must be owned and controlled by a Cluster.
return HasExactOwners(owners, clusterController)
},
dockerClusterTemplateKind: func(owners []metav1.OwnerReference) error {
// DockerClusterTemplate must be owned by a ClusterClass.
return HasExactOwners(owners, clusterClassOwner)
},
dockerMachinePoolKind: func(owners []metav1.OwnerReference) error {
// DockerMachinePool must be owned by a MachinePool.
return HasExactOwners(owners, machinePoolOwner)
},
}
func HasExactOwners(gotOwners []metav1.OwnerReference, wantOwners ...metav1.OwnerReference) error {
wantComparable := []string{}
gotComparable := []string{}
for _, ref := range gotOwners {
gotComparable = append(gotComparable, ownerReferenceString(ref))
}
for _, ref := range wantOwners {
wantComparable = append(wantComparable, ownerReferenceString(ref))
}
sort.Strings(gotComparable)
sort.Strings(wantComparable)
if !reflect.DeepEqual(gotComparable, wantComparable) {
return fmt.Errorf("wanted %v, actual %v", wantOwners, gotOwners)
}
return nil
}
func ownerReferenceString(ref metav1.OwnerReference) string {
controller := false
if ref.Controller != nil && *ref.Controller {
controller = true
}
return fmt.Sprintf("%s/%s/%v", ref.APIVersion, ref.Kind, controller)
}
// HasOneOfExactOwners is a convenience approach for checking owner references on objects that can have different owner references depending on the cluster.
// In a follow-up iteration we can make improvements to check owner references according to the specific use cases vs checking generically "oneOf".
func HasOneOfExactOwners(refList []metav1.OwnerReference, possibleOwners ...[]metav1.OwnerReference) error {
var allErrs []error
for _, wantOwner := range possibleOwners {
err := HasExactOwners(refList, wantOwner...)
if err != nil {
allErrs = append(allErrs, err)
continue
}
return nil
}
return kerrors.NewAggregate(allErrs)
}
func setClusterPause(ctx context.Context, cli client.Client, clusterKey types.NamespacedName, value bool) {
cluster := &clusterv1.Cluster{}
Expect(cli.Get(ctx, clusterKey, cluster)).To(Succeed())
pausePatch := client.RawPatch(types.MergePatchType, []byte(fmt.Sprintf("{\"spec\":{\"paused\":%v}}", value)))
Expect(cli.Patch(ctx, cluster, pausePatch)).To(Succeed())
}
// forceClusterClassReconcile force reconciliation of the ClusterClass associated with the Cluster if one exists. If the
// Cluster has no ClusterClass this is a no-op.
func forceClusterClassReconcile(ctx context.Context, cli client.Client, clusterKey types.NamespacedName) {
cluster := &clusterv1.Cluster{}
Expect(cli.Get(ctx, clusterKey, cluster)).To(Succeed())
if cluster.Spec.Topology != nil {
class := &clusterv1.ClusterClass{}
Expect(cli.Get(ctx, client.ObjectKey{Namespace: clusterKey.Namespace, Name: cluster.Spec.Topology.Class}, class)).To(Succeed())
annotationPatch := client.RawPatch(types.MergePatchType, []byte(fmt.Sprintf("{\"metadata\":{\"annotations\":{\"cluster.x-k8s.io/modifiedAt\":\"%v\"}}}", time.Now().Format(time.RFC3339))))
Expect(cli.Patch(ctx, class, annotationPatch)).To(Succeed())
}
}
// forceClusterResourceSetReconcile forces reconciliation of all ClusterResourceSets.
func forceClusterResourceSetReconcile(ctx context.Context, cli client.Client, namespace string) {
crsList := &addonsv1.ClusterResourceSetList{}
Expect(cli.List(ctx, crsList, client.InNamespace(namespace))).To(Succeed())
for _, crs := range crsList.Items {
annotationPatch := client.RawPatch(types.MergePatchType, []byte(fmt.Sprintf("{\"metadata\":{\"annotations\":{\"cluster.x-k8s.io/modifiedAt\":\"%v\"}}}", time.Now().Format(time.RFC3339))))
Expect(cli.Patch(ctx, crs.DeepCopy(), annotationPatch)).To(Succeed())
}
}
func changeOwnerReferencesAPIVersion(ctx context.Context, proxy ClusterProxy, namespace string) {
graph, err := clusterctlcluster.GetOwnerGraph(ctx, namespace, proxy.GetKubeconfigPath())
Expect(err).ToNot(HaveOccurred())
for _, object := range graph {
ref := object.Object
obj := new(unstructured.Unstructured)
obj.SetAPIVersion(ref.APIVersion)
obj.SetKind(ref.Kind)
obj.SetName(ref.Name)
Expect(proxy.GetClient().Get(ctx, client.ObjectKey{Namespace: namespace, Name: object.Object.Name}, obj)).To(Succeed())
helper, err := patch.NewHelper(obj, proxy.GetClient())
Expect(err).ToNot(HaveOccurred())
newOwners := []metav1.OwnerReference{}
for _, owner := range obj.GetOwnerReferences() {
gv, err := schema.ParseGroupVersion(owner.APIVersion)
Expect(err).To(Succeed())
gv.Version = "v1alpha1"
owner.APIVersion = gv.String()
newOwners = append(newOwners, owner)
}
obj.SetOwnerReferences(newOwners)
Expect(helper.Patch(ctx, obj)).To(Succeed())
}
}
func removeOwnerReferences(ctx context.Context, proxy ClusterProxy, namespace string) {
graph, err := clusterctlcluster.GetOwnerGraph(ctx, namespace, proxy.GetKubeconfigPath())
Expect(err).ToNot(HaveOccurred())
for _, object := range graph {
ref := object.Object
obj := new(unstructured.Unstructured)
obj.SetAPIVersion(ref.APIVersion)
obj.SetKind(ref.Kind)
obj.SetName(ref.Name)
Expect(proxy.GetClient().Get(ctx, client.ObjectKey{Namespace: namespace, Name: object.Object.Name}, obj)).To(Succeed())
helper, err := patch.NewHelper(obj, proxy.GetClient())
Expect(err).ToNot(HaveOccurred())
obj.SetOwnerReferences([]metav1.OwnerReference{})
Expect(helper.Patch(ctx, obj)).To(Succeed())
}
}