Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix goroutine leak in WatchSet.watchMany #128

Merged
merged 2 commits into from
Oct 20, 2022
Merged

Fix goroutine leak in WatchSet.watchMany #128

merged 2 commits into from
Oct 20, 2022

Conversation

mechpen
Copy link
Contributor

@mechpen mechpen commented Oct 17, 2022

No description provided.

@hashicorp-cla
Copy link

hashicorp-cla commented Oct 17, 2022

CLA assistant check
All committers have signed the CLA.

@kisunji
Copy link
Contributor

kisunji commented Oct 19, 2022

Thanks for this.

Would you be able to add a test confirming the behavior? This is what I used - you can feel free to copy-paste

func TestWatchCtxLeak(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// We add a large number of channels to a WatchSet then
	// call WatchCtx. If one of those channels fires, we
	// expect to see all the goroutines spawned by WatchCtx
	// cleaned up.
	pprof.Do(ctx, pprof.Labels("foo", "bar"), func(ctx context.Context) {
		ws := NewWatchSet()
		fireCh := make(chan struct{})
		ws.Add(fireCh)
		for i := 0; i < 10000; i++ {
			watchCh := make(chan struct{})
			ws.Add(watchCh)
		}
		result := make(chan error)
		go func() {
			result <- ws.WatchCtx(ctx)
		}()

		fireCh <- struct{}{}

		if err := <-result; err != nil {
			t.Fatalf("expected no err got: %v", err)
		}
	})

	numRetries := 3
	var gced bool
	for i := 0; i < numRetries; i++ {
		var pb bytes.Buffer
		profiler := pprof.Lookup("goroutine")
		if profiler == nil {
			t.Fatal("unable to find profile")
		}
		err := profiler.WriteTo(&pb, 1)
		if err != nil {
			t.Fatalf("unable to read profile: %v", err)
		}
		// If the debug profile dump contains the string "foo",
		// it means one of the goroutines spawned in pprof.Do above
		// still appears in the capture.
		if !strings.Contains(pb.String(), "foo") {
			gced = true
			break
		} else {
			t.Log("retrying")
			time.Sleep(1 * time.Second)
		}
	}
	if !gced {
		t.Errorf("goroutines were not garbage collected after %d retries", numRetries)
	}
}

@mechpen
Copy link
Contributor Author

mechpen commented Oct 19, 2022

Thank you @kisunji ! I copy/pasted in the test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants