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 02:56:11 +00: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 01:54:59 +00: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 04:53:43 +00:00
|
|
|
tb.Helper()
|
2023-10-07 01:54:59 +00: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() {
|
2024-10-14 09:02:04 +00:00
|
|
|
// Test has failed - but this doesn't catch panics due to
|
|
|
|
// https://github.com/golang/go/issues/49929.
|
2021-02-02 19:30:46 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
// Goroutines might be still exiting.
|
2024-04-16 20:15:13 +00: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 22:29:44 +00: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 16:48:35 +00:00
|
|
|
if endN <= startN {
|
|
|
|
return
|
|
|
|
}
|
2021-02-02 19:30:46 +00:00
|
|
|
tb.Logf("goroutine diff:\n%v\n", cmp.Diff(startStacks, endStacks))
|
2024-10-14 09:02:04 +00:00
|
|
|
|
|
|
|
// tb.Failed() above won't report on panics, so we shouldn't call Fatal
|
|
|
|
// here or we risk suppressing reporting of the panic.
|
|
|
|
tb.Errorf("goroutine count: expected %d, got %d\n", startN, endN)
|
2021-02-02 19:30:46 +00:00
|
|
|
})
|
|
|
|
}
|
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
|
|
|
}
|