testwrapper.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // testwrapper is a wrapper for retrying flaky tests. It is an alternative to
  4. // `go test` and re-runs failed marked flaky tests (using the flakytest pkg). It
  5. // takes different arguments than go test and requires the first positional
  6. // argument to be the pattern to test.
  7. package main
  8. import (
  9. "bufio"
  10. "bytes"
  11. "context"
  12. "encoding/json"
  13. "errors"
  14. "flag"
  15. "fmt"
  16. "io"
  17. "log"
  18. "os"
  19. "os/exec"
  20. "slices"
  21. "sort"
  22. "strings"
  23. "time"
  24. xmaps "golang.org/x/exp/maps"
  25. "tailscale.com/cmd/testwrapper/flakytest"
  26. )
  27. const maxAttempts = 3
  28. type testAttempt struct {
  29. pkg string // "tailscale.com/types/key"
  30. testName string // "TestFoo"
  31. outcome string // "pass", "fail", "skip"
  32. logs bytes.Buffer
  33. isMarkedFlaky bool // set if the test is marked as flaky
  34. issueURL string // set if the test is marked as flaky
  35. pkgFinished bool
  36. }
  37. // packageTests describes what to run.
  38. // It's also JSON-marshalled to output for analysys tools to parse
  39. // so the fields are all exported.
  40. // TODO(bradfitz): move this type to its own types package?
  41. type packageTests struct {
  42. // Pattern is the package Pattern to run.
  43. // Must be a single Pattern, not a list of patterns.
  44. Pattern string // "./...", "./types/key"
  45. // Tests is a list of Tests to run. If empty, all Tests in the package are
  46. // run.
  47. Tests []string // ["TestFoo", "TestBar"]
  48. // IssueURLs maps from a test name to a URL tracking its flake.
  49. IssueURLs map[string]string // "TestFoo" => "https://github.com/foo/bar/issue/123"
  50. }
  51. type goTestOutput struct {
  52. Time time.Time
  53. Action string
  54. Package string
  55. Test string
  56. Output string
  57. }
  58. var debug = os.Getenv("TS_TESTWRAPPER_DEBUG") != ""
  59. // runTests runs the tests in pt and sends the results on ch. It sends a
  60. // testAttempt for each test and a final testAttempt per pkg with pkgFinished
  61. // set to true. Package build errors will not emit a testAttempt (as no valid
  62. // JSON is produced) but the [os/exec.ExitError] will be returned.
  63. // It calls close(ch) when it's done.
  64. func runTests(ctx context.Context, attempt int, pt *packageTests, otherArgs []string, ch chan<- *testAttempt) error {
  65. defer close(ch)
  66. args := []string{"test", "-json", pt.Pattern}
  67. args = append(args, otherArgs...)
  68. if len(pt.Tests) > 0 {
  69. runArg := strings.Join(pt.Tests, "|")
  70. args = append(args, "-run", runArg)
  71. }
  72. if debug {
  73. fmt.Println("running", strings.Join(args, " "))
  74. }
  75. cmd := exec.CommandContext(ctx, "go", args...)
  76. r, err := cmd.StdoutPipe()
  77. if err != nil {
  78. log.Printf("error creating stdout pipe: %v", err)
  79. }
  80. defer r.Close()
  81. cmd.Stderr = os.Stderr
  82. cmd.Env = os.Environ()
  83. cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%d", flakytest.FlakeAttemptEnv, attempt))
  84. if err := cmd.Start(); err != nil {
  85. log.Printf("error starting test: %v", err)
  86. os.Exit(1)
  87. }
  88. s := bufio.NewScanner(r)
  89. resultMap := make(map[string]map[string]*testAttempt) // pkg -> test -> testAttempt
  90. for s.Scan() {
  91. var goOutput goTestOutput
  92. if err := json.Unmarshal(s.Bytes(), &goOutput); err != nil {
  93. if errors.Is(err, io.EOF) || errors.Is(err, os.ErrClosed) {
  94. break
  95. }
  96. // `go test -json` outputs invalid JSON when a build fails.
  97. // In that case, discard the the output and start reading again.
  98. // The build error will be printed to stderr.
  99. // See: https://github.com/golang/go/issues/35169
  100. if _, ok := err.(*json.SyntaxError); ok {
  101. fmt.Println(s.Text())
  102. continue
  103. }
  104. panic(err)
  105. }
  106. pkg := goOutput.Package
  107. pkgTests := resultMap[pkg]
  108. if goOutput.Test == "" {
  109. switch goOutput.Action {
  110. case "fail", "pass", "skip":
  111. for _, test := range pkgTests {
  112. if test.outcome == "" {
  113. test.outcome = "fail"
  114. ch <- test
  115. }
  116. }
  117. ch <- &testAttempt{
  118. pkg: goOutput.Package,
  119. outcome: goOutput.Action,
  120. pkgFinished: true,
  121. }
  122. }
  123. continue
  124. }
  125. if pkgTests == nil {
  126. pkgTests = make(map[string]*testAttempt)
  127. resultMap[pkg] = pkgTests
  128. }
  129. testName := goOutput.Test
  130. if test, _, isSubtest := strings.Cut(goOutput.Test, "/"); isSubtest {
  131. testName = test
  132. if goOutput.Action == "output" {
  133. resultMap[pkg][testName].logs.WriteString(goOutput.Output)
  134. }
  135. continue
  136. }
  137. switch goOutput.Action {
  138. case "start":
  139. // ignore
  140. case "run":
  141. pkgTests[testName] = &testAttempt{
  142. pkg: pkg,
  143. testName: testName,
  144. }
  145. case "skip", "pass", "fail":
  146. pkgTests[testName].outcome = goOutput.Action
  147. ch <- pkgTests[testName]
  148. case "output":
  149. if suffix, ok := strings.CutPrefix(strings.TrimSpace(goOutput.Output), flakytest.FlakyTestLogMessage); ok {
  150. pkgTests[testName].isMarkedFlaky = true
  151. pkgTests[testName].issueURL = strings.TrimPrefix(suffix, ": ")
  152. } else {
  153. pkgTests[testName].logs.WriteString(goOutput.Output)
  154. }
  155. }
  156. }
  157. if err := cmd.Wait(); err != nil {
  158. return err
  159. }
  160. if err := s.Err(); err != nil {
  161. return fmt.Errorf("reading go test stdout: %w", err)
  162. }
  163. return nil
  164. }
  165. func main() {
  166. ctx := context.Background()
  167. // We only need to parse the -v flag to figure out whether to print the logs
  168. // for a test. We don't need to parse any other flags, so we just use the
  169. // flag package to parse the -v flag and then pass the rest of the args
  170. // through to 'go test'.
  171. // We run `go test -json` which returns the same information as `go test -v`,
  172. // but in a machine-readable format. So this flag is only for testwrapper's
  173. // output.
  174. v := flag.Bool("v", false, "verbose")
  175. flag.Usage = func() {
  176. fmt.Println("usage: testwrapper [testwrapper-flags] [pattern] [build/test flags & test binary flags]")
  177. fmt.Println()
  178. fmt.Println("testwrapper-flags:")
  179. flag.CommandLine.PrintDefaults()
  180. fmt.Println()
  181. fmt.Println("examples:")
  182. fmt.Println("\ttestwrapper -v ./... -count=1")
  183. fmt.Println("\ttestwrapper ./pkg/foo -run TestBar -count=1")
  184. fmt.Println()
  185. fmt.Println("Unlike 'go test', testwrapper requires a package pattern as the first positional argument and only supports a single pattern.")
  186. }
  187. flag.Parse()
  188. args := flag.Args()
  189. if len(args) < 1 || strings.HasPrefix(args[0], "-") {
  190. fmt.Println("no pattern specified")
  191. flag.Usage()
  192. os.Exit(1)
  193. } else if len(args) > 1 && !strings.HasPrefix(args[1], "-") {
  194. fmt.Println("expected single pattern")
  195. flag.Usage()
  196. os.Exit(1)
  197. }
  198. pattern, otherArgs := args[0], args[1:]
  199. type nextRun struct {
  200. tests []*packageTests
  201. attempt int // starting at 1
  202. }
  203. toRun := []*nextRun{
  204. {
  205. tests: []*packageTests{{Pattern: pattern}},
  206. attempt: 1,
  207. },
  208. }
  209. printPkgOutcome := func(pkg, outcome string, attempt int) {
  210. if outcome == "skip" {
  211. fmt.Printf("?\t%s [skipped/no tests] \n", pkg)
  212. return
  213. }
  214. if outcome == "pass" {
  215. outcome = "ok"
  216. }
  217. if outcome == "fail" {
  218. outcome = "FAIL"
  219. }
  220. if attempt > 1 {
  221. fmt.Printf("%s\t%s [attempt=%d]\n", outcome, pkg, attempt)
  222. return
  223. }
  224. fmt.Printf("%s\t%s\n", outcome, pkg)
  225. }
  226. for len(toRun) > 0 {
  227. var thisRun *nextRun
  228. thisRun, toRun = toRun[0], toRun[1:]
  229. if thisRun.attempt > maxAttempts {
  230. fmt.Println("max attempts reached")
  231. os.Exit(1)
  232. }
  233. if thisRun.attempt > 1 {
  234. j, _ := json.Marshal(thisRun.tests)
  235. fmt.Printf("\n\nAttempt #%d: Retrying flaky tests:\n\nflakytest failures JSON: %s\n\n", thisRun.attempt, j)
  236. }
  237. toRetry := make(map[string][]*testAttempt) // pkg -> tests to retry
  238. for _, pt := range thisRun.tests {
  239. ch := make(chan *testAttempt)
  240. runErr := make(chan error, 1)
  241. go func() {
  242. defer close(runErr)
  243. runErr <- runTests(ctx, thisRun.attempt, pt, otherArgs, ch)
  244. }()
  245. var failed bool
  246. for tr := range ch {
  247. // Go assigns the package name "command-line-arguments" when you
  248. // `go test FILE` rather than `go test PKG`. It's more
  249. // convenient for us to to specify files in tests, so fix tr.pkg
  250. // so that subsequent testwrapper attempts run correctly.
  251. if tr.pkg == "command-line-arguments" {
  252. tr.pkg = pattern
  253. }
  254. if tr.pkgFinished {
  255. if tr.outcome == "fail" && len(toRetry[tr.pkg]) == 0 {
  256. // If a package fails and we don't have any tests to
  257. // retry, then we should fail. This typically happens
  258. // when a package times out.
  259. failed = true
  260. }
  261. printPkgOutcome(tr.pkg, tr.outcome, thisRun.attempt)
  262. continue
  263. }
  264. if *v || tr.outcome == "fail" {
  265. io.Copy(os.Stdout, &tr.logs)
  266. }
  267. if tr.outcome != "fail" {
  268. continue
  269. }
  270. if tr.isMarkedFlaky {
  271. toRetry[tr.pkg] = append(toRetry[tr.pkg], tr)
  272. } else {
  273. failed = true
  274. }
  275. }
  276. if failed {
  277. fmt.Println("\n\nNot retrying flaky tests because non-flaky tests failed.")
  278. os.Exit(1)
  279. }
  280. // If there's nothing to retry and no non-retryable tests have
  281. // failed then we've probably hit a build error.
  282. if err := <-runErr; len(toRetry) == 0 && err != nil {
  283. var exit *exec.ExitError
  284. if errors.As(err, &exit) {
  285. if code := exit.ExitCode(); code > -1 {
  286. os.Exit(exit.ExitCode())
  287. }
  288. }
  289. log.Printf("testwrapper: %s", err)
  290. os.Exit(1)
  291. }
  292. }
  293. if len(toRetry) == 0 {
  294. continue
  295. }
  296. pkgs := xmaps.Keys(toRetry)
  297. sort.Strings(pkgs)
  298. nextRun := &nextRun{
  299. attempt: thisRun.attempt + 1,
  300. }
  301. for _, pkg := range pkgs {
  302. tests := toRetry[pkg]
  303. slices.SortFunc(tests, func(a, b *testAttempt) int { return strings.Compare(a.testName, b.testName) })
  304. issueURLs := map[string]string{} // test name => URL
  305. var testNames []string
  306. for _, ta := range tests {
  307. issueURLs[ta.testName] = ta.issueURL
  308. testNames = append(testNames, ta.testName)
  309. }
  310. nextRun.tests = append(nextRun.tests, &packageTests{
  311. Pattern: pkg,
  312. Tests: testNames,
  313. IssueURLs: issueURLs,
  314. })
  315. }
  316. toRun = append(toRun, nextRun)
  317. }
  318. }