leak.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package testutil
  5. import (
  6. "fmt"
  7. "net/http"
  8. "os"
  9. "regexp"
  10. "runtime"
  11. "sort"
  12. "strings"
  13. "testing"
  14. "time"
  15. )
  16. /*
  17. CheckLeakedGoroutine verifies tests do not leave any leaky
  18. goroutines. It returns true when there are goroutines still
  19. running(leaking) after all tests.
  20. import "github.com/coreos/etcd/pkg/testutil"
  21. func TestMain(m *testing.M) {
  22. v := m.Run()
  23. if v == 0 && testutil.CheckLeakedGoroutine() {
  24. os.Exit(1)
  25. }
  26. os.Exit(v)
  27. }
  28. func TestSample(t *testing.T) {
  29. defer testutil.AfterTest(t)
  30. ...
  31. }
  32. */
  33. func CheckLeakedGoroutine() bool {
  34. if testing.Short() {
  35. // not counting goroutines for leakage in -short mode
  36. return false
  37. }
  38. gs := interestingGoroutines()
  39. if len(gs) == 0 {
  40. return false
  41. }
  42. stackCount := make(map[string]int)
  43. re := regexp.MustCompile("\\(0[0-9a-fx, ]*\\)")
  44. for _, g := range gs {
  45. // strip out pointer arguments in first function of stack dump
  46. normalized := string(re.ReplaceAll([]byte(g), []byte("(...)")))
  47. stackCount[normalized]++
  48. }
  49. fmt.Fprintf(os.Stderr, "Too many goroutines running after all test(s).\n")
  50. for stack, count := range stackCount {
  51. fmt.Fprintf(os.Stderr, "%d instances of:\n%s\n", count, stack)
  52. }
  53. return true
  54. }
  55. func AfterTest(t *testing.T) {
  56. http.DefaultTransport.(*http.Transport).CloseIdleConnections()
  57. if testing.Short() {
  58. return
  59. }
  60. var bad string
  61. badSubstring := map[string]string{
  62. ").writeLoop(": "a Transport",
  63. "created by net/http/httptest.(*Server).Start": "an httptest.Server",
  64. "timeoutHandler": "a TimeoutHandler",
  65. "net.(*netFD).connect(": "a timing out dial",
  66. ").noteClientGone(": "a closenotifier sender",
  67. }
  68. // readLoop was buggy before go1.5:
  69. // https://github.com/golang/go/issues/10457
  70. if getAtLeastGo15() {
  71. badSubstring[").readLoop("] = "a Transport"
  72. }
  73. var stacks string
  74. for i := 0; i < 6; i++ {
  75. bad = ""
  76. stacks = strings.Join(interestingGoroutines(), "\n\n")
  77. for substr, what := range badSubstring {
  78. if strings.Contains(stacks, substr) {
  79. bad = what
  80. }
  81. }
  82. if bad == "" {
  83. return
  84. }
  85. // Bad stuff found, but goroutines might just still be
  86. // shutting down, so give it some time.
  87. time.Sleep(50 * time.Millisecond)
  88. }
  89. t.Errorf("Test appears to have leaked %s:\n%s", bad, stacks)
  90. }
  91. func interestingGoroutines() (gs []string) {
  92. buf := make([]byte, 2<<20)
  93. buf = buf[:runtime.Stack(buf, true)]
  94. for _, g := range strings.Split(string(buf), "\n\n") {
  95. sl := strings.SplitN(g, "\n", 2)
  96. if len(sl) != 2 {
  97. continue
  98. }
  99. stack := strings.TrimSpace(sl[1])
  100. if stack == "" ||
  101. strings.Contains(stack, "created by testing.RunTests") ||
  102. strings.Contains(stack, "testing.Main(") ||
  103. strings.Contains(stack, "runtime.goexit") ||
  104. strings.Contains(stack, "github.com/coreos/etcd/pkg/testutil.interestingGoroutines") ||
  105. strings.Contains(stack, "github.com/coreos/etcd/pkg/logutil.(*MergeLogger).outputLoop") ||
  106. strings.Contains(stack, "github.com/golang/glog.(*loggingT).flushDaemon") ||
  107. strings.Contains(stack, "created by runtime.gc") ||
  108. strings.Contains(stack, "runtime.MHeap_Scavenger") {
  109. continue
  110. }
  111. gs = append(gs, stack)
  112. }
  113. sort.Strings(gs)
  114. return
  115. }
  116. // getAtLeastGo15 returns true if the runtime has go1.5+.
  117. func getAtLeastGo15() bool {
  118. var major, minor int
  119. var discard string
  120. i, err := fmt.Sscanf(runtime.Version(), "go%d.%d%s", &major, &minor, &discard)
  121. return (err == nil && i == 3 && (major > 1 || major == 1 && minor >= 5))
  122. }