├── .github ├── dependabot.yml └── workflows │ └── release.yml ├── .gitignore ├── .goreleaser.yaml ├── Dockerfile ├── LICENSE ├── README.md ├── bench_server └── main.go ├── charts.go ├── demo.gif ├── echarts.min.js ├── go.mod ├── go.sum ├── jquery.min.js ├── main.go ├── print.go ├── report.go └── requester.go /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: gomod 9 | directory: "/" 10 | schedule: 11 | interval: weekly 12 | 13 | - package-ecosystem: "github-actions" 14 | directory: "/" 15 | schedule: 16 | interval: weekly 17 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: 6 | - 'main' 7 | tags: 8 | - 'v*' 9 | pull_request: 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Set up Go 17 | uses: actions/setup-go@v3 18 | with: 19 | go-version: 1.23 20 | - name: Cache Go modules 21 | uses: actions/cache@v3.0.5 22 | with: 23 | path: ~/go/pkg/mod 24 | key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 25 | restore-keys: | 26 | ${{ runner.os }}-go- 27 | # - 28 | # name: Tests 29 | # run: | 30 | # go mod tidy 31 | # go test -v ./... 32 | - name: Docker Login 33 | uses: docker/login-action@v2 34 | with: 35 | registry: ghcr.io 36 | username: ${{ github.repository_owner }} 37 | password: ${{ secrets.GITHUB_TOKEN }} 38 | - name: Run GoReleaser 39 | uses: goreleaser/goreleaser-action@v3 40 | if: success() && startsWith(github.ref, 'refs/tags/') 41 | with: 42 | version: latest 43 | args: release 44 | env: 45 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | .idea/ 8 | .DS_Store 9 | 10 | # Test binary, built with `go test -c` 11 | *.test 12 | 13 | # Output of the go coverage tool, specifically when used with LiteIDE 14 | *.out 15 | 16 | vendor/ 17 | bench_server/bench_server 18 | plow* 19 | dist/ 20 | -------------------------------------------------------------------------------- /.goreleaser.yaml: -------------------------------------------------------------------------------- 1 | project_name: plow 2 | builds: 3 | - env: [CGO_ENABLED=0] 4 | goos: 5 | - linux 6 | - windows 7 | - darwin 8 | goarch: 9 | - amd64 10 | - arm64 11 | dockers: 12 | - image_templates: ["ghcr.io/six-ddc/plow:{{ .Version }}"] 13 | dockerfile: Dockerfile 14 | build_flag_templates: 15 | - --label=org.opencontainers.image.title={{ .ProjectName }} 16 | - --label=org.opencontainers.image.description={{ .ProjectName }} 17 | - --label=org.opencontainers.image.url=https://github.com/six-ddc/plow 18 | - --label=org.opencontainers.image.source=https://github.com/six-ddc/plow 19 | - --label=org.opencontainers.image.version={{ .Version }} 20 | - --label=org.opencontainers.image.created={{ time "2006-01-02T15:04:05Z07:00" }} 21 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 22 | - --label=org.opencontainers.image.licenses=Apache-2.0 23 | - image_templates: ["ghcr.io/six-ddc/plow"] 24 | dockerfile: Dockerfile 25 | build_flag_templates: 26 | - --label=org.opencontainers.image.title={{ .ProjectName }} 27 | - --label=org.opencontainers.image.description={{ .ProjectName }} 28 | - --label=org.opencontainers.image.url=https://github.com/six-ddc/plow 29 | - --label=org.opencontainers.image.source=https://github.com/six-ddc/plow 30 | - --label=org.opencontainers.image.version={{ .Version }} 31 | - --label=org.opencontainers.image.created={{ time "2006-01-02T15:04:05Z07:00" }} 32 | - --label=org.opencontainers.image.revision={{ .FullCommit }} 33 | - --label=org.opencontainers.image.licenses=Apache-2.0 34 | nfpms: 35 | - maintainer: six-ddc@github 36 | description: A high-performance HTTP benchmarking tool with real-time web UI and terminal displaying. 37 | homepage: https://github.com/six-ddc/plow 38 | license: Apache-2.0 39 | formats: 40 | - deb 41 | - rpm 42 | - apk 43 | 44 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM scratch 2 | COPY plow /usr/bin/plow 3 | ENTRYPOINT ["/usr/bin/plow"] 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # plow 2 | 3 | [![build](https://github.com/six-ddc/plow/actions/workflows/release.yml/badge.svg)](https://github.com/six-ddc/plow/actions/workflows/release.yml) 4 | [![Homebrew](https://img.shields.io/badge/dynamic/json.svg?url=https://formulae.brew.sh/api/formula/plow.json&query=$.versions.stable&label=homebrew)](https://formulae.brew.sh/formula/plow) 5 | [![GitHub license](https://img.shields.io/github/license/six-ddc/plow.svg)](https://github.com/six-ddc/plow/blob/main/LICENSE) 6 | [![made-with-Go](https://img.shields.io/badge/Made%20with-Go-1f425f.svg)](http://golang.org) 7 | 8 | Plow is an HTTP(S) benchmarking tool, written in Golang. It uses 9 | excellent [fasthttp](https://github.com/valyala/fasthttp#http-client-comparison-with-nethttp) instead of Go's default 10 | net/http due to its lightning fast performance. 11 | 12 | Plow runs at a specified connections(option `-c`) concurrently and **real-time** records a summary statistics, histogram 13 | of execution time and calculates percentiles to display on Web UI and terminal. It can run for a set duration( 14 | option `-d`), for a fixed number of requests(option `-n`), or until Ctrl-C interrupted. 15 | 16 | The implementation of real-time computing Histograms and Quantiles using stream-based algorithms inspired 17 | by [prometheus](https://github.com/prometheus/client_golang) with low memory and CPU bounds. so it's almost no 18 | additional performance overhead for benchmarking. 19 | 20 | ![](https://github.com/six-ddc/plow/blob/main/demo.gif?raw=true) 21 | 22 | ```text 23 | ❯ ./plow http://127.0.0.1:8080/hello -c 20 24 | Benchmarking http://127.0.0.1:8080/hello using 20 connection(s). 25 | @ Real-time charts is listening on http://[::]:18888 26 | 27 | Summary: 28 | Elapsed 8.6s 29 | Count 969657 30 | 2xx 776392 31 | 4xx 193265 32 | RPS 112741.713 33 | Reads 10.192MB/s 34 | Writes 6.774MB/s 35 | 36 | Statistics Min Mean StdDev Max 37 | Latency 32µs 176µs 37µs 1.839ms 38 | RPS 108558.4 112818.12 2456.63 115949.98 39 | 40 | Latency Percentile: 41 | P50 P75 P90 P95 P99 P99.9 P99.99 42 | 173µs 198µs 222µs 238µs 274µs 352µs 498µs 43 | 44 | Latency Histogram: 45 | 141µs 273028 ■■■■■■■■■■■■■■■■■■■■■■■■ 46 | 177µs 458955 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 47 | 209µs 204717 ■■■■■■■■■■■■■■■■■■ 48 | 235µs 26146 ■■ 49 | 269µs 6029 ■ 50 | 320µs 721 51 | 403µs 58 52 | 524µs 3 53 | ``` 54 | 55 | - [Installation](#installation) 56 | - [Via Go](#via-go) 57 | - [Via Homebrew](#via-homebrew) 58 | - [Via Docker](#via-docker) 59 | - [Usage](#usage) 60 | - [Options](#options) 61 | - [Examples](#examples) 62 | - [Stargazers](#Stargazers) 63 | - [License](#license) 64 | 65 | ## Installation 66 | 67 | Binary and image distributions are available through the [releases](https://github.com/six-ddc/plow/releases) 68 | assets page. 69 | 70 | ### Via Go 71 | 72 | ```bash 73 | go install github.com/six-ddc/plow@latest 74 | ``` 75 | 76 | ### Via Homebrew 77 | 78 | ```sh 79 | # brew update 80 | brew install plow 81 | ``` 82 | 83 | ### Via Docker 84 | 85 | ```bash 86 | docker run --rm --net=host ghcr.io/six-ddc/plow 87 | # docker run --rm -p 18888:18888 ghcr.io/six-ddc/plow 88 | ``` 89 | 90 | ## Usage 91 | 92 | ### Options 93 | 94 | ```bash 95 | usage: plow [] 96 | 97 | A high-performance HTTP benchmarking tool with real-time web UI and terminal displaying 98 | 99 | Examples: 100 | 101 | plow http://127.0.0.1:8080/ -c 20 -n 100000 102 | plow https://httpbin.org/post -c 20 -d 5m --body @file.json -T 'application/json' -m POST 103 | 104 | Flags: 105 | --help Show context-sensitive help. 106 | -c, --concurrency=1 Number of connections to run concurrently 107 | --rate=infinity Number of requests per time unit, examples: --rate 50 --rate 10/ms 108 | -n, --requests=-1 Number of requests to run 109 | -d, --duration=DURATION Duration of test, examples: -d 10s -d 3m 110 | -i, --interval=200ms Print snapshot result every interval, use 0 to print once at the end 111 | --seconds Use seconds as time unit to print 112 | --json Print snapshot result as JSON 113 | -b, --body=BODY HTTP request body, if start the body with @, the rest should be a filename to read 114 | --stream Specify whether to stream file specified by '--body @file' using chunked encoding or to read into memory 115 | -m, --method="GET" HTTP method 116 | -H, --header=K:V ... Custom HTTP headers 117 | --host=HOST Host header 118 | -T, --content=CONTENT Content-Type header 119 | --cert=CERT Path to the client's TLS Certificate 120 | --key=KEY Path to the client's TLS Certificate Private Key 121 | -k, --insecure Controls whether a client verifies the server's certificate chain and host name 122 | --listen=":18888" Listen addr to serve Web UI 123 | --timeout=DURATION Timeout for each http request 124 | --dial-timeout=DURATION Timeout for dial addr 125 | --req-timeout=DURATION Timeout for full request writing 126 | --resp-timeout=DURATION Timeout for full response reading 127 | --socks5=ip:port Socks5 proxy 128 | --auto-open-browser Specify whether auto open browser to show Web charts 129 | --[no-]clean Clean the histogram bar once its finished. Default is true 130 | --summary Only print the summary without realtime reports 131 | --version Show application version. 132 | 133 | Flags default values also read from env PLOW_SOME_FLAG, such as PLOW_TIMEOUT=5s equals to --timeout=5s 134 | 135 | Args: 136 | request url 137 | ``` 138 | 139 | ### Examples 140 | 141 | Basic usage: 142 | 143 | ```bash 144 | plow http://127.0.0.1:8080/ -c 20 -n 10000 -d 10s 145 | ``` 146 | 147 | POST a json file: 148 | 149 | ```bash 150 | plow https://httpbin.org/post -c 20 --body @file.json -T 'application/json' -m POST 151 | ``` 152 | 153 | ### Bash/ZSH Shell Completion 154 | 155 | ```bash 156 | # Add the statement to their bash_profile (or equivalent): 157 | eval "$(plow --completion-script-bash)" 158 | # Or for ZSH 159 | eval "$(plow --completion-script-zsh)" 160 | ``` 161 | 162 | ## Stargazers 163 | 164 | [![Stargazers over time](https://starchart.cc/six-ddc/plow.svg)](https://starchart.cc/six-ddc/plow) 165 | 166 | ## License 167 | 168 | See [LICENSE](https://github.com/six-ddc/plow/blob/master/LICENSE). 169 | -------------------------------------------------------------------------------- /bench_server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "log" 6 | "math/rand" 7 | "net/http" 8 | "strconv" 9 | 10 | "github.com/valyala/fasthttp" 11 | ) 12 | 13 | var serverPort = flag.Int("p", 8080, "port to use for benchmarks") 14 | 15 | func main() { 16 | flag.Parse() 17 | addr := "localhost:" + strconv.Itoa(*serverPort) 18 | log.Println("Starting HTTP server on:", addr) 19 | log.Fatalln(fasthttp.ListenAndServe(addr, func(c *fasthttp.RequestCtx) { 20 | //time.Sleep(time.Duration(rand.Int63n(int64(5 * time.Second)))) 21 | statusCodes := []int{ 22 | http.StatusOK, http.StatusOK, http.StatusBadRequest, http.StatusTooManyRequests, http.StatusBadGateway, 23 | } 24 | c.SetStatusCode(statusCodes[rand.Intn(len(statusCodes))]) 25 | _, werr := c.Write(c.Request.Body()) 26 | if werr != nil { 27 | log.Println(werr) 28 | } 29 | })) 30 | } 31 | -------------------------------------------------------------------------------- /charts.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "embed" 6 | "encoding/json" 7 | "fmt" 8 | "net" 9 | "os" 10 | "os/exec" 11 | "runtime" 12 | "strings" 13 | "text/template" 14 | "time" 15 | 16 | _ "embed" 17 | 18 | cors "github.com/AdhityaRamadhanus/fasthttpcors" 19 | "github.com/go-echarts/go-echarts/v2/charts" 20 | "github.com/go-echarts/go-echarts/v2/components" 21 | "github.com/go-echarts/go-echarts/v2/opts" 22 | "github.com/go-echarts/go-echarts/v2/templates" 23 | "github.com/valyala/fasthttp" 24 | ) 25 | 26 | //go:embed echarts.min.js 27 | //go:embed jquery.min.js 28 | var assetsFS embed.FS 29 | 30 | var ( 31 | assetsPath = "/echarts/statics/" 32 | apiPath = "/data/" 33 | latencyView = "latency" 34 | rpsView = "rps" 35 | codeView = "code" 36 | concurrencyView = "concurrency" 37 | timeFormat = "15:04:05" 38 | refreshInterval = time.Second 39 | 40 | templateRegistry = map[string]string{ 41 | rpsView: ViewTpl, 42 | latencyView: ViewTpl, 43 | codeView: CodeViewTpl, 44 | concurrencyView: ViewTpl, 45 | } 46 | ) 47 | 48 | const ( 49 | ViewTpl = ` 50 | $(function () { setInterval({{ .ViewID }}_sync, {{ .Interval }}); }); 51 | function {{ .ViewID }}_sync() { 52 | $.ajax({ 53 | type: "GET", 54 | url: "{{ .APIPath }}{{ .Route }}", 55 | dataType: "json", 56 | success: function (result) { 57 | let opt = goecharts_{{ .ViewID }}.getOption(); 58 | let x = opt.xAxis[0].data; 59 | x.push(result.time); 60 | opt.xAxis[0].data = x; 61 | for (let i = 0; i < result.values.length; i++) { 62 | let y = opt.series[i].data; 63 | y.push({ value: result.values[i] }); 64 | opt.series[i].data = y; 65 | goecharts_{{ .ViewID }}.setOption(opt); 66 | } 67 | } 68 | }); 69 | }` 70 | PageTpl = ` 71 | {{- define "page" }} 72 | 73 | 74 | {{- template "header" . }} 75 | 76 |

🚀 Plow %s

77 | 78 |
{{- range .Charts }} {{ template "base" . }} {{- end }}
79 | 80 | 81 | {{ end }} 82 | ` 83 | CodeViewTpl = ` 84 | $(function () { setInterval({{ .ViewID }}_sync, {{ .Interval }}); }); 85 | function {{ .ViewID }}_sync() { 86 | $.ajax({ 87 | type: "GET", 88 | url: "{{ .APIPath }}{{ .Route }}", 89 | dataType: "json", 90 | success: function (result) { 91 | let opt = goecharts_{{ .ViewID }}.getOption(); 92 | let x = opt.xAxis[0].data; 93 | x.push(result.time); 94 | opt.xAxis[0].data = x; 95 | 96 | let nameAndSeriesMapping = {}; 97 | for (let i = 0; i < opt.series.length; i++) { 98 | nameAndSeriesMapping[opt.series[i].name] = opt.series[i]; 99 | } 100 | 101 | let code200Count = nameAndSeriesMapping['200'].data.length; 102 | 103 | let codes = result.values[0]; 104 | if (codes === null){ 105 | for (let key in nameAndSeriesMapping) { 106 | let series = nameAndSeriesMapping[key]; 107 | series.data.push({value:null}); 108 | } 109 | }else{ 110 | if (!('200' in codes)) { 111 | codes['200'] = null; 112 | } 113 | 114 | for (let code in codes) { 115 | let count = codes[code]; 116 | if (code in nameAndSeriesMapping){ 117 | let series = nameAndSeriesMapping[code]; 118 | series.data.push({value:count}); 119 | }else{ 120 | let data = []; 121 | for (let i = 0; i < code200Count; i++) { 122 | data.push[null]; 123 | } 124 | var newSeries = { 125 | name: code, 126 | type: 'line', 127 | data: data 128 | }; 129 | opt.series.push(newSeries); 130 | } 131 | } 132 | } 133 | 134 | goecharts_{{ .ViewID }}.setOption(opt); 135 | } 136 | }); 137 | }` 138 | ) 139 | 140 | func (c *Charts) genViewTemplate(vid, route string) string { 141 | tpl, err := template.New("view").Parse(templateRegistry[route]) 142 | if err != nil { 143 | panic("failed to parse template " + err.Error()) 144 | } 145 | 146 | var d = struct { 147 | Interval int 148 | APIPath string 149 | Route string 150 | ViewID string 151 | }{ 152 | Interval: int(refreshInterval.Milliseconds()), 153 | APIPath: apiPath, 154 | Route: route, 155 | ViewID: vid, 156 | } 157 | 158 | buf := bytes.Buffer{} 159 | if err := tpl.Execute(&buf, d); err != nil { 160 | panic("failed to execute template " + err.Error()) 161 | } 162 | 163 | return buf.String() 164 | } 165 | 166 | func (c *Charts) newBasicView(route string) *charts.Line { 167 | graph := charts.NewLine() 168 | graph.SetGlobalOptions( 169 | charts.WithTooltipOpts(opts.Tooltip{Show: opts.Bool(true), Trigger: "axis"}), 170 | charts.WithXAxisOpts(opts.XAxis{Name: "Time"}), 171 | charts.WithInitializationOpts(opts.Initialization{ 172 | Width: "700px", 173 | Height: "400px", 174 | }), 175 | charts.WithDataZoomOpts(opts.DataZoom{ 176 | Type: "slider", 177 | XAxisIndex: []int{0}, 178 | }), 179 | ) 180 | graph.SetXAxis([]string{}).SetSeriesOptions(charts.WithLineChartOpts(opts.LineChart{Smooth: opts.Bool(true)})) 181 | graph.AddJSFuncs(c.genViewTemplate(graph.ChartID, route)) 182 | return graph 183 | } 184 | 185 | func (c *Charts) newLatencyView() components.Charter { 186 | graph := c.newBasicView(latencyView) 187 | graph.SetGlobalOptions( 188 | charts.WithTitleOpts(opts.Title{Title: "Latency"}), 189 | charts.WithYAxisOpts(opts.YAxis{Scale: opts.Bool(true), AxisLabel: &opts.AxisLabel{Formatter: "{value} ms"}}), 190 | charts.WithLegendOpts(opts.Legend{Show: opts.Bool(true), Selected: map[string]bool{"Min": false, "Max": false}}), 191 | ) 192 | graph.AddSeries("Min", []opts.LineData{}). 193 | AddSeries("Mean", []opts.LineData{}). 194 | AddSeries("Max", []opts.LineData{}) 195 | return graph 196 | } 197 | 198 | func (c *Charts) newRPSView() components.Charter { 199 | graph := c.newBasicView(rpsView) 200 | graph.SetGlobalOptions( 201 | charts.WithTitleOpts(opts.Title{Title: "Reqs/sec"}), 202 | charts.WithYAxisOpts(opts.YAxis{Scale: opts.Bool(true)}), 203 | ) 204 | graph.AddSeries("RPS", []opts.LineData{}) 205 | return graph 206 | } 207 | 208 | func (c *Charts) newCodeView() components.Charter { 209 | graph := c.newBasicView(codeView) 210 | graph.SetGlobalOptions( 211 | charts.WithTitleOpts(opts.Title{Title: "Response Status"}), 212 | charts.WithYAxisOpts(opts.YAxis{Scale: opts.Bool(true)}), 213 | charts.WithLegendOpts(opts.Legend{Show: opts.Bool(true)}), 214 | ) 215 | graph.AddSeries("200", []opts.LineData{}) 216 | return graph 217 | } 218 | 219 | func (c *Charts) newConcurrencyView() components.Charter { 220 | graph := c.newBasicView(concurrencyView) 221 | graph.SetGlobalOptions( 222 | charts.WithTitleOpts(opts.Title{Title: "Concurrency"}), 223 | charts.WithYAxisOpts(opts.YAxis{Scale: opts.Bool(true)}), 224 | ) 225 | graph.AddSeries("Concurrency", []opts.LineData{}) 226 | return graph 227 | } 228 | 229 | type Metrics struct { 230 | Values []interface{} `json:"values"` 231 | Time string `json:"time"` 232 | } 233 | 234 | type Charts struct { 235 | page *components.Page 236 | ln net.Listener 237 | dataFunc func() *ChartsReport 238 | } 239 | 240 | func NewCharts(ln net.Listener, dataFunc func() *ChartsReport, desc string) (*Charts, error) { 241 | templates.PageTpl = fmt.Sprintf(PageTpl, desc) 242 | 243 | c := &Charts{ln: ln, dataFunc: dataFunc} 244 | c.page = components.NewPage() 245 | c.page.PageTitle = "plow" 246 | c.page.AssetsHost = assetsPath 247 | c.page.Assets.JSAssets.Add("jquery.min.js") 248 | c.page.AddCharts(c.newLatencyView(), c.newRPSView(), c.newCodeView(), c.newConcurrencyView()) 249 | 250 | return c, nil 251 | } 252 | 253 | func (c *Charts) Handler(ctx *fasthttp.RequestCtx) { 254 | path := string(ctx.Path()) 255 | if strings.HasPrefix(path, apiPath) { 256 | view := path[len(apiPath):] 257 | var values []interface{} 258 | reportData := c.dataFunc() 259 | switch view { 260 | case latencyView: 261 | if reportData != nil { 262 | values = append(values, reportData.Latency.min/1e6) 263 | values = append(values, reportData.Latency.Mean()/1e6) 264 | values = append(values, reportData.Latency.max/1e6) 265 | } else { 266 | values = append(values, nil, nil, nil) 267 | } 268 | case rpsView: 269 | if reportData != nil { 270 | values = append(values, reportData.RPS) 271 | } else { 272 | values = append(values, nil) 273 | } 274 | case codeView: 275 | if reportData != nil { 276 | values = append(values, reportData.CodeMap) 277 | } else { 278 | values = append(values, nil) 279 | } 280 | case concurrencyView: 281 | if reportData != nil { 282 | values = append(values, reportData.Concurrency) 283 | } else { 284 | values = append(values, nil) 285 | } 286 | } 287 | metrics := &Metrics{ 288 | Time: time.Now().Format(timeFormat), 289 | Values: values, 290 | } 291 | _ = json.NewEncoder(ctx).Encode(metrics) 292 | } else if path == "/" { 293 | ctx.SetContentType("text/html") 294 | _ = c.page.Render(ctx) 295 | } else if strings.HasPrefix(path, assetsPath) { 296 | ap := path[len(assetsPath):] 297 | f, err := assetsFS.Open(ap) 298 | if err != nil { 299 | ctx.Error(err.Error(), 404) 300 | } else { 301 | ctx.SetBodyStream(f, -1) 302 | } 303 | } else { 304 | ctx.Error("NotFound", fasthttp.StatusNotFound) 305 | } 306 | } 307 | 308 | func (c *Charts) Serve(open bool) { 309 | server := fasthttp.Server{ 310 | Handler: cors.DefaultHandler().CorsMiddleware(c.Handler), 311 | } 312 | if open { 313 | go openBrowser("http://" + c.ln.Addr().String()) 314 | } 315 | _ = server.Serve(c.ln) 316 | } 317 | 318 | // openBrowser go/src/cmd/internal/browser/browser.go 319 | func openBrowser(url string) bool { 320 | var cmds [][]string 321 | if exe := os.Getenv("BROWSER"); exe != "" { 322 | cmds = append(cmds, []string{exe}) 323 | } 324 | switch runtime.GOOS { 325 | case "darwin": 326 | cmds = append(cmds, []string{"/usr/bin/open"}) 327 | case "windows": 328 | cmds = append(cmds, []string{"cmd", "/c", "start"}) 329 | default: 330 | if os.Getenv("DISPLAY") != "" { 331 | // xdg-open is only for use in a desktop environment. 332 | cmds = append(cmds, []string{"xdg-open"}) 333 | } 334 | } 335 | cmds = append(cmds, 336 | []string{"chrome"}, 337 | []string{"google-chrome"}, 338 | []string{"chromium"}, 339 | []string{"firefox"}, 340 | ) 341 | for _, args := range cmds { 342 | cmd := exec.Command(args[0], append(args[1:], url)...) 343 | if cmd.Start() == nil && appearsSuccessful(cmd, 3*time.Second) { 344 | return true 345 | } 346 | } 347 | return false 348 | } 349 | 350 | // appearsSuccessful reports whether the command appears to have run successfully. 351 | // If the command runs longer than the timeout, it's deemed successful. 352 | // If the command runs within the timeout, it's deemed successful if it exited cleanly. 353 | func appearsSuccessful(cmd *exec.Cmd, timeout time.Duration) bool { 354 | errc := make(chan error, 1) 355 | go func() { 356 | errc <- cmd.Wait() 357 | }() 358 | 359 | select { 360 | case <-time.After(timeout): 361 | return true 362 | case err := <-errc: 363 | return err == nil 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/six-ddc/plow/0f4cba736bb25b0dc3da749502c94922fe74905b/demo.gif -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/six-ddc/plow 2 | 3 | go 1.21 4 | 5 | toolchain go1.23.0 6 | 7 | require ( 8 | github.com/AdhityaRamadhanus/fasthttpcors v0.0.0-20170121111917-d4c07198763a 9 | github.com/beorn7/perks v1.0.1 10 | github.com/go-echarts/go-echarts/v2 v2.4.5 11 | github.com/mattn/go-isatty v0.0.20 12 | github.com/mattn/go-runewidth v0.0.16 13 | github.com/valyala/fasthttp v1.57.0 14 | go.uber.org/automaxprocs v1.6.0 15 | golang.org/x/time v0.8.0 16 | gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20191105091915-95d230a53780 17 | ) 18 | 19 | require ( 20 | github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // indirect 21 | github.com/andybalholm/brotli v1.1.1 // indirect 22 | github.com/klauspost/compress v1.17.11 // indirect 23 | github.com/nicksnyder/go-i18n v1.10.3 // indirect 24 | github.com/pelletier/go-toml v1.9.5 // indirect 25 | github.com/rivo/uniseg v0.4.7 // indirect 26 | github.com/valyala/bytebufferpool v1.0.0 // indirect 27 | golang.org/x/net v0.31.0 // indirect 28 | golang.org/x/sys v0.27.0 // indirect 29 | golang.org/x/text v0.20.0 // indirect 30 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 31 | gopkg.in/yaml.v2 v2.4.0 // indirect 32 | ) 33 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/AdhityaRamadhanus/fasthttpcors v0.0.0-20170121111917-d4c07198763a h1:XVdatQFSP2YhJGjqLLIfW8QBk4loz/SCe/PxkXDiW+s= 2 | github.com/AdhityaRamadhanus/fasthttpcors v0.0.0-20170121111917-d4c07198763a/go.mod h1:C0A1KeiVHs+trY6gUTPhhGammbrZ30ZfXRW/nuT7HLw= 3 | github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b h1:mimo19zliBX/vSQ6PWWSL9lK8qwHozUj03+zLoEB8O0= 4 | github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b/go.mod h1:fvzegU4vN3H1qMT+8wDmzjAcDONcgo2/SZ/TyfdUOFs= 5 | github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= 6 | github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= 7 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= 8 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 9 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 11 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/go-echarts/go-echarts/v2 v2.4.5 h1:gwDqxdi5x329sg+g2ws2OklreJ1K34FCimraInurzwk= 13 | github.com/go-echarts/go-echarts/v2 v2.4.5/go.mod h1:56YlvzhW/a+du15f3S2qUGNDfKnFOeJSThBIrVFHDtI= 14 | github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= 15 | github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= 16 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= 17 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 18 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 19 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 20 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 21 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 22 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 23 | github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= 24 | github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 25 | github.com/nicksnyder/go-i18n v1.10.3 h1:0U60fnLBNrLBVt8vb8Q67yKNs+gykbQuLsIkiesJL+w= 26 | github.com/nicksnyder/go-i18n v1.10.3/go.mod h1:hvLG5HTlZ4UfSuVLSRuX7JRUomIaoKQM19hm6f+no7o= 27 | github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= 28 | github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= 29 | github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= 30 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 31 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 32 | github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= 33 | github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= 34 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 35 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= 36 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 37 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 38 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 39 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 40 | github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= 41 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 42 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 43 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 44 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 45 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 46 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 47 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 48 | github.com/valyala/fasthttp v1.57.0 h1:Xw8SjWGEP/+wAAgyy5XTvgrWlOD1+TxbbvNADYCm1Tg= 49 | github.com/valyala/fasthttp v1.57.0/go.mod h1:h6ZBaPRlzpZ6O3H5t2gEk1Qi33+TmLvfwgLLp0t9CpE= 50 | github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= 51 | github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= 52 | go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= 53 | go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= 54 | golang.org/x/net v0.31.0 h1:68CPQngjLL0r2AlUKiSxtQFKvzRVbnzLwMUn5SzcLHo= 55 | golang.org/x/net v0.31.0/go.mod h1:P4fl1q7dY2hnZFxEk4pPSkDHF+QqjitcnDjUQyMM+pM= 56 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 57 | golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= 58 | golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 59 | golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug= 60 | golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4= 61 | golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= 62 | golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= 63 | gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20191105091915-95d230a53780 h1:CEBpW6C191eozfEuWdUmIAHn7lwlLxJ7HVdr2e2Tsrw= 64 | gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20191105091915-95d230a53780/go.mod h1:3HH7i1SgMqlzxCcBmUHW657sD4Kvv9sC3HpL3YukzwA= 65 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 66 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 67 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 68 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 69 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 70 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 71 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 72 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 73 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 74 | -------------------------------------------------------------------------------- /jquery.min.js: -------------------------------------------------------------------------------- 1 | /*! jQuery v3.6.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */ 2 | !function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="
",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0{{if .Value|IsCumulative}} ...{{end}}{{if not .Required}}]{{end}}{{end -}} 69 | {{end -}} 70 | 71 | {{define "FormatCommandList" -}} 72 | {{range . -}} 73 | {{if not .Hidden -}} 74 | {{.Depth|Indent}}{{.Name}}{{if .Default}}*{{end}}{{template "FormatCommand" .}} 75 | {{end -}} 76 | {{template "FormatCommandList" .Commands -}} 77 | {{end -}} 78 | {{end -}} 79 | 80 | {{define "FormatUsage" -}} 81 | {{template "FormatCommand" .}}{{if .Commands}} [ ...]{{end}} 82 | {{if .Help}} 83 | {{.Help|Wrap 0 -}} 84 | {{end -}} 85 | 86 | {{end -}} 87 | 88 | {{if .Context.SelectedCommand -}} 89 | {{T "usage:"}} {{.App.Name}} {{template "FormatUsage" .Context.SelectedCommand}} 90 | {{else -}} 91 | {{T "usage:"}} {{.App.Name}}{{template "FormatUsage" .App}} 92 | {{end -}} 93 | Examples: 94 | 95 | plow http://127.0.0.1:8080/ -c 20 -n 100000 96 | plow https://httpbin.org/post -c 20 -d 5m --body @file.json -T 'application/json' -m POST 97 | 98 | {{if .Context.Flags -}} 99 | {{T "Flags:"}} 100 | {{.Context.Flags|FlagsToTwoColumns|FormatTwoColumns}} 101 | Flags default values also read from env PLOW_SOME_FLAG, such as PLOW_TIMEOUT=5s equals to --timeout=5s 102 | 103 | {{end -}} 104 | {{if .Context.Args -}} 105 | {{T "Args:"}} 106 | {{.Context.Args|ArgsToTwoColumns|FormatTwoColumns}} 107 | {{end -}} 108 | {{if .Context.SelectedCommand -}} 109 | {{if .Context.SelectedCommand.Commands -}} 110 | {{T "Commands:"}} 111 | {{.Context.SelectedCommand}} 112 | {{.Context.SelectedCommand.Commands|CommandsToTwoColumns|FormatTwoColumns}} 113 | {{end -}} 114 | {{else if .App.Commands -}} 115 | {{T "Commands:"}} 116 | {{.App.Commands|CommandsToTwoColumns|FormatTwoColumns}} 117 | {{end -}} 118 | ` 119 | 120 | type rateFlagValue struct { 121 | infinity bool 122 | limit rate.Limit 123 | v string 124 | } 125 | 126 | func (f *rateFlagValue) Set(v string) error { 127 | if v == "infinity" { 128 | f.infinity = true 129 | return nil 130 | } 131 | 132 | retErr := fmt.Errorf("--rate format %q doesn't match the \"freq/duration\" (i.e. 50/1s)", v) 133 | ps := strings.SplitN(v, "/", 2) 134 | switch len(ps) { 135 | case 1: 136 | ps = append(ps, "1s") 137 | case 0: 138 | return retErr 139 | } 140 | 141 | freq, err := strconv.Atoi(ps[0]) 142 | if err != nil { 143 | return retErr 144 | } 145 | if freq == 0 { 146 | f.infinity = true 147 | return nil 148 | } 149 | 150 | switch ps[1] { 151 | case "ns", "us", "µs", "ms", "s", "m", "h": 152 | ps[1] = "1" + ps[1] 153 | } 154 | 155 | per, err := time.ParseDuration(ps[1]) 156 | if err != nil { 157 | return retErr 158 | } 159 | 160 | f.limit = rate.Limit(float64(freq) / per.Seconds()) 161 | f.v = v 162 | return nil 163 | } 164 | 165 | func (f *rateFlagValue) Limit() *rate.Limit { 166 | if f.infinity { 167 | return nil 168 | } 169 | return &f.limit 170 | } 171 | 172 | func (f *rateFlagValue) String() string { 173 | return f.v 174 | } 175 | 176 | func rateFlag(c *kingpin.Clause) (target *rateFlagValue) { 177 | target = new(rateFlagValue) 178 | c.SetValue(target) 179 | return 180 | } 181 | 182 | func main() { 183 | kingpin.UsageTemplate(CompactUsageTemplate). 184 | Version(version). 185 | Author("six-ddc@github"). 186 | Resolver(kingpin.PrefixedEnvarResolver("PLOW_", ";")). 187 | Help = `A high-performance HTTP benchmarking tool with real-time web UI and terminal displaying` 188 | kingpin.Parse() 189 | 190 | if *requests >= 0 && *requests < int64(*concurrency) { 191 | errAndExit("requests must greater than or equal concurrency") 192 | return 193 | } 194 | if (*cert != "" && *key == "") || (*cert == "" && *key != "") { 195 | errAndExit("must specify cert and key at the same time") 196 | return 197 | } 198 | 199 | if *pprofAddr != "" { 200 | go http.ListenAndServe(*pprofAddr, nil) 201 | } 202 | 203 | var err error 204 | var bodyBytes []byte 205 | var bodyFile string 206 | 207 | if *body != "" { 208 | if strings.HasPrefix(*body, "@") { 209 | fileName := (*body)[1:] 210 | if _, err = os.Stat(fileName); err != nil { 211 | errAndExit(err.Error()) 212 | return 213 | } 214 | if *stream { 215 | bodyFile = fileName 216 | } else { 217 | bodyBytes, err = os.ReadFile(fileName) 218 | if err != nil { 219 | errAndExit(err.Error()) 220 | return 221 | } 222 | } 223 | } else { 224 | bodyBytes = []byte(*body) 225 | } 226 | 227 | if !methodSet { 228 | *method = "POST" 229 | } 230 | } 231 | 232 | errWriter := io.Discard 233 | if *outputErrors != "" { 234 | errWriter, err = os.Create(*outputErrors) 235 | if err != nil { 236 | errAndExit(err.Error()) 237 | return 238 | } 239 | } 240 | 241 | clientOpt := ClientOpt{ 242 | url: *url, 243 | method: *method, 244 | headers: *headers, 245 | bodyBytes: bodyBytes, 246 | bodyFile: bodyFile, 247 | 248 | certPath: *cert, 249 | keyPath: *key, 250 | insecure: *insecure, 251 | 252 | maxConns: *concurrency, 253 | doTimeout: *timeout, 254 | readTimeout: *respReadTimeout, 255 | writeTimeout: *reqWriteTimeout, 256 | dialTimeout: *dialTimeout, 257 | 258 | socks5Proxy: *socks5, 259 | contentType: *contentType, 260 | host: *host, 261 | } 262 | 263 | requester, err := NewRequester(*concurrency, *requests, *duration, reqRate.Limit(), errWriter, &clientOpt, *rampUp) 264 | if err != nil { 265 | errAndExit(err.Error()) 266 | return 267 | } 268 | 269 | // description 270 | var desc string 271 | desc = fmt.Sprintf("Benchmarking %s", *url) 272 | if *requests > 0 { 273 | desc += fmt.Sprintf(" with %d request(s)", *requests) 274 | } 275 | if *duration > 0 { 276 | desc += fmt.Sprintf(" for %s", duration.String()) 277 | } 278 | if *rampUp > 0 { 279 | desc += fmt.Sprintf(" with ramp up %d pre second", *rampUp) 280 | } 281 | desc += fmt.Sprintf(" using %d connection(s).", *concurrency) 282 | fmt.Fprintln(os.Stderr, desc) 283 | 284 | // charts listener 285 | var ln net.Listener 286 | if *chartsListenAddr != "" { 287 | ln, err = net.Listen("tcp", *chartsListenAddr) 288 | if err != nil { 289 | errAndExit(err.Error()) 290 | return 291 | } 292 | fmt.Fprintf(os.Stderr, "@ Real-time charts is listening on http://%s\n", ln.Addr().String()) 293 | } 294 | fmt.Fprintln(os.Stderr, "") 295 | 296 | // do request 297 | go requester.Run() 298 | 299 | // metrics collection 300 | report := NewStreamReport() 301 | go report.Collect(requester.RecordChan()) 302 | 303 | if ln != nil { 304 | // serve charts data 305 | charts, err := NewCharts(ln, report.Charts, desc) 306 | if err != nil { 307 | errAndExit(err.Error()) 308 | return 309 | } 310 | go charts.Serve(*autoOpenBrowser) 311 | } 312 | 313 | // terminal printer 314 | printer := NewPrinter(*requests, *duration, !*clean, *summary) 315 | printer.PrintLoop(report.Snapshot, *interval, *seconds, *jsonFormat, report.Done()) 316 | } 317 | -------------------------------------------------------------------------------- /print.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "math" 8 | "os" 9 | "regexp" 10 | "sort" 11 | "strconv" 12 | "strings" 13 | "time" 14 | 15 | "github.com/mattn/go-isatty" 16 | "github.com/mattn/go-runewidth" 17 | ) 18 | 19 | var ( 20 | maxBarLen = 40 21 | barStart = "|" 22 | barBody = "■" 23 | barEnd = "|" 24 | barSpinner = []string{"|", "/", "-", "\\"} 25 | clearLine = []byte("\r\033[K") 26 | isTerminal = isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) 27 | ) 28 | 29 | type Printer struct { 30 | maxNum int64 31 | maxDuration time.Duration 32 | curNum int64 33 | curDuration time.Duration 34 | pbInc int64 35 | pbNumStr string 36 | pbDurStr string 37 | noClean bool 38 | summary bool 39 | } 40 | 41 | func NewPrinter(maxNum int64, maxDuration time.Duration, noCleanBar, summary bool) *Printer { 42 | return &Printer{maxNum: maxNum, maxDuration: maxDuration, noClean: noCleanBar, summary: summary} 43 | } 44 | 45 | func (p *Printer) updateProgressValue(rs *SnapshotReport) { 46 | p.pbInc++ 47 | if p.maxDuration > 0 { 48 | n := rs.Elapsed 49 | if n > p.maxDuration { 50 | n = p.maxDuration 51 | } 52 | p.curDuration = n 53 | barLen := int((p.curDuration*time.Duration(maxBarLen-2) + p.maxDuration/2) / p.maxDuration) 54 | p.pbDurStr = barStart + strings.Repeat(barBody, barLen) + strings.Repeat(" ", maxBarLen-2-barLen) + barEnd 55 | } 56 | if p.maxNum > 0 { 57 | p.curNum = rs.Count 58 | if p.maxNum > 0 { 59 | barLen := int((p.curNum*int64(maxBarLen-2) + p.maxNum/2) / p.maxNum) 60 | p.pbNumStr = barStart + strings.Repeat(barBody, barLen) + strings.Repeat(" ", maxBarLen-2-barLen) + barEnd 61 | } else { 62 | idx := p.pbInc % int64(len(barSpinner)) 63 | p.pbNumStr = barSpinner[int(idx)] 64 | } 65 | } 66 | } 67 | 68 | func (p *Printer) PrintLoop(snapshot func() *SnapshotReport, interval time.Duration, useSeconds bool, json bool, doneChan <-chan struct{}) { 69 | var buf bytes.Buffer 70 | 71 | var backCursor string 72 | cl := clearLine 73 | if p.summary || interval == 0 || !isTerminal { 74 | cl = nil 75 | } 76 | echo := func(isFinal bool) { 77 | report := snapshot() 78 | p.updateProgressValue(report) 79 | os.Stdout.WriteString(backCursor) 80 | buf.Reset() 81 | if json { 82 | p.formatJSONReports(&buf, report, isFinal, useSeconds) 83 | } else { 84 | p.formatTableReports(&buf, report, isFinal, useSeconds) 85 | } 86 | result := buf.Bytes() 87 | n := 0 88 | for { 89 | i := bytes.IndexByte(result, '\n') 90 | if i == -1 { 91 | os.Stdout.Write(cl) 92 | os.Stdout.Write(result) 93 | break 94 | } 95 | n++ 96 | os.Stdout.Write(cl) 97 | os.Stdout.Write(result[:i]) 98 | os.Stdout.Write([]byte("\n")) 99 | result = result[i+1:] 100 | } 101 | os.Stdout.Sync() 102 | if isTerminal { 103 | backCursor = fmt.Sprintf("\033[%dA", n) 104 | } 105 | } 106 | 107 | if interval > 0 { 108 | ticker := time.NewTicker(interval) 109 | loop: 110 | for { 111 | select { 112 | case <-ticker.C: 113 | if !p.summary { 114 | echo(false) 115 | } 116 | case <-doneChan: 117 | ticker.Stop() 118 | break loop 119 | } 120 | } 121 | } else { 122 | <-doneChan 123 | } 124 | echo(true) 125 | } 126 | 127 | // nolint 128 | const ( 129 | FgBlackColor int = iota + 30 130 | FgRedColor 131 | FgGreenColor 132 | FgYellowColor 133 | FgBlueColor 134 | FgMagentaColor 135 | FgCyanColor 136 | FgWhiteColor 137 | ) 138 | 139 | func colorize(s string, seq int) string { 140 | if !isTerminal { 141 | return s 142 | } 143 | return fmt.Sprintf("\033[%dm%s\033[0m", seq, s) 144 | } 145 | 146 | func durationToString(d time.Duration, useSeconds bool) string { 147 | d = d.Truncate(time.Microsecond) 148 | if useSeconds { 149 | return formatFloat64(d.Seconds()) 150 | } 151 | return d.String() 152 | } 153 | 154 | func alignBulk(bulk [][]string, aligns ...int) { 155 | maxLen := map[int]int{} 156 | for _, b := range bulk { 157 | for i, bb := range b { 158 | lbb := displayWidth(bb) 159 | if maxLen[i] < lbb { 160 | maxLen[i] = lbb 161 | } 162 | } 163 | } 164 | for _, b := range bulk { 165 | for i, ali := range aligns { 166 | if len(b) >= i+1 { 167 | if i == len(aligns)-1 && ali == AlignLeft { 168 | continue 169 | } 170 | b[i] = padString(b[i], " ", maxLen[i], ali) 171 | } 172 | } 173 | } 174 | } 175 | 176 | func writeBulkWith(writer *bytes.Buffer, bulk [][]string, lineStart, sep, lineEnd string) { 177 | for _, b := range bulk { 178 | writer.WriteString(lineStart) 179 | writer.WriteString(b[0]) 180 | for _, bb := range b[1:] { 181 | writer.WriteString(sep) 182 | writer.WriteString(bb) 183 | } 184 | writer.WriteString(lineEnd) 185 | } 186 | } 187 | 188 | func writeBulk(writer *bytes.Buffer, bulk [][]string) { 189 | writeBulkWith(writer, bulk, " ", " ", "\n") 190 | } 191 | 192 | func formatFloat64(f float64) string { 193 | return strconv.FormatFloat(f, 'f', -1, 64) 194 | } 195 | 196 | func (p *Printer) formatJSONReports(writer *bytes.Buffer, snapshot *SnapshotReport, _ bool, useSeconds bool) { 197 | indent := 0 198 | writer.WriteString("{\n") 199 | indent++ 200 | p.buildJSONSummary(writer, snapshot, indent) 201 | if len(snapshot.Errors) != 0 { 202 | writer.WriteString(",\n") 203 | p.buildJSONErrors(writer, snapshot, indent) 204 | } 205 | writer.WriteString(",\n") 206 | p.buildJSONStats(writer, snapshot, useSeconds, indent) 207 | writer.WriteString(",\n") 208 | p.buildJSONPercentile(writer, snapshot, useSeconds, indent) 209 | writer.WriteString(",\n") 210 | p.buildJSONHistogram(writer, snapshot, useSeconds, indent) 211 | writer.WriteString("\n}\n") 212 | } 213 | 214 | func (p *Printer) formatTableReports(writer *bytes.Buffer, snapshot *SnapshotReport, isFinal bool, useSeconds bool) { 215 | summaryBulk := p.buildSummary(snapshot, isFinal) 216 | errorsBulks := p.buildErrors(snapshot) 217 | statsBulk := p.buildStats(snapshot, useSeconds) 218 | percBulk := p.buildPercentile(snapshot, useSeconds) 219 | hisBulk := p.buildHistogram(snapshot, useSeconds, isFinal) 220 | 221 | writer.WriteString("Summary:\n") 222 | writeBulk(writer, summaryBulk) 223 | writer.WriteString("\n") 224 | 225 | if errorsBulks != nil { 226 | writer.WriteString("Error:\n") 227 | writeBulk(writer, errorsBulks) 228 | writer.WriteString("\n") 229 | } 230 | 231 | writeBulkWith(writer, statsBulk, "", " ", "\n") 232 | writer.WriteString("\n") 233 | 234 | writer.WriteString("Latency Percentile:\n") 235 | writeBulk(writer, percBulk) 236 | writer.WriteString("\n") 237 | 238 | writer.WriteString("Latency Histogram:\n") 239 | writeBulk(writer, hisBulk) 240 | } 241 | 242 | func (p *Printer) buildJSONHistogram(writer *bytes.Buffer, snapshot *SnapshotReport, useSeconds bool, indent int) { 243 | tab0 := strings.Repeat(" ", indent) 244 | writer.WriteString(tab0 + "\"Histograms\": [\n") 245 | tab1 := strings.Repeat(" ", indent+1) 246 | 247 | maxCount := 0 248 | hisSum := 0 249 | for _, bin := range snapshot.Histograms { 250 | if maxCount < bin.Count { 251 | maxCount = bin.Count 252 | } 253 | hisSum += bin.Count 254 | } 255 | for i, bin := range snapshot.Histograms { 256 | writer.WriteString(fmt.Sprintf(`%s[ "%s", %d ]`, tab1, 257 | durationToString(bin.Mean, useSeconds), bin.Count)) 258 | if i != len(snapshot.Histograms)-1 { 259 | writer.WriteString(",") 260 | } 261 | writer.WriteString("\n") 262 | } 263 | writer.WriteString(tab0 + "]") 264 | } 265 | 266 | func (p *Printer) buildHistogram(snapshot *SnapshotReport, useSeconds bool, isFinal bool) [][]string { 267 | hisBulk := make([][]string, 0, 8) 268 | maxCount := 0 269 | hisSum := 0 270 | for _, bin := range snapshot.Histograms { 271 | if maxCount < bin.Count { 272 | maxCount = bin.Count 273 | } 274 | hisSum += bin.Count 275 | } 276 | for _, bin := range snapshot.Histograms { 277 | row := []string{durationToString(bin.Mean, useSeconds), strconv.Itoa(bin.Count)} 278 | if isFinal { 279 | row = append(row, fmt.Sprintf("%.2f%%", math.Floor(float64(bin.Count)*1e4/float64(hisSum)+0.5)/100.0)) 280 | } 281 | if !isFinal || p.noClean { 282 | barLen := 0 283 | if maxCount > 0 { 284 | barLen = (bin.Count*maxBarLen + maxCount/2) / maxCount 285 | } 286 | row = append(row, strings.Repeat(barBody, barLen)) 287 | } 288 | hisBulk = append(hisBulk, row) 289 | } 290 | if isFinal { 291 | alignBulk(hisBulk, AlignLeft, AlignRight, AlignRight) 292 | } else { 293 | alignBulk(hisBulk, AlignLeft, AlignRight, AlignLeft) 294 | } 295 | return hisBulk 296 | } 297 | 298 | func (p *Printer) buildJSONPercentile(writer *bytes.Buffer, snapshot *SnapshotReport, useSeconds bool, indent int) { 299 | tab0 := strings.Repeat(" ", indent) 300 | writer.WriteString(tab0 + "\"Percentiles\": {\n") 301 | tab1 := strings.Repeat(" ", indent+1) 302 | for i, percentile := range snapshot.Percentiles { 303 | perc := formatFloat64(percentile.Percentile * 100) 304 | writer.WriteString(fmt.Sprintf(`%s"%s": "%s"`, tab1, "P"+perc, 305 | durationToString(percentile.Latency, useSeconds))) 306 | if i != len(snapshot.Percentiles)-1 { 307 | writer.WriteString(",") 308 | } 309 | writer.WriteString("\n") 310 | } 311 | writer.WriteString(tab0 + "}") 312 | } 313 | 314 | func (p *Printer) buildPercentile(snapshot *SnapshotReport, useSeconds bool) [][]string { 315 | percBulk := make([][]string, 2) 316 | percAligns := make([]int, 0, len(snapshot.Percentiles)) 317 | for _, percentile := range snapshot.Percentiles { 318 | perc := formatFloat64(percentile.Percentile * 100) 319 | percBulk[0] = append(percBulk[0], "P"+perc) 320 | percBulk[1] = append(percBulk[1], durationToString(percentile.Latency, useSeconds)) 321 | percAligns = append(percAligns, AlignCenter) 322 | } 323 | percAligns[0] = AlignLeft 324 | alignBulk(percBulk, percAligns...) 325 | return percBulk 326 | } 327 | 328 | func (p *Printer) buildJSONStats(writer *bytes.Buffer, snapshot *SnapshotReport, useSeconds bool, indent int) { 329 | tab0 := strings.Repeat(" ", indent) 330 | writer.WriteString(tab0 + "\"Statistics\": {\n") 331 | tab1 := strings.Repeat(" ", indent+1) 332 | writer.WriteString(fmt.Sprintf(`%s"Latency": { "Min": "%s", "Mean": "%s", "StdDev": "%s", "Max": "%s" }`, 333 | tab1, 334 | durationToString(snapshot.Stats.Min, useSeconds), 335 | durationToString(snapshot.Stats.Mean, useSeconds), 336 | durationToString(snapshot.Stats.StdDev, useSeconds), 337 | durationToString(snapshot.Stats.Max, useSeconds), 338 | )) 339 | if snapshot.RpsStats != nil { 340 | writer.WriteString(",\n") 341 | writer.WriteString(fmt.Sprintf(`%s"RPS": { "Min": %s, "Mean": %s, "StdDev": %s, "Max": %s }`, 342 | tab1, 343 | formatFloat64(math.Trunc(snapshot.RpsStats.Min*100)/100.0), 344 | formatFloat64(math.Trunc(snapshot.RpsStats.Mean*100)/100.0), 345 | formatFloat64(math.Trunc(snapshot.RpsStats.StdDev*100)/100.0), 346 | formatFloat64(math.Trunc(snapshot.RpsStats.Max*100)/100.0), 347 | )) 348 | } 349 | writer.WriteString("\n" + tab0 + "}") 350 | } 351 | 352 | func (p *Printer) buildStats(snapshot *SnapshotReport, useSeconds bool) [][]string { 353 | var statsBulk [][]string 354 | statsBulk = append(statsBulk, 355 | []string{"Statistics", "Min", "Mean", "StdDev", "Max"}, 356 | []string{ 357 | " Latency", 358 | durationToString(snapshot.Stats.Min, useSeconds), 359 | durationToString(snapshot.Stats.Mean, useSeconds), 360 | durationToString(snapshot.Stats.StdDev, useSeconds), 361 | durationToString(snapshot.Stats.Max, useSeconds), 362 | }, 363 | ) 364 | if snapshot.RpsStats != nil { 365 | statsBulk = append(statsBulk, 366 | []string{ 367 | " RPS", 368 | formatFloat64(math.Trunc(snapshot.RpsStats.Min*100) / 100.0), 369 | formatFloat64(math.Trunc(snapshot.RpsStats.Mean*100) / 100.0), 370 | formatFloat64(math.Trunc(snapshot.RpsStats.StdDev*100) / 100.0), 371 | formatFloat64(math.Trunc(snapshot.RpsStats.Max*100) / 100.0), 372 | }, 373 | ) 374 | } 375 | alignBulk(statsBulk, AlignLeft, AlignCenter, AlignCenter, AlignCenter, AlignCenter) 376 | return statsBulk 377 | } 378 | 379 | func (p *Printer) buildJSONErrors(writer *bytes.Buffer, snapshot *SnapshotReport, indent int) { 380 | tab0 := strings.Repeat(" ", indent) 381 | writer.WriteString(tab0 + "\"Error\": {\n") 382 | tab1 := strings.Repeat(" ", indent+1) 383 | errors := sortMapStrInt(snapshot.Errors) 384 | for i, v := range errors { 385 | v[1] = colorize(v[1], FgRedColor) 386 | vb, _ := json.Marshal(v[0]) 387 | writer.WriteString(fmt.Sprintf(`%s%s: %s`, tab1, vb, v[1])) 388 | if i != len(errors)-1 { 389 | writer.WriteString(",") 390 | } 391 | writer.WriteString("\n") 392 | } 393 | writer.WriteString(tab0 + "}") 394 | } 395 | 396 | func (p *Printer) buildErrors(snapshot *SnapshotReport) [][]string { 397 | var errorsBulks [][]string 398 | for k, v := range snapshot.Errors { 399 | vs := colorize(strconv.FormatInt(v, 10), FgRedColor) 400 | errorsBulks = append(errorsBulks, []string{vs, "\"" + k + "\""}) 401 | } 402 | if errorsBulks != nil { 403 | sort.Slice(errorsBulks, func(i, j int) bool { return errorsBulks[i][1] < errorsBulks[j][1] }) 404 | } 405 | alignBulk(errorsBulks, AlignLeft, AlignLeft) 406 | return errorsBulks 407 | } 408 | 409 | func sortMapStrInt(m map[string]int64) (ret [][]string) { 410 | for k, v := range m { 411 | ret = append(ret, []string{k, strconv.FormatInt(v, 10)}) 412 | } 413 | sort.Slice(ret, func(i, j int) bool { return ret[i][0] < ret[j][0] }) 414 | return 415 | } 416 | 417 | func (p *Printer) buildJSONSummary(writer *bytes.Buffer, snapshot *SnapshotReport, indent int) { 418 | tab0 := strings.Repeat(" ", indent) 419 | writer.WriteString(tab0 + "\"Summary\": {\n") 420 | { 421 | tab1 := strings.Repeat(" ", indent+1) 422 | writer.WriteString(fmt.Sprintf("%s\"Elapsed\": \"%s\",\n", tab1, snapshot.Elapsed.Truncate(100*time.Millisecond).String())) 423 | writer.WriteString(fmt.Sprintf("%s\"Count\": %d,\n", tab1, snapshot.Count)) 424 | writer.WriteString(fmt.Sprintf("%s\"Counts\": {\n", tab1)) 425 | i := 0 426 | tab2 := strings.Repeat(" ", indent+2) 427 | codes := sortMapStrInt(snapshot.Codes) 428 | for _, v := range codes { 429 | i++ 430 | if v[0] != "2xx" { 431 | v[1] = colorize(v[1], FgMagentaColor) 432 | } 433 | writer.WriteString(fmt.Sprintf(`%s"%s": %s`, tab2, v[0], v[1])) 434 | if i != len(snapshot.Codes) { 435 | writer.WriteString(",") 436 | } 437 | writer.WriteString("\n") 438 | } 439 | writer.WriteString(tab1 + "},\n") 440 | writer.WriteString(fmt.Sprintf("%s\"RPS\": %.3f,\n", tab1, snapshot.RPS)) 441 | writer.WriteString(fmt.Sprintf("%s\"Concurrency\": %d,\n", tab1, snapshot.concurrencyCount)) 442 | writer.WriteString(fmt.Sprintf("%s\"Reads\": \"%.3fMB/s\",\n", tab1, snapshot.ReadThroughput)) 443 | writer.WriteString(fmt.Sprintf("%s\"Writes\": \"%.3fMB/s\"\n", tab1, snapshot.WriteThroughput)) 444 | } 445 | writer.WriteString(tab0 + "}") 446 | } 447 | 448 | func (p *Printer) buildSummary(snapshot *SnapshotReport, isFinal bool) [][]string { 449 | summarybulk := make([][]string, 0, 8) 450 | elapsedLine := []string{"Elapsed", snapshot.Elapsed.Truncate(100 * time.Millisecond).String()} 451 | if p.maxDuration > 0 && !isFinal { 452 | elapsedLine = append(elapsedLine, p.pbDurStr) 453 | } 454 | countLine := []string{"Count", strconv.FormatInt(snapshot.Count, 10)} 455 | if p.maxNum > 0 && !isFinal { 456 | countLine = append(countLine, p.pbNumStr) 457 | } 458 | summarybulk = append( 459 | summarybulk, 460 | elapsedLine, 461 | countLine, 462 | ) 463 | 464 | codes := sortMapStrInt(snapshot.Codes) 465 | for _, v := range codes { 466 | if v[0] != "2xx" { 467 | v[1] = colorize(v[1], FgMagentaColor) 468 | } 469 | summarybulk = append(summarybulk, []string{" " + v[0], v[1]}) 470 | } 471 | summarybulk = append(summarybulk, 472 | []string{"RPS", fmt.Sprintf("%.3f", snapshot.RPS)}, 473 | []string{"Concurrency", fmt.Sprintf("%d", snapshot.concurrencyCount)}, 474 | []string{"Reads", fmt.Sprintf("%.3fMB/s", snapshot.ReadThroughput)}, 475 | []string{"Writes", fmt.Sprintf("%.3fMB/s", snapshot.WriteThroughput)}, 476 | ) 477 | alignBulk(summarybulk, AlignLeft, AlignRight) 478 | return summarybulk 479 | } 480 | 481 | var ansi = regexp.MustCompile("\033\\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]") 482 | 483 | func displayWidth(str string) int { 484 | return runewidth.StringWidth(ansi.ReplaceAllLiteralString(str, "")) 485 | } 486 | 487 | const ( 488 | AlignLeft = iota 489 | AlignRight 490 | AlignCenter 491 | ) 492 | 493 | func padString(s, pad string, width int, align int) string { 494 | gap := width - displayWidth(s) 495 | if gap > 0 { 496 | if align == AlignLeft { 497 | return s + strings.Repeat(pad, gap) 498 | } else if align == AlignRight { 499 | return strings.Repeat(pad, gap) + s 500 | } else if align == AlignCenter { 501 | gapLeft := gap / 2 502 | gapRight := gap - gapLeft 503 | return strings.Repeat(pad, gapLeft) + s + strings.Repeat(pad, gapRight) 504 | } 505 | } 506 | return s 507 | } 508 | -------------------------------------------------------------------------------- /report.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "sync" 6 | "sync/atomic" 7 | "time" 8 | 9 | "github.com/beorn7/perks/histogram" 10 | "github.com/beorn7/perks/quantile" 11 | ) 12 | 13 | var quantiles = []float64{0.50, 0.75, 0.90, 0.95, 0.99, 0.999, 0.9999} 14 | 15 | var quantilesTarget = map[float64]float64{ 16 | 0.50: 0.01, 17 | 0.75: 0.01, 18 | 0.90: 0.001, 19 | 0.95: 0.001, 20 | 0.99: 0.001, 21 | 0.999: 0.0001, 22 | 0.9999: 0.00001, 23 | } 24 | 25 | var httpStatusSectionLabelMap = map[int]string{ 26 | 1: "1xx", 27 | 2: "2xx", 28 | 3: "3xx", 29 | 4: "4xx", 30 | 5: "5xx", 31 | } 32 | 33 | type Stats struct { 34 | count int64 35 | sum float64 36 | sumSq float64 37 | min float64 38 | max float64 39 | } 40 | 41 | func (s *Stats) Update(v float64) { 42 | s.count++ 43 | s.sum += v 44 | s.sumSq += v * v 45 | if v < s.min || s.count == 1 { 46 | s.min = v 47 | } 48 | if v > s.max || s.count == 1 { 49 | s.max = v 50 | } 51 | } 52 | 53 | func (s *Stats) Stddev() float64 { 54 | num := (float64(s.count) * s.sumSq) - math.Pow(s.sum, 2) 55 | div := float64(s.count * (s.count - 1)) 56 | if div == 0 { 57 | return 0 58 | } 59 | return math.Sqrt(num / div) 60 | } 61 | 62 | func (s *Stats) Mean() float64 { 63 | if s.count == 0 { 64 | return 0 65 | } 66 | return s.sum / float64(s.count) 67 | } 68 | 69 | func (s *Stats) Reset() { 70 | s.count = 0 71 | s.sum = 0 72 | s.sumSq = 0 73 | s.min = 0 74 | s.max = 0 75 | } 76 | 77 | type StreamReport struct { 78 | lock sync.Mutex 79 | 80 | latencyStats *Stats 81 | rpsStats *Stats 82 | latencyQuantile *quantile.Stream 83 | latencyHistogram *histogram.Histogram 84 | codes map[int]int64 85 | errors map[string]int64 86 | concurrencyCount int 87 | 88 | latencyWithinSec *Stats 89 | rpsWithinSec float64 90 | noDateWithinSec bool 91 | 92 | readBytes int64 93 | writeBytes int64 94 | 95 | doneChan chan struct{} 96 | } 97 | 98 | func NewStreamReport() *StreamReport { 99 | return &StreamReport{ 100 | latencyQuantile: quantile.NewTargeted(quantilesTarget), 101 | latencyHistogram: histogram.New(8), 102 | codes: make(map[int]int64, 1), 103 | errors: make(map[string]int64, 1), 104 | doneChan: make(chan struct{}, 1), 105 | latencyStats: &Stats{}, 106 | rpsStats: &Stats{}, 107 | latencyWithinSec: &Stats{}, 108 | } 109 | } 110 | 111 | func (s *StreamReport) insert(v float64) { 112 | s.latencyQuantile.Insert(v) 113 | s.latencyHistogram.Insert(v) 114 | s.latencyStats.Update(v) 115 | } 116 | 117 | func (s *StreamReport) Collect(records <-chan *ReportRecord) { 118 | latencyWithinSecTemp := &Stats{} 119 | go func() { 120 | startTime := time.Unix(0, atomic.LoadInt64(&startTimeUnixNano)) 121 | ticker := time.NewTicker(time.Second) 122 | lastCount := int64(0) 123 | lastTime := startTime 124 | for { 125 | select { 126 | case <-ticker.C: 127 | s.lock.Lock() 128 | dc := s.latencyStats.count - lastCount 129 | if dc > 0 { 130 | rps := float64(dc) / time.Since(lastTime).Seconds() 131 | s.rpsStats.Update(rps) 132 | lastCount = s.latencyStats.count 133 | lastTime = time.Now() 134 | 135 | *s.latencyWithinSec = *latencyWithinSecTemp 136 | s.rpsWithinSec = rps 137 | latencyWithinSecTemp.Reset() 138 | s.noDateWithinSec = false 139 | } else { 140 | s.noDateWithinSec = true 141 | } 142 | s.lock.Unlock() 143 | case <-s.doneChan: 144 | return 145 | } 146 | } 147 | }() 148 | 149 | for { 150 | r, ok := <-records 151 | if !ok { 152 | close(s.doneChan) 153 | break 154 | } 155 | s.lock.Lock() 156 | latencyWithinSecTemp.Update(float64(r.cost)) 157 | s.insert(float64(r.cost)) 158 | if r.code != 0 { 159 | s.codes[r.code]++ 160 | } 161 | if r.error != "" { 162 | s.errors[r.error]++ 163 | } 164 | s.readBytes = r.readBytes 165 | s.writeBytes = r.writeBytes 166 | s.concurrencyCount = r.concurrencyCount 167 | s.lock.Unlock() 168 | recordPool.Put(r) 169 | } 170 | } 171 | func (s *StreamReport) copyCodes() map[int]int64 { 172 | res := make(map[int]int64, len(s.codes)) 173 | for k, v := range s.codes { 174 | res[k] = v 175 | } 176 | return res 177 | } 178 | 179 | type SnapshotReport struct { 180 | Elapsed time.Duration 181 | Count int64 182 | Codes map[string]int64 183 | Errors map[string]int64 184 | RPS float64 185 | ReadThroughput float64 186 | WriteThroughput float64 187 | concurrencyCount int 188 | 189 | Stats *struct { 190 | Min time.Duration 191 | Mean time.Duration 192 | StdDev time.Duration 193 | Max time.Duration 194 | } 195 | 196 | RpsStats *struct { 197 | Min float64 198 | Mean float64 199 | StdDev float64 200 | Max float64 201 | } 202 | 203 | Percentiles []*struct { 204 | Percentile float64 205 | Latency time.Duration 206 | } 207 | 208 | Histograms []*struct { 209 | Mean time.Duration 210 | Count int 211 | } 212 | } 213 | 214 | func (s *StreamReport) Snapshot() *SnapshotReport { 215 | s.lock.Lock() 216 | startTime := time.Unix(0, atomic.LoadInt64(&startTimeUnixNano)) 217 | rs := &SnapshotReport{ 218 | Elapsed: time.Since(startTime), 219 | Count: s.latencyStats.count, 220 | Stats: &struct { 221 | Min time.Duration 222 | Mean time.Duration 223 | StdDev time.Duration 224 | Max time.Duration 225 | }{time.Duration(s.latencyStats.min), time.Duration(s.latencyStats.Mean()), 226 | time.Duration(s.latencyStats.Stddev()), time.Duration(s.latencyStats.max)}, 227 | } 228 | if s.rpsStats.count > 0 { 229 | rs.RpsStats = &struct { 230 | Min float64 231 | Mean float64 232 | StdDev float64 233 | Max float64 234 | }{s.rpsStats.min, s.rpsStats.Mean(), 235 | s.rpsStats.Stddev(), s.rpsStats.max} 236 | } 237 | 238 | elapseInSec := rs.Elapsed.Seconds() 239 | rs.RPS = float64(rs.Count) / elapseInSec 240 | rs.ReadThroughput = float64(s.readBytes) / 1024.0 / 1024.0 / elapseInSec 241 | rs.WriteThroughput = float64(s.writeBytes) / 1024.0 / 1024.0 / elapseInSec 242 | rs.concurrencyCount = s.concurrencyCount 243 | 244 | rs.Codes = make(map[string]int64, len(s.codes)) 245 | for k, v := range s.codes { 246 | section := k / 100 247 | rs.Codes[httpStatusSectionLabelMap[section]] = v 248 | } 249 | rs.Errors = make(map[string]int64, len(s.errors)) 250 | for k, v := range s.errors { 251 | rs.Errors[k] = v 252 | } 253 | 254 | rs.Percentiles = make([]*struct { 255 | Percentile float64 256 | Latency time.Duration 257 | }, len(quantiles)) 258 | for i, p := range quantiles { 259 | rs.Percentiles[i] = &struct { 260 | Percentile float64 261 | Latency time.Duration 262 | }{p, time.Duration(s.latencyQuantile.Query(p))} 263 | } 264 | 265 | hisBins := s.latencyHistogram.Bins() 266 | rs.Histograms = make([]*struct { 267 | Mean time.Duration 268 | Count int 269 | }, len(hisBins)) 270 | for i, b := range hisBins { 271 | rs.Histograms[i] = &struct { 272 | Mean time.Duration 273 | Count int 274 | }{time.Duration(b.Mean()), b.Count} 275 | } 276 | 277 | s.lock.Unlock() 278 | return rs 279 | } 280 | 281 | func (s *StreamReport) Done() <-chan struct{} { 282 | return s.doneChan 283 | } 284 | 285 | type ChartsReport struct { 286 | RPS float64 287 | Latency Stats 288 | CodeMap map[int]int64 289 | Concurrency int 290 | } 291 | 292 | func (s *StreamReport) Charts() *ChartsReport { 293 | s.lock.Lock() 294 | var cr *ChartsReport 295 | if s.noDateWithinSec { 296 | cr = nil 297 | } else { 298 | cr = &ChartsReport{ 299 | RPS: s.rpsWithinSec, 300 | Latency: *s.latencyWithinSec, 301 | CodeMap: s.copyCodes(), 302 | Concurrency: s.concurrencyCount, 303 | } 304 | } 305 | s.lock.Unlock() 306 | return cr 307 | } 308 | -------------------------------------------------------------------------------- /requester.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "fmt" 7 | "io" 8 | "math" 9 | "net" 10 | url2 "net/url" 11 | "os" 12 | "os/signal" 13 | "strconv" 14 | "strings" 15 | "sync" 16 | "sync/atomic" 17 | "syscall" 18 | "time" 19 | 20 | "github.com/valyala/fasthttp" 21 | "github.com/valyala/fasthttp/fasthttpproxy" 22 | "go.uber.org/automaxprocs/maxprocs" 23 | "golang.org/x/time/rate" 24 | ) 25 | 26 | var ( 27 | startTimeUnixNano int64 28 | sendOnCloseError interface{} 29 | ) 30 | 31 | type ReportRecord struct { 32 | cost time.Duration 33 | code int 34 | error string 35 | readBytes int64 36 | writeBytes int64 37 | concurrencyCount int 38 | } 39 | 40 | var recordPool = sync.Pool{ 41 | New: func() interface{} { return new(ReportRecord) }, 42 | } 43 | 44 | func init() { 45 | // Honoring env GOMAXPROCS 46 | _, _ = maxprocs.Set() 47 | defer func() { 48 | sendOnCloseError = recover() 49 | }() 50 | func() { 51 | cc := make(chan struct{}, 1) 52 | close(cc) 53 | cc <- struct{}{} 54 | }() 55 | } 56 | 57 | type MyConn struct { 58 | net.Conn 59 | r, w *int64 60 | } 61 | 62 | func NewMyConn(conn net.Conn, r, w *int64) (*MyConn, error) { 63 | myConn := &MyConn{Conn: conn, r: r, w: w} 64 | return myConn, nil 65 | } 66 | 67 | func (c *MyConn) Read(b []byte) (n int, err error) { 68 | sz, err := c.Conn.Read(b) 69 | 70 | if err == nil { 71 | atomic.AddInt64(c.r, int64(sz)) 72 | } 73 | return sz, err 74 | } 75 | 76 | func (c *MyConn) Write(b []byte) (n int, err error) { 77 | sz, err := c.Conn.Write(b) 78 | 79 | if err == nil { 80 | atomic.AddInt64(c.w, int64(sz)) 81 | } 82 | return sz, err 83 | } 84 | 85 | func ThroughputInterceptorDial(dial fasthttp.DialFunc, r *int64, w *int64) fasthttp.DialFunc { 86 | return func(addr string) (net.Conn, error) { 87 | conn, err := dial(addr) 88 | if err != nil { 89 | return nil, err 90 | } 91 | return NewMyConn(conn, r, w) 92 | } 93 | } 94 | 95 | type Requester struct { 96 | concurrency int 97 | reqRate *rate.Limit 98 | requests int64 99 | duration time.Duration 100 | rampUp int 101 | clientOpt *ClientOpt 102 | httpClient *fasthttp.HostClient 103 | httpHeader *fasthttp.RequestHeader 104 | errWriter io.Writer 105 | 106 | recordChan chan *ReportRecord 107 | closeOnce sync.Once 108 | wg sync.WaitGroup 109 | 110 | readBytes int64 111 | writeBytes int64 112 | 113 | cancel func() 114 | } 115 | 116 | type ClientOpt struct { 117 | url string 118 | method string 119 | headers []string 120 | bodyBytes []byte 121 | bodyFile string 122 | 123 | certPath string 124 | keyPath string 125 | insecure bool 126 | 127 | maxConns int 128 | doTimeout time.Duration 129 | readTimeout time.Duration 130 | writeTimeout time.Duration 131 | dialTimeout time.Duration 132 | 133 | socks5Proxy string 134 | contentType string 135 | host string 136 | } 137 | 138 | func NewRequester(concurrency int, requests int64, duration time.Duration, reqRate *rate.Limit, errWriter io.Writer, clientOpt *ClientOpt, rampUp int) (*Requester, error) { 139 | maxResult := concurrency * 100 140 | if maxResult > 8192 { 141 | maxResult = 8192 142 | } 143 | r := &Requester{ 144 | concurrency: concurrency, 145 | reqRate: reqRate, 146 | requests: requests, 147 | duration: duration, 148 | rampUp: rampUp, 149 | errWriter: errWriter, 150 | clientOpt: clientOpt, 151 | recordChan: make(chan *ReportRecord, maxResult), 152 | } 153 | client, header, err := buildRequestClient(clientOpt, &r.readBytes, &r.writeBytes) 154 | if err != nil { 155 | return nil, err 156 | } 157 | r.httpClient = client 158 | r.httpHeader = header 159 | return r, nil 160 | } 161 | 162 | func addMissingPort(addr string, isTLS bool) string { 163 | n := strings.Index(addr, ":") 164 | if n >= 0 { 165 | return addr 166 | } 167 | port := 80 168 | if isTLS { 169 | port = 443 170 | } 171 | return net.JoinHostPort(addr, strconv.Itoa(port)) 172 | } 173 | 174 | func buildTLSConfig(opt *ClientOpt) (*tls.Config, error) { 175 | var certs []tls.Certificate 176 | if opt.certPath != "" && opt.keyPath != "" { 177 | c, err := tls.LoadX509KeyPair(opt.certPath, opt.keyPath) 178 | if err != nil { 179 | return nil, err 180 | } 181 | certs = append(certs, c) 182 | } 183 | return &tls.Config{ 184 | InsecureSkipVerify: opt.insecure, 185 | Certificates: certs, 186 | }, nil 187 | } 188 | 189 | func buildRequestClient(opt *ClientOpt, r *int64, w *int64) (*fasthttp.HostClient, *fasthttp.RequestHeader, error) { 190 | u, err := url2.Parse(opt.url) 191 | if err != nil { 192 | return nil, nil, err 193 | } 194 | httpClient := &fasthttp.HostClient{ 195 | Addr: addMissingPort(u.Host, u.Scheme == "https"), 196 | IsTLS: u.Scheme == "https", 197 | Name: "plow", 198 | MaxConns: opt.maxConns, 199 | ReadTimeout: opt.readTimeout, 200 | WriteTimeout: opt.writeTimeout, 201 | DisableHeaderNamesNormalizing: true, 202 | } 203 | if opt.socks5Proxy != "" { 204 | if !strings.Contains(opt.socks5Proxy, "://") { 205 | opt.socks5Proxy = "socks5://" + opt.socks5Proxy 206 | } 207 | httpClient.Dial = fasthttpproxy.FasthttpSocksDialer(opt.socks5Proxy) 208 | } else { 209 | httpClient.Dial = fasthttpproxy.FasthttpProxyHTTPDialerTimeout(opt.dialTimeout) 210 | } 211 | httpClient.Dial = ThroughputInterceptorDial(httpClient.Dial, r, w) 212 | 213 | tlsConfig, err := buildTLSConfig(opt) 214 | if err != nil { 215 | return nil, nil, err 216 | } 217 | httpClient.TLSConfig = tlsConfig 218 | 219 | var requestHeader fasthttp.RequestHeader 220 | if opt.contentType != "" { 221 | requestHeader.SetContentType(opt.contentType) 222 | } 223 | if opt.host != "" { 224 | requestHeader.SetHost(opt.host) 225 | } else { 226 | requestHeader.SetHost(u.Host) 227 | } 228 | requestHeader.SetMethod(opt.method) 229 | requestHeader.SetRequestURI(u.RequestURI()) 230 | for _, h := range opt.headers { 231 | n := strings.SplitN(h, ":", 2) 232 | if len(n) != 2 { 233 | return nil, nil, fmt.Errorf("invalid header: %s", h) 234 | } 235 | requestHeader.Set(n[0], n[1]) 236 | } 237 | 238 | return httpClient, &requestHeader, nil 239 | } 240 | 241 | func (r *Requester) Cancel() { 242 | r.cancel() 243 | } 244 | 245 | func (r *Requester) RecordChan() <-chan *ReportRecord { 246 | return r.recordChan 247 | } 248 | 249 | func (r *Requester) closeRecord() { 250 | r.closeOnce.Do(func() { 251 | close(r.recordChan) 252 | }) 253 | } 254 | 255 | func (r *Requester) DoRequest(req *fasthttp.Request, resp *fasthttp.Response, rr *ReportRecord) { 256 | startTime := time.Unix(0, atomic.LoadInt64(&startTimeUnixNano)) 257 | t1 := time.Since(startTime) 258 | var err error 259 | if r.clientOpt.doTimeout > 0 { 260 | err = r.httpClient.DoTimeout(req, resp, r.clientOpt.doTimeout) 261 | } else { 262 | err = r.httpClient.Do(req, resp) 263 | } 264 | 265 | if err != nil { 266 | rr.cost = time.Since(startTime) - t1 267 | rr.error = err.Error() 268 | return 269 | } 270 | 271 | writeTo := io.Discard 272 | if resp.StatusCode() >= 500 { 273 | writeTo = r.errWriter 274 | _, _ = r.errWriter.Write([]byte(fmt.Sprintf("\n%d %s\n", resp.StatusCode(), rr.cost))) 275 | _, _ = r.errWriter.Write([]byte(fmt.Sprintf("%s", &resp.Header))) 276 | } 277 | err = resp.BodyWriteTo(writeTo) 278 | if err != nil { 279 | rr.cost = time.Since(startTime) - t1 280 | rr.error = err.Error() 281 | return 282 | } 283 | 284 | rr.cost = time.Since(startTime) - t1 285 | rr.code = resp.StatusCode() 286 | rr.error = "" 287 | } 288 | 289 | func (r *Requester) Run() { 290 | // handle ctrl-c 291 | sigs := make(chan os.Signal, 1) 292 | signal.Notify(sigs, os.Interrupt, syscall.SIGTERM) 293 | defer signal.Stop(sigs) 294 | 295 | ctx, cancelFunc := context.WithCancel(context.Background()) 296 | r.cancel = cancelFunc 297 | go func() { 298 | <-sigs 299 | r.closeRecord() 300 | cancelFunc() 301 | }() 302 | atomic.StoreInt64(&startTimeUnixNano, time.Now().UnixNano()) 303 | if r.duration > 0 { 304 | time.AfterFunc(r.duration, func() { 305 | r.closeRecord() 306 | cancelFunc() 307 | }) 308 | } 309 | 310 | var limiter *rate.Limiter 311 | if r.reqRate != nil { 312 | limiter = rate.NewLimiter(*r.reqRate, 1) 313 | } 314 | 315 | semaphore := r.requests 316 | if r.rampUp <= 0 { 317 | r.rampUp = r.concurrency 318 | } 319 | concurrencyCount := 0 320 | loopCount := int(math.Ceil(float64(r.concurrency) / float64(r.rampUp))) 321 | for i := 0; i < loopCount; i++ { 322 | for j := 0; j < r.rampUp; j++ { 323 | if concurrencyCount > r.concurrency { 324 | break 325 | } 326 | concurrencyCount++ 327 | r.wg.Add(1) 328 | go func() { 329 | defer func() { 330 | r.wg.Done() 331 | v := recover() 332 | if v != nil && v != sendOnCloseError { 333 | panic(v) 334 | } 335 | }() 336 | req := &fasthttp.Request{} 337 | resp := &fasthttp.Response{} 338 | r.httpHeader.CopyTo(&req.Header) 339 | if r.httpClient.IsTLS { 340 | req.URI().SetScheme("https") 341 | req.URI().SetHostBytes(req.Header.Host()) 342 | } 343 | 344 | for { 345 | select { 346 | case <-ctx.Done(): 347 | return 348 | default: 349 | } 350 | 351 | if limiter != nil { 352 | err := limiter.Wait(ctx) 353 | if err != nil { 354 | continue 355 | } 356 | } 357 | 358 | if r.requests > 0 && atomic.AddInt64(&semaphore, -1) < 0 { 359 | cancelFunc() 360 | return 361 | } 362 | 363 | if r.clientOpt.bodyFile != "" { 364 | file, err := os.Open(r.clientOpt.bodyFile) 365 | if err != nil { 366 | rr := recordPool.Get().(*ReportRecord) 367 | rr.cost = 0 368 | rr.error = err.Error() 369 | rr.readBytes = atomic.LoadInt64(&r.readBytes) 370 | rr.writeBytes = atomic.LoadInt64(&r.writeBytes) 371 | rr.concurrencyCount = concurrencyCount 372 | r.recordChan <- rr 373 | continue 374 | } 375 | req.SetBodyStream(file, -1) 376 | } else { 377 | req.SetBodyRaw(r.clientOpt.bodyBytes) 378 | } 379 | resp.Reset() 380 | rr := recordPool.Get().(*ReportRecord) 381 | r.DoRequest(req, resp, rr) 382 | rr.readBytes = atomic.LoadInt64(&r.readBytes) 383 | rr.writeBytes = atomic.LoadInt64(&r.writeBytes) 384 | rr.concurrencyCount = concurrencyCount 385 | r.recordChan <- rr 386 | } 387 | }() 388 | } 389 | if r.rampUp != r.concurrency { 390 | time.Sleep(time.Second) 391 | } 392 | } 393 | 394 | r.wg.Wait() 395 | r.closeRecord() 396 | } 397 | --------------------------------------------------------------------------------