-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathcache_test.go
2558 lines (2304 loc) · 93.8 KB
/
cache_test.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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2018 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 cache_test
import (
"context"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
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/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
kscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
kcache "k8s.io/client-go/tools/cache"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllertest"
)
const testNodeOne = "test-node-1"
const testNodeTwo = "test-node-2"
const testNamespaceOne = "test-namespace-1"
const testNamespaceTwo = "test-namespace-2"
const testNamespaceThree = "test-namespace-3"
// TODO(community): Pull these helper functions into testenv.
// Restart policy is included to allow indexing on that field.
func createPodWithLabels(name, namespace string, restartPolicy corev1.RestartPolicy, labels map[string]string) client.Object {
three := int64(3)
if labels == nil {
labels = map[string]string{}
}
labels["test-label"] = name
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
Labels: labels,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{{Name: "nginx", Image: "nginx"}},
RestartPolicy: restartPolicy,
ActiveDeadlineSeconds: &three,
},
}
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
err = cl.Create(context.Background(), pod)
Expect(err).NotTo(HaveOccurred())
return pod
}
func createSvc(name, namespace string, cl client.Client) client.Object {
svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{{Port: 1}},
},
}
err := cl.Create(context.Background(), svc)
Expect(err).NotTo(HaveOccurred())
return svc
}
func createSA(name, namespace string, cl client.Client) client.Object {
sa := &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
}
err := cl.Create(context.Background(), sa)
Expect(err).NotTo(HaveOccurred())
return sa
}
func createPod(name, namespace string, restartPolicy corev1.RestartPolicy) client.Object {
return createPodWithLabels(name, namespace, restartPolicy, nil)
}
func deletePod(pod client.Object) {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
err = cl.Delete(context.Background(), pod)
Expect(err).NotTo(HaveOccurred())
}
var _ = Describe("Informer Cache", func() {
CacheTest(cache.New, cache.Options{})
NonBlockingGetTest(cache.New, cache.Options{})
})
var _ = Describe("Informer Cache with ReaderFailOnMissingInformer", func() {
CacheTestReaderFailOnMissingInformer(cache.New, cache.Options{ReaderFailOnMissingInformer: true})
})
var _ = Describe("Multi-Namespace Informer Cache", func() {
CacheTest(cache.New, cache.Options{
DefaultNamespaces: map[string]cache.Config{
cache.AllNamespaces: {FieldSelector: fields.OneTermEqualSelector("metadata.namespace", testNamespaceOne)},
testNamespaceTwo: {},
"default": {},
},
})
NonBlockingGetTest(cache.New, cache.Options{
DefaultNamespaces: map[string]cache.Config{
cache.AllNamespaces: {FieldSelector: fields.OneTermEqualSelector("metadata.namespace", testNamespaceOne)},
testNamespaceTwo: {},
"default": {},
},
})
})
var _ = Describe("Informer Cache without global DeepCopy", func() {
CacheTest(cache.New, cache.Options{
DefaultUnsafeDisableDeepCopy: ptr.To(true),
})
NonBlockingGetTest(cache.New, cache.Options{
DefaultUnsafeDisableDeepCopy: ptr.To(true),
})
})
var _ = Describe("Cache with transformers", func() {
var (
informerCache cache.Cache
informerCacheCtx context.Context
informerCacheCancel context.CancelFunc
knownPod1 client.Object
knownPod2 client.Object
knownPod3 client.Object
knownPod4 client.Object
knownPod5 client.Object
knownPod6 client.Object
)
getTransformValue := func(obj client.Object) string {
accessor, err := meta.Accessor(obj)
if err == nil {
annotations := accessor.GetAnnotations()
if val, exists := annotations["transformed"]; exists {
return val
}
}
return ""
}
BeforeEach(func() {
informerCacheCtx, informerCacheCancel = context.WithCancel(context.Background())
Expect(cfg).NotTo(BeNil())
By("creating three pods")
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
err = ensureNode(testNodeOne, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceOne, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceTwo, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceThree, cl)
Expect(err).NotTo(HaveOccurred())
// Includes restart policy since these objects are indexed on this field.
knownPod1 = createPod("test-pod-1", testNamespaceOne, corev1.RestartPolicyNever)
knownPod2 = createPod("test-pod-2", testNamespaceTwo, corev1.RestartPolicyAlways)
knownPod3 = createPodWithLabels("test-pod-3", testNamespaceTwo, corev1.RestartPolicyOnFailure, map[string]string{"common-label": "common"})
knownPod4 = createPodWithLabels("test-pod-4", testNamespaceThree, corev1.RestartPolicyNever, map[string]string{"common-label": "common"})
knownPod5 = createPod("test-pod-5", testNamespaceOne, corev1.RestartPolicyNever)
knownPod6 = createPod("test-pod-6", testNamespaceTwo, corev1.RestartPolicyAlways)
podGVK := schema.GroupVersionKind{
Kind: "Pod",
Version: "v1",
}
knownPod1.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod2.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod3.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod4.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod5.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod6.GetObjectKind().SetGroupVersionKind(podGVK)
By("creating the informer cache")
informerCache, err = cache.New(cfg, cache.Options{
DefaultTransform: func(i interface{}) (interface{}, error) {
obj := i.(runtime.Object)
Expect(obj).NotTo(BeNil())
accessor, err := meta.Accessor(obj)
Expect(err).ToNot(HaveOccurred())
annotations := accessor.GetAnnotations()
if _, exists := annotations["transformed"]; exists {
// Avoid performing transformation multiple times.
return i, nil
}
if annotations == nil {
annotations = make(map[string]string)
}
annotations["transformed"] = "default"
accessor.SetAnnotations(annotations)
return i, nil
},
ByObject: map[client.Object]cache.ByObject{
&corev1.Pod{}: {
Transform: func(i interface{}) (interface{}, error) {
obj := i.(runtime.Object)
Expect(obj).NotTo(BeNil())
accessor, err := meta.Accessor(obj)
Expect(err).ToNot(HaveOccurred())
annotations := accessor.GetAnnotations()
if _, exists := annotations["transformed"]; exists {
// Avoid performing transformation multiple times.
return i, nil
}
if annotations == nil {
annotations = make(map[string]string)
}
annotations["transformed"] = "explicit"
accessor.SetAnnotations(annotations)
return i, nil
},
},
},
})
Expect(err).NotTo(HaveOccurred())
By("running the cache and waiting for it to sync")
// pass as an arg so that we don't race between close and re-assign
go func(ctx context.Context) {
defer GinkgoRecover()
Expect(informerCache.Start(ctx)).To(Succeed())
}(informerCacheCtx)
Expect(informerCache.WaitForCacheSync(informerCacheCtx)).To(BeTrue())
})
AfterEach(func() {
By("cleaning up created pods")
deletePod(knownPod1)
deletePod(knownPod2)
deletePod(knownPod3)
deletePod(knownPod4)
deletePod(knownPod5)
deletePod(knownPod6)
informerCacheCancel()
})
Context("with structured objects", func() {
It("should apply transformers to explicitly specified GVKS", func() {
By("listing pods")
out := corev1.PodList{}
Expect(informerCache.List(context.Background(), &out)).To(Succeed())
By("verifying that the returned pods were transformed")
for i := 0; i < len(out.Items); i++ {
Expect(getTransformValue(&out.Items[i])).To(BeIdenticalTo("explicit"))
}
})
It("should apply default transformer to objects when none is specified", func() {
By("getting the Kubernetes service")
svc := &corev1.Service{}
svcKey := client.ObjectKey{Namespace: "default", Name: "kubernetes"}
Expect(informerCache.Get(context.Background(), svcKey, svc)).To(Succeed())
By("verifying that the returned service was transformed")
Expect(getTransformValue(svc)).To(BeIdenticalTo("default"))
})
})
Context("with unstructured objects", func() {
It("should apply transformers to explicitly specified GVKS", func() {
By("listing pods")
out := unstructured.UnstructuredList{}
out.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "PodList",
})
Expect(informerCache.List(context.Background(), &out)).To(Succeed())
By("verifying that the returned pods were transformed")
for i := 0; i < len(out.Items); i++ {
Expect(getTransformValue(&out.Items[i])).To(BeIdenticalTo("explicit"))
}
})
It("should apply default transformer to objects when none is specified", func() {
By("getting the Kubernetes service")
svc := &unstructured.Unstructured{}
svc.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "Service",
})
svcKey := client.ObjectKey{Namespace: "default", Name: "kubernetes"}
Expect(informerCache.Get(context.Background(), svcKey, svc)).To(Succeed())
By("verifying that the returned service was transformed")
Expect(getTransformValue(svc)).To(BeIdenticalTo("default"))
})
})
Context("with metadata-only objects", func() {
It("should apply transformers to explicitly specified GVKS", func() {
By("listing pods")
out := metav1.PartialObjectMetadataList{}
out.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "PodList",
})
Expect(informerCache.List(context.Background(), &out)).To(Succeed())
By("verifying that the returned pods were transformed")
for i := 0; i < len(out.Items); i++ {
Expect(getTransformValue(&out.Items[i])).To(BeIdenticalTo("explicit"))
}
})
It("should apply default transformer to objects when none is specified", func() {
By("getting the Kubernetes service")
svc := &metav1.PartialObjectMetadata{}
svc.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "Service",
})
svcKey := client.ObjectKey{Namespace: "default", Name: "kubernetes"}
Expect(informerCache.Get(context.Background(), svcKey, svc)).To(Succeed())
By("verifying that the returned service was transformed")
Expect(getTransformValue(svc)).To(BeIdenticalTo("default"))
})
})
})
var _ = Describe("Cache with selectors", func() {
defer GinkgoRecover()
var (
informerCache cache.Cache
informerCacheCtx context.Context
informerCacheCancel context.CancelFunc
)
BeforeEach(func() {
informerCacheCtx, informerCacheCancel = context.WithCancel(context.Background())
Expect(cfg).NotTo(BeNil())
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceOne, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceTwo, cl)
Expect(err).NotTo(HaveOccurred())
for idx, namespace := range []string{testNamespaceOne, testNamespaceTwo} {
_ = createSA("test-sa-"+strconv.Itoa(idx), namespace, cl)
_ = createSvc("test-svc-"+strconv.Itoa(idx), namespace, cl)
}
opts := cache.Options{
DefaultFieldSelector: fields.OneTermEqualSelector("metadata.namespace", testNamespaceTwo),
ByObject: map[client.Object]cache.ByObject{
&corev1.ServiceAccount{}: {
Field: fields.OneTermEqualSelector("metadata.namespace", testNamespaceOne),
},
},
}
By("creating the informer cache")
informerCache, err = cache.New(cfg, opts)
Expect(err).NotTo(HaveOccurred())
By("running the cache and waiting for it to sync")
// pass as an arg so that we don't race between close and re-assign
go func(ctx context.Context) {
defer GinkgoRecover()
Expect(informerCache.Start(ctx)).To(Succeed())
}(informerCacheCtx)
Expect(informerCache.WaitForCacheSync(informerCacheCtx)).To(BeTrue())
})
AfterEach(func() {
ctx := context.Background()
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
for idx, namespace := range []string{testNamespaceOne, testNamespaceTwo} {
err = cl.Delete(ctx, &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: "test-sa-" + strconv.Itoa(idx)}})
Expect(err).NotTo(HaveOccurred())
err = cl.Delete(ctx, &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: "test-svc-" + strconv.Itoa(idx)}})
Expect(err).NotTo(HaveOccurred())
}
informerCacheCancel()
})
It("Should list serviceaccounts and find exactly one in namespace "+testNamespaceOne, func() {
var sas corev1.ServiceAccountList
err := informerCache.List(informerCacheCtx, &sas)
Expect(err).NotTo(HaveOccurred())
Expect(sas.Items).To(HaveLen(1))
Expect(sas.Items[0].Namespace).To(Equal(testNamespaceOne))
})
It("Should list services and find exactly one in namespace "+testNamespaceTwo, func() {
var svcs corev1.ServiceList
err := informerCache.List(informerCacheCtx, &svcs)
Expect(err).NotTo(HaveOccurred())
Expect(svcs.Items).To(HaveLen(1))
Expect(svcs.Items[0].Namespace).To(Equal(testNamespaceTwo))
})
})
func CacheTestReaderFailOnMissingInformer(createCacheFunc func(config *rest.Config, opts cache.Options) (cache.Cache, error), opts cache.Options) {
Describe("Cache test with ReaderFailOnMissingInformer = true", func() {
var (
informerCache cache.Cache
informerCacheCtx context.Context
informerCacheCancel context.CancelFunc
errNotCached *cache.ErrResourceNotCached
)
BeforeEach(func() {
informerCacheCtx, informerCacheCancel = context.WithCancel(context.Background())
Expect(cfg).NotTo(BeNil())
By("creating the informer cache")
var err error
informerCache, err = createCacheFunc(cfg, opts)
Expect(err).NotTo(HaveOccurred())
By("running the cache and waiting for it to sync")
// pass as an arg so that we don't race between close and re-assign
go func(ctx context.Context) {
defer GinkgoRecover()
Expect(informerCache.Start(ctx)).To(Succeed())
}(informerCacheCtx)
Expect(informerCache.WaitForCacheSync(informerCacheCtx)).To(BeTrue())
})
AfterEach(func() {
informerCacheCancel()
})
Describe("as a Reader", func() {
Context("with structured objects", func() {
It("should not be able to list objects that haven't been watched previously", func() {
By("listing all services in the cluster")
listObj := &corev1.ServiceList{}
Expect(errors.As(informerCache.List(context.Background(), listObj), &errNotCached)).To(BeTrue())
})
It("should not be able to get objects that haven't been watched previously", func() {
By("getting the Kubernetes service")
svc := &corev1.Service{}
svcKey := client.ObjectKey{Namespace: "default", Name: "kubernetes"}
Expect(errors.As(informerCache.Get(context.Background(), svcKey, svc), &errNotCached)).To(BeTrue())
})
It("should be able to list objects that are configured to be watched", func() {
By("indicating that we need to watch services")
_, err := informerCache.GetInformer(context.Background(), &corev1.Service{})
Expect(err).ToNot(HaveOccurred())
By("listing all services in the cluster")
svcList := &corev1.ServiceList{}
Expect(informerCache.List(context.Background(), svcList)).To(Succeed())
By("verifying that the returned service looks reasonable")
Expect(svcList.Items).To(HaveLen(1))
Expect(svcList.Items[0].Name).To(Equal("kubernetes"))
Expect(svcList.Items[0].Namespace).To(Equal("default"))
})
It("should be able to get objects that are configured to be watched", func() {
By("indicating that we need to watch services")
_, err := informerCache.GetInformer(context.Background(), &corev1.Service{})
Expect(err).ToNot(HaveOccurred())
By("getting the Kubernetes service")
svc := &corev1.Service{}
svcKey := client.ObjectKey{Namespace: "default", Name: "kubernetes"}
Expect(informerCache.Get(context.Background(), svcKey, svc)).To(Succeed())
By("verifying that the returned service looks reasonable")
Expect(svc.Name).To(Equal("kubernetes"))
Expect(svc.Namespace).To(Equal("default"))
})
})
})
})
}
func NonBlockingGetTest(createCacheFunc func(config *rest.Config, opts cache.Options) (cache.Cache, error), opts cache.Options) {
Describe("non-blocking get test", func() {
var (
informerCache cache.Cache
informerCacheCtx context.Context
informerCacheCancel context.CancelFunc
)
BeforeEach(func() {
informerCacheCtx, informerCacheCancel = context.WithCancel(context.Background())
Expect(cfg).NotTo(BeNil())
By("creating expected namespaces")
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
err = ensureNode(testNodeOne, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceOne, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceTwo, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceThree, cl)
Expect(err).NotTo(HaveOccurred())
By("creating the informer cache")
opts.NewInformer = func(_ kcache.ListerWatcher, _ runtime.Object, _ time.Duration, _ kcache.Indexers) kcache.SharedIndexInformer {
return &controllertest.FakeInformer{Synced: false}
}
informerCache, err = createCacheFunc(cfg, opts)
Expect(err).NotTo(HaveOccurred())
By("running the cache and waiting for it to sync")
// pass as an arg so that we don't race between close and re-assign
go func(ctx context.Context) {
defer GinkgoRecover()
Expect(informerCache.Start(ctx)).To(Succeed())
}(informerCacheCtx)
Expect(informerCache.WaitForCacheSync(informerCacheCtx)).To(BeTrue())
})
AfterEach(func() {
By("cleaning up created pods")
informerCacheCancel()
})
Describe("as an Informer", func() {
It("should be able to get informer for the object without blocking", func() {
By("getting a shared index informer for a pod")
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "informer-obj",
Namespace: "default",
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "nginx",
Image: "nginx",
},
},
},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
sii, err := informerCache.GetInformer(ctx, pod, cache.BlockUntilSynced(false))
Expect(err).NotTo(HaveOccurred())
Expect(sii).NotTo(BeNil())
Expect(sii.HasSynced()).To(BeFalse())
})
})
})
}
func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (cache.Cache, error), opts cache.Options) {
Describe("Cache test", func() {
var (
informerCache cache.Cache
informerCacheCtx context.Context
informerCacheCancel context.CancelFunc
knownPod1 client.Object
knownPod2 client.Object
knownPod3 client.Object
knownPod4 client.Object
knownPod5 client.Object
knownPod6 client.Object
)
BeforeEach(func() {
informerCacheCtx, informerCacheCancel = context.WithCancel(context.Background())
Expect(cfg).NotTo(BeNil())
By("creating three pods")
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
err = ensureNode(testNodeOne, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNode(testNodeTwo, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceOne, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceTwo, cl)
Expect(err).NotTo(HaveOccurred())
err = ensureNamespace(testNamespaceThree, cl)
Expect(err).NotTo(HaveOccurred())
// Includes restart policy since these objects are indexed on this field.
knownPod1 = createPod("test-pod-1", testNamespaceOne, corev1.RestartPolicyNever)
knownPod2 = createPod("test-pod-2", testNamespaceTwo, corev1.RestartPolicyAlways)
knownPod3 = createPodWithLabels("test-pod-3", testNamespaceTwo, corev1.RestartPolicyOnFailure, map[string]string{"common-label": "common"})
knownPod4 = createPodWithLabels("test-pod-4", testNamespaceThree, corev1.RestartPolicyNever, map[string]string{"common-label": "common"})
knownPod5 = createPod("test-pod-5", testNamespaceOne, corev1.RestartPolicyNever)
knownPod6 = createPod("test-pod-6", testNamespaceTwo, corev1.RestartPolicyAlways)
podGVK := schema.GroupVersionKind{
Kind: "Pod",
Version: "v1",
}
knownPod1.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod2.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod3.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod4.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod5.GetObjectKind().SetGroupVersionKind(podGVK)
knownPod6.GetObjectKind().SetGroupVersionKind(podGVK)
By("creating the informer cache")
informerCache, err = createCacheFunc(cfg, opts)
Expect(err).NotTo(HaveOccurred())
By("running the cache and waiting for it to sync")
// pass as an arg so that we don't race between close and re-assign
go func(ctx context.Context) {
defer GinkgoRecover()
Expect(informerCache.Start(ctx)).To(Succeed())
}(informerCacheCtx)
Expect(informerCache.WaitForCacheSync(informerCacheCtx)).To(BeTrue())
})
AfterEach(func() {
By("cleaning up created pods")
deletePod(knownPod1)
deletePod(knownPod2)
deletePod(knownPod3)
deletePod(knownPod4)
deletePod(knownPod5)
deletePod(knownPod6)
informerCacheCancel()
})
Describe("as a Reader", func() {
Context("with structured objects", func() {
It("should be able to list objects that haven't been watched previously", func() {
By("listing all services in the cluster")
listObj := &corev1.ServiceList{}
Expect(informerCache.List(context.Background(), listObj)).To(Succeed())
By("verifying that the returned list contains the Kubernetes service")
// NB: kubernetes default service is automatically created in testenv.
Expect(listObj.Items).NotTo(BeEmpty())
hasKubeService := false
for i := range listObj.Items {
svc := &listObj.Items[i]
if isKubeService(svc) {
hasKubeService = true
break
}
}
Expect(hasKubeService).To(BeTrue())
})
It("should be able to get objects that haven't been watched previously", func() {
By("getting the Kubernetes service")
svc := &corev1.Service{}
svcKey := client.ObjectKey{Namespace: "default", Name: "kubernetes"}
Expect(informerCache.Get(context.Background(), svcKey, svc)).To(Succeed())
By("verifying that the returned service looks reasonable")
Expect(svc.Name).To(Equal("kubernetes"))
Expect(svc.Namespace).To(Equal("default"))
})
It("should support filtering by labels in a single namespace", func() {
By("listing pods with a particular label")
// NB: each pod has a "test-label": <pod-name>
out := corev1.PodList{}
Expect(informerCache.List(context.Background(), &out,
client.InNamespace(testNamespaceTwo),
client.MatchingLabels(map[string]string{"test-label": "test-pod-2"}))).To(Succeed())
By("verifying the returned pods have the correct label")
Expect(out.Items).NotTo(BeEmpty())
Expect(out.Items).Should(HaveLen(1))
actual := out.Items[0]
Expect(actual.Labels["test-label"]).To(Equal("test-pod-2"))
})
It("should support filtering by labels from multiple namespaces", func() {
By("creating another pod with the same label but different namespace")
anotherPod := createPod("test-pod-2", testNamespaceOne, corev1.RestartPolicyAlways)
defer deletePod(anotherPod)
By("listing pods with a particular label")
// NB: each pod has a "test-label": <pod-name>
out := corev1.PodList{}
labels := map[string]string{"test-label": "test-pod-2"}
Expect(informerCache.List(context.Background(), &out, client.MatchingLabels(labels))).To(Succeed())
By("verifying multiple pods with the same label in different namespaces are returned")
Expect(out.Items).NotTo(BeEmpty())
Expect(out.Items).Should(HaveLen(2))
for _, actual := range out.Items {
Expect(actual.Labels["test-label"]).To(Equal("test-pod-2"))
}
})
if !isPodDisableDeepCopy(opts) {
It("should be able to list objects with GVK populated", func() {
By("listing pods")
out := &corev1.PodList{}
Expect(informerCache.List(context.Background(), out)).To(Succeed())
By("verifying that the returned pods have GVK populated")
Expect(out.Items).NotTo(BeEmpty())
Expect(out.Items).Should(SatisfyAny(HaveLen(5), HaveLen(6)))
for _, p := range out.Items {
Expect(p.GroupVersionKind()).To(Equal(corev1.SchemeGroupVersion.WithKind("Pod")))
}
})
}
It("should be able to list objects by namespace", func() {
By("listing pods in test-namespace-1")
listObj := &corev1.PodList{}
Expect(informerCache.List(context.Background(), listObj,
client.InNamespace(testNamespaceOne))).To(Succeed())
By("verifying that the returned pods are in test-namespace-1")
Expect(listObj.Items).NotTo(BeEmpty())
Expect(listObj.Items).Should(HaveLen(2))
for _, item := range listObj.Items {
Expect(item.Namespace).To(Equal(testNamespaceOne))
}
})
if !isPodDisableDeepCopy(opts) {
It("should deep copy the object unless told otherwise", func() {
By("retrieving a specific pod from the cache")
out := &corev1.Pod{}
podKey := client.ObjectKey{Name: "test-pod-2", Namespace: testNamespaceTwo}
Expect(informerCache.Get(context.Background(), podKey, out)).To(Succeed())
By("verifying the retrieved pod is equal to a known pod")
Expect(out).To(Equal(knownPod2))
By("altering a field in the retrieved pod")
*out.Spec.ActiveDeadlineSeconds = 4
By("verifying the pods are no longer equal")
Expect(out).NotTo(Equal(knownPod2))
})
} else {
It("should not deep copy the object if UnsafeDisableDeepCopy is enabled", func() {
By("getting a specific pod from the cache twice")
podKey := client.ObjectKey{Name: "test-pod-2", Namespace: testNamespaceTwo}
out1 := &corev1.Pod{}
Expect(informerCache.Get(context.Background(), podKey, out1)).To(Succeed())
out2 := &corev1.Pod{}
Expect(informerCache.Get(context.Background(), podKey, out2)).To(Succeed())
By("verifying the pointer fields in pod have the same addresses")
Expect(out1).To(Equal(out2))
Expect(reflect.ValueOf(out1.Labels).Pointer()).To(BeIdenticalTo(reflect.ValueOf(out2.Labels).Pointer()))
By("listing pods from the cache twice")
outList1 := &corev1.PodList{}
Expect(informerCache.List(context.Background(), outList1, client.InNamespace(testNamespaceOne))).To(Succeed())
outList2 := &corev1.PodList{}
Expect(informerCache.List(context.Background(), outList2, client.InNamespace(testNamespaceOne))).To(Succeed())
By("verifying the pointer fields in pod have the same addresses")
Expect(outList1.Items).To(HaveLen(len(outList2.Items)))
sort.SliceStable(outList1.Items, func(i, j int) bool { return outList1.Items[i].Name <= outList1.Items[j].Name })
sort.SliceStable(outList2.Items, func(i, j int) bool { return outList2.Items[i].Name <= outList2.Items[j].Name })
for i := range outList1.Items {
a := &outList1.Items[i]
b := &outList2.Items[i]
Expect(a).To(Equal(b))
Expect(reflect.ValueOf(a.Labels).Pointer()).To(BeIdenticalTo(reflect.ValueOf(b.Labels).Pointer()))
}
})
}
It("should return an error if the object is not found", func() {
By("getting a service that does not exists")
svc := &corev1.Service{}
svcKey := client.ObjectKey{Namespace: testNamespaceOne, Name: "unknown"}
By("verifying that an error is returned")
err := informerCache.Get(context.Background(), svcKey, svc)
Expect(err).To(HaveOccurred())
Expect(apierrors.IsNotFound(err)).To(BeTrue())
})
It("should return an error if getting object in unwatched namespace", func() {
By("getting a service that does not exists")
svc := &corev1.Service{}
svcKey := client.ObjectKey{Namespace: "unknown", Name: "unknown"}
By("verifying that an error is returned")
err := informerCache.Get(context.Background(), svcKey, svc)
Expect(err).To(HaveOccurred())
})
It("should return an error when context is cancelled", func() {
By("cancelling the context")
informerCacheCancel()
By("listing pods in test-namespace-1 with a cancelled context")
listObj := &corev1.PodList{}
err := informerCache.List(informerCacheCtx, listObj, client.InNamespace(testNamespaceOne))
By("verifying that an error is returned")
Expect(err).To(HaveOccurred())
Expect(apierrors.IsTimeout(err)).To(BeTrue())
})
It("should set the Limit option and limit number of objects to Limit when List is called", func() {
opts := &client.ListOptions{Limit: int64(3)}
By("verifying that only Limit (3) number of objects are retrieved from the cache")
listObj := &corev1.PodList{}
Expect(informerCache.List(context.Background(), listObj, opts)).To(Succeed())
Expect(listObj.Items).Should(HaveLen(3))
})
It("should return a limited result set matching the correct label", func() {
listObj := &corev1.PodList{}
labelOpt := client.MatchingLabels(map[string]string{"common-label": "common"})
limitOpt := client.Limit(1)
By("verifying that only Limit (1) number of objects are retrieved from the cache")
Expect(informerCache.List(context.Background(), listObj, labelOpt, limitOpt)).To(Succeed())
Expect(listObj.Items).Should(HaveLen(1))
})
It("should return an error if pagination is used", func() {
listObj := &corev1.PodList{}
By("verifying that the first list works and returns a sentinel continue")
err := informerCache.List(context.Background(), listObj)
Expect(err).ToNot(HaveOccurred())
Expect(listObj.Continue).To(Equal("continue-not-supported"))
By("verifying that an error is returned")
err = informerCache.List(context.Background(), listObj, client.Continue(listObj.Continue))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("continue list option is not supported by the cache"))
})
It("should return an error if the continue list options is set", func() {
listObj := &corev1.PodList{}
continueOpt := client.Continue("token")
By("verifying that an error is returned")
err := informerCache.List(context.Background(), listObj, continueOpt)
Expect(err).To(HaveOccurred())
})
})
Context("with unstructured objects", func() {
It("should be able to list objects that haven't been watched previously", func() {
By("listing all services in the cluster")
listObj := &unstructured.UnstructuredList{}
listObj.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "ServiceList",
})
err := informerCache.List(context.Background(), listObj)
Expect(err).To(Succeed())
By("verifying that the returned list contains the Kubernetes service")
// NB: kubernetes default service is automatically created in testenv.
Expect(listObj.Items).NotTo(BeEmpty())
hasKubeService := false
for i := range listObj.Items {
svc := &listObj.Items[i]
if isKubeService(svc) {
hasKubeService = true
break
}
}
Expect(hasKubeService).To(BeTrue())
})
It("should be able to get objects that haven't been watched previously", func() {
By("getting the Kubernetes service")
svc := &unstructured.Unstructured{}
svc.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "Service",
})
svcKey := client.ObjectKey{Namespace: "default", Name: "kubernetes"}
Expect(informerCache.Get(context.Background(), svcKey, svc)).To(Succeed())
By("verifying that the returned service looks reasonable")
Expect(svc.GetName()).To(Equal("kubernetes"))
Expect(svc.GetNamespace()).To(Equal("default"))
})
It("should support filtering by labels in a single namespace", func() {
By("listing pods with a particular label")
// NB: each pod has a "test-label": <pod-name>
out := unstructured.UnstructuredList{}
out.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "PodList",
})
err := informerCache.List(context.Background(), &out,
client.InNamespace(testNamespaceTwo),
client.MatchingLabels(map[string]string{"test-label": "test-pod-2"}))
Expect(err).To(Succeed())
By("verifying the returned pods have the correct label")
Expect(out.Items).NotTo(BeEmpty())
Expect(out.Items).Should(HaveLen(1))
actual := out.Items[0]
Expect(actual.GetLabels()["test-label"]).To(Equal("test-pod-2"))
})
It("should support filtering by labels from multiple namespaces", func() {
By("creating another pod with the same label but different namespace")
anotherPod := createPod("test-pod-2", testNamespaceOne, corev1.RestartPolicyAlways)
defer deletePod(anotherPod)
By("listing pods with a particular label")
// NB: each pod has a "test-label": <pod-name>
out := unstructured.UnstructuredList{}
out.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "PodList",
})
labels := map[string]string{"test-label": "test-pod-2"}
err := informerCache.List(context.Background(), &out, client.MatchingLabels(labels))
Expect(err).To(Succeed())
By("verifying multiple pods with the same label in different namespaces are returned")
Expect(out.Items).NotTo(BeEmpty())
Expect(out.Items).Should(HaveLen(2))
for _, actual := range out.Items {
Expect(actual.GetLabels()["test-label"]).To(Equal("test-pod-2"))
}
})
It("should be able to list objects by namespace", func() {
By("listing pods in test-namespace-1")
listObj := &unstructured.UnstructuredList{}
listObj.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "PodList",
})
err := informerCache.List(context.Background(), listObj, client.InNamespace(testNamespaceOne))
Expect(err).To(Succeed())
By("verifying that the returned pods are in test-namespace-1")
Expect(listObj.Items).NotTo(BeEmpty())
Expect(listObj.Items).Should(HaveLen(2))
for _, item := range listObj.Items {
Expect(item.GetNamespace()).To(Equal(testNamespaceOne))
}
})
cacheRestrictSubTests := []struct {
nameSuffix string
cacheOpts cache.Options
}{
{
nameSuffix: "by using the per-gvk setting",
cacheOpts: cache.Options{
ByObject: map[client.Object]cache.ByObject{
&corev1.Pod{}: {