diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 6862fd62bd..f89800ca2f 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -113,6 +113,12 @@ type Options struct { // [1] https://pkg.go.dev/k8s.io/apimachinery/pkg/fields#Selector // [2] https://pkg.go.dev/k8s.io/apimachinery/pkg/fields#Set SelectorsByObject SelectorsByObject + + // UnsafeDisableDeepCopyByObject indicates not to deep copy objects during get or + // list objects per GVK at the specified object. + // Be very careful with this, when enabled you must DeepCopy any object before mutating it, + // otherwise you will mutate the object in the cache. + UnsafeDisableDeepCopyByObject DisableDeepCopyByObject } var defaultResyncTime = 10 * time.Hour @@ -127,7 +133,11 @@ func New(config *rest.Config, opts Options) (Cache, error) { if err != nil { return nil, err } - im := internal.NewInformersMap(config, opts.Scheme, opts.Mapper, *opts.Resync, opts.Namespace, selectorsByGVK) + disableDeepCopyByGVK, err := convertToDisableDeepCopyByGVK(opts.UnsafeDisableDeepCopyByObject, opts.Scheme) + if err != nil { + return nil, err + } + im := internal.NewInformersMap(config, opts.Scheme, opts.Mapper, *opts.Resync, opts.Namespace, selectorsByGVK, disableDeepCopyByGVK) return &informerCache{InformersMap: im}, nil } @@ -136,6 +146,8 @@ func New(config *rest.Config, opts Options) (Cache, error) { // SelectorsByObject // WARNING: if SelectorsByObject is specified. filtered out resources are not // returned. +// WARNING: if UnsafeDisableDeepCopy is enabled, you must DeepCopy any object +// returned from cache get/list before mutating it. func BuilderWithOptions(options Options) NewCacheFunc { return func(config *rest.Config, opts Options) (Cache, error) { if opts.Scheme == nil { @@ -151,6 +163,7 @@ func BuilderWithOptions(options Options) NewCacheFunc { opts.Namespace = options.Namespace } opts.SelectorsByObject = options.SelectorsByObject + opts.UnsafeDisableDeepCopyByObject = options.UnsafeDisableDeepCopyByObject return New(config, opts) } } @@ -189,3 +202,30 @@ func convertToSelectorsByGVK(selectorsByObject SelectorsByObject, scheme *runtim } return selectorsByGVK, nil } + +// DisableDeepCopyByObject associate a client.Object's GVK to disable DeepCopy during get or list from cache. +type DisableDeepCopyByObject map[client.Object]bool + +var _ client.Object = &ObjectAll{} + +// ObjectAll is the argument to represent all objects' types. +type ObjectAll struct { + client.Object +} + +func convertToDisableDeepCopyByGVK(disableDeepCopyByObject DisableDeepCopyByObject, scheme *runtime.Scheme) (internal.DisableDeepCopyByGVK, error) { + disableDeepCopyByGVK := internal.DisableDeepCopyByGVK{} + for obj, disable := range disableDeepCopyByObject { + switch obj.(type) { + case ObjectAll, *ObjectAll: + disableDeepCopyByGVK[internal.GroupVersionKindAll] = disable + default: + gvk, err := apiutil.GVKForObject(obj, scheme) + if err != nil { + return nil, err + } + disableDeepCopyByGVK[gvk] = disable + } + } + return disableDeepCopyByGVK, nil +} diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index b8df99ede1..9ae290636c 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -19,6 +19,8 @@ package cache_test import ( "context" "fmt" + "reflect" + "sort" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" @@ -83,13 +85,16 @@ func deletePod(pod client.Object) { } var _ = Describe("Informer Cache", func() { - CacheTest(cache.New) + CacheTest(cache.New, cache.Options{}) }) var _ = Describe("Multi-Namespace Informer Cache", func() { - CacheTest(cache.MultiNamespacedCacheBuilder([]string{testNamespaceOne, testNamespaceTwo, "default"})) + CacheTest(cache.MultiNamespacedCacheBuilder([]string{testNamespaceOne, testNamespaceTwo, "default"}), cache.Options{}) +}) +var _ = Describe("Informer Cache without DeepCopy", func() { + CacheTest(cache.New, cache.Options{UnsafeDisableDeepCopyByObject: cache.DisableDeepCopyByObject{cache.ObjectAll{}: true}}) }) -func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (cache.Cache, error)) { +func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (cache.Cache, error), opts cache.Options) { Describe("Cache test", func() { var ( informerCache cache.Cache @@ -139,7 +144,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca knownPod6.GetObjectKind().SetGroupVersionKind(podGVK) By("creating the informer cache") - informerCache, err = createCacheFunc(cfg, cache.Options{}) + 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 @@ -228,18 +233,20 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca } }) - 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"))) - } - }) + 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") @@ -255,21 +262,53 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca } }) - 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()) + 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("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("altering a field in the retrieved pod") + *out.Spec.ActiveDeadlineSeconds = 4 - By("verifying the pods are no longer equal") - Expect(out).NotTo(Equal(knownPod2)) - }) + 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(len(outList1.Items)).To(Equal(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") @@ -485,30 +524,66 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(namespacedCache.Get(context.Background(), key2, node)).To(Succeed()) }) - It("should deep copy the object unless told otherwise", func() { - By("retrieving a specific pod from the cache") - out := &unstructured.Unstructured{} - out.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "", - Version: "v1", - Kind: "Pod", + if !isPodDisableDeepCopy(opts) { + It("should deep copy the object unless told otherwise", func() { + By("retrieving a specific pod from the cache") + out := &unstructured.Unstructured{} + out.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "", + Version: "v1", + Kind: "Pod", + }) + uKnownPod2 := &unstructured.Unstructured{} + Expect(kscheme.Scheme.Convert(knownPod2, uKnownPod2, nil)).To(Succeed()) + + 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(uKnownPod2)) + + By("altering a field in the retrieved pod") + m, _ := out.Object["spec"].(map[string]interface{}) + m["activeDeadlineSeconds"] = 4 + + By("verifying the pods are no longer equal") + Expect(out).NotTo(Equal(knownPod2)) }) - uKnownPod2 := &unstructured.Unstructured{} - Expect(kscheme.Scheme.Convert(knownPod2, uKnownPod2, nil)).To(Succeed()) - - 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(uKnownPod2)) - - By("altering a field in the retrieved pod") - m, _ := out.Object["spec"].(map[string]interface{}) - m["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 := &unstructured.Unstructured{} + out1.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"}) + Expect(informerCache.Get(context.Background(), podKey, out1)).To(Succeed()) + out2 := &unstructured.Unstructured{} + out2.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "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.Object).Pointer()).To(BeIdenticalTo(reflect.ValueOf(out2.Object).Pointer())) + + By("listing pods from the cache twice") + outList1 := &unstructured.UnstructuredList{} + outList1.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PodList"}) + Expect(informerCache.List(context.Background(), outList1, client.InNamespace(testNamespaceOne))).To(Succeed()) + outList2 := &unstructured.UnstructuredList{} + outList2.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PodList"}) + Expect(informerCache.List(context.Background(), outList2, client.InNamespace(testNamespaceOne))).To(Succeed()) + + By("verifying the pointer fields in pod have the same addresses") + Expect(len(outList1.Items)).To(Equal(len(outList2.Items))) + sort.SliceStable(outList1.Items, func(i, j int) bool { return outList1.Items[i].GetName() <= outList1.Items[j].GetName() }) + sort.SliceStable(outList2.Items, func(i, j int) bool { return outList2.Items[i].GetName() <= outList2.Items[j].GetName() }) + for i := range outList1.Items { + a := &outList1.Items[i] + b := &outList2.Items[i] + Expect(a).To(Equal(b)) + Expect(reflect.ValueOf(a.Object).Pointer()).To(BeIdenticalTo(reflect.ValueOf(b.Object).Pointer())) + } + }) + } It("should return an error if the object is not found", func() { By("getting a service that does not exists") @@ -730,34 +805,71 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(namespacedCache.Get(context.Background(), key2, node)).To(Succeed()) }) - It("should deep copy the object unless told otherwise", func() { - By("retrieving a specific pod from the cache") - out := &metav1.PartialObjectMetadata{} - out.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "", - Version: "v1", - Kind: "Pod", + if !isPodDisableDeepCopy(opts) { + It("should deep copy the object unless told otherwise", func() { + By("retrieving a specific pod from the cache") + out := &metav1.PartialObjectMetadata{} + out.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "", + Version: "v1", + Kind: "Pod", + }) + uKnownPod2 := &metav1.PartialObjectMetadata{} + knownPod2.(*corev1.Pod).ObjectMeta.DeepCopyInto(&uKnownPod2.ObjectMeta) + uKnownPod2.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "", + Version: "v1", + Kind: "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(uKnownPod2)) + + By("altering a field in the retrieved pod") + out.Labels["foo"] = "bar" + + By("verifying the pods are no longer equal") + Expect(out).NotTo(Equal(knownPod2)) }) - uKnownPod2 := &metav1.PartialObjectMetadata{} - knownPod2.(*corev1.Pod).ObjectMeta.DeepCopyInto(&uKnownPod2.ObjectMeta) - uKnownPod2.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "", - Version: "v1", - Kind: "Pod", + } 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 := &metav1.PartialObjectMetadata{} + out1.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"}) + Expect(informerCache.Get(context.Background(), podKey, out1)).To(Succeed()) + out2 := &metav1.PartialObjectMetadata{} + out2.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"}) + Expect(informerCache.Get(context.Background(), podKey, out2)).To(Succeed()) + + By("verifying the pods have the same pointer addresses") + 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 := &metav1.PartialObjectMetadataList{} + outList1.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PodList"}) + Expect(informerCache.List(context.Background(), outList1, client.InNamespace(testNamespaceOne))).To(Succeed()) + outList2 := &metav1.PartialObjectMetadataList{} + outList2.SetGroupVersionKind(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PodList"}) + Expect(informerCache.List(context.Background(), outList2, client.InNamespace(testNamespaceOne))).To(Succeed()) + + By("verifying the pointer fields in pod have the same addresses") + Expect(len(outList1.Items)).To(Equal(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())) + } }) - - 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(uKnownPod2)) - - By("altering a field in the retrieved pod") - out.Labels["foo"] = "bar" - - By("verifying the pods are no longer equal") - Expect(out).NotTo(Equal(knownPod2)) - }) + } It("should return an error if the object is not found", func() { By("getting a service that does not exists") @@ -1319,3 +1431,14 @@ func isKubeService(svc metav1.Object) bool { // grumble grumble linters grumble grumble return svc.GetNamespace() == "default" && svc.GetName() == "kubernetes" } + +func isPodDisableDeepCopy(opts cache.Options) bool { + if d, ok := opts.UnsafeDisableDeepCopyByObject[&corev1.Pod{}]; ok { + return d + } else if d, ok = opts.UnsafeDisableDeepCopyByObject[cache.ObjectAll{}]; ok { + return d + } else if d, ok = opts.UnsafeDisableDeepCopyByObject[&cache.ObjectAll{}]; ok { + return d + } + return false +} diff --git a/pkg/cache/internal/cache_reader.go b/pkg/cache/internal/cache_reader.go index 95084821fe..b95af18d78 100644 --- a/pkg/cache/internal/cache_reader.go +++ b/pkg/cache/internal/cache_reader.go @@ -46,6 +46,11 @@ type CacheReader struct { // scopeName is the scope of the resource (namespaced or cluster-scoped). scopeName apimeta.RESTScopeName + + // disableDeepCopy indicates not to deep copy objects during get or list objects. + // Be very careful with this, when enabled you must DeepCopy any object before mutating it, + // otherwise you will mutate the object in the cache. + disableDeepCopy bool } // Get checks the indexer for the object and writes a copy of it if found. @@ -76,9 +81,13 @@ func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Ob return fmt.Errorf("cache contained %T, which is not an Object", obj) } - // deep copy to avoid mutating cache - // TODO(directxman12): revisit the decision to always deepcopy - obj = obj.(runtime.Object).DeepCopyObject() + if c.disableDeepCopy { + // skip deep copy which might be unsafe + // you must DeepCopy any object before mutating it outside + } else { + // deep copy to avoid mutating cache + obj = obj.(runtime.Object).DeepCopyObject() + } // Copy the value of the item in the cache to the returned value // TODO(directxman12): this is a terrible hack, pls fix (we should have deepcopyinto) @@ -88,7 +97,9 @@ func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Ob return fmt.Errorf("cache had type %s, but %s was asked for", objVal.Type(), outVal.Type()) } reflect.Indirect(outVal).Set(reflect.Indirect(objVal)) - out.GetObjectKind().SetGroupVersionKind(c.groupVersionKind) + if !c.disableDeepCopy { + out.GetObjectKind().SetGroupVersionKind(c.groupVersionKind) + } return nil } @@ -150,8 +161,15 @@ func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...cli } } - outObj := obj.DeepCopyObject() - outObj.GetObjectKind().SetGroupVersionKind(c.groupVersionKind) + var outObj runtime.Object + if c.disableDeepCopy { + // skip deep copy which might be unsafe + // you must DeepCopy any object before mutating it outside + outObj = obj + } else { + outObj = obj.DeepCopyObject() + outObj.GetObjectKind().SetGroupVersionKind(c.groupVersionKind) + } runtimeObjs = append(runtimeObjs, outObj) } return apimeta.SetList(out, runtimeObjs) diff --git a/pkg/cache/internal/deleg_map.go b/pkg/cache/internal/deleg_map.go index 841f1657eb..9bfc8463fd 100644 --- a/pkg/cache/internal/deleg_map.go +++ b/pkg/cache/internal/deleg_map.go @@ -51,11 +51,12 @@ func NewInformersMap(config *rest.Config, resync time.Duration, namespace string, selectors SelectorsByGVK, + disableDeepCopy DisableDeepCopyByGVK, ) *InformersMap { return &InformersMap{ - structured: newStructuredInformersMap(config, scheme, mapper, resync, namespace, selectors), - unstructured: newUnstructuredInformersMap(config, scheme, mapper, resync, namespace, selectors), - metadata: newMetadataInformersMap(config, scheme, mapper, resync, namespace, selectors), + structured: newStructuredInformersMap(config, scheme, mapper, resync, namespace, selectors, disableDeepCopy), + unstructured: newUnstructuredInformersMap(config, scheme, mapper, resync, namespace, selectors, disableDeepCopy), + metadata: newMetadataInformersMap(config, scheme, mapper, resync, namespace, selectors, disableDeepCopy), Scheme: scheme, } @@ -107,18 +108,18 @@ func (m *InformersMap) Get(ctx context.Context, gvk schema.GroupVersionKind, obj // newStructuredInformersMap creates a new InformersMap for structured objects. func newStructuredInformersMap(config *rest.Config, scheme *runtime.Scheme, mapper meta.RESTMapper, resync time.Duration, - namespace string, selectors SelectorsByGVK) *specificInformersMap { - return newSpecificInformersMap(config, scheme, mapper, resync, namespace, selectors, createStructuredListWatch) + namespace string, selectors SelectorsByGVK, disableDeepCopy DisableDeepCopyByGVK) *specificInformersMap { + return newSpecificInformersMap(config, scheme, mapper, resync, namespace, selectors, disableDeepCopy, createStructuredListWatch) } // newUnstructuredInformersMap creates a new InformersMap for unstructured objects. func newUnstructuredInformersMap(config *rest.Config, scheme *runtime.Scheme, mapper meta.RESTMapper, resync time.Duration, - namespace string, selectors SelectorsByGVK) *specificInformersMap { - return newSpecificInformersMap(config, scheme, mapper, resync, namespace, selectors, createUnstructuredListWatch) + namespace string, selectors SelectorsByGVK, disableDeepCopy DisableDeepCopyByGVK) *specificInformersMap { + return newSpecificInformersMap(config, scheme, mapper, resync, namespace, selectors, disableDeepCopy, createUnstructuredListWatch) } // newMetadataInformersMap creates a new InformersMap for metadata-only objects. func newMetadataInformersMap(config *rest.Config, scheme *runtime.Scheme, mapper meta.RESTMapper, resync time.Duration, - namespace string, selectors SelectorsByGVK) *specificInformersMap { - return newSpecificInformersMap(config, scheme, mapper, resync, namespace, selectors, createMetadataListWatch) + namespace string, selectors SelectorsByGVK, disableDeepCopy DisableDeepCopyByGVK) *specificInformersMap { + return newSpecificInformersMap(config, scheme, mapper, resync, namespace, selectors, disableDeepCopy, createMetadataListWatch) } diff --git a/pkg/cache/internal/disabledeepcopy.go b/pkg/cache/internal/disabledeepcopy.go new file mode 100644 index 0000000000..54bd7eec93 --- /dev/null +++ b/pkg/cache/internal/disabledeepcopy.go @@ -0,0 +1,35 @@ +/* +Copyright 2021 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 internal + +import "k8s.io/apimachinery/pkg/runtime/schema" + +// GroupVersionKindAll is the argument to represent all GroupVersionKind types. +var GroupVersionKindAll = schema.GroupVersionKind{} + +// DisableDeepCopyByGVK associate a GroupVersionKind to disable DeepCopy during get or list from cache. +type DisableDeepCopyByGVK map[schema.GroupVersionKind]bool + +// IsDisabled returns whether a GroupVersionKind is disabled DeepCopy. +func (disableByGVK DisableDeepCopyByGVK) IsDisabled(gvk schema.GroupVersionKind) bool { + if d, ok := disableByGVK[gvk]; ok { + return d + } else if d, ok = disableByGVK[GroupVersionKindAll]; ok { + return d + } + return false +} diff --git a/pkg/cache/internal/informers_map.go b/pkg/cache/internal/informers_map.go index 007a28e727..413b048f0c 100644 --- a/pkg/cache/internal/informers_map.go +++ b/pkg/cache/internal/informers_map.go @@ -52,6 +52,7 @@ func newSpecificInformersMap(config *rest.Config, resync time.Duration, namespace string, selectors SelectorsByGVK, + disableDeepCopy DisableDeepCopyByGVK, createListWatcher createListWatcherFunc) *specificInformersMap { ip := &specificInformersMap{ config: config, @@ -65,6 +66,7 @@ func newSpecificInformersMap(config *rest.Config, createListWatcher: createListWatcher, namespace: namespace, selectors: selectors, + disableDeepCopy: disableDeepCopy, } return ip } @@ -129,6 +131,9 @@ type specificInformersMap struct { // selectors are the label or field selectors that will be added to the // ListWatch ListOptions. selectors SelectorsByGVK + + // disableDeepCopy indicates not to deep copy objects during get or list objects. + disableDeepCopy DisableDeepCopyByGVK } // Start calls Run on each of the informers and sets started to true. Blocks on the context. @@ -234,7 +239,12 @@ func (ip *specificInformersMap) addInformerToMap(gvk schema.GroupVersionKind, ob i := &MapEntry{ Informer: ni, - Reader: CacheReader{indexer: ni.GetIndexer(), groupVersionKind: gvk, scopeName: rm.Scope.Name()}, + Reader: CacheReader{ + indexer: ni.GetIndexer(), + groupVersionKind: gvk, + scopeName: rm.Scope.Name(), + disableDeepCopy: ip.disableDeepCopy.IsDisabled(gvk), + }, } ip.informersByGVK[gvk] = i