-
Notifications
You must be signed in to change notification settings - Fork 43
/
main.go
220 lines (184 loc) · 5.55 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package main // import "github.com/INFURA/versus"
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/signal"
"strconv"
"time"
flags "github.com/jessevdk/go-flags"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
)
// Version of the binary, assigned during build.
var Version string = "dev"
// Options contains the flag options
type Options struct {
Args struct {
Endpoints []string `positional-arg-name:"endpoint" description:"API endpoint to load test, such as \"http://localhost:8080/\""`
} `positional-args:"yes"`
Timeout string `long:"timeout" description:"Abort request after duration" default:"30s"`
StopAfter string `long:"stop-after" description:"Stop after N requests per endpoint, N can be a number or duration."`
Concurrency int `long:"concurrency" description:"Concurrent requests per endpoint" default:"1"`
//CompareResponse string `long:"compare-response" description:"Load all response bodies and compare between endpoints, will affect throughput." default:"on"`
//Source string `long:"source" description:"Where requests come from (options: stdin-post, stdin-get)" default:"stdin-jsons"` // Someday: stdin-tcpdump, file://foo.json, ws://remote-endpoint
// TODO: Specify additional headers/configs per-endpoint (e.g. auth headers)
// TODO: Periodic reporting for long-running tests?
// TODO: Toggle compare results? Could probably reach higher throughput without result comparison.
// TODO: Add latency offcheck set before starting
Verbose []bool `long:"verbose" short:"v" description:"Show verbose logging."`
Version bool `long:"version" description:"Print version and exit."`
}
func exit(code int, format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
os.Exit(code)
}
func main() {
options := Options{}
p, err := flags.NewParser(&options, flags.Default).ParseArgs(os.Args[1:])
if err != nil {
if p == nil {
fmt.Println(err)
}
return
}
if options.Version {
fmt.Println(Version)
os.Exit(0)
}
if len(options.Args.Endpoints) == 0 {
exit(1, "must specify at least one endpoint\n")
}
switch len(options.Verbose) {
case 0:
logger = logger.Level(zerolog.WarnLevel)
case 1:
logger = logger.Level(zerolog.InfoLevel)
default:
logger = logger.Level(zerolog.DebugLevel)
}
// Setup signals
ctx, abort := context.WithCancel(context.Background())
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
go func(abort context.CancelFunc) {
<-sigCh
logger.Warn().Msg("interrupt received, shutting down")
abort()
<-sigCh
logger.Error().Msg("second interrupt received, panicking")
panic("aborted")
}(abort)
if err := run(ctx, options); err != nil {
exit(2, "error during run: %s\n", err)
}
}
func parseStopAfter(s string) (time.Duration, int, error) {
n, err := strconv.ParseUint(s, 10, 32)
if err == nil {
return 0, int(n), nil
}
d, err := time.ParseDuration(s)
if err != nil {
return 0, 0, fmt.Errorf("failed to parse duration: %w", err)
}
return d, 0, nil
}
func run(ctx context.Context, options Options) error {
var stopAfter int
if options.StopAfter != "" {
d, n, err := parseStopAfter(options.StopAfter)
if err != nil {
return err
}
if d > 0 {
timeoutCtx, cancel := context.WithTimeout(ctx, d)
defer cancel()
ctx = timeoutCtx
}
stopAfter = n
}
var timeout time.Duration
if options.Timeout != "" {
d, err := time.ParseDuration(options.Timeout)
if err != nil {
return fmt.Errorf("failed to parse request timeout: %w", err)
}
timeout = d
}
if options.Concurrency < 1 {
logger.Info().Int("concurrency", options.Concurrency).Msg("concurrency is less than 1, overriding to 1")
options.Concurrency = 1
}
g, ctx := errgroup.WithContext(ctx)
respBuffer := options.Concurrency * 4
if respBuffer < 50 {
respBuffer = 50
}
// responses is closed when clients are shut down
responses := make(chan Response, respBuffer)
// Launch clients
clients, err := NewClients(options.Args.Endpoints, options.Concurrency, timeout)
if err != nil {
return fmt.Errorf("failed to create clients: %w", err)
}
r := report{Clients: clients}
g.Go(func() error {
return r.Serve(ctx, responses)
})
if len(options.Verbose) > 0 {
r.MismatchedResponse = func(resps []Response) {
logger.Info().Int("id", int(resps[0].ID)).Msgf("mismatched responses: %s", Responses(resps).String())
}
}
g.Go(func() error {
defer close(responses)
return clients.Serve(ctx, responses)
})
logger.Info().Int("clients", len(clients)).Msg("started endpoint clients, waiting for stdin")
g.Go(func() error {
return pump(ctx, os.Stdin, clients, stopAfter)
})
if err := g.Wait(); err == context.Canceled {
// Shutting down
} else if err != nil {
return fmt.Errorf("failed to serve: %w", err)
}
// Report
return r.Render(os.Stdout)
}
// pump takes lines from a reader and pumps them into the clients
func pump(ctx context.Context, r io.Reader, clients Clients, stopAfter int) error {
defer clients.Finalize()
scanner := bufio.NewScanner(r)
// Some lines are really long, let's allocate a big fat megabyte for lines.
buf := make([]byte, 1024*1024)
scanner.Buffer(buf, cap(buf))
n := 0
for scanner.Scan() {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
line := scanner.Bytes()
if len(line) == 0 { // Done
logger.Debug().Msg("reached end of feed")
return nil
}
if err := clients.Send(ctx, line); err != nil {
return err
}
n += 1
if stopAfter > 0 && n >= stopAfter {
logger.Info().Msgf("stopping request feed after %d requests", n)
return nil
}
}
if err := scanner.Err(); err != nil {
return err
}
return nil
}