Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
fix(sources): stop UnitHook Close racing in-flight Finish sends (#5154)
Bill Richa0fc8c812ac0
diff --git a/pkg/sources/job_progress_hook.go b/pkg/sources/job_progress_hook.goindex 6f94feff2..973f2b76e 100644--- a/pkg/sources/job_progress_hook.go+++ b/pkg/sources/job_progress_hook.go@@ -17,6 +17,13 @@ type UnitHook struct {mu sync.MutexfinishedMetrics chan UnitMetricslogBackPressure func()+ // closeMu, closed, done, and inflight coordinate Close with in-flight+ // ejectFinishedMetrics sends from still-running job goroutines, so+ // finishedMetrics is never closed while a send is possible.+ closeMu sync.Mutex+ closed bool+ done chan struct{}+ inflight sync.WaitGroupNoopHook}@@ -36,6 +43,7 @@ func NewUnitHook(ctx context.Context, opts ...UnitHookOpt) (*UnitHook, <-chan Unhook := UnitHook{metrics: make(map[string]*UnitMetrics, runtime.NumCPU()),finishedMetrics: make(chan UnitMetrics, 1024),+ done: make(chan struct{}),logBackPressure: func() {once.Do(func() {ctx.Logger().Info("back pressure detected in unit hook")@@ -71,6 +79,17 @@ func (u *UnitHook) id(ref JobProgressRef, unit SourceUnit) string {}func (u *UnitHook) ejectFinishedMetrics(metrics UnitMetrics) {+ // Register as an in-flight sender so Close waits for us before closing+ // the channel; metrics arriving after Close are dropped.+ u.closeMu.Lock()+ if u.closed {+ u.closeMu.Unlock()+ return+ }+ u.inflight.Add(1)+ u.closeMu.Unlock()+ defer u.inflight.Done()+// Intentionally block the hook from returning to supply back-pressure// to the source.select {@@ -79,7 +98,12 @@ func (u *UnitHook) ejectFinishedMetrics(metrics UnitMetrics) {default:u.logBackPressure()}- u.finishedMetrics <- metrics+ select {+ case u.finishedMetrics <- metrics:+ case <-u.done:+ // Close was called with no consumer draining the channel; drop the+ // metrics rather than block Close forever.+ }}func (u *UnitHook) StartUnitChunking(ref JobProgressRef, unit SourceUnit, start time.Time) {@@ -189,6 +213,19 @@ func (u *UnitHook) InProgressSnapshot() []UnitMetrics {}func (u *UnitHook) Close() error {+ u.closeMu.Lock()+ if u.closed {+ u.closeMu.Unlock()+ return nil+ }+ u.closed = true+ close(u.done)+ u.closeMu.Unlock()++ // Wait for in-flight sends before closing the channel; a send on a+ // closed channel is a panic, and job goroutines can still be finishing+ // units when Close is called.+ u.inflight.Wait()close(u.finishedMetrics)return nil}diff --git a/pkg/sources/source_manager.go b/pkg/sources/source_manager.goindex 5b5078b2b..283c57327 100644--- a/pkg/sources/source_manager.go+++ b/pkg/sources/source_manager.go@@ -150,10 +150,12 @@ func (s *SourceManager) EnumerateAndScan(ctx context.Context, sourceName string,}s.wg.Add(1)go func() {- // Call Finish after the semaphore has been released.+ // Call Finish after the semaphore has been released, and release+ // the WaitGroup only after Finish's hooks have run: Wait() closes+ // the hooks, so it must not return while a hook can still fire.+ defer s.wg.Done()defer progress.Finish()defer sem.Release(1)- defer s.wg.Done()ctx := context.WithValues(ctx,"source_manager_worker_id", common.RandomID(5),)@@ -198,9 +200,11 @@ func (s *SourceManager) Enumerate(ctx context.Context, sourceName string, sources.wg.Add(1)go func() {- // Call Finish after the semaphore has been released.- defer progress.Finish()+ // Release the WaitGroup only after Finish's hooks have run: Wait()+ // closes the hooks, so it must not return while a hook can still+ // fire.defer s.wg.Done()+ defer progress.Finish()ctx := context.WithValues(ctx,"source_manager_worker_id", common.RandomID(5),)@@ -240,10 +244,12 @@ func (s *SourceManager) Scan(ctx context.Context, sourceName string, source Sour}s.wg.Add(1)go func() {- // Call Finish after the semaphore has been released.+ // Call Finish after the semaphore has been released, and release+ // the WaitGroup only after Finish's hooks have run: Wait() closes+ // the hooks, so it must not return while a hook can still fire.+ defer s.wg.Done()defer progress.Finish()defer s.sem.Release(1)- defer s.wg.Done()ctx := context.WithValues(ctx,"source_manager_worker_id", common.RandomID(5),)diff --git a/pkg/sources/source_manager_test.go b/pkg/sources/source_manager_test.goindex 3cbfc025d..c01b6803e 100644--- a/pkg/sources/source_manager_test.go+++ b/pkg/sources/source_manager_test.go@@ -4,6 +4,7 @@ import ("errors""fmt""sort"+ "sync""testing""time"@@ -511,3 +512,33 @@ func TestSourceManagerUnitHookNoUnits(t *testing.T) {assert.NotZero(t, m.ElapsedTime())assert.Equal(t, 0, len(m.Errors))}++// TestUnitHookCloseConcurrentWithFinish tests that Close does not panic with+// "send on closed channel" when job goroutines are still ejecting finished+// metrics. Close must wait for in-flight sends and drop metrics that arrive+// after it.+func TestUnitHookCloseConcurrentWithFinish(t *testing.T) {+ hook, ch := NewUnitHook(context.TODO())++ // Drain the channel until Close closes it.+ drained := make(chan struct{})+ go func() {+ defer close(drained)+ for range ch {+ }+ }()++ var wg sync.WaitGroup+ for i := 0; i < 100; i++ {+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ ref := JobProgressRef{SourceID: SourceID(i), JobID: JobID(i)}+ hook.StartUnitChunking(ref, nil, time.Now())+ hook.Finish(ref)+ }(i)+ }+ assert.NoError(t, hook.Close())+ wg.Wait()+ <-drained+}