From 33d6b7a269715f294e15ae0d9415915926a34e64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patryk=20Ma=C5=82ek?= Date: Fri, 10 Feb 2023 13:27:57 +0100 Subject: [PATCH] feat: make cleaner safe for concurrent use --- CHANGELOG.md | 5 +++++ pkg/clusters/cleanup.go | 10 ++++++++++ pkg/clusters/cleanup_test.go | 22 ++++++++++++++++++++++ 3 files changed, 37 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b31c3e80..babc3e7c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## Unreleased + +- `clusters.Cleaner` can be used concurrently + [#552](https://github.com/Kong/kubernetes-testing-framework/pull/552) + ## v0.28.1 - Fix command error handling when error is `nil` diff --git a/pkg/clusters/cleanup.go b/pkg/clusters/cleanup.go index 001170d26..d9b364145 100644 --- a/pkg/clusters/cleanup.go +++ b/pkg/clusters/cleanup.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "strings" + "sync" "golang.org/x/sync/errgroup" corev1 "k8s.io/api/core/v1" @@ -28,6 +29,7 @@ type Cleaner struct { objects []client.Object manifests []string namespaces []*corev1.Namespace + lock sync.RWMutex } // NewCleaner provides a new initialized *Cleaner object. @@ -40,18 +42,26 @@ func NewCleaner(cluster Cluster) *Cleaner { // ----------------------------------------------------------------------------- func (c *Cleaner) Add(obj client.Object) { + c.lock.Lock() + defer c.lock.Unlock() c.objects = append([]client.Object{obj}, c.objects...) } func (c *Cleaner) AddManifest(manifest string) { + c.lock.Lock() + defer c.lock.Unlock() c.manifests = append(c.manifests, manifest) } func (c *Cleaner) AddNamespace(namespace *corev1.Namespace) { + c.lock.Lock() + defer c.lock.Unlock() c.namespaces = append(c.namespaces, namespace) } func (c *Cleaner) Cleanup(ctx context.Context) error { + c.lock.RLock() + defer c.lock.RUnlock() dyn, err := dynamic.NewForConfig(c.cluster.Config()) if err != nil { return err diff --git a/pkg/clusters/cleanup_test.go b/pkg/clusters/cleanup_test.go index 6d5e0ab70..045ce9eb7 100644 --- a/pkg/clusters/cleanup_test.go +++ b/pkg/clusters/cleanup_test.go @@ -1,9 +1,11 @@ package clusters import ( + "fmt" "testing" "github.com/stretchr/testify/assert" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client" @@ -119,3 +121,23 @@ func TestFixupObjKinds(t *testing.T) { }) } } + +func TestCleanerCanBeUsedConcurrently(t *testing.T) { + cleaner := NewCleaner(nil) + for i := 0; i < 100; i++ { + i := i + go func() { + cleaner.Add(&v1.Pod{}) + }() + go func() { + cleaner.AddManifest(fmt.Sprintf("manifest-%d.yaml", i)) + }() + go func() { + cleaner.AddNamespace(&v1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("ns-%d", i), + }, + }) + }() + } +}