testwrapper.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. "fmt"
  15. "io"
  16. "log"
  17. "os"
  18. "os/exec"
  19. "slices"
  20. "sort"
  21. "strings"
  22. "time"
  23. "unicode"
  24. "github.com/dave/courtney/scanner"
  25. "github.com/dave/courtney/shared"
  26. "github.com/dave/courtney/tester"
  27. "github.com/dave/patsy"
  28. "github.com/dave/patsy/vos"
  29. xmaps "golang.org/x/exp/maps"
  30. "tailscale.com/cmd/testwrapper/flakytest"
  31. )
  32. const (
  33. maxAttempts = 3
  34. )
  35. type testAttempt struct {
  36. pkg string // "tailscale.com/types/key"
  37. testName string // "TestFoo"
  38. outcome string // "pass", "fail", "skip"
  39. logs bytes.Buffer
  40. isMarkedFlaky bool // set if the test is marked as flaky
  41. issueURL string // set if the test is marked as flaky
  42. pkgFinished bool
  43. }
  44. // packageTests describes what to run.
  45. // It's also JSON-marshalled to output for analysys tools to parse
  46. // so the fields are all exported.
  47. // TODO(bradfitz): move this type to its own types package?
  48. type packageTests struct {
  49. // Pattern is the package Pattern to run.
  50. // Must be a single Pattern, not a list of patterns.
  51. Pattern string // "./...", "./types/key"
  52. // Tests is a list of Tests to run. If empty, all Tests in the package are
  53. // run.
  54. Tests []string // ["TestFoo", "TestBar"]
  55. // IssueURLs maps from a test name to a URL tracking its flake.
  56. IssueURLs map[string]string // "TestFoo" => "https://github.com/foo/bar/issue/123"
  57. }
  58. type goTestOutput struct {
  59. Time time.Time
  60. Action string
  61. Package string
  62. Test string
  63. Output string
  64. }
  65. var debug = os.Getenv("TS_TESTWRAPPER_DEBUG") != ""
  66. // runTests runs the tests in pt and sends the results on ch. It sends a
  67. // testAttempt for each test and a final testAttempt per pkg with pkgFinished
  68. // set to true. Package build errors will not emit a testAttempt (as no valid
  69. // JSON is produced) but the [os/exec.ExitError] will be returned.
  70. // It calls close(ch) when it's done.
  71. func runTests(ctx context.Context, attempt int, pt *packageTests, goTestArgs, testArgs []string, ch chan<- *testAttempt) error {
  72. defer close(ch)
  73. args := []string{"test"}
  74. args = append(args, goTestArgs...)
  75. args = append(args, pt.Pattern)
  76. if len(pt.Tests) > 0 {
  77. runArg := strings.Join(pt.Tests, "|")
  78. args = append(args, "--run", runArg)
  79. }
  80. args = append(args, testArgs...)
  81. args = append(args, "-json")
  82. if debug {
  83. fmt.Println("running", strings.Join(args, " "))
  84. }
  85. cmd := exec.CommandContext(ctx, "go", args...)
  86. if len(pt.Tests) > 0 {
  87. cmd.Env = append(os.Environ(), "TS_TEST_SHARD=") // clear test shard; run all tests we say to run
  88. }
  89. r, err := cmd.StdoutPipe()
  90. if err != nil {
  91. log.Printf("error creating stdout pipe: %v", err)
  92. }
  93. defer r.Close()
  94. cmd.Stderr = os.Stderr
  95. cmd.Env = os.Environ()
  96. cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%d", flakytest.FlakeAttemptEnv, attempt))
  97. if err := cmd.Start(); err != nil {
  98. log.Printf("error starting test: %v", err)
  99. os.Exit(1)
  100. }
  101. s := bufio.NewScanner(r)
  102. resultMap := make(map[string]map[string]*testAttempt) // pkg -> test -> testAttempt
  103. for s.Scan() {
  104. var goOutput goTestOutput
  105. if err := json.Unmarshal(s.Bytes(), &goOutput); err != nil {
  106. if errors.Is(err, io.EOF) || errors.Is(err, os.ErrClosed) {
  107. break
  108. }
  109. // `go test -json` outputs invalid JSON when a build fails.
  110. // In that case, discard the the output and start reading again.
  111. // The build error will be printed to stderr.
  112. // See: https://github.com/golang/go/issues/35169
  113. if _, ok := err.(*json.SyntaxError); ok {
  114. fmt.Println(s.Text())
  115. continue
  116. }
  117. panic(err)
  118. }
  119. pkg := goOutput.Package
  120. pkgTests := resultMap[pkg]
  121. if goOutput.Test == "" {
  122. switch goOutput.Action {
  123. case "fail", "pass", "skip":
  124. for _, test := range pkgTests {
  125. if test.outcome == "" {
  126. test.outcome = "fail"
  127. ch <- test
  128. }
  129. }
  130. ch <- &testAttempt{
  131. pkg: goOutput.Package,
  132. outcome: goOutput.Action,
  133. pkgFinished: true,
  134. }
  135. }
  136. continue
  137. }
  138. if pkgTests == nil {
  139. pkgTests = make(map[string]*testAttempt)
  140. resultMap[pkg] = pkgTests
  141. }
  142. testName := goOutput.Test
  143. if test, _, isSubtest := strings.Cut(goOutput.Test, "/"); isSubtest {
  144. testName = test
  145. if goOutput.Action == "output" {
  146. resultMap[pkg][testName].logs.WriteString(goOutput.Output)
  147. }
  148. continue
  149. }
  150. switch goOutput.Action {
  151. case "start":
  152. // ignore
  153. case "run":
  154. pkgTests[testName] = &testAttempt{
  155. pkg: pkg,
  156. testName: testName,
  157. }
  158. case "skip", "pass", "fail":
  159. pkgTests[testName].outcome = goOutput.Action
  160. ch <- pkgTests[testName]
  161. case "output":
  162. if suffix, ok := strings.CutPrefix(strings.TrimSpace(goOutput.Output), flakytest.FlakyTestLogMessage); ok {
  163. pkgTests[testName].isMarkedFlaky = true
  164. pkgTests[testName].issueURL = strings.TrimPrefix(suffix, ": ")
  165. } else {
  166. pkgTests[testName].logs.WriteString(goOutput.Output)
  167. }
  168. }
  169. }
  170. if err := cmd.Wait(); err != nil {
  171. return err
  172. }
  173. if err := s.Err(); err != nil {
  174. return fmt.Errorf("reading go test stdout: %w", err)
  175. }
  176. return nil
  177. }
  178. func main() {
  179. goTestArgs, packages, testArgs, err := splitArgs(os.Args[1:])
  180. if err != nil {
  181. log.Fatal(err)
  182. return
  183. }
  184. if len(packages) == 0 {
  185. fmt.Println("testwrapper: no packages specified")
  186. return
  187. }
  188. ctx := context.Background()
  189. type nextRun struct {
  190. tests []*packageTests
  191. attempt int // starting at 1
  192. }
  193. firstRun := &nextRun{
  194. attempt: 1,
  195. }
  196. for _, pkg := range packages {
  197. firstRun.tests = append(firstRun.tests, &packageTests{Pattern: pkg})
  198. }
  199. toRun := []*nextRun{firstRun}
  200. printPkgOutcome := func(pkg, outcome string, attempt int) {
  201. if outcome == "skip" {
  202. fmt.Printf("?\t%s [skipped/no tests] \n", pkg)
  203. return
  204. }
  205. if outcome == "pass" {
  206. outcome = "ok"
  207. }
  208. if outcome == "fail" {
  209. outcome = "FAIL"
  210. }
  211. if attempt > 1 {
  212. fmt.Printf("%s\t%s [attempt=%d]\n", outcome, pkg, attempt)
  213. return
  214. }
  215. fmt.Printf("%s\t%s\n", outcome, pkg)
  216. }
  217. // Check for -coverprofile argument and filter it out
  218. combinedCoverageFilename := ""
  219. filteredGoTestArgs := make([]string, 0, len(goTestArgs))
  220. preceededByCoverProfile := false
  221. for _, arg := range goTestArgs {
  222. if arg == "-coverprofile" {
  223. preceededByCoverProfile = true
  224. } else if preceededByCoverProfile {
  225. combinedCoverageFilename = strings.TrimSpace(arg)
  226. preceededByCoverProfile = false
  227. } else {
  228. filteredGoTestArgs = append(filteredGoTestArgs, arg)
  229. }
  230. }
  231. goTestArgs = filteredGoTestArgs
  232. runningWithCoverage := combinedCoverageFilename != ""
  233. if runningWithCoverage {
  234. fmt.Printf("Will log coverage to %v\n", combinedCoverageFilename)
  235. }
  236. // Keep track of all test coverage files. With each retry, we'll end up
  237. // with additional coverage files that will be combined when we finish.
  238. coverageFiles := make([]string, 0)
  239. for len(toRun) > 0 {
  240. var thisRun *nextRun
  241. thisRun, toRun = toRun[0], toRun[1:]
  242. if thisRun.attempt > maxAttempts {
  243. fmt.Println("max attempts reached")
  244. os.Exit(1)
  245. }
  246. if thisRun.attempt > 1 {
  247. j, _ := json.Marshal(thisRun.tests)
  248. fmt.Printf("\n\nAttempt #%d: Retrying flaky tests:\n\nflakytest failures JSON: %s\n\n", thisRun.attempt, j)
  249. }
  250. goTestArgsWithCoverage := testArgs
  251. if runningWithCoverage {
  252. coverageFile := fmt.Sprintf("/tmp/coverage_%d.out", thisRun.attempt)
  253. coverageFiles = append(coverageFiles, coverageFile)
  254. goTestArgsWithCoverage = make([]string, len(goTestArgs), len(goTestArgs)+2)
  255. copy(goTestArgsWithCoverage, goTestArgs)
  256. goTestArgsWithCoverage = append(
  257. goTestArgsWithCoverage,
  258. fmt.Sprintf("-coverprofile=%v", coverageFile),
  259. "-covermode=set",
  260. "-coverpkg=./...",
  261. )
  262. }
  263. toRetry := make(map[string][]*testAttempt) // pkg -> tests to retry
  264. for _, pt := range thisRun.tests {
  265. ch := make(chan *testAttempt)
  266. runErr := make(chan error, 1)
  267. go func() {
  268. defer close(runErr)
  269. runErr <- runTests(ctx, thisRun.attempt, pt, goTestArgsWithCoverage, testArgs, ch)
  270. }()
  271. var failed bool
  272. for tr := range ch {
  273. // Go assigns the package name "command-line-arguments" when you
  274. // `go test FILE` rather than `go test PKG`. It's more
  275. // convenient for us to to specify files in tests, so fix tr.pkg
  276. // so that subsequent testwrapper attempts run correctly.
  277. if tr.pkg == "command-line-arguments" {
  278. tr.pkg = packages[0]
  279. }
  280. if tr.pkgFinished {
  281. if tr.outcome == "fail" && len(toRetry[tr.pkg]) == 0 {
  282. // If a package fails and we don't have any tests to
  283. // retry, then we should fail. This typically happens
  284. // when a package times out.
  285. failed = true
  286. }
  287. printPkgOutcome(tr.pkg, tr.outcome, thisRun.attempt)
  288. continue
  289. }
  290. if testingVerbose || tr.outcome == "fail" {
  291. io.Copy(os.Stdout, &tr.logs)
  292. }
  293. if tr.outcome != "fail" {
  294. continue
  295. }
  296. if tr.isMarkedFlaky {
  297. toRetry[tr.pkg] = append(toRetry[tr.pkg], tr)
  298. } else {
  299. failed = true
  300. }
  301. }
  302. if failed {
  303. fmt.Println("\n\nNot retrying flaky tests because non-flaky tests failed.")
  304. os.Exit(1)
  305. }
  306. // If there's nothing to retry and no non-retryable tests have
  307. // failed then we've probably hit a build error.
  308. if err := <-runErr; len(toRetry) == 0 && err != nil {
  309. var exit *exec.ExitError
  310. if errors.As(err, &exit) {
  311. if code := exit.ExitCode(); code > -1 {
  312. os.Exit(exit.ExitCode())
  313. }
  314. }
  315. log.Printf("testwrapper: %s", err)
  316. os.Exit(1)
  317. }
  318. }
  319. if len(toRetry) == 0 {
  320. continue
  321. }
  322. pkgs := xmaps.Keys(toRetry)
  323. sort.Strings(pkgs)
  324. nextRun := &nextRun{
  325. attempt: thisRun.attempt + 1,
  326. }
  327. for _, pkg := range pkgs {
  328. tests := toRetry[pkg]
  329. slices.SortFunc(tests, func(a, b *testAttempt) int { return strings.Compare(a.testName, b.testName) })
  330. issueURLs := map[string]string{} // test name => URL
  331. var testNames []string
  332. for _, ta := range tests {
  333. issueURLs[ta.testName] = ta.issueURL
  334. testNames = append(testNames, ta.testName)
  335. }
  336. nextRun.tests = append(nextRun.tests, &packageTests{
  337. Pattern: pkg,
  338. Tests: testNames,
  339. IssueURLs: issueURLs,
  340. })
  341. }
  342. toRun = append(toRun, nextRun)
  343. }
  344. if runningWithCoverage {
  345. intermediateCoverageFilename := "/tmp/coverage.out_intermediate"
  346. if err := combineCoverageFiles(intermediateCoverageFilename, coverageFiles); err != nil {
  347. fmt.Printf("error combining coverage files: %v\n", err)
  348. os.Exit(2)
  349. }
  350. if err := processCoverageWithCourtney(intermediateCoverageFilename, combinedCoverageFilename, testArgs); err != nil {
  351. fmt.Printf("error processing coverage with courtney: %v\n", err)
  352. os.Exit(3)
  353. }
  354. fmt.Printf("Wrote combined coverage to %v\n", combinedCoverageFilename)
  355. }
  356. }
  357. func combineCoverageFiles(intermediateCoverageFilename string, coverageFiles []string) error {
  358. combinedCoverageFile, err := os.OpenFile(intermediateCoverageFilename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
  359. if err != nil {
  360. return fmt.Errorf("create /tmp/coverage.out: %w", err)
  361. }
  362. defer combinedCoverageFile.Close()
  363. w := bufio.NewWriter(combinedCoverageFile)
  364. defer w.Flush()
  365. for fileNumber, coverageFile := range coverageFiles {
  366. f, err := os.Open(coverageFile)
  367. if err != nil {
  368. return fmt.Errorf("open %v: %w", coverageFile, err)
  369. }
  370. defer f.Close()
  371. in := bufio.NewReader(f)
  372. line := 0
  373. for {
  374. r, _, err := in.ReadRune()
  375. if err != nil {
  376. if err != io.EOF {
  377. return fmt.Errorf("read %v: %w", coverageFile, err)
  378. }
  379. break
  380. }
  381. // On all but the first coverage file, skip the coverage file header
  382. if fileNumber > 0 && line == 0 {
  383. continue
  384. }
  385. if r == '\n' {
  386. line++
  387. }
  388. // filter for only printable characters because coverage file sometimes includes junk on 2nd line
  389. if unicode.IsPrint(r) || r == '\n' {
  390. if _, err := w.WriteRune(r); err != nil {
  391. return fmt.Errorf("write %v: %w", combinedCoverageFile.Name(), err)
  392. }
  393. }
  394. }
  395. }
  396. return nil
  397. }
  398. // processCoverageWithCourtney post-processes code coverage to exclude less
  399. // meaningful sections like 'if err != nil { return err}', as well as
  400. // anything marked with a '// notest' comment.
  401. //
  402. // instead of running the courtney as a separate program, this embeds
  403. // courtney for easier integration.
  404. func processCoverageWithCourtney(intermediateCoverageFilename, combinedCoverageFilename string, testArgs []string) error {
  405. env := vos.Os()
  406. setup := &shared.Setup{
  407. Env: vos.Os(),
  408. Paths: patsy.NewCache(env),
  409. TestArgs: testArgs,
  410. Load: intermediateCoverageFilename,
  411. Output: combinedCoverageFilename,
  412. }
  413. if err := setup.Parse(testArgs); err != nil {
  414. return fmt.Errorf("parse args: %w", err)
  415. }
  416. s := scanner.New(setup)
  417. if err := s.LoadProgram(); err != nil {
  418. return fmt.Errorf("load program: %w", err)
  419. }
  420. if err := s.ScanPackages(); err != nil {
  421. return fmt.Errorf("scan packages: %w", err)
  422. }
  423. t := tester.New(setup)
  424. if err := t.Load(); err != nil {
  425. return fmt.Errorf("load: %w", err)
  426. }
  427. if err := t.ProcessExcludes(s.Excludes); err != nil {
  428. return fmt.Errorf("process excludes: %w", err)
  429. }
  430. if err := t.Save(); err != nil {
  431. return fmt.Errorf("save: %w", err)
  432. }
  433. return nil
  434. }