如何在測試中發現Goroutine泄漏
前言
哈嘍,大家好,我是asong;
眾所周知,gorourtine的設計是Go語言并發實現的核心組成部分,易上手,但是也會遭遇各種疑難雜癥,其中goroutine泄漏就是重癥之一,其出現往往需要排查很久,有人說可以使用pprof來排查,雖然其可以達到目的,但是這些性能分析工具往往是在出現問題后借助其輔助排查使用的,有沒有一款可以防患于未然的工具嗎?當然有,goleak他來了,其由 Uber 團隊開源,可以用來檢測goroutine泄漏,并且可以結合單元測試,可以達到防范于未然的目的,本文我們就一起來看一看goleak。
goroutine泄漏
不知道你們在日常開發中是否有遇到過goroutine泄漏,goroutine泄漏其實就是goroutine阻塞,這些阻塞的goroutine會一直存活直到進程終結,他們占用的棧內存一直無法釋放,從而導致系統的可用內存會越來越少,直至崩潰!簡單總結了幾種常見的泄漏原因:
- Goroutine內的邏輯進入死循壞,一直占用資源
- Goroutine配合channel/mutex使用時,由于使用不當導致一直被阻塞
- Goroutine內的邏輯長時間等待,導致Goroutine數量暴增
接下來我們使用Goroutine+channel的經典組合來展示goroutine泄漏;
func GetData() {
var ch chan struct{}
go func() {
<- ch
}()
}
func main() {
defer func() {
fmt.Println("goroutines: ", runtime.NumGoroutine())
}()
GetData()
time.Sleep(2 * time.Second)
}
這個例子是channel忘記初始化,無論是讀寫操作都會造成阻塞,這個方法如果是寫單測是檢查不出來問題的:
func TestGetData(t *testing.T) {
GetData()
}
運行結果:
=== RUN TestGetData
--- PASS: TestGetData (0.00s)
PASS
內置測試無法滿足,接下來我們引入goleak來測試一下。
goleak
github地址:https://github.com/uber-go/goleak
使用goleak主要關注兩個方法即可:VerifyNone、VerifyTestMain,VerifyNone用于單一測試用例中測試,VerifyTestMain可以在TestMain中添加,可以減少對測試代碼的入侵,舉例如下:
使用VerifyNone:
func TestGetDataWithGoleak(t *testing.T) {
defer goleak.VerifyNone(t)
GetData()
}
運行結果:
=== RUN TestGetDataWithGoleak
leaks.go:78: found unexpected goroutines:
[Goroutine 35 in state chan receive (nil chan), with asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector.GetData.func1 on top of the stack:
goroutine 35 [chan receive (nil chan)]:
asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector.GetData.func1()
/Users/go/src/asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector/main.go:12 +0x1f
created by asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector.GetData
/Users/go/src/asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector/main.go:11 +0x3c
]
--- FAIL: TestGetDataWithGoleak (0.45s)
FAIL
Process finished with the exit code 1
通過運行結果看到具體發生goroutine泄漏的具體代碼段;使用VerifyNone會對我們的測試代碼有入侵,可以采用VerifyTestMain方法可以更快的集成到測試中:
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}
運行結果:
=== RUN TestGetData
--- PASS: TestGetData (0.00s)
PASS
goleak: Errors on successful test run: found unexpected goroutines:
[Goroutine 5 in state chan receive (nil chan), with asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector.GetData.func1 on top of the stack:
goroutine 5 [chan receive (nil chan)]:
asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector.GetData.func1()
/Users/go/src/asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector/main.go:12 +0x1f
created by asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector.GetData
/Users/go/src/asong.cloud/Golang_Dream/code_demo/goroutine_oos_detector/main.go:11 +0x3c
]
Process finished with the exit code 1
VerifyTestMain的運行結果與VerifyNone有一點不同,VerifyTestMain會先報告測試用例執行結果,然后報告泄漏分析,如果測試的用例中有多個goroutine泄漏,無法精確定位到發生泄漏的具體test,需要使用如下腳本進一步分析:
# Create a test binary which will be used to run each test individually
$ go test -c -o tests
# Run each test individually, printing "." for successful tests, or the test name
# for failing tests.
$ for test in $(go test -list . | grep -E "^(Test|Example)"); do ./tests -test.run "^$test\$" &>/dev/null && echo -n "." || echo -e "\n$test failed"; done
這樣會打印出具體哪個測試用例失敗。
goleak實現原理
從VerifyNone入口,我們查看源代碼,其調用了Find方法:
// Find looks for extra goroutines, and returns a descriptive error if
// any are found.
func Find(options ...Option) error {
// 獲取當前goroutine的ID
cur := stack.Current().ID()
opts := buildOpts(options...)
var stacks []stack.Stack
retry := true
for i := 0; retry; i++ {
// 過濾無用的goroutine
stacks = filterStacks(stack.All(), cur, opts)
if len(stacks) == 0 {
return nil
}
retry = opts.retry(i)
}
return fmt.Errorf("found unexpected goroutines:\n%s", stacks)
}
我們在看一下filterStacks方法:
// filterStacks will filter any stacks excluded by the given opts.
// filterStacks modifies the passed in stacks slice.
func filterStacks(stacks []stack.Stack, skipID int, opts *opts) []stack.Stack {
filtered := stacks[:0]
for _, stack := range stacks {
// Always skip the running goroutine.
if stack.ID() == skipID {
continue
}
// Run any default or user-specified filters.
if opts.filter(stack) {
continue
}
filtered = append(filtered, stack)
}
return filtered
}
這里主要是過濾掉一些不參與檢測的goroutine stack,如果沒有自定義filters,則使用默認的filters:
func buildOpts(options ...Option) *opts {
opts := &opts{
maxRetries: _defaultRetries,
maxSleep: 100 * time.Millisecond,
}
opts.filters = append(opts.filters,
isTestStack,
isSyscallStack,
isStdLibStack,
isTraceStack,
)
for _, option := range options {
option.apply(opts)
}
return opts
}
從這里可以看出,默認檢測20次,每次默認間隔100ms;添加默認filters;
總結一下goleak的實現原理:
使用runtime.Stack()方法獲取當前運行的所有goroutine的棧信息,默認定義不需要檢測的過濾項,默認定義檢測次數+檢測間隔,不斷周期進行檢測,最終在多次檢查后仍沒有找到剩下的goroutine則判斷沒有發生goroutine泄漏。
總結
本文我們分享了一個可以在測試中發現goroutine泄漏的工具,但是其還是需要完備的測試用例支持,這就暴露出測試用例的重要性,朋友們好的工具可以助我們更快的發現問題,但是代碼質量還是掌握在我們自己的手中,加油吧,少年們~。
好啦,本文到這里就結束了,我是asong,我們下期見。