Skip to content

Commit

Permalink
feat: make cleaner safe for concurrent use
Browse files Browse the repository at this point in the history
  • Loading branch information
pmalek committed Feb 10, 2023
1 parent 7d8bff7 commit 81921a0
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

- Fix calico manifests URL
[#555](https://github.com/Kong/kubernetes-testing-framework/pull/555)
- `clusters.Cleaner` can be used concurrently
[#552](https://github.com/Kong/kubernetes-testing-framework/pull/552)

## v0.28.1

Expand Down
10 changes: 10 additions & 0 deletions pkg/clusters/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"strings"
"sync"

"golang.org/x/sync/errgroup"
corev1 "k8s.io/api/core/v1"
Expand All @@ -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.
Expand All @@ -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
Expand Down
22 changes: 22 additions & 0 deletions pkg/clusters/cleanup_test.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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),
},
})
}()
}
}

0 comments on commit 81921a0

Please sign in to comment.