Skip to content

Commit

Permalink
:sparkling: Add TransformStripManagedFields
Browse files Browse the repository at this point in the history
This change adds `TransformStripManagedFields` to the Cache, a
transform func that strips off all managed fields for objects. There are
no known issues when using this as a `DefaultTransform` unless there is
explicit code to access objects `ManagedFields` and can lead to a
significant reduction in memory usage.
  • Loading branch information
alvaroaleman committed Apr 21, 2024
1 parent a92b961 commit 01dce5f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pkg/cache/cache.go
Expand Up @@ -344,6 +344,19 @@ func New(cfg *rest.Config, opts Options) (Cache, error) {
return delegating, nil
}

// TransformStripManagedFields strips the managed fields of an object before it is committed to the cache.
// If you are not explicitly accessing managedFields from your code, setting this as `DefaultTransform`
// on the cache can lead to a significant reduction in memory usage.
func TransformStripManagedFields() toolscache.TransformFunc {
return func(in any) (any, error) {
if obj, ok := in.(metav1.Object); ok {
obj.SetManagedFields(nil)
}

return in, nil
}
}

func optionDefaultsToConfig(opts *Options) Config {
return Config{
LabelSelector: opts.DefaultLabelSelector,
Expand Down
19 changes: 19 additions & 0 deletions pkg/cache/cache_test.go
Expand Up @@ -2421,6 +2421,25 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca
})
}

var _ = Describe("TransformStripManagedFields", func() {
It("should strip managed fields from an object", func() {
obj := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{
ManagedFields: []metav1.ManagedFieldsEntry{{
Manager: "foo",
}},
}}
transformed, err := cache.TransformStripManagedFields()(obj)
Expect(err).NotTo(HaveOccurred())
Expect(transformed).To(Equal(&corev1.Pod{ObjectMeta: metav1.ObjectMeta{}}))
})

It("should not trip over an unexpected object", func() {
transformed, err := cache.TransformStripManagedFields()("foo")
Expect(err).NotTo(HaveOccurred())
Expect(transformed).To(Equal("foo"))
})
})

// ensureNamespace installs namespace of a given name if not exists.
func ensureNamespace(namespace string, client client.Client) error {
ns := corev1.Namespace{
Expand Down

0 comments on commit 01dce5f

Please sign in to comment.