From c39f492f4f9b336ef99fb6cff681e772b9117401 Mon Sep 17 00:00:00 2001 From: scott Date: Fri, 20 May 2022 17:38:26 +0800 Subject: [PATCH] fix audit union loop variables in closures Kubernetes-commit: b24dfdee1e081afbda716b2ab66377cfcc260eb0 --- pkg/audit/union.go | 1 + pkg/audit/union_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/pkg/audit/union.go b/pkg/audit/union.go index 39dd74f74..0766a9207 100644 --- a/pkg/audit/union.go +++ b/pkg/audit/union.go @@ -48,6 +48,7 @@ func (u union) ProcessEvents(events ...*auditinternal.Event) bool { func (u union) Run(stopCh <-chan struct{}) error { var funcs []func() error for _, backend := range u.backends { + backend := backend funcs = append(funcs, func() error { return backend.Run(stopCh) }) diff --git a/pkg/audit/union_test.go b/pkg/audit/union_test.go index 4ab1de0c8..3db253a27 100644 --- a/pkg/audit/union_test.go +++ b/pkg/audit/union_test.go @@ -80,3 +80,36 @@ func TestUnion(t *testing.T) { } } } + +type cannotMultipleRunBackend struct { + started chan struct{} +} + +func (b *cannotMultipleRunBackend) ProcessEvents(events ...*auditinternal.Event) bool { + return true +} + +func (b *cannotMultipleRunBackend) Run(stopCh <-chan struct{}) error { + close(b.started) + return nil +} + +func (b *cannotMultipleRunBackend) Shutdown() {} + +func (b *cannotMultipleRunBackend) String() string { + return "cannotMultipleRunBackend" +} + +func TestUnionRun(t *testing.T) { + backends := []Backend{ + &cannotMultipleRunBackend{started: make(chan struct{})}, + &cannotMultipleRunBackend{started: make(chan struct{})}, + &cannotMultipleRunBackend{started: make(chan struct{})}, + } + + b := Union(backends...) + + if err := b.Run(make(chan struct{})); err != nil { + t.Errorf("union backend run: %v", err) + } +}