-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
requester.go
243 lines (212 loc) · 5.95 KB
/
requester.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
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package requester provides commands to run load tests and display results.
package requester
import (
"bytes"
"crypto/tls"
"io"
"io/ioutil"
"net/http"
"net/http/httptrace"
"net/url"
"os"
"sync"
"time"
"golang.org/x/net/http2"
)
const heyUA = "hey/0.0.1"
type result struct {
err error
statusCode int
duration time.Duration
connDuration time.Duration // connection setup(DNS lookup + Dial up) duration
dnsDuration time.Duration // dns lookup duration
reqDuration time.Duration // request "write" duration
resDuration time.Duration // response "read" duration
delayDuration time.Duration // delay between response and request
contentLength int64
}
type Work struct {
// Request is the request to be made.
Request *http.Request
RequestBody []byte
// N is the total number of requests to make.
N int
// C is the concurrency level, the number of concurrent workers to run.
C int
// H2 is an option to make HTTP/2 requests
H2 bool
// Timeout in seconds.
Timeout int
// Qps is the rate limit.
QPS int
// DisableCompression is an option to disable compression in response
DisableCompression bool
// DisableKeepAlives is an option to prevents re-use of TCP connections between different HTTP requests
DisableKeepAlives bool
// DisableRedirects is an option to prevent the following of HTTP redirects
DisableRedirects bool
// Output represents the output type. If "csv" is provided, the
// output will be dumped as a csv stream.
Output string
// ProxyAddr is the address of HTTP proxy server in the format on "host:port".
// Optional.
ProxyAddr *url.URL
// Writer is where results will be written. If nil, results are written to stdout.
Writer io.Writer
results chan *result
stopCh chan struct{}
start time.Time
}
func (b *Work) writer() io.Writer {
if b.Writer == nil {
return os.Stdout
}
return b.Writer
}
// Run makes all the requests, prints the summary. It blocks until
// all work is done.
func (b *Work) Run() {
// append hey's user agent
ua := b.Request.UserAgent()
if ua == "" {
ua = heyUA
} else {
ua += " " + heyUA
}
b.results = make(chan *result, b.N)
b.stopCh = make(chan struct{}, 1000)
b.start = time.Now()
b.runWorkers()
b.Finish()
}
func (b *Work) Finish() {
b.stopCh <- struct{}{}
close(b.results)
total := time.Now().Sub(b.start)
newReport(b.writer(), b.N, b.results, b.Output, total).finalize()
}
func (b *Work) makeRequest(c *http.Client) {
s := time.Now()
var size int64
var code int
var dnsStart, connStart, resStart, reqStart, delayStart time.Time
var dnsDuration, connDuration, resDuration, reqDuration, delayDuration time.Duration
req := cloneRequest(b.Request, b.RequestBody)
trace := &httptrace.ClientTrace{
DNSStart: func(info httptrace.DNSStartInfo) {
dnsStart = time.Now()
},
DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
dnsDuration = time.Now().Sub(dnsStart)
},
GetConn: func(h string) {
connStart = time.Now()
},
GotConn: func(connInfo httptrace.GotConnInfo) {
connDuration = time.Now().Sub(connStart)
reqStart = time.Now()
},
WroteRequest: func(w httptrace.WroteRequestInfo) {
reqDuration = time.Now().Sub(reqStart)
delayStart = time.Now()
},
GotFirstResponseByte: func() {
delayDuration = time.Now().Sub(delayStart)
resStart = time.Now()
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
resp, err := c.Do(req)
if err == nil {
size = resp.ContentLength
code = resp.StatusCode
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}
t := time.Now()
resDuration = t.Sub(resStart)
finish := t.Sub(s)
b.results <- &result{
statusCode: code,
duration: finish,
err: err,
contentLength: size,
connDuration: connDuration,
dnsDuration: dnsDuration,
reqDuration: reqDuration,
resDuration: resDuration,
delayDuration: delayDuration,
}
}
func (b *Work) runWorker(n int) {
var throttle <-chan time.Time
if b.QPS > 0 {
throttle = time.Tick(time.Duration(1e6/(b.QPS)) * time.Microsecond)
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
DisableCompression: b.DisableCompression,
DisableKeepAlives: b.DisableKeepAlives,
Proxy: http.ProxyURL(b.ProxyAddr),
}
if b.H2 {
http2.ConfigureTransport(tr)
} else {
tr.TLSNextProto = make(map[string]func(string, *tls.Conn) http.RoundTripper)
}
client := &http.Client{Transport: tr, Timeout: time.Duration(b.Timeout) * time.Second}
if b.DisableRedirects {
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
for i := 0; i < n; i++ {
if b.QPS > 0 {
<-throttle
}
b.makeRequest(client)
}
}
func (b *Work) runWorkers() {
var wg sync.WaitGroup
wg.Add(b.C)
// Ignore the case where b.N % b.C != 0.
for i := 0; i < b.C; i++ {
go func() {
b.runWorker(b.N / b.C)
wg.Done()
}()
}
wg.Wait()
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request, body []byte) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header, len(r.Header))
for k, s := range r.Header {
r2.Header[k] = append([]string(nil), s...)
}
if len(body) > 0 {
r2.Body = ioutil.NopCloser(bytes.NewReader(body))
}
return r2
}