2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-04-29 03:56:11 +01:00
|
|
|
package tstest
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"runtime"
|
|
|
|
"runtime/pprof"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/google/go-cmp/cmp"
|
|
|
|
)
|
|
|
|
|
2023-10-07 02:54:59 +01:00
|
|
|
// ResourceCheck takes a snapshot of the current goroutines and registers a
|
|
|
|
// cleanup on tb to verify that after the rest, all goroutines created by the
|
|
|
|
// test go away. (well, at least that the count matches. Maybe in the future it
|
|
|
|
// can look at specific routines).
|
|
|
|
//
|
|
|
|
// It panics if called from a parallel test.
|
2021-02-02 19:30:46 +00:00
|
|
|
func ResourceCheck(tb testing.TB) {
|
2021-06-23 05:53:43 +01:00
|
|
|
tb.Helper()
|
2023-10-07 02:54:59 +01:00
|
|
|
|
|
|
|
// Set an environment variable (anything at all) just for the
|
|
|
|
// side effect of tb.Setenv panicking if we're in a parallel test.
|
|
|
|
tb.Setenv("TS_CHECKING_RESOURCES", "1")
|
|
|
|
|
2021-02-02 19:30:46 +00:00
|
|
|
startN, startStacks := goroutines()
|
|
|
|
tb.Cleanup(func() {
|
|
|
|
if tb.Failed() {
|
|
|
|
// Something else went wrong.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Goroutines might be still exiting.
|
2024-04-16 21:15:13 +01:00
|
|
|
for range 300 {
|
2021-02-02 19:30:46 +00:00
|
|
|
if runtime.NumGoroutine() <= startN {
|
|
|
|
return
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2023-09-06 23:29:44 +01:00
|
|
|
time.Sleep(10 * time.Millisecond)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-02-02 19:30:46 +00:00
|
|
|
endN, endStacks := goroutines()
|
2022-07-29 17:48:35 +01:00
|
|
|
if endN <= startN {
|
|
|
|
return
|
|
|
|
}
|
2021-02-02 19:30:46 +00:00
|
|
|
tb.Logf("goroutine diff:\n%v\n", cmp.Diff(startStacks, endStacks))
|
|
|
|
tb.Fatalf("goroutine count: expected %d, got %d\n", startN, endN)
|
|
|
|
})
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2021-02-02 19:30:46 +00:00
|
|
|
func goroutines() (int, []byte) {
|
|
|
|
p := pprof.Lookup("goroutine")
|
|
|
|
b := new(bytes.Buffer)
|
|
|
|
p.WriteTo(b, 1)
|
|
|
|
return p.Count(), b.Bytes()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|