pax_global_header00006660000000000000000000000064146327165260014526gustar00rootroot0000000000000052 comment=37225312b0d31a8df6a869cc1e6a0c8a4b278851 hey-0.1.4+ds/000077500000000000000000000000001463271652600127175ustar00rootroot00000000000000hey-0.1.4+ds/.gitignore000066400000000000000000000000041463271652600147010ustar00rootroot00000000000000bin/hey-0.1.4+ds/.travis.yml000066400000000000000000000000341463271652600150250ustar00rootroot00000000000000language: go go: - "1.12" hey-0.1.4+ds/LICENSE000066400000000000000000000261401463271652600137270ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} 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. hey-0.1.4+ds/Makefile000066400000000000000000000004171463271652600143610ustar00rootroot00000000000000binary = hey release: GOOS=windows GOARCH=amd64 go build -o ./bin/$(binary)_windows_amd64 GOOS=linux GOARCH=amd64 go build -o ./bin/$(binary)_linux_amd64 GOOS=darwin GOARCH=amd64 go build -o ./bin/$(binary)_darwin_amd64 push: gsutil cp bin/* gs://$(binary)-release hey-0.1.4+ds/README.md000066400000000000000000000052501463271652600142000ustar00rootroot00000000000000![hey](http://i.imgur.com/szzD9q0.png) [![Build Status](https://travis-ci.org/rakyll/hey.svg?branch=master)](https://travis-ci.org/rakyll/hey) hey is a tiny program that sends some load to a web application. hey was originally called boom and was influenced from Tarek Ziade's tool at [tarekziade/boom](https://github.com/tarekziade/boom). Using the same name was a mistake as it resulted in cases where binary name conflicts created confusion. To preserve the name for its original owner, we renamed this project to hey. ## Installation * Linux 64-bit: https://storage.googleapis.com/hey-release/hey_linux_amd64 * Mac 64-bit: https://storage.googleapis.com/hey-release/hey_darwin_amd64 * Windows 64-bit: https://storage.googleapis.com/hey-release/hey_windows_amd64 ### Package Managers macOS: - [Homebrew](https://brew.sh/) users can use `brew install hey`. ## Usage hey runs provided number of requests in the provided concurrency level and prints stats. It also supports HTTP2 endpoints. ``` Usage: hey [options...] Options: -n Number of requests to run. Default is 200. -c Number of workers to run concurrently. Total number of requests cannot be smaller than the concurrency level. Default is 50. -q Rate limit, in queries per second (QPS) per worker. Default is no rate limit. -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. -o Output type. If none provided, a summary is printed. "csv" is the only supported alternative. Dumps the response metrics in comma-separated values format. -m HTTP method, one of GET, POST, PUT, DELETE, HEAD, OPTIONS. -H Custom HTTP header. You can specify as many as needed by repeating the flag. For example, -H "Accept: text/html" -H "Content-Type: application/xml" . -t Timeout for each request in seconds. Default is 20, use 0 for infinite. -A HTTP Accept header. -d HTTP request body. -D HTTP request body from file. For example, /home/user/file.txt or ./file.txt. -T Content-type, defaults to "text/html". -a Basic authentication, username:password. -x HTTP Proxy address as host:port. -h2 Enable HTTP/2. -host HTTP Host header. -disable-compression Disable compression. -disable-keepalive Disable keep-alive, prevents re-use of TCP connections between different HTTP requests. -disable-redirects Disable following of HTTP redirects -cpus Number of used cpu cores. (default for current machine is 8 cores) ``` Previously known as [github.com/rakyll/boom](https://github.com/rakyll/boom). hey-0.1.4+ds/go.mod000066400000000000000000000002161463271652600140240ustar00rootroot00000000000000module github.com/rakyll/hey require ( golang.org/x/net v0.0.0-20181017193950-04a2e542c03f golang.org/x/text v0.3.0 // indirect ) go 1.13 hey-0.1.4+ds/go.sum000066400000000000000000000005501463271652600140520ustar00rootroot00000000000000golang.org/x/net v0.0.0-20181017193950-04a2e542c03f h1:4pRM7zYwpBjCnfA1jRmhItLxYJkaEnsmuAcRtA347DA= golang.org/x/net v0.0.0-20181017193950-04a2e542c03f/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= hey-0.1.4+ds/hey.go000066400000000000000000000154141463271652600140400ustar00rootroot00000000000000// 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. // Command hey is an HTTP load generator. package main import ( "flag" "fmt" "io/ioutil" "math" "net/http" gourl "net/url" "os" "os/signal" "regexp" "runtime" "strings" "time" "github.com/rakyll/hey/requester" ) const ( headerRegexp = `^([\w-]+):\s*(.+)` authRegexp = `^(.+):([^\s].+)` heyUA = "hey/0.0.1" ) var ( m = flag.String("m", "GET", "") headers = flag.String("h", "", "") body = flag.String("d", "", "") bodyFile = flag.String("D", "", "") accept = flag.String("A", "", "") contentType = flag.String("T", "text/html", "") authHeader = flag.String("a", "", "") hostHeader = flag.String("host", "", "") output = flag.String("o", "", "") c = flag.Int("c", 50, "") n = flag.Int("n", 200, "") q = flag.Float64("q", 0, "") t = flag.Int("t", 20, "") z = flag.Duration("z", 0, "") h2 = flag.Bool("h2", false, "") cpus = flag.Int("cpus", runtime.GOMAXPROCS(-1), "") disableCompression = flag.Bool("disable-compression", false, "") disableKeepAlives = flag.Bool("disable-keepalive", false, "") disableRedirects = flag.Bool("disable-redirects", false, "") proxyAddr = flag.String("x", "", "") ) var usage = `Usage: hey [options...] Options: -n Number of requests to run. Default is 200. -c Number of workers to run concurrently. Total number of requests cannot be smaller than the concurrency level. Default is 50. -q Rate limit, in queries per second (QPS) per worker. Default is no rate limit. -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. -o Output type. If none provided, a summary is printed. "csv" is the only supported alternative. Dumps the response metrics in comma-separated values format. -m HTTP method, one of GET, POST, PUT, DELETE, HEAD, OPTIONS. -H Custom HTTP header. You can specify as many as needed by repeating the flag. For example, -H "Accept: text/html" -H "Content-Type: application/xml" . -t Timeout for each request in seconds. Default is 20, use 0 for infinite. -A HTTP Accept header. -d HTTP request body. -D HTTP request body from file. For example, /home/user/file.txt or ./file.txt. -T Content-type, defaults to "text/html". -a Basic authentication, username:password. -x HTTP Proxy address as host:port. -h2 Enable HTTP/2. -host HTTP Host header. -disable-compression Disable compression. -disable-keepalive Disable keep-alive, prevents re-use of TCP connections between different HTTP requests. -disable-redirects Disable following of HTTP redirects -cpus Number of used cpu cores. (default for current machine is %d cores) ` func main() { flag.Usage = func() { fmt.Fprint(os.Stderr, fmt.Sprintf(usage, runtime.NumCPU())) } var hs headerSlice flag.Var(&hs, "H", "") flag.Parse() if flag.NArg() < 1 { usageAndExit("") } runtime.GOMAXPROCS(*cpus) num := *n conc := *c q := *q dur := *z if dur > 0 { num = math.MaxInt32 if conc <= 0 { usageAndExit("-c cannot be smaller than 1.") } } else { if num <= 0 || conc <= 0 { usageAndExit("-n and -c cannot be smaller than 1.") } if num < conc { usageAndExit("-n cannot be less than -c.") } } url := flag.Args()[0] method := strings.ToUpper(*m) // set content-type header := make(http.Header) header.Set("Content-Type", *contentType) // set any other additional headers if *headers != "" { usageAndExit("Flag '-h' is deprecated, please use '-H' instead.") } // set any other additional repeatable headers for _, h := range hs { match, err := parseInputWithRegexp(h, headerRegexp) if err != nil { usageAndExit(err.Error()) } header.Set(match[1], match[2]) } if *accept != "" { header.Set("Accept", *accept) } // set basic auth if set var username, password string if *authHeader != "" { match, err := parseInputWithRegexp(*authHeader, authRegexp) if err != nil { usageAndExit(err.Error()) } username, password = match[1], match[2] } var bodyAll []byte if *body != "" { bodyAll = []byte(*body) } if *bodyFile != "" { slurp, err := ioutil.ReadFile(*bodyFile) if err != nil { errAndExit(err.Error()) } bodyAll = slurp } var proxyURL *gourl.URL if *proxyAddr != "" { var err error proxyURL, err = gourl.Parse(*proxyAddr) if err != nil { usageAndExit(err.Error()) } } req, err := http.NewRequest(method, url, nil) if err != nil { usageAndExit(err.Error()) } req.ContentLength = int64(len(bodyAll)) if username != "" || password != "" { req.SetBasicAuth(username, password) } // set host header if set if *hostHeader != "" { req.Host = *hostHeader } ua := req.UserAgent() if ua == "" { ua = heyUA } else { ua += " " + heyUA } header.Set("User-Agent", ua) req.Header = header w := &requester.Work{ Request: req, RequestBody: bodyAll, N: num, C: conc, QPS: q, Timeout: *t, DisableCompression: *disableCompression, DisableKeepAlives: *disableKeepAlives, DisableRedirects: *disableRedirects, H2: *h2, ProxyAddr: proxyURL, Output: *output, } w.Init() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { <-c w.Stop() }() if dur > 0 { go func() { time.Sleep(dur) w.Stop() }() } w.Run() } 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 parseInputWithRegexp(input, regx string) ([]string, error) { re := regexp.MustCompile(regx) matches := re.FindStringSubmatch(input) if len(matches) < 1 { return nil, fmt.Errorf("could not parse the provided input; input = %v", input) } return matches, nil } type headerSlice []string func (h *headerSlice) String() string { return fmt.Sprintf("%s", *h) } func (h *headerSlice) Set(value string) error { *h = append(*h, value) return nil } hey-0.1.4+ds/hey_test.go000066400000000000000000000040561463271652600150770ustar00rootroot00000000000000// 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 main import ( "testing" ) func TestParseValidHeaderFlag(t *testing.T) { match, err := parseInputWithRegexp("X-Something: !Y10K:;(He@poverflow?)", headerRegexp) if err != nil { t.Errorf("parseInputWithRegexp errored: %v", err) } if got, want := match[1], "X-Something"; got != want { t.Errorf("got %v; want %v", got, want) } if got, want := match[2], "!Y10K:;(He@poverflow?)"; got != want { t.Errorf("got %v; want %v", got, want) } } func TestParseInvalidHeaderFlag(t *testing.T) { _, err := parseInputWithRegexp("X|oh|bad-input: badbadbad", headerRegexp) if err == nil { t.Errorf("Header parsing errored; want no errors") } } func TestParseValidAuthFlag(t *testing.T) { match, err := parseInputWithRegexp("_coo-kie_:!!bigmonster@1969sid", authRegexp) if err != nil { t.Errorf("A valid auth flag was not parsed correctly: %v", err) } if got, want := match[1], "_coo-kie_"; got != want { t.Errorf("got %v; want %v", got, want) } if got, want := match[2], "!!bigmonster@1969sid"; got != want { t.Errorf("got %v; want %v", got, want) } } func TestParseInvalidAuthFlag(t *testing.T) { _, err := parseInputWithRegexp("X|oh|bad-input: badbadbad", authRegexp) if err == nil { t.Errorf("Header parsing errored; want no errors") } } func TestParseAuthMetaCharacters(t *testing.T) { _, err := parseInputWithRegexp("plus+$*{:boom", authRegexp) if err != nil { t.Errorf("Auth header with a plus sign in the user name errored: %v", err) } } hey-0.1.4+ds/requester/000077500000000000000000000000001463271652600147365ustar00rootroot00000000000000hey-0.1.4+ds/requester/now_other.go000066400000000000000000000014361463271652600172750ustar00rootroot00000000000000// Copyright 2018 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. // +build !windows package requester import "time" var startTime = time.Now() // now returns time.Duration using stdlib time func now() time.Duration { return time.Since(startTime) } hey-0.1.4+ds/requester/now_windows.go000066400000000000000000000030161463271652600176420ustar00rootroot00000000000000// Copyright 2018 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 import ( "syscall" "time" "unsafe" ) // now returns time.Duration using queryPerformanceCounter func now() time.Duration { var now int64 syscall.Syscall(queryPerformanceCounterProc.Addr(), 1, uintptr(unsafe.Pointer(&now)), 0, 0) return time.Duration(now) * time.Second / (time.Duration(qpcFrequency) * time.Nanosecond) } // precision timing var ( modkernel32 = syscall.NewLazyDLL("kernel32.dll") queryPerformanceFrequencyProc = modkernel32.NewProc("QueryPerformanceFrequency") queryPerformanceCounterProc = modkernel32.NewProc("QueryPerformanceCounter") qpcFrequency = queryPerformanceFrequency() ) // queryPerformanceFrequency returns frequency in ticks per second func queryPerformanceFrequency() int64 { var freq int64 r1, _, _ := syscall.Syscall(queryPerformanceFrequencyProc.Addr(), 1, uintptr(unsafe.Pointer(&freq)), 0, 0) if r1 == 0 { panic("call failed") } return freq } hey-0.1.4+ds/requester/print.go000066400000000000000000000115111463271652600164200ustar00rootroot00000000000000// 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. /* Hey supports two output formats: summary and CSV The summary output presents a number of statistics about the requests in a human-readable format, including: - general statistics: requests/second, total runtime, and average, fastest, and slowest requests. - a response time histogram. - a percentile latency distribution. - statistics (average, fastest, slowest) on the stages of the requests. The comma-separated CSV format is proceeded by a header, and consists of the following columns: 1. response-time: Total time taken for request (in seconds) 2. DNS+dialup: Time taken to establish the TCP connection (in seconds) 3. DNS: Time taken to do the DNS lookup (in seconds) 4. Request-write: Time taken to write full request (in seconds) 5. Response-delay: Time taken to first byte received (in seconds) 6. Response-read: Time taken to read full response (in seconds) 7. status-code: HTTP status code of the response (e.g. 200) 8. offset: The time since the start of the benchmark when the request was started. (in seconds) */ package requester import ( "bytes" "encoding/json" "fmt" "strings" "text/template" ) func newTemplate(output string) *template.Template { outputTmpl := output switch outputTmpl { case "": outputTmpl = defaultTmpl case "csv": outputTmpl = csvTmpl } return template.Must(template.New("tmpl").Funcs(tmplFuncMap).Parse(outputTmpl)) } var tmplFuncMap = template.FuncMap{ "formatNumber": formatNumber, "formatNumberInt": formatNumberInt, "histogram": histogram, "jsonify": jsonify, } func jsonify(v interface{}) string { d, _ := json.Marshal(v) return string(d) } func formatNumber(duration float64) string { return fmt.Sprintf("%4.4f", duration) } func formatNumberInt(duration int) string { return fmt.Sprintf("%d", duration) } func histogram(buckets []Bucket) string { max := 0 for _, b := range buckets { if v := b.Count; v > max { max = v } } res := new(bytes.Buffer) for i := 0; i < len(buckets); i++ { // Normalize bar lengths. var barLen int if max > 0 { barLen = (buckets[i].Count*40 + max/2) / max } res.WriteString(fmt.Sprintf(" %4.3f [%v]\t|%v\n", buckets[i].Mark, buckets[i].Count, strings.Repeat(barChar, barLen))) } return res.String() } var ( defaultTmpl = ` Summary: Total: {{ formatNumber .Total.Seconds }} secs Slowest: {{ formatNumber .Slowest }} secs Fastest: {{ formatNumber .Fastest }} secs Average: {{ formatNumber .Average }} secs Requests/sec: {{ formatNumber .Rps }} {{ if gt .SizeTotal 0 }} Total data: {{ .SizeTotal }} bytes Size/request: {{ .SizeReq }} bytes{{ end }} Response time histogram: {{ histogram .Histogram }} Latency distribution:{{ range .LatencyDistribution }} {{ .Percentage }}%% in {{ formatNumber .Latency }} secs{{ end }} Details (average, fastest, slowest): DNS+dialup: {{ formatNumber .AvgConn }} secs, {{ formatNumber .Fastest }} secs, {{ formatNumber .Slowest }} secs DNS-lookup: {{ formatNumber .AvgDNS }} secs, {{ formatNumber .DnsMax }} secs, {{ formatNumber .DnsMin }} secs req write: {{ formatNumber .AvgReq }} secs, {{ formatNumber .ReqMax }} secs, {{ formatNumber .ReqMin }} secs resp wait: {{ formatNumber .AvgDelay }} secs, {{ formatNumber .DelayMax }} secs, {{ formatNumber .DelayMin }} secs resp read: {{ formatNumber .AvgRes }} secs, {{ formatNumber .ResMax }} secs, {{ formatNumber .ResMin }} secs Status code distribution:{{ range $code, $num := .StatusCodeDist }} [{{ $code }}] {{ $num }} responses{{ end }} {{ if gt (len .ErrorDist) 0 }}Error distribution:{{ range $err, $num := .ErrorDist }} [{{ $num }}] {{ $err }}{{ end }}{{ end }} ` csvTmpl = `{{ $connLats := .ConnLats }}{{ $dnsLats := .DnsLats }}{{ $dnsLats := .DnsLats }}{{ $reqLats := .ReqLats }}{{ $delayLats := .DelayLats }}{{ $resLats := .ResLats }}{{ $statusCodeLats := .StatusCodes }}{{ $offsets := .Offsets}}response-time,DNS+dialup,DNS,Request-write,Response-delay,Response-read,status-code,offset{{ range $i, $v := .Lats }} {{ formatNumber $v }},{{ formatNumber (index $connLats $i) }},{{ formatNumber (index $dnsLats $i) }},{{ formatNumber (index $reqLats $i) }},{{ formatNumber (index $delayLats $i) }},{{ formatNumber (index $resLats $i) }},{{ formatNumberInt (index $statusCodeLats $i) }},{{ formatNumber (index $offsets $i) }}{{ end }}` ) hey-0.1.4+ds/requester/report.go000066400000000000000000000172721463271652600166110ustar00rootroot00000000000000// 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 import ( "bytes" "fmt" "io" "log" "sort" "time" ) const ( barChar = "■" ) // We report for max 1M results. const maxRes = 1000000 type report struct { avgTotal float64 fastest float64 slowest float64 average float64 rps float64 avgConn float64 avgDNS float64 avgReq float64 avgRes float64 avgDelay float64 connLats []float64 dnsLats []float64 reqLats []float64 resLats []float64 delayLats []float64 offsets []float64 statusCodes []int results chan *result done chan bool total time.Duration errorDist map[string]int lats []float64 sizeTotal int64 numRes int64 output string w io.Writer } func newReport(w io.Writer, results chan *result, output string, n int) *report { cap := min(n, maxRes) return &report{ output: output, results: results, done: make(chan bool, 1), errorDist: make(map[string]int), w: w, connLats: make([]float64, 0, cap), dnsLats: make([]float64, 0, cap), reqLats: make([]float64, 0, cap), resLats: make([]float64, 0, cap), delayLats: make([]float64, 0, cap), lats: make([]float64, 0, cap), statusCodes: make([]int, 0, cap), } } func runReporter(r *report) { // Loop will continue until channel is closed for res := range r.results { r.numRes++ if res.err != nil { r.errorDist[res.err.Error()]++ } else { r.avgTotal += res.duration.Seconds() r.avgConn += res.connDuration.Seconds() r.avgDelay += res.delayDuration.Seconds() r.avgDNS += res.dnsDuration.Seconds() r.avgReq += res.reqDuration.Seconds() r.avgRes += res.resDuration.Seconds() if len(r.resLats) < maxRes { r.lats = append(r.lats, res.duration.Seconds()) r.connLats = append(r.connLats, res.connDuration.Seconds()) r.dnsLats = append(r.dnsLats, res.dnsDuration.Seconds()) r.reqLats = append(r.reqLats, res.reqDuration.Seconds()) r.delayLats = append(r.delayLats, res.delayDuration.Seconds()) r.resLats = append(r.resLats, res.resDuration.Seconds()) r.statusCodes = append(r.statusCodes, res.statusCode) r.offsets = append(r.offsets, res.offset.Seconds()) } if res.contentLength > 0 { r.sizeTotal += res.contentLength } } } // Signal reporter is done. r.done <- true } func (r *report) finalize(total time.Duration) { r.total = total r.rps = float64(r.numRes) / r.total.Seconds() r.average = r.avgTotal / float64(len(r.lats)) r.avgConn = r.avgConn / float64(len(r.lats)) r.avgDelay = r.avgDelay / float64(len(r.lats)) r.avgDNS = r.avgDNS / float64(len(r.lats)) r.avgReq = r.avgReq / float64(len(r.lats)) r.avgRes = r.avgRes / float64(len(r.lats)) r.print() } func (r *report) print() { buf := &bytes.Buffer{} if err := newTemplate(r.output).Execute(buf, r.snapshot()); err != nil { log.Println("error:", err.Error()) return } r.printf(buf.String()) r.printf("\n") } func (r *report) printf(s string, v ...interface{}) { fmt.Fprintf(r.w, s, v...) } func (r *report) snapshot() Report { snapshot := Report{ AvgTotal: r.avgTotal, Average: r.average, Rps: r.rps, SizeTotal: r.sizeTotal, AvgConn: r.avgConn, AvgDNS: r.avgDNS, AvgReq: r.avgReq, AvgRes: r.avgRes, AvgDelay: r.avgDelay, Total: r.total, ErrorDist: r.errorDist, NumRes: r.numRes, Lats: make([]float64, len(r.lats)), ConnLats: make([]float64, len(r.lats)), DnsLats: make([]float64, len(r.lats)), ReqLats: make([]float64, len(r.lats)), ResLats: make([]float64, len(r.lats)), DelayLats: make([]float64, len(r.lats)), Offsets: make([]float64, len(r.lats)), StatusCodes: make([]int, len(r.lats)), } if len(r.lats) == 0 { return snapshot } snapshot.SizeReq = r.sizeTotal / int64(len(r.lats)) copy(snapshot.Lats, r.lats) copy(snapshot.ConnLats, r.connLats) copy(snapshot.DnsLats, r.dnsLats) copy(snapshot.ReqLats, r.reqLats) copy(snapshot.ResLats, r.resLats) copy(snapshot.DelayLats, r.delayLats) copy(snapshot.StatusCodes, r.statusCodes) copy(snapshot.Offsets, r.offsets) sort.Float64s(r.lats) r.fastest = r.lats[0] r.slowest = r.lats[len(r.lats)-1] sort.Float64s(r.connLats) sort.Float64s(r.dnsLats) sort.Float64s(r.reqLats) sort.Float64s(r.resLats) sort.Float64s(r.delayLats) snapshot.Histogram = r.histogram() snapshot.LatencyDistribution = r.latencies() snapshot.Fastest = r.fastest snapshot.Slowest = r.slowest snapshot.ConnMax = r.connLats[0] snapshot.ConnMin = r.connLats[len(r.connLats)-1] snapshot.DnsMax = r.dnsLats[0] snapshot.DnsMin = r.dnsLats[len(r.dnsLats)-1] snapshot.ReqMax = r.reqLats[0] snapshot.ReqMin = r.reqLats[len(r.reqLats)-1] snapshot.DelayMax = r.delayLats[0] snapshot.DelayMin = r.delayLats[len(r.delayLats)-1] snapshot.ResMax = r.resLats[0] snapshot.ResMin = r.resLats[len(r.resLats)-1] statusCodeDist := make(map[int]int, len(snapshot.StatusCodes)) for _, statusCode := range snapshot.StatusCodes { statusCodeDist[statusCode]++ } snapshot.StatusCodeDist = statusCodeDist return snapshot } func (r *report) latencies() []LatencyDistribution { pctls := []int{10, 25, 50, 75, 90, 95, 99} data := make([]float64, len(pctls)) j := 0 for i := 0; i < len(r.lats) && j < len(pctls); i++ { current := i * 100 / len(r.lats) if current >= pctls[j] { data[j] = r.lats[i] j++ } } res := make([]LatencyDistribution, len(pctls)) for i := 0; i < len(pctls); i++ { if data[i] > 0 { res[i] = LatencyDistribution{Percentage: pctls[i], Latency: data[i]} } } return res } func (r *report) histogram() []Bucket { bc := 10 buckets := make([]float64, bc+1) counts := make([]int, bc+1) bs := (r.slowest - r.fastest) / float64(bc) for i := 0; i < bc; i++ { buckets[i] = r.fastest + bs*float64(i) } buckets[bc] = r.slowest var bi int var max int for i := 0; i < len(r.lats); { if r.lats[i] <= buckets[bi] { i++ counts[bi]++ if max < counts[bi] { max = counts[bi] } } else if bi < len(buckets)-1 { bi++ } } res := make([]Bucket, len(buckets)) for i := 0; i < len(buckets); i++ { res[i] = Bucket{ Mark: buckets[i], Count: counts[i], Frequency: float64(counts[i]) / float64(len(r.lats)), } } return res } type Report struct { AvgTotal float64 Fastest float64 Slowest float64 Average float64 Rps float64 AvgConn float64 AvgDNS float64 AvgReq float64 AvgRes float64 AvgDelay float64 ConnMax float64 ConnMin float64 DnsMax float64 DnsMin float64 ReqMax float64 ReqMin float64 ResMax float64 ResMin float64 DelayMax float64 DelayMin float64 Lats []float64 ConnLats []float64 DnsLats []float64 ReqLats []float64 ResLats []float64 DelayLats []float64 Offsets []float64 StatusCodes []int Total time.Duration ErrorDist map[string]int StatusCodeDist map[int]int SizeTotal int64 SizeReq int64 NumRes int64 LatencyDistribution []LatencyDistribution Histogram []Bucket } type LatencyDistribution struct { Percentage int Latency float64 } type Bucket struct { Mark float64 Count int Frequency float64 } hey-0.1.4+ds/requester/requester.go000066400000000000000000000157051463271652600173140ustar00rootroot00000000000000// 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" ) // Max size of the buffer of result channel. const maxResult = 1000000 const maxIdleConn = 500 type result struct { err error statusCode int offset time.Duration 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 // RequestFunc is a function to generate requests. If it is nil, then // Request and RequestData are cloned for each request. RequestFunc func() *http.Request // 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 in queries per second. QPS float64 // 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 initOnce sync.Once results chan *result stopCh chan struct{} start time.Duration report *report } func (b *Work) writer() io.Writer { if b.Writer == nil { return os.Stdout } return b.Writer } // Init initializes internal data-structures func (b *Work) Init() { b.initOnce.Do(func() { b.results = make(chan *result, min(b.C*1000, maxResult)) b.stopCh = make(chan struct{}, b.C) }) } // Run makes all the requests, prints the summary. It blocks until // all work is done. func (b *Work) Run() { b.Init() b.start = now() b.report = newReport(b.writer(), b.results, b.Output, b.N) // Run the reporter first, it polls the result channel until it is closed. go func() { runReporter(b.report) }() b.runWorkers() b.Finish() } func (b *Work) Stop() { // Send stop signal so that workers can stop gracefully. for i := 0; i < b.C; i++ { b.stopCh <- struct{}{} } } func (b *Work) Finish() { close(b.results) total := now() - b.start // Wait until the reporter is done. <-b.report.done b.report.finalize(total) } func (b *Work) makeRequest(c *http.Client) { s := now() var size int64 var code int var dnsStart, connStart, resStart, reqStart, delayStart time.Duration var dnsDuration, connDuration, resDuration, reqDuration, delayDuration time.Duration var req *http.Request if b.RequestFunc != nil { req = b.RequestFunc() } else { req = cloneRequest(b.Request, b.RequestBody) } trace := &httptrace.ClientTrace{ DNSStart: func(info httptrace.DNSStartInfo) { dnsStart = now() }, DNSDone: func(dnsInfo httptrace.DNSDoneInfo) { dnsDuration = now() - dnsStart }, GetConn: func(h string) { connStart = now() }, GotConn: func(connInfo httptrace.GotConnInfo) { if !connInfo.Reused { connDuration = now() - connStart } reqStart = now() }, WroteRequest: func(w httptrace.WroteRequestInfo) { reqDuration = now() - reqStart delayStart = now() }, GotFirstResponseByte: func() { delayDuration = now() - delayStart resStart = 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 := now() resDuration = t - resStart finish := t - s b.results <- &result{ offset: s, statusCode: code, duration: finish, err: err, contentLength: size, connDuration: connDuration, dnsDuration: dnsDuration, reqDuration: reqDuration, resDuration: resDuration, delayDuration: delayDuration, } } func (b *Work) runWorker(client *http.Client, n int) { var throttle <-chan time.Time if b.QPS > 0 { throttle = time.Tick(time.Duration(1e6/(b.QPS)) * time.Microsecond) } if b.DisableRedirects { client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } } for i := 0; i < n; i++ { // Check if application is stopped. Do not send into a closed channel. select { case <-b.stopCh: return default: if b.QPS > 0 { <-throttle } b.makeRequest(client) } } } func (b *Work) runWorkers() { var wg sync.WaitGroup wg.Add(b.C) tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: b.Request.Host, }, MaxIdleConnsPerHost: min(b.C, maxIdleConn), 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} // Ignore the case where b.N % b.C != 0. for i := 0; i < b.C; i++ { go func() { b.runWorker(client, 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 } func min(a, b int) int { if a < b { return a } return b } hey-0.1.4+ds/requester/requester_test.go000066400000000000000000000063571463271652600203560ustar00rootroot00000000000000// 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 import ( "bytes" "io/ioutil" "net/http" "net/http/httptest" "sync" "sync/atomic" "testing" "time" ) func TestN(t *testing.T) { var count int64 handler := func(w http.ResponseWriter, r *http.Request) { atomic.AddInt64(&count, int64(1)) } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() req, _ := http.NewRequest("GET", server.URL, nil) w := &Work{ Request: req, N: 20, C: 2, } w.Run() if count != 20 { t.Errorf("Expected to send 20 requests, found %v", count) } } func TestQps(t *testing.T) { var wg sync.WaitGroup var count int64 handler := func(w http.ResponseWriter, r *http.Request) { atomic.AddInt64(&count, int64(1)) } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() req, _ := http.NewRequest("GET", server.URL, nil) w := &Work{ Request: req, N: 20, C: 2, QPS: 1, } wg.Add(1) time.AfterFunc(time.Second, func() { if count > 2 { t.Errorf("Expected to work at most 2 times, found %v", count) } wg.Done() }) go w.Run() wg.Wait() } func TestRequest(t *testing.T) { var uri, contentType, some, auth string handler := func(w http.ResponseWriter, r *http.Request) { uri = r.RequestURI contentType = r.Header.Get("Content-type") some = r.Header.Get("X-some") auth = r.Header.Get("Authorization") } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() header := make(http.Header) header.Add("Content-type", "text/html") header.Add("X-some", "value") req, _ := http.NewRequest("GET", server.URL, nil) req.Header = header req.SetBasicAuth("username", "password") w := &Work{ Request: req, N: 1, C: 1, } w.Run() if uri != "/" { t.Errorf("Uri is expected to be /, %v is found", uri) } if contentType != "text/html" { t.Errorf("Content type is expected to be text/html, %v is found", contentType) } if some != "value" { t.Errorf("X-some header is expected to be value, %v is found", some) } if auth != "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" { t.Errorf("Basic authorization is not properly set") } } func TestBody(t *testing.T) { var count int64 handler := func(w http.ResponseWriter, r *http.Request) { body, _ := ioutil.ReadAll(r.Body) if string(body) == "Body" { atomic.AddInt64(&count, 1) } } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() req, _ := http.NewRequest("POST", server.URL, bytes.NewBuffer([]byte("Body"))) w := &Work{ Request: req, RequestBody: []byte("Body"), N: 10, C: 1, } w.Run() if count != 10 { t.Errorf("Expected to work 10 times, found %v", count) } }