-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
util.go
764 lines (669 loc) · 23.9 KB
/
util.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
/*
Copyright 2017 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 util implements utilities.
package util
import (
"context"
"encoding/json"
"fmt"
"math"
"math/rand"
"reflect"
"strings"
"time"
"github.com/blang/semver/v4"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/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/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
k8sversion "k8s.io/apimachinery/pkg/version"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/util/annotations"
"sigs.k8s.io/cluster-api/util/contract"
"sigs.k8s.io/cluster-api/util/labels/format"
)
const (
// CharSet defines the alphanumeric set for random string generation.
CharSet = "0123456789abcdefghijklmnopqrstuvwxyz"
)
var (
rnd = rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec
// ErrNoCluster is returned when the cluster
// label could not be found on the object passed in.
ErrNoCluster = fmt.Errorf("no %q label present", clusterv1.ClusterNameLabel)
// ErrUnstructuredFieldNotFound determines that a field
// in an unstructured object could not be found.
ErrUnstructuredFieldNotFound = fmt.Errorf("field not found")
)
// RandomString returns a random alphanumeric string.
func RandomString(n int) string {
result := make([]byte, n)
for i := range result {
result[i] = CharSet[rnd.Intn(len(CharSet))]
}
return string(result)
}
// Ordinalize takes an int and returns the ordinalized version of it.
// Eg. 1 --> 1st, 103 --> 103rd.
func Ordinalize(n int) string {
m := map[int]string{
0: "th",
1: "st",
2: "nd",
3: "rd",
4: "th",
5: "th",
6: "th",
7: "th",
8: "th",
9: "th",
}
an := int(math.Abs(float64(n)))
if an < 10 {
return fmt.Sprintf("%d%s", n, m[an])
}
return fmt.Sprintf("%d%s", n, m[an%10])
}
// IsExternalManagedControlPlane returns a bool indicating whether the control plane referenced
// in the passed Unstructured resource is an externally managed control plane such as AKS, EKS, GKE, etc.
func IsExternalManagedControlPlane(controlPlane *unstructured.Unstructured) bool {
managed, found, err := unstructured.NestedBool(controlPlane.Object, "status", "externalManagedControlPlane")
if err != nil || !found {
return false
}
return managed
}
// GetMachineIfExists gets a machine from the API server if it exists.
func GetMachineIfExists(ctx context.Context, c client.Client, namespace, name string) (*clusterv1.Machine, error) {
if c == nil {
// Being called before k8s is setup as part of control plane VM creation
return nil, nil
}
// Machines are identified by name
machine := &clusterv1.Machine{}
err := c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, machine)
if err != nil {
if apierrors.IsNotFound(err) {
return nil, nil
}
return nil, err
}
return machine, nil
}
// IsControlPlaneMachine checks machine is a control plane node.
func IsControlPlaneMachine(machine *clusterv1.Machine) bool {
_, ok := machine.ObjectMeta.Labels[clusterv1.MachineControlPlaneLabel]
return ok
}
// IsNodeReady returns true if a node is ready.
func IsNodeReady(node *corev1.Node) bool {
for _, condition := range node.Status.Conditions {
if condition.Type == corev1.NodeReady {
return condition.Status == corev1.ConditionTrue
}
}
return false
}
// GetClusterFromMetadata returns the Cluster object (if present) using the object metadata.
func GetClusterFromMetadata(ctx context.Context, c client.Client, obj metav1.ObjectMeta) (*clusterv1.Cluster, error) {
if obj.Labels[clusterv1.ClusterNameLabel] == "" {
return nil, errors.WithStack(ErrNoCluster)
}
return GetClusterByName(ctx, c, obj.Namespace, obj.Labels[clusterv1.ClusterNameLabel])
}
// GetOwnerCluster returns the Cluster object owning the current resource.
func GetOwnerCluster(ctx context.Context, c client.Client, obj metav1.ObjectMeta) (*clusterv1.Cluster, error) {
for _, ref := range obj.GetOwnerReferences() {
if ref.Kind != "Cluster" {
continue
}
gv, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
return nil, errors.WithStack(err)
}
if gv.Group == clusterv1.GroupVersion.Group {
return GetClusterByName(ctx, c, obj.Namespace, ref.Name)
}
}
return nil, nil
}
// GetClusterByName finds and return a Cluster object using the specified params.
func GetClusterByName(ctx context.Context, c client.Client, namespace, name string) (*clusterv1.Cluster, error) {
cluster := &clusterv1.Cluster{}
key := client.ObjectKey{
Namespace: namespace,
Name: name,
}
if err := c.Get(ctx, key, cluster); err != nil {
return nil, errors.Wrapf(err, "failed to get Cluster/%s", name)
}
return cluster, nil
}
// ObjectKey returns client.ObjectKey for the object.
func ObjectKey(object metav1.Object) client.ObjectKey {
return client.ObjectKey{
Namespace: object.GetNamespace(),
Name: object.GetName(),
}
}
// ClusterToInfrastructureMapFunc returns a handler.ToRequestsFunc that watches for
// Cluster events and returns reconciliation requests for an infrastructure provider object.
func ClusterToInfrastructureMapFunc(ctx context.Context, gvk schema.GroupVersionKind, c client.Client, providerCluster client.Object) handler.MapFunc {
log := ctrl.LoggerFrom(ctx)
return func(ctx context.Context, o client.Object) []reconcile.Request {
cluster, ok := o.(*clusterv1.Cluster)
if !ok {
return nil
}
// Return early if the InfrastructureRef is nil.
if cluster.Spec.InfrastructureRef == nil {
return nil
}
gk := gvk.GroupKind()
// Return early if the GroupKind doesn't match what we expect.
infraGK := cluster.Spec.InfrastructureRef.GroupVersionKind().GroupKind()
if gk != infraGK {
return nil
}
providerCluster := providerCluster.DeepCopyObject().(client.Object)
key := types.NamespacedName{Namespace: cluster.Namespace, Name: cluster.Spec.InfrastructureRef.Name}
if err := c.Get(ctx, key, providerCluster); err != nil {
log.V(4).Error(err, fmt.Sprintf("Failed to get %T", providerCluster))
return nil
}
if annotations.IsExternallyManaged(providerCluster) {
log.V(4).Info(fmt.Sprintf("%T is externally managed, skipping mapping", providerCluster))
return nil
}
return []reconcile.Request{
{
NamespacedName: client.ObjectKey{
Namespace: cluster.Namespace,
Name: cluster.Spec.InfrastructureRef.Name,
},
},
}
}
}
// GetOwnerMachine returns the Machine object owning the current resource.
func GetOwnerMachine(ctx context.Context, c client.Client, obj metav1.ObjectMeta) (*clusterv1.Machine, error) {
for _, ref := range obj.GetOwnerReferences() {
gv, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
return nil, err
}
if ref.Kind == "Machine" && gv.Group == clusterv1.GroupVersion.Group {
return GetMachineByName(ctx, c, obj.Namespace, ref.Name)
}
}
return nil, nil
}
// GetMachineByName finds and return a Machine object using the specified params.
func GetMachineByName(ctx context.Context, c client.Client, namespace, name string) (*clusterv1.Machine, error) {
m := &clusterv1.Machine{}
key := client.ObjectKey{Name: name, Namespace: namespace}
if err := c.Get(ctx, key, m); err != nil {
return nil, err
}
return m, nil
}
// MachineToInfrastructureMapFunc returns a handler.ToRequestsFunc that watches for
// Machine events and returns reconciliation requests for an infrastructure provider object.
func MachineToInfrastructureMapFunc(gvk schema.GroupVersionKind) handler.MapFunc {
return func(_ context.Context, o client.Object) []reconcile.Request {
m, ok := o.(*clusterv1.Machine)
if !ok {
return nil
}
gk := gvk.GroupKind()
// Return early if the GroupKind doesn't match what we expect.
infraGK := m.Spec.InfrastructureRef.GroupVersionKind().GroupKind()
if gk != infraGK {
return nil
}
return []reconcile.Request{
{
NamespacedName: client.ObjectKey{
Namespace: m.Namespace,
Name: m.Spec.InfrastructureRef.Name,
},
},
}
}
}
// HasOwnerRef returns true if the OwnerReference is already in the slice. It matches based on Group, Kind and Name.
func HasOwnerRef(ownerReferences []metav1.OwnerReference, ref metav1.OwnerReference) bool {
return indexOwnerRef(ownerReferences, ref) > -1
}
// EnsureOwnerRef makes sure the slice contains the OwnerReference.
// Note: EnsureOwnerRef will update the version of the OwnerReference fi it exists with a different version. It will also update the UID.
func EnsureOwnerRef(ownerReferences []metav1.OwnerReference, ref metav1.OwnerReference) []metav1.OwnerReference {
idx := indexOwnerRef(ownerReferences, ref)
if idx == -1 {
return append(ownerReferences, ref)
}
ownerReferences[idx] = ref
return ownerReferences
}
// ReplaceOwnerRef re-parents an object from one OwnerReference to another
// It compares strictly based on UID to avoid reparenting across an intentional deletion: if an object is deleted
// and re-created with the same name and namespace, the only way to tell there was an in-progress deletion
// is by comparing the UIDs.
func ReplaceOwnerRef(ownerReferences []metav1.OwnerReference, source metav1.Object, target metav1.OwnerReference) []metav1.OwnerReference {
fi := -1
for index, r := range ownerReferences {
if r.UID == source.GetUID() {
fi = index
ownerReferences[index] = target
break
}
}
if fi < 0 {
ownerReferences = append(ownerReferences, target)
}
return ownerReferences
}
// RemoveOwnerRef returns the slice of owner references after removing the supplied owner ref.
// Note: RemoveOwnerRef ignores apiVersion and UID. It will remove the passed ownerReference where it matches Name, Group and Kind.
func RemoveOwnerRef(ownerReferences []metav1.OwnerReference, inputRef metav1.OwnerReference) []metav1.OwnerReference {
if index := indexOwnerRef(ownerReferences, inputRef); index != -1 {
return append(ownerReferences[:index], ownerReferences[index+1:]...)
}
return ownerReferences
}
// indexOwnerRef returns the index of the owner reference in the slice if found, or -1.
func indexOwnerRef(ownerReferences []metav1.OwnerReference, ref metav1.OwnerReference) int {
for index, r := range ownerReferences {
if referSameObject(r, ref) {
return index
}
}
return -1
}
// IsOwnedByObject returns true if any of the owner references point to the given target.
// It matches the object based on the Group, Kind and Name.
func IsOwnedByObject(obj metav1.Object, target client.Object) bool {
for _, ref := range obj.GetOwnerReferences() {
if refersTo(&ref, target) {
return true
}
}
return false
}
// IsControlledBy differs from metav1.IsControlledBy. This function matches on Group, Kind and Name. The metav1.IsControlledBy function matches on UID only.
func IsControlledBy(obj metav1.Object, owner client.Object) bool {
controllerRef := metav1.GetControllerOfNoCopy(obj)
if controllerRef == nil {
return false
}
return refersTo(controllerRef, owner)
}
// Returns true if a and b point to the same object based on Group, Kind and Name.
func referSameObject(a, b metav1.OwnerReference) bool {
aGV, err := schema.ParseGroupVersion(a.APIVersion)
if err != nil {
return false
}
bGV, err := schema.ParseGroupVersion(b.APIVersion)
if err != nil {
return false
}
return aGV.Group == bGV.Group && a.Kind == b.Kind && a.Name == b.Name
}
// Returns true if ref refers to obj based on Group, Kind and Name.
func refersTo(ref *metav1.OwnerReference, obj client.Object) bool {
refGv, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
return false
}
gvk := obj.GetObjectKind().GroupVersionKind()
return refGv.Group == gvk.Group && ref.Kind == gvk.Kind && ref.Name == obj.GetName()
}
// UnstructuredUnmarshalField is a wrapper around json and unstructured objects to decode and copy a specific field
// value into an object.
func UnstructuredUnmarshalField(obj *unstructured.Unstructured, v interface{}, fields ...string) error {
if obj == nil || obj.Object == nil {
return errors.Errorf("failed to unmarshal unstructured object: object is nil")
}
value, found, err := unstructured.NestedFieldNoCopy(obj.Object, fields...)
if err != nil {
return errors.Wrapf(err, "failed to retrieve field %q from %q", strings.Join(fields, "."), obj.GroupVersionKind())
}
if !found || value == nil {
return ErrUnstructuredFieldNotFound
}
valueBytes, err := json.Marshal(value)
if err != nil {
return errors.Wrapf(err, "failed to json-encode field %q value from %q", strings.Join(fields, "."), obj.GroupVersionKind())
}
if err := json.Unmarshal(valueBytes, v); err != nil {
return errors.Wrapf(err, "failed to json-decode field %q value from %q", strings.Join(fields, "."), obj.GroupVersionKind())
}
return nil
}
// HasOwner checks if any of the references in the passed list match the given group from apiVersion and one of the given kinds.
func HasOwner(refList []metav1.OwnerReference, apiVersion string, kinds []string) bool {
gv, err := schema.ParseGroupVersion(apiVersion)
if err != nil {
return false
}
kindMap := make(map[string]bool)
for _, kind := range kinds {
kindMap[kind] = true
}
for _, mr := range refList {
mrGroupVersion, err := schema.ParseGroupVersion(mr.APIVersion)
if err != nil {
return false
}
if mrGroupVersion.Group == gv.Group && kindMap[mr.Kind] {
return true
}
}
return false
}
// GetGVKMetadata retrieves a CustomResourceDefinition metadata from the API server using partial object metadata.
//
// This function is greatly more efficient than GetCRDWithContract and should be preferred in most cases.
func GetGVKMetadata(ctx context.Context, c client.Client, gvk schema.GroupVersionKind) (*metav1.PartialObjectMetadata, error) {
meta := &metav1.PartialObjectMetadata{}
meta.SetName(contract.CalculateCRDName(gvk.Group, gvk.Kind))
meta.SetGroupVersionKind(apiextensionsv1.SchemeGroupVersion.WithKind("CustomResourceDefinition"))
if err := c.Get(ctx, client.ObjectKeyFromObject(meta), meta); err != nil {
return meta, errors.Wrap(err, "failed to retrieve metadata from GVK resource")
}
return meta, nil
}
// KubeAwareAPIVersions is a sortable slice of kube-like version strings.
//
// Kube-like version strings are starting with a v, followed by a major version,
// optional "alpha" or "beta" strings followed by a minor version (e.g. v1, v2beta1).
// Versions will be sorted based on GA/alpha/beta first and then major and minor
// versions. e.g. v2, v1, v1beta2, v1beta1, v1alpha1.
type KubeAwareAPIVersions []string
func (k KubeAwareAPIVersions) Len() int { return len(k) }
func (k KubeAwareAPIVersions) Swap(i, j int) { k[i], k[j] = k[j], k[i] }
func (k KubeAwareAPIVersions) Less(i, j int) bool {
return k8sversion.CompareKubeAwareVersionStrings(k[i], k[j]) < 0
}
// ClusterToTypedObjectsMapper returns a mapper function that gets a cluster and lists all objects for the object passed in
// and returns a list of requests.
// Note: This function uses the passed in typed ObjectList and thus with the default client configuration all list calls
// will be cached.
// NB: The objects are required to have `clusterv1.ClusterNameLabel` applied.
func ClusterToTypedObjectsMapper(c client.Client, ro client.ObjectList, scheme *runtime.Scheme) (handler.MapFunc, error) {
gvk, err := apiutil.GVKForObject(ro, scheme)
if err != nil {
return nil, err
}
// Note: we create the typed ObjectList once here, so we don't have to use
// reflection in every execution of the actual event handler.
obj, err := scheme.New(gvk)
if err != nil {
return nil, errors.Wrapf(err, "failed to construct object of type %s", gvk)
}
objectList, ok := obj.(client.ObjectList)
if !ok {
return nil, errors.Errorf("expected object to be a client.ObjectList, is actually %T", obj)
}
isNamespaced, err := isAPINamespaced(gvk, c.RESTMapper())
if err != nil {
return nil, err
}
return func(ctx context.Context, o client.Object) []ctrl.Request {
cluster, ok := o.(*clusterv1.Cluster)
if !ok {
return nil
}
listOpts := []client.ListOption{
client.MatchingLabels{
clusterv1.ClusterNameLabel: cluster.Name,
},
}
if isNamespaced {
listOpts = append(listOpts, client.InNamespace(cluster.Namespace))
}
objectList = objectList.DeepCopyObject().(client.ObjectList)
if err := c.List(ctx, objectList, listOpts...); err != nil {
return nil
}
objects, err := meta.ExtractList(objectList)
if err != nil {
return nil
}
results := []ctrl.Request{}
for _, obj := range objects {
// Note: We don't check if the type cast succeeds as all items in an client.ObjectList
// are client.Objects.
o := obj.(client.Object)
results = append(results, ctrl.Request{
NamespacedName: client.ObjectKey{Namespace: o.GetNamespace(), Name: o.GetName()},
})
}
return results
}, nil
}
// MachineDeploymentToObjectsMapper returns a mapper function that gets a machinedeployment
// and lists all objects for the object passed in and returns a list of requests.
// NB: The objects are required to have `clusterv1.MachineDeploymentNameLabel` applied.
func MachineDeploymentToObjectsMapper(c client.Client, ro client.ObjectList, scheme *runtime.Scheme) (handler.MapFunc, error) {
gvk, err := apiutil.GVKForObject(ro, scheme)
if err != nil {
return nil, err
}
// Note: we create the typed ObjectList once here, so we don't have to use
// reflection in every execution of the actual event handler.
obj, err := scheme.New(gvk)
if err != nil {
return nil, errors.Wrapf(err, "failed to construct object of type %s", gvk)
}
objectList, ok := obj.(client.ObjectList)
if !ok {
return nil, errors.Errorf("expected object to be a client.ObjectList, is actually %T", obj)
}
isNamespaced, err := isAPINamespaced(gvk, c.RESTMapper())
if err != nil {
return nil, err
}
return func(ctx context.Context, o client.Object) []ctrl.Request {
md, ok := o.(*clusterv1.MachineDeployment)
if !ok {
return nil
}
listOpts := []client.ListOption{
client.MatchingLabels{
clusterv1.MachineDeploymentNameLabel: md.Name,
},
}
if isNamespaced {
listOpts = append(listOpts, client.InNamespace(md.Namespace))
}
objectList = objectList.DeepCopyObject().(client.ObjectList)
if err := c.List(ctx, objectList, listOpts...); err != nil {
return nil
}
objects, err := meta.ExtractList(objectList)
if err != nil {
return nil
}
results := []ctrl.Request{}
for _, obj := range objects {
// Note: We don't check if the type cast succeeds as all items in an client.ObjectList
// are client.Objects.
o := obj.(client.Object)
results = append(results, ctrl.Request{
NamespacedName: client.ObjectKey{Namespace: o.GetNamespace(), Name: o.GetName()},
})
}
return results
}, nil
}
// MachineSetToObjectsMapper returns a mapper function that gets a machineset
// and lists all objects for the object passed in and returns a list of requests.
// NB: The objects are required to have `clusterv1.MachineSetNameLabel` applied.
func MachineSetToObjectsMapper(c client.Client, ro client.ObjectList, scheme *runtime.Scheme) (handler.MapFunc, error) {
gvk, err := apiutil.GVKForObject(ro, scheme)
if err != nil {
return nil, err
}
// Note: we create the typed ObjectList once here, so we don't have to use
// reflection in every execution of the actual event handler.
obj, err := scheme.New(gvk)
if err != nil {
return nil, errors.Wrapf(err, "failed to construct object of type %s", gvk)
}
objectList, ok := obj.(client.ObjectList)
if !ok {
return nil, errors.Errorf("expected object to be a client.ObjectList, is actually %T", obj)
}
isNamespaced, err := isAPINamespaced(gvk, c.RESTMapper())
if err != nil {
return nil, err
}
return func(ctx context.Context, o client.Object) []ctrl.Request {
ms, ok := o.(*clusterv1.MachineSet)
if !ok {
return nil
}
listOpts := []client.ListOption{
client.MatchingLabels{
clusterv1.MachineSetNameLabel: format.MustFormatValue(ms.Name),
},
}
if isNamespaced {
listOpts = append(listOpts, client.InNamespace(ms.Namespace))
}
objectList = objectList.DeepCopyObject().(client.ObjectList)
if err := c.List(ctx, objectList, listOpts...); err != nil {
return nil
}
objects, err := meta.ExtractList(objectList)
if err != nil {
return nil
}
results := []ctrl.Request{}
for _, obj := range objects {
// Note: We don't check if the type cast succeeds as all items in an client.ObjectList
// are client.Objects.
o := obj.(client.Object)
results = append(results, ctrl.Request{
NamespacedName: client.ObjectKey{Namespace: o.GetNamespace(), Name: o.GetName()},
})
}
return results
}, nil
}
// isAPINamespaced detects if a GroupVersionKind is namespaced.
func isAPINamespaced(gk schema.GroupVersionKind, restmapper meta.RESTMapper) (bool, error) {
restMapping, err := restmapper.RESTMapping(schema.GroupKind{Group: gk.Group, Kind: gk.Kind})
if err != nil {
return false, fmt.Errorf("failed to get restmapping: %w", err)
}
switch restMapping.Scope.Name() {
case "":
return false, errors.New("Scope cannot be identified. Empty scope returned")
case meta.RESTScopeNameRoot:
return false, nil
default:
return true, nil
}
}
// ObjectReferenceToUnstructured converts an object reference to an unstructured object.
func ObjectReferenceToUnstructured(in corev1.ObjectReference) *unstructured.Unstructured {
out := &unstructured.Unstructured{}
out.SetKind(in.Kind)
out.SetAPIVersion(in.APIVersion)
out.SetNamespace(in.Namespace)
out.SetName(in.Name)
return out
}
// IsSupportedVersionSkew will return true if a and b are no more than one minor version off from each other.
func IsSupportedVersionSkew(a, b semver.Version) bool {
if a.Major != b.Major {
return false
}
if a.Minor > b.Minor {
return a.Minor-b.Minor == 1
}
return b.Minor-a.Minor <= 1
}
// LowestNonZeroResult compares two reconciliation results
// and returns the one with lowest requeue time.
func LowestNonZeroResult(i, j ctrl.Result) ctrl.Result {
switch {
case i.IsZero():
return j
case j.IsZero():
return i
case i.Requeue:
return i
case j.Requeue:
return j
case i.RequeueAfter < j.RequeueAfter:
return i
default:
return j
}
}
// LowestNonZeroInt32 returns the lowest non-zero value of the two provided values.
func LowestNonZeroInt32(i, j int32) int32 {
if i == 0 {
return j
}
if j == 0 {
return i
}
if i < j {
return i
}
return j
}
// IsNil returns an error if the passed interface is equal to nil or if it has an interface value of nil.
func IsNil(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Ptr, reflect.Map, reflect.Chan, reflect.Slice, reflect.Interface, reflect.UnsafePointer, reflect.Func:
return reflect.ValueOf(i).IsValid() && reflect.ValueOf(i).IsNil()
}
return false
}
// MergeMap merges maps.
// NOTE: In case a key exists in multiple maps, the value of the first map is preserved.
func MergeMap(maps ...map[string]string) map[string]string {
m := make(map[string]string)
for i := len(maps) - 1; i >= 0; i-- {
for k, v := range maps[i] {
m[k] = v
}
}
// Nil the result if the map is empty, thus avoiding triggering infinite reconcile
// given that at json level label: {} or annotation: {} is different from no field, which is the
// corresponding value stored in etcd given that those fields are defined as omitempty.
if len(m) == 0 {
return nil
}
return m
}