forked from bojand/ghz
/
main.go
270 lines (221 loc) · 7.98 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"runtime"
"strings"
"time"
"github.com/bojand/ghz"
"github.com/bojand/ghz/config"
"github.com/bojand/ghz/printer"
"github.com/bojand/ghz/protodesc"
"github.com/jhump/protoreflect/desc"
)
var (
// set by goreleaser with -ldflags="-X main.version=..."
version = "dev"
proto = flag.String("proto", "", `The .proto file.`)
protoset = flag.String("protoset", "", `The .protoset file.`)
call = flag.String("call", "", `A fully-qualified symbol name.`)
cert = flag.String("cert", "", "Client certificate file. If Omitted insecure is used.")
cname = flag.String("cname", "", "Server Cert CName Override - useful for self signed certs.")
cPath = flag.String("config", "", "Path to the config JSON file.")
insecure = flag.Bool("insecure", false, "Specify for non TLS connection")
c = flag.Int("c", 50, "Number of requests to run concurrently.")
n = flag.Int("n", 200, "Number of requests to run. Default is 200.")
q = flag.Int("q", 0, "Rate limit, in queries per second (QPS). Default is no rate limit.")
t = flag.Int("t", 20, "Timeout for each request in seconds.")
z = flag.Duration("z", 0, "Duration of application to send requests.")
x = flag.Duration("x", 0, "Maximum duration of application to send requests.")
data = flag.String("d", "", "The call data as stringified JSON. If the value is '@' then the request contents are read from stdin.")
dataPath = flag.String("D", "", "Path for call data JSON file.")
binData = flag.Bool("b", false, "The call data as serialized binary message read from stdin.")
binPath = flag.String("B", "", "The call data as serialized binary message read from a file.")
md = flag.String("m", "", "Request metadata as stringified JSON.")
mdPath = flag.String("M", "", "Path for call metadata JSON file.")
paths = flag.String("i", "", "Comma separated list of proto import paths")
output = flag.String("o", "", "Output path")
format = flag.String("O", "", "Output format")
ct = flag.Int("T", 10, "Connection timeout in seconds for the initial connection dial.")
kt = flag.Int("L", 0, "Keepalive time in seconds.")
name = flag.String("name", "", "Name of the test.")
cpus = flag.Int("cpus", runtime.GOMAXPROCS(-1), "")
v = flag.Bool("v", false, "Print the version.")
localConfigName = "ghz.json"
)
var usage = `Usage: ghz [options...] <host>
Options:
-proto The protocol buffer file.
-protoset The compiled protoset file. Alternative to proto. -proto takes precedence.
-call A fully-qualified method name in 'service/method' or 'service.method' format.
-cert The file containing the CA root cert file.
-cname An override of the expect Server Cname presented by the server.
-config Path to the config JSON file
-insecure Specify for non TLS connection
-c Number of requests to run concurrently. Total number of requests cannot
be smaller than the concurrency level. Default is 50.
-n Number of requests to run. Default is 200.
-q Rate limit, in queries per second (QPS). Default is no rate limit.
-t Timeout for each request in seconds. Default is 20, use 0 for infinite.
-z Duration of application to send requests. When duration is reached,
application stops and exits. If duration is specified, n is ignored.
Examples: -z 10s -z 3m.
-x Maximum duration of application to send requests with n setting respected.
If duration is reached before n requests are completed, application stops and exits.
Examples: -x 10s -x 3m.
-d The call data as stringified JSON.
If the value is '@' then the request contents are read from stdin.
-D Path for call data JSON file. For example, /home/user/file.json or ./file.json.
-b The call data comes as serialized binary message read from stdin.
-B Path for the call data as serialized binary message.
-m Request metadata as stringified JSON.
-M Path for call metadata JSON file. For example, /home/user/metadata.json or ./metadata.json.
-o Output path. If none provided stdout is used.
-O Output type. If none provided, a summary is printed.
"csv" outputs the response metrics in comma-separated values format.
"json" outputs the metrics report in JSON format.
"pretty" outputs the metrics report in pretty JSON format.
"html" outputs the metrics report as HTML.
"influx-summary" outputs the metrics summary as influxdb line protocol.
"influx-details" outputs the metrics details as influxdb line protocol.
-i Comma separated list of proto import paths. The current working directory and the directory
of the protocol buffer file are automatically added to the import list.
-T Connection timeout in seconds for the initial connection dial. Default is 10.
-L Keepalive time in seconds. Only used if present and above 0.
-name Name of the test.
-cpus Number of used cpu cores. (default for current machine is %d cores)
-v Print the version.
`
func main() {
flag.Usage = func() {
fmt.Fprint(os.Stderr, fmt.Sprintf(usage, runtime.NumCPU()))
}
flag.Parse()
if *v {
fmt.Println(version)
os.Exit(0)
}
var cfg *config.Config
cfgPath := strings.TrimSpace(*cPath)
if cfgPath != "" {
var err error
cfg, err = config.ReadConfig(cfgPath)
if err != nil {
errAndExit(err.Error())
}
} else if _, err := os.Stat(localConfigName); err == nil {
cfg, err = config.ReadConfig(localConfigName)
if err != nil {
errAndExit(err.Error())
}
} else {
if flag.NArg() < 1 {
usageAndExit("")
}
host := flag.Args()[0]
iPaths := []string{}
pathsTrimmed := strings.TrimSpace(*paths)
if pathsTrimmed != "" {
iPaths = strings.Split(pathsTrimmed, ",")
}
cfg, err = config.New(*proto, *protoset, *call, *cert, *cname, *n, *c, *q, *z, *x, *t,
*data, *dataPath, *binData, *binPath, *md, *mdPath, *output, *format, host,
*ct, *kt, *cpus, iPaths, *insecure, *name)
if err != nil {
errAndExit(err.Error())
}
}
runtime.GOMAXPROCS(cfg.CPUs)
report, err := runTest(cfg)
if err != nil {
errAndExit(err.Error())
}
output := os.Stdout
outputPath := strings.TrimSpace(cfg.Output)
if outputPath != "" {
f, err := os.Create(outputPath)
if err != nil {
errAndExit(err.Error())
}
defer f.Close()
output = f
}
p := printer.ReportPrinter{
Report: report,
Out: output}
p.Print(cfg.Format)
}
func errAndExit(msg string) {
fmt.Fprintf(os.Stderr, msg)
fmt.Fprintf(os.Stderr, "\n")
os.Exit(1)
}
func usageAndExit(msg string) {
if msg != "" {
fmt.Fprintf(os.Stderr, msg)
fmt.Fprintf(os.Stderr, "\n\n")
}
flag.Usage()
fmt.Fprintf(os.Stderr, "\n")
os.Exit(1)
}
func runTest(config *config.Config) (*ghz.Report, error) {
mtd, err := getMethodDesc(config)
if err != nil {
return nil, err
}
input := config.Proto
if config.Protoset != "" {
input = config.Protoset
}
binary := false
if len(config.BinData) > 0 {
binary = true
}
opts := &ghz.Options{
Proto: input,
Call: config.Call,
Host: config.Host,
Cert: config.Cert,
CName: config.CName,
N: config.N,
C: config.C,
QPS: config.QPS,
Z: config.Z,
Timeout: config.Timeout,
DialTimtout: config.DialTimeout,
KeepaliveTime: config.KeepaliveTime,
Data: config.Data,
BinData: config.BinData,
Binary: binary,
Metadata: config.Metadata,
Insecure: config.Insecure,
Name: config.Name,
}
reqr, err := ghz.New(mtd, opts)
if err != nil {
return nil, err
}
cancel := make(chan os.Signal, 1)
signal.Notify(cancel, os.Interrupt)
go func() {
<-cancel
reqr.Stop()
}()
if config.Z > 0 {
go func() {
time.Sleep(config.Z)
reqr.Stop()
fmt.Printf("Stopped due to test timeout after %+v\n", config.Z)
}()
}
return reqr.Run()
}
func getMethodDesc(config *config.Config) (*desc.MethodDescriptor, error) {
if config.Proto != "" {
return protodesc.GetMethodDescFromProto(config.Call, config.Proto, config.ImportPaths)
}
return protodesc.GetMethodDescFromProtoSet(config.Call, config.Protoset)
}