Debian Codegraph @

cmd/stress/stress.go

raw symbols SCIP
1 // Copyright 2015 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
5 //go:build unix || aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || windows
6
7 // The stress utility is intended for catching sporadic failures.
8 // It runs a given process in parallel in a loop and collects any failures.
9 // Usage:
10 //
11 // $ stress ./fmt.test -test.run=TestSometing -test.cpu=10
12 //
13 // You can also specify a number of parallel processes with -p flag;
14 // instruct the utility to not kill hanged processes for gdb attach;
15 // or specify the failure output you are looking for (if you want to
16 // ignore some other sporadic failures).
17 package main
18
19 import (
20 "bytes"
21 "flag"
22 "fmt"
23 "os"
24 "os/exec"
25 "path/filepath"
26 "regexp"
27 "runtime"
28 "sync/atomic"
29 "syscall"
30 "time"
31 )
32
33 var (
34 flagCount = flag.Int("count", 0, "stop after `N` runs (default never stop)")
35 flagFailfast = flag.Bool("failfast", false, "exit on first failure and write failure output to stderr")
36 flagFailure = flag.String("failure", "", "fail only if output matches `regexp`")
37 flagIgnore = flag.String("ignore", "", "ignore failure if output matches `regexp`")
38 flagKill = flag.Bool("kill", true, "kill timed out processes if true, otherwise just print pid (to attach with gdb)")
39 flagOutput = flag.String("o", defaultPrefix(), "output failure logs to `path` plus a unique suffix")
40 flagP = flag.Int("p", runtime.NumCPU(), "run `N` processes in parallel")
41 flagTimeout = flag.Duration("timeout", 10*time.Minute, "timeout each process after `duration`")
42 )
43
44 func init() {
45 flag.Usage = func() {
46 os.Stderr.WriteString(`The stress utility is intended for catching sporadic failures.
47 It runs a given process in parallel in a loop and collects any failures.
48 Usage:
49
50 $ stress ./fmt.test -test.run=TestSometing -test.cpu=10
51
52 `)
53 flag.PrintDefaults()
54 }
55 }
56
57 func defaultPrefix() string {
58 date := time.Now().Format("go-stress-20060102T150405-")
59 return filepath.Join(os.TempDir(), date)
60 }
61
62 func main() {
63 flag.Parse()
64 if *flagP <= 0 || *flagTimeout <= 0 || len(flag.Args()) == 0 {
65 flag.Usage()
66 os.Exit(1)
67 }
68 var failureRe, ignoreRe *regexp.Regexp
69 if *flagFailure != "" {
70 var err error
71 if failureRe, err = regexp.Compile(*flagFailure); err != nil {
72 fmt.Println("bad failure regexp:", err)
73 os.Exit(1)
74 }
75 }
76 if *flagIgnore != "" {
77 var err error
78 if ignoreRe, err = regexp.Compile(*flagIgnore); err != nil {
79 fmt.Println("bad ignore regexp:", err)
80 os.Exit(1)
81 }
82 }
83 res := make(chan []byte)
84 var started atomic.Int64
85 for i := 0; i < *flagP; i++ {
86 go func() {
87 for {
88 // Note: Must started.Add(1) even if not using -count,
89 // because it enables the '%d active' print below.
90 if started.Add(1) > int64(*flagCount) && *flagCount > 0 {
91 break
92 }
93 cmd := exec.Command(flag.Args()[0], flag.Args()[1:]...)
94 var buf bytes.Buffer
95 cmd.Stdout = &buf
96 cmd.Stderr = &buf
97 err := cmd.Start() // make cmd.Process valid for timeout goroutine
98 done := make(chan bool)
99 if err == nil && *flagTimeout > 0 {
100 go func() {
101 select {
102 case <-done:
103 return
104 case <-time.After(*flagTimeout):
105 }
106 if !*flagKill {
107 fmt.Printf("process %v timed out\n", cmd.Process.Pid)
108 return
109 }
110 cmd.Process.Signal(syscall.SIGABRT)
111 select {
112 case <-done:
113 return
114 case <-time.After(10 * time.Second):
115 }
116 cmd.Process.Kill()
117 }()
118 }
119 if err == nil {
120 err = cmd.Wait()
121 }
122 out := buf.Bytes()
123 close(done)
124 if err != nil && (failureRe == nil || failureRe.Match(out)) && (ignoreRe == nil || !ignoreRe.Match(out)) {
125 out = append(out, fmt.Sprintf("\n\nERROR: %v\n", err)...)
126 } else {
127 out = []byte{}
128 }
129 res <- out
130 }
131 }()
132 }
133 runs, fails := 0, 0
134 start := time.Now()
135 ticker := time.NewTicker(5 * time.Second).C
136 status := func(context string) {
137 elapsed := time.Since(start).Truncate(time.Second)
138 var pct string
139 if fails > 0 {
140 pct = fmt.Sprintf(" (%0.2f%%)", 100.0*float64(fails)/float64(runs))
141 }
142 var active string
143 n := started.Load() - int64(runs)
144 if *flagCount > 0 {
145 // started counts past *flagCount at end; do not count those
146 // TODO: n = min(n, int64(*flagCount-runs))
147 if x := int64(*flagCount - runs); n > x {
148 n = x
149 }
150 }
151 if n > 0 {
152 active = fmt.Sprintf(", %d active", n)
153 }
154 fmt.Printf("%v: %v runs %s, %v failures%s%s\n", elapsed, runs, context, fails, pct, active)
155 }
156 for {
157 select {
158 case out := <-res:
159 runs++
160 if len(out) > 0 {
161 fails++
162 if *flagFailfast {
163 os.Stderr.Write(out)
164 os.Exit(1)
165 }
166 dir, path := filepath.Split(*flagOutput)
167 f, err := os.CreateTemp(dir, path)
168 if err != nil {
169 fmt.Printf("failed to create temp file: %v\n", err)
170 os.Exit(1)
171 }
172 f.Write(out)
173 f.Close()
174 if len(out) > 2<<10 {
175 out := out[:2<<10]
176 fmt.Printf("\n%s\n%s\n…\n", f.Name(), out)
177 } else {
178 fmt.Printf("\n%s\n%s\n", f.Name(), out)
179 }
180 }
181 if *flagCount > 0 && runs >= *flagCount {
182 status("total")
183 if fails > 0 {
184 os.Exit(1)
185 }
186 os.Exit(0)
187 }
188 case <-ticker:
189 status("so far")
190 }
191 }
192 }