├── .github └── workflows │ └── vulncheck.yml ├── .gitignore ├── .golangci.yml ├── .goreleaser.yml ├── CREDITS ├── Dockerfile ├── LICENSE ├── README.md ├── client ├── client.go └── table.go ├── cmd └── hperf │ ├── analyze.go │ ├── bandwidth.go │ ├── csv.go │ ├── delete.go │ ├── download.go │ ├── latency.go │ ├── list.go │ ├── listen.go │ ├── main.go │ ├── requests.go │ ├── server.go │ ├── stop.go │ └── stream.go ├── go.mod ├── go.sum ├── helm-reindex.sh ├── helm └── hperf │ ├── .helmignore │ ├── Chart.yaml │ ├── templates │ ├── NOTES.txt │ ├── _helpers.tpl │ ├── service.yaml │ ├── serviceaccount.yaml │ └── statefulset.yaml │ └── values.yaml ├── server ├── file.go ├── helpers_linux.go ├── helpers_others.go └── server.go └── shared ├── shared.go ├── sorting.go └── stats.go /.github/workflows/vulncheck.yml: -------------------------------------------------------------------------------- 1 | name: VulnCheck 2 | on: 3 | pull_request: 4 | branches: 5 | - master 6 | - main 7 | push: 8 | branches: 9 | - master 10 | - main 11 | jobs: 12 | vulncheck: 13 | name: Analysis 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | go-version: [ 1.24.2 ] 18 | steps: 19 | - name: Check out code into the Go module directory 20 | uses: actions/checkout@v4 21 | - uses: actions/setup-go@v5 22 | with: 23 | go-version: ${{ matrix.go-version }} 24 | check-latest: true 25 | - name: Get govulncheck 26 | run: go install golang.org/x/vuln/cmd/govulncheck@latest 27 | shell: bash 28 | - name: Run govulncheck 29 | run: govulncheck ./... 30 | shell: bash 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | linters-settings: 2 | golint: 3 | min-confidence: 0 4 | 5 | misspell: 6 | locale: US 7 | 8 | linters: 9 | disable-all: true 10 | enable: 11 | - typecheck 12 | - goimports 13 | - misspell 14 | - govet 15 | - golint 16 | - ineffassign 17 | - gosimple 18 | - deadcode 19 | - structcheck 20 | 21 | issues: 22 | exclude-use-default: false 23 | exclude: 24 | - should have a package comment 25 | - error strings should not be capitalized or end with punctuation or a newline 26 | service: 27 | golangci-lint-version: 1.20.0 # use the fixed version to not introduce new linters unexpectedly 28 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | project_name: hperf 2 | 3 | release: 4 | name_template: "Release version {{.Version}}" 5 | 6 | github: 7 | owner: minio 8 | name: hperf 9 | 10 | before: 11 | hooks: 12 | - go mod tidy 13 | 14 | builds: 15 | - 16 | goos: 17 | - linux 18 | - darwin 19 | - windows 20 | goarch: 21 | - amd64 22 | - arm64 23 | - ppc64le 24 | - s390x 25 | ignore: 26 | - goos: windows 27 | goarch: arm64 28 | env: 29 | - CGO_ENABLED=0 30 | flags: 31 | - -trimpath 32 | - --tags=kqueue 33 | ldflags: 34 | - "-s -w -X main.version={{.Version}}" 35 | main: ./cmd/hperf 36 | 37 | archives: 38 | - 39 | name_template: "{{ .ProjectName }}-{{ .Os }}-{{ .Arch }}" 40 | format: binary 41 | 42 | nfpms: 43 | - 44 | vendor: MinIO, Inc. 45 | homepage: https://github.com/minio/hperf 46 | maintainer: MinIO Development 47 | description: Nperf tool performs N peers to N peers cross network benchmark measuring RX/TX bandwidth for each peers 48 | license: GNU Affero General Public License v3.0 49 | formats: 50 | - deb 51 | - rpm 52 | 53 | signs: 54 | - 55 | signature: "${artifact}.minisig" 56 | cmd: "sh" 57 | args: 58 | - '-c' 59 | - 'minisign -s /media/${USER}/minio/minisign.key -Sm ${artifact} < /media/${USER}/minio/minisign-passphrase' 60 | artifacts: all 61 | 62 | snapshot: 63 | name_template: v0.0.0@{{.ShortCommit}} 64 | 65 | changelog: 66 | sort: asc 67 | 68 | dockers: 69 | - image_templates: 70 | - "quay.io/minio/hperf:{{ .Tag }}-amd64" 71 | use: buildx 72 | dockerfile: Dockerfile 73 | extra_files: 74 | - LICENSE 75 | - CREDITS 76 | build_flag_templates: 77 | - "--platform=linux/amd64" 78 | - image_templates: 79 | - "quay.io/minio/hperf:{{ .Tag }}-ppc64le" 80 | use: buildx 81 | dockerfile: Dockerfile 82 | extra_files: 83 | - LICENSE 84 | - CREDITS 85 | build_flag_templates: 86 | - "--platform=linux/ppc64le" 87 | - image_templates: 88 | - "quay.io/minio/hperf:{{ .Tag }}-s390x" 89 | use: buildx 90 | dockerfile: Dockerfile 91 | extra_files: 92 | - LICENSE 93 | - CREDITS 94 | build_flag_templates: 95 | - "--platform=linux/s390x" 96 | - image_templates: 97 | - "quay.io/minio/hperf:{{ .Tag }}-arm64" 98 | use: buildx 99 | goarch: arm64 100 | dockerfile: Dockerfile 101 | extra_files: 102 | - LICENSE 103 | - CREDITS 104 | build_flag_templates: 105 | - "--platform=linux/arm64" 106 | docker_manifests: 107 | - name_template: quay.io/minio/hperf:{{ .Tag }} 108 | image_templates: 109 | - quay.io/minio/hperf:{{ .Tag }}-amd64 110 | - quay.io/minio/hperf:{{ .Tag }}-arm64 111 | - quay.io/minio/hperf:{{ .Tag }}-ppc64le 112 | - quay.io/minio/hperf:{{ .Tag }}-s390x 113 | - name_template: quay.io/minio/hperf:latest 114 | image_templates: 115 | - quay.io/minio/hperf:{{ .Tag }}-amd64 116 | - quay.io/minio/hperf:{{ .Tag }}-arm64 117 | - quay.io/minio/hperf:{{ .Tag }}-ppc64le 118 | - quay.io/minio/hperf:{{ .Tag }}-s390x 119 | -------------------------------------------------------------------------------- /CREDITS: -------------------------------------------------------------------------------- 1 | Go (the standard library) 2 | https://golang.org/ 3 | ---------------------------------------------------------------- 4 | Copyright (c) 2009 The Go Authors. All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are 8 | met: 9 | 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above 13 | copyright notice, this list of conditions and the following disclaimer 14 | in the documentation and/or other materials provided with the 15 | distribution. 16 | * Neither the name of Google Inc. nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | ================================================================ 33 | 34 | github.com/google/uuid 35 | https://github.com/google/uuid 36 | ---------------------------------------------------------------- 37 | Copyright (c) 2009,2014 Google Inc. All rights reserved. 38 | 39 | Redistribution and use in source and binary forms, with or without 40 | modification, are permitted provided that the following conditions are 41 | met: 42 | 43 | * Redistributions of source code must retain the above copyright 44 | notice, this list of conditions and the following disclaimer. 45 | * Redistributions in binary form must reproduce the above 46 | copyright notice, this list of conditions and the following disclaimer 47 | in the documentation and/or other materials provided with the 48 | distribution. 49 | * Neither the name of Google Inc. nor the names of its 50 | contributors may be used to endorse or promote products derived from 51 | this software without specific prior written permission. 52 | 53 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 54 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 55 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 56 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 57 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 58 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 59 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 60 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 61 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 62 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 63 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 64 | 65 | ================================================================ 66 | 67 | golang.org/x/sys 68 | https://golang.org/x/sys 69 | ---------------------------------------------------------------- 70 | Copyright (c) 2009 The Go Authors. All rights reserved. 71 | 72 | Redistribution and use in source and binary forms, with or without 73 | modification, are permitted provided that the following conditions are 74 | met: 75 | 76 | * Redistributions of source code must retain the above copyright 77 | notice, this list of conditions and the following disclaimer. 78 | * Redistributions in binary form must reproduce the above 79 | copyright notice, this list of conditions and the following disclaimer 80 | in the documentation and/or other materials provided with the 81 | distribution. 82 | * Neither the name of Google Inc. nor the names of its 83 | contributors may be used to endorse or promote products derived from 84 | this software without specific prior written permission. 85 | 86 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 87 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 88 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 89 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 90 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 91 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 92 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 93 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 94 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 95 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 96 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 97 | 98 | ================================================================ 99 | 100 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM scratch 2 | MAINTAINER MinIO Development "dev@min.io" 3 | 4 | EXPOSE 9999 5 | 6 | COPY ./hperf /hperf 7 | 8 | ENTRYPOINT ["/hperf"] 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hperf 2 | 3 | hperf is a tool for active measurements of the maximum achievable bandwidth between N peers, measuring RX/TX bandwidth for each peers. 4 | 5 | ## What is hperf for 6 | Hperf was made to test networks in large infrastructure. It's highly scalable and capable of running parallel tests over a long period of time. 7 | 8 | ## Common use cases 9 | - Debugging link/nic MTU issues 10 | - Optimizing throughput speed for specific payload/buffer sizes 11 | - Finding servers that present latency on the application level when ping is showing no latency 12 | - Testing overall network throughput 13 | - Testing server to server connectivity 14 | 15 | 16 | ## Core concepts 17 | ### The hperf binary 18 | The binary can act as both client and server. 19 | 20 | ### Client 21 | The client part of hperf is responsible for orchestrating the servers. Its only job is to send commands to the servers and receive incremental stats updates. It can be executed from any machine that can talk to the servers. 22 | 23 | ### Servers 24 | Servers are the machines we are testing. To launch the hperf command in servers mode use the `server` command: 25 | 26 | ```bash 27 | $ ./hperf server --help 28 | ``` 29 | 30 | This command will start an API and websocket on the given `--address` and save test results to `--storage-path`. 31 | 32 | WARNING: do not expose `--address` to the internet 33 | NOTE: if the `--address` is not the same as your external IP addres used for communications between servers then you need to set `--real-ip`, otherwise the server will report internal IPs in the stats and it will run the test against itself, causing invalid results. 34 | 35 | ### The listen command 36 | Hperf can run tests without a specific `client` needing to be constantly connected. Once the `client` has started a test, the `client` can exit without affecting the test. 37 | 38 | Any `client` can hook into the list test at runtime using the `--id` of the test. 39 | There can even be multiple `clients` listening to the same test. 40 | 41 | Example: 42 | ```bash 43 | $ ./hperf listen --hosts 10.10.1.{2...10} --id [TEST_ID] 44 | ``` 45 | 46 | ## Getting started 47 | 48 | ### Download 49 | [Download Binary Releases](https://github.com/minio/hperf/releases) for various platforms and place in a directory of 50 | your choosing. 51 | 52 | You can also install via source: 53 | ``` 54 | go install github.com/minio/hperf/cmd/hperf@latest 55 | ``` 56 | 57 | ### Server 58 | Run server with default settings: 59 | NOTE: this will place all test result files in the same directory and use 0.0.0.0 as bind ip. We do not recommend this for larger tests. 60 | ```bash 61 | $ ./hperf server 62 | ``` 63 | 64 | Run the server with custom `--address`, `--real-ip` and `--storage-path` 65 | ```bash 66 | $ ./hperf server --address 10.10.2.10:5000 --real-ip 150.150.20.2 --storage-path /tmp/hperf/ 67 | ``` 68 | 69 | ### Client 70 | If the `server` command was executed with a custom `--address`, the port can be specified in the `client` using `--port`. 71 | 72 | The `--hosts` and `--id` flags are especially important to understand. 73 | 74 | `--hosts` is where we determine which machines we will send the current command to. The hosts parameter supports 75 | the same ellipsis pattern as minio and also a comma separate list of hosts as well as a file: input. The file expects a 76 | host per file line. 77 | 78 | ```bash 79 | ./hperf [command] --hosts 1.1.1.1,2.2.2.2 80 | ./hperf [command] --hosts 1.1.1.{1...100} 81 | ./hperf [command] --hosts file:/home/user/hosts 82 | ``` 83 | 84 | `--id` is used to start, stop, listen to tests, or get results. 85 | NOTE: Be careful not to re-use the ID's if you care about fetching results at a later date. 86 | 87 | ```bash 88 | # listen in on a running test 89 | ./hperf listen --hosts 1.1.1.{1...100} --id [my_test_id] 90 | 91 | # stop a running test 92 | ./hperf stop --hosts 1.1.1.{1...100} --id [my_test_id] 93 | 94 | # download test results 95 | ./hperf download --hosts 1.1.1.{1...100} --id [my_test_id] --file /tmp/test.out 96 | 97 | # analyze test results 98 | ./hperf analyze --file /tmp/test.out 99 | 100 | # analyze test results with full print output 101 | ./hperf analyze --file /tmp/test.out --print-stats --print-errors 102 | 103 | # Generate a .csv file from a .json test file 104 | ./hperf csv --file /tmp/test.out 105 | ``` 106 | 107 | 108 | 109 | # Full test scenario using (requests, download, analysis and csv export) 110 | ## On the servers 111 | ```bash 112 | $ ./hperf server --address 0.0.0.0:6000 --real-ip 10.10.10.2 --storage-path /tmp/hperf/ 113 | ``` 114 | 115 | ## The client 116 | 117 | ### Run test 118 | ```bash 119 | ./hperf latency --hosts 10.10.10.{2...3} --port 6000 --duration 10 --id latency-test-1 120 | 121 | Test ID: latency-test-1 122 | 123 | #ERR #TX TX(high) TX(low) TX(total) RMS(high) RMS(low) TTFB(high) TTFB(low) #Dropped Mem(high) Mem(low) CPU(high) CPU(low) 124 | 0 8 4.00 KB/s 4.00 KB/s 8.00 KB 1 0 0 0 937405 1 1 0 0 125 | 0 26 5.00 KB/s 4.00 KB/s 18.00 KB 1 0 0 0 1874810 1 1 0 0 126 | 0 73 5.00 KB/s 4.00 KB/s 33.00 KB 1 0 0 0 3317563 1 1 0 0 127 | 0 92 5.00 KB/s 4.00 KB/s 38.00 KB 1 0 0 0 3749634 1 1 0 0 128 | 0 140 5.00 KB/s 4.00 KB/s 48.00 KB 1 0 0 0 4687048 1 1 0 0 129 | 0 198 5.00 KB/s 4.00 KB/s 58.00 KB 1 0 0 0 5624466 1 1 0 0 130 | 0 266 5.00 KB/s 4.00 KB/s 68.00 KB 1 0 0 0 6561889 1 1 0 0 131 | 0 344 5.00 KB/s 4.00 KB/s 78.00 KB 1 0 0 0 7499312 1 1 0 0 132 | 0 432 5.00 KB/s 4.00 KB/s 88.00 KB 9 0 0 0 8436740 1 1 0 0 133 | 0 530 5.00 KB/s 4.00 KB/s 98.00 KB 9 0 0 0 9374172 1 1 0 0 134 | 135 | Testing finished .. 136 | Analyzing data .. 137 | 138 | 139 | _____ P99 data points _____ 140 | 141 | Created Local Remote RMS(high) RMS(low) TTFB(high) TTFB(low) TX #TX #ERR #Dropped Mem(used) CPU(used) 142 | 10:30:54 10.10.10.3 10.10.10.3 9 0 0 0 5.00 KB/s 44 0 432076 1 0 143 | 144 | Sorting: RMSH 145 | Time: Milliseconds 146 | 147 | P10 count sum min avg max 148 | 18 30 0 1 9 149 | P50 count sum min avg max 150 | 10 25 0 2 9 151 | P90 count sum min avg max 152 | 2 18 9 9 9 153 | P99 count sum min avg max 154 | 1 9 9 9 9 155 | 156 | ``` 157 | 158 | ### Explaining the stats above. 159 | The first section includes the combined highs/lows and counters for ALL servers beings tested. 160 | Each line represents a 1 second stat point. 161 | Here is a breakdown of the individual stats: 162 | 163 | - `#ERR`: number of errors ( all servers ) 164 | - `#TX`: total number of HTTP requests made ( all servers ) 165 | - `TX(high/low)`: highest and lowest transfer rate seen ( single server ) 166 | - `RMS(high/low)`: longest and fastest round trip latency ( single server ) 167 | - `TTFB(high/low)`: The time it took to read the first byte ( single server ) 168 | - `#Dropped`: highest count of dropped packets ( single server ) 169 | - `Mem(high/low)`: highest and lowest memory usage ( single server ) 170 | - `CPU(high/low)`: highest and lowest cpu usage ( single server ) 171 | 172 | The next section is a print-out for the `p99` data points. 173 | p99 represents the 1% of the worst data points and all statistics are related to 174 | that single data point between `Local` and `Remote`. 175 | 176 | Finally we have the p10 to p99 breakdown. 177 | - `Sorting`: the data point being sorted/used for the data breakdown 178 | - `Time:`: the time unit being used. Default is milliseconds but can be changed to microseconds `--micro` 179 | - `count`: the total number of data points in this category 180 | - `sum`: the sum of all valuesa in thie category 181 | - `min`: the single lowest value in this category 182 | - `avg`: the avarage for all values in this category 183 | - `max`: the highest value in this category 184 | 185 | ### Download test 186 | ```bash 187 | ./hperf download --hosts 10.10.10.{2...3} --port 6000 --id latency-test-1 --file latency-test-1 188 | ``` 189 | 190 | ### Analyze test 191 | NOTE: this analysis will display the same output as the final step when running the test above. 192 | ```bash 193 | ./hperf analyze --file latency-test-1 --print-stats --print-errors 194 | ``` 195 | 196 | ### Export csv 197 | ```bash 198 | ./hperf csv --file latency-test-1 199 | ``` 200 | 201 | # Random Example tests 202 | 203 | ## Example: Basic latency testing 204 | This will run a 20 second latency test and analyze+print the results when done 205 | ``` 206 | $ ./hperf latency --hosts file:./hosts --port [PORT] --duration 20 --print-all 207 | ``` 208 | 209 | ## Example: Basic bandwidth testing 210 | This will run a 20 second bandwidth test and print the results when done 211 | ``` 212 | $ ./hperf bandwidth --hosts file:./hosts --port [PORT] --duration 20 --concurrency 10 --print-all 213 | ``` 214 | 215 | ## Example: 20 second HTTP payload transfer test using a stream 216 | This will perform a 20 second bandwidth test with 12 concurrent HTTP streams: 217 | ``` 218 | $ ./hperf bandwidth --hosts file:./hosts --id http-test-2 --duration 20 --concurrency 12 219 | ``` 220 | 221 | ## Example: 5 Minute latency test using a 1000 Byte buffer, with a delay of 50ms between requests 222 | This test will send a single round trip request between servers to test base latency and reachability: 223 | ``` 224 | $ ./hperf latency --hosts file:./hosts --id http-test-2 --duration 360 --concurrency 1 --requestDelay 50 225 | --bufferSize 1000 --payloadSize 1000 226 | ``` 227 | -------------------------------------------------------------------------------- /client/client.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package client 19 | 20 | import ( 21 | "bufio" 22 | "bytes" 23 | "context" 24 | "encoding/csv" 25 | "encoding/json" 26 | "errors" 27 | "fmt" 28 | "math" 29 | "net/http" 30 | "os" 31 | "reflect" 32 | "runtime/debug" 33 | "slices" 34 | "strconv" 35 | "sync" 36 | "sync/atomic" 37 | "time" 38 | 39 | "github.com/charmbracelet/lipgloss" 40 | "github.com/fasthttp/websocket" 41 | "github.com/minio/hperf/shared" 42 | ) 43 | 44 | var ( 45 | responseDPS = make([]shared.DP, 0) 46 | responseERR = make([]shared.TError, 0) 47 | responseLock = sync.Mutex{} 48 | websockets []*wsClient 49 | hostsDoingWork atomic.Int32 50 | ) 51 | 52 | type wsClient struct { 53 | ID int 54 | Host string 55 | Con *websocket.Conn 56 | } 57 | 58 | func (c *wsClient) SendError(e error) error { 59 | if e == nil { 60 | return nil 61 | } 62 | msg := new(shared.WebsocketSignal) 63 | msg.SType = shared.Err 64 | msg.Error = e.Error() 65 | return c.Con.WriteJSON(msg) 66 | } 67 | 68 | func (c *wsClient) Close() (err error) { 69 | return c.Remove() 70 | } 71 | 72 | func (c *wsClient) Remove() (err error) { 73 | err = c.Con.Close() 74 | websockets[c.ID] = nil 75 | return 76 | } 77 | 78 | func itterateWebsockets(action func(c *wsClient)) { 79 | for i := 0; i < len(websockets); i++ { 80 | if websockets[i] == nil { 81 | continue 82 | } 83 | action(websockets[i]) 84 | } 85 | } 86 | 87 | func (c *wsClient) NewSignal(signal shared.SignalType, conf *shared.Config) *shared.WebsocketSignal { 88 | msg := new(shared.WebsocketSignal) 89 | msg.SType = signal 90 | msg.Config = conf 91 | return msg 92 | } 93 | 94 | func (c *wsClient) Ping() (err error) { 95 | msg := new(shared.WebsocketSignal) 96 | msg.SType = shared.Ping 97 | err = c.Con.WriteJSON(msg) 98 | return 99 | } 100 | 101 | var ( 102 | testList = make(map[string]shared.TestInfo) 103 | testLock = sync.Mutex{} 104 | ) 105 | 106 | func initializeClient(ctx context.Context, c *shared.Config) (err error) { 107 | websockets = make([]*wsClient, len(c.Hosts)) 108 | 109 | clientID := 0 110 | done := make(chan struct{}, len(c.Hosts)) 111 | for _, host := range c.Hosts { 112 | go handleWSConnection(ctx, c, host, clientID, done) 113 | clientID++ 114 | } 115 | 116 | doneCount := 0 117 | timeout := time.NewTicker(time.Second * 10) 118 | 119 | for { 120 | select { 121 | case <-done: 122 | doneCount++ 123 | hostsDoingWork.Add(1) 124 | if doneCount == len(c.Hosts) { 125 | return 126 | } 127 | case <-ctx.Done(): 128 | return errors.New("Context canceled") 129 | case <-timeout.C: 130 | return errors.New("Timeout when connecting to hosts") 131 | } 132 | } 133 | } 134 | 135 | func handleWSConnection(ctx context.Context, c *shared.Config, host string, id int, done chan struct{}) { 136 | var err error 137 | defer func() { 138 | r := recover() 139 | if r != nil { 140 | fmt.Println(r, string(debug.Stack())) 141 | } 142 | if ctx.Err() != nil { 143 | hostsDoingWork.Add(-1) 144 | return 145 | } 146 | if c.RestartOnError && err != nil { 147 | time.Sleep(500 * time.Millisecond) 148 | go handleWSConnection(ctx, c, host, id, done) 149 | } else { 150 | hostsDoingWork.Add(-1) 151 | } 152 | }() 153 | 154 | socket := websockets[id] 155 | if socket == nil { 156 | websockets[id] = new(wsClient) 157 | socket = websockets[id] 158 | socket.ID = id 159 | } 160 | 161 | socket.Host = host 162 | 163 | dialer := websocket.Dialer{ 164 | Proxy: http.ProxyFromEnvironment, 165 | HandshakeTimeout: time.Second * c.DialTimeout, 166 | ReadBufferSize: 1000000, 167 | WriteBufferSize: 1000000, 168 | } 169 | 170 | shared.DEBUG(WarningStyle.Render("Connecting to ", host, ":", c.Port)) 171 | 172 | connectString := "wss://" + host + ":" + c.Port + "/ws/" + host 173 | if c.Insecure { 174 | connectString = "ws://" + host + ":" + c.Port + "/ws/" + host 175 | } 176 | 177 | con, _, dialErr := dialer.DialContext( 178 | ctx, 179 | connectString, 180 | nil) 181 | if dialErr != nil { 182 | PrintError(dialErr) 183 | err = dialErr 184 | return 185 | } 186 | socket.Con = con 187 | 188 | msg := new(shared.WebsocketSignal) 189 | err = con.ReadJSON(&msg) 190 | if err != nil { 191 | err = fmt.Errorf("Unable to read message from server on first connect %s", err) 192 | PrintError(err) 193 | return 194 | } 195 | if msg.Code != shared.OK { 196 | err = fmt.Errorf("Received %d from server on connect", msg.Code) 197 | PrintError(err) 198 | return 199 | } 200 | shared.DEBUG(SuccessStyle.Render("Connected to ", host, ":", c.Port)) 201 | 202 | done <- struct{}{} 203 | for { 204 | signal := new(shared.WebsocketSignal) 205 | err = con.ReadJSON(&signal) 206 | if err != nil { 207 | PrintError(err) 208 | return 209 | } 210 | if shared.DebugEnabled { 211 | fmt.Printf("WebsocketSignal: %+v\n", signal) 212 | } 213 | switch signal.SType { 214 | case shared.Stats: 215 | go collectDataPointv2(signal.DataPoint) 216 | case shared.ListTests: 217 | go parseTestList(signal.TestList) 218 | case shared.GetTest: 219 | go receiveJSONDataPoint(signal.Data, c) 220 | case shared.Err: 221 | go PrintErrorString(signal.Error) 222 | case shared.Done: 223 | shared.DEBUG(SuccessStyle.Render("Host Finished: ", con.RemoteAddr().String())) 224 | return 225 | } 226 | } 227 | } 228 | 229 | func PrintTError(err shared.TError) { 230 | fmt.Println(ErrorStyle.Render(err.Created.Format(time.RFC3339), " - ", err.Error)) 231 | } 232 | 233 | func PrintErrorString(err string) { 234 | fmt.Println(ErrorStyle.Render(err)) 235 | } 236 | 237 | func PrintError(err error) { 238 | if err == nil { 239 | return 240 | } 241 | fmt.Println(ErrorStyle.Render("ERROR: ", err.Error())) 242 | } 243 | 244 | func receiveJSONDataPoint(data []byte, _ *shared.Config) { 245 | responseLock.Lock() 246 | defer responseLock.Unlock() 247 | 248 | if bytes.HasPrefix(data, shared.ErrorPoint.String()) { 249 | dp := new(shared.TError) 250 | err := json.Unmarshal(data[1:], &dp) 251 | if err != nil { 252 | PrintError(err) 253 | return 254 | } 255 | responseERR = append(responseERR, *dp) 256 | } else if bytes.HasPrefix(data, shared.DataPoint.String()) { 257 | dp := new(shared.DP) 258 | err := json.Unmarshal(data[1:], &dp) 259 | if err != nil { 260 | PrintError(err) 261 | return 262 | } 263 | responseDPS = append(responseDPS, *dp) 264 | } else { 265 | PrintError(fmt.Errorf("Uknown data point: %s", data)) 266 | } 267 | } 268 | 269 | func keepAliveLoop(ctx context.Context, c *shared.Config, tickerfunc func() (shouldExit bool)) error { 270 | start := time.Now() 271 | for ctx.Err() == nil { 272 | time.Sleep(1 * time.Second) 273 | if time.Since(start).Seconds() > float64(c.Duration)+20 { 274 | return errors.New("Total duration reached 20 seconds past the configured duration") 275 | } 276 | 277 | select { 278 | case <-ctx.Done(): 279 | return ctx.Err() 280 | default: 281 | } 282 | 283 | if tickerfunc != nil && tickerfunc() { 284 | break 285 | } 286 | 287 | if hostsDoingWork.Load() <= 0 { 288 | return ctx.Err() 289 | } 290 | 291 | } 292 | return ctx.Err() 293 | } 294 | 295 | func Listen(ctx context.Context, c shared.Config) (err error) { 296 | cancelContext, cancel := context.WithCancel(ctx) 297 | defer cancel() 298 | err = initializeClient(cancelContext, &c) 299 | if err != nil { 300 | return 301 | } 302 | 303 | itterateWebsockets(func(ws *wsClient) { 304 | err = ws.Con.WriteJSON(ws.NewSignal(shared.ListenTest, &c)) 305 | if err != nil { 306 | return 307 | } 308 | }) 309 | 310 | return keepAliveLoop(ctx, &c, nil) 311 | } 312 | 313 | func Stop(ctx context.Context, c shared.Config) (err error) { 314 | cancelContext, cancel := context.WithCancel(ctx) 315 | defer cancel() 316 | err = initializeClient(cancelContext, &c) 317 | if err != nil { 318 | return 319 | } 320 | 321 | itterateWebsockets(func(ws *wsClient) { 322 | err = ws.Con.WriteJSON(ws.NewSignal(shared.StopAllTests, &c)) 323 | if err != nil { 324 | return 325 | } 326 | }) 327 | 328 | return keepAliveLoop(ctx, &c, nil) 329 | } 330 | 331 | func RunTest(ctx context.Context, c shared.Config) (err error) { 332 | cancelContext, cancel := context.WithCancel(ctx) 333 | defer cancel() 334 | err = initializeClient(cancelContext, &c) 335 | if err != nil { 336 | return 337 | } 338 | 339 | itterateWebsockets(func(ws *wsClient) { 340 | err = ws.Con.WriteJSON(ws.NewSignal(shared.RunTest, &c)) 341 | if err != nil { 342 | return 343 | } 344 | }) 345 | 346 | printCount := 0 347 | 348 | printOnTick := func() bool { 349 | if len(responseDPS) == 0 { 350 | return false 351 | } 352 | printCount++ 353 | 354 | to := new(shared.TestOutput) 355 | to.ErrCount = len(responseERR) 356 | to.TXL = math.MaxInt64 357 | to.RMSL = math.MaxInt64 358 | to.TTFBL = math.MaxInt64 359 | to.ML = responseDPS[0].MemoryUsedPercent 360 | to.CL = responseDPS[0].CPUUsedPercent 361 | tt := responseDPS[0].Type 362 | 363 | for i := range responseDPS { 364 | to.TXC += responseDPS[i].TXCount 365 | to.TXT += responseDPS[i].TXTotal 366 | 367 | if to.DP < responseDPS[i].DroppedPackets { 368 | to.DP = responseDPS[i].DroppedPackets 369 | } 370 | 371 | if to.TXL > responseDPS[i].TX { 372 | to.TXL = responseDPS[i].TX 373 | } 374 | if to.RMSL > responseDPS[i].RMSL { 375 | to.RMSL = responseDPS[i].RMSL 376 | } 377 | if to.TTFBL > responseDPS[i].TTFBL { 378 | to.TTFBL = responseDPS[i].TTFBL 379 | } 380 | if to.ML > responseDPS[i].MemoryUsedPercent { 381 | to.ML = responseDPS[i].MemoryUsedPercent 382 | } 383 | if to.CL > responseDPS[i].CPUUsedPercent { 384 | to.CL = responseDPS[i].CPUUsedPercent 385 | } 386 | 387 | if to.TXH < responseDPS[i].TX { 388 | to.TXH = responseDPS[i].TX 389 | } 390 | if to.RMSH < responseDPS[i].RMSH { 391 | to.RMSH = responseDPS[i].RMSH 392 | } 393 | if to.TTFBH < responseDPS[i].TTFBH { 394 | to.TTFBH = responseDPS[i].TTFBH 395 | } 396 | if to.MH < responseDPS[i].MemoryUsedPercent { 397 | to.MH = responseDPS[i].MemoryUsedPercent 398 | } 399 | if to.CH < responseDPS[i].CPUUsedPercent { 400 | to.CH = responseDPS[i].CPUUsedPercent 401 | } 402 | } 403 | 404 | if !c.Micro { 405 | to.TTFBH = to.TTFBH / 1000 406 | to.TTFBL = to.TTFBL / 1000 407 | to.RMSH = to.RMSH / 1000 408 | to.RMSL = to.RMSL / 1000 409 | } 410 | 411 | for i := range responseERR { 412 | PrintErrorString(responseERR[i].Error) 413 | } 414 | 415 | if printCount%10 == 1 { 416 | printRealTimeHeaders(tt) 417 | } 418 | printRealTimeRow(BaseStyle, to, tt) 419 | 420 | return false 421 | } 422 | 423 | return keepAliveLoop(ctx, &c, printOnTick) 424 | } 425 | 426 | func ListTests(ctx context.Context, c shared.Config) (err error) { 427 | cancelContext, cancel := context.WithCancel(ctx) 428 | defer cancel() 429 | err = initializeClient(cancelContext, &c) 430 | if err != nil { 431 | return 432 | } 433 | 434 | itterateWebsockets(func(ws *wsClient) { 435 | err = ws.Con.WriteJSON(ws.NewSignal(shared.ListTests, &c)) 436 | if err != nil { 437 | return 438 | } 439 | }) 440 | 441 | err = keepAliveLoop(ctx, &c, nil) 442 | if err != nil { 443 | return 444 | } 445 | 446 | printHeader(ListHeaders) 447 | tableStyle := lipgloss.NewStyle() 448 | 449 | keys := []string{} 450 | for id := range testList { 451 | keys = append(keys, id) 452 | } 453 | 454 | slices.SortFunc(keys, func(a string, b string) int { 455 | if testList[a].Time.Before(testList[b].Time) { 456 | return 1 457 | } else { 458 | return -1 459 | } 460 | }) 461 | 462 | for i := range keys { 463 | PrintColumns( 464 | tableStyle, 465 | column{strconv.Itoa(i), headerSlice[IntNumber].width}, 466 | column{keys[i], headerSlice[ID].width}, 467 | column{testList[keys[i]].Time.Format("02/01/2006 3:04 PM"), headerSlice[ID].width}, 468 | ) 469 | } 470 | 471 | return err 472 | } 473 | 474 | func DeleteTests(ctx context.Context, c shared.Config) (err error) { 475 | cancelContext, cancel := context.WithCancel(ctx) 476 | defer cancel() 477 | err = initializeClient(cancelContext, &c) 478 | if err != nil { 479 | return 480 | } 481 | 482 | itterateWebsockets(func(ws *wsClient) { 483 | err = ws.Con.WriteJSON(ws.NewSignal(shared.DeleteTests, &c)) 484 | if err != nil { 485 | return 486 | } 487 | }) 488 | 489 | return keepAliveLoop(ctx, &c, nil) 490 | } 491 | 492 | func parseTestList(list []shared.TestInfo) { 493 | testLock.Lock() 494 | defer testLock.Unlock() 495 | 496 | for i := range list { 497 | _, ok := testList[list[i].ID] 498 | if !ok { 499 | testList[list[i].ID] = list[i] 500 | } 501 | } 502 | } 503 | 504 | func DownloadTest(ctx context.Context, c shared.Config) (err error) { 505 | cancelContext, cancel := context.WithCancel(ctx) 506 | defer cancel() 507 | err = initializeClient(cancelContext, &c) 508 | if err != nil { 509 | return 510 | } 511 | 512 | itterateWebsockets(func(ws *wsClient) { 513 | err = ws.Con.WriteJSON(ws.NewSignal(shared.GetTest, &c)) 514 | if err != nil { 515 | fmt.Println(err) 516 | return 517 | } 518 | }) 519 | 520 | _ = keepAliveLoop(ctx, &c, nil) 521 | 522 | slices.SortFunc(responseERR, func(a shared.TError, b shared.TError) int { 523 | if a.Created.Before(b.Created) { 524 | return -1 525 | } else { 526 | return 1 527 | } 528 | }) 529 | 530 | slices.SortFunc(responseDPS, func(a shared.DP, b shared.DP) int { 531 | if a.Created.Before(b.Created) { 532 | return -1 533 | } else { 534 | return 1 535 | } 536 | }) 537 | 538 | f, err := os.Create(c.File) 539 | if err != nil { 540 | return err 541 | } 542 | defer f.Close() 543 | for i := range responseDPS { 544 | _, err := shared.WriteStructAndNewLineToFile(f, shared.DataPoint, responseDPS[i]) 545 | if err != nil { 546 | return err 547 | } 548 | } 549 | for i := range responseERR { 550 | _, err := shared.WriteStructAndNewLineToFile(f, shared.ErrorPoint, responseERR[i]) 551 | if err != nil { 552 | return err 553 | } 554 | } 555 | 556 | return nil 557 | } 558 | 559 | func AnalyzeBandwidthTest(ctx context.Context, c shared.Config) (err error) { 560 | _, cancel := context.WithCancel(ctx) 561 | defer cancel() 562 | 563 | if c.PrintAll { 564 | shared.INFO(" Printing all data points ..") 565 | fmt.Println("") 566 | 567 | printSliceOfDataPoints(responseDPS, c) 568 | 569 | if len(responseERR) > 0 { 570 | fmt.Println(" ____ ERRORS ____") 571 | } 572 | for i := range responseERR { 573 | PrintTError(responseERR[i]) 574 | } 575 | if len(responseERR) > 0 { 576 | fmt.Println("") 577 | } 578 | } 579 | 580 | if len(responseDPS) == 0 { 581 | fmt.Println("No datapoints found") 582 | return 583 | } 584 | 585 | return nil 586 | } 587 | 588 | func AnalyzeLatencyTest(ctx context.Context, c shared.Config) (err error) { 589 | _, cancel := context.WithCancel(ctx) 590 | defer cancel() 591 | 592 | if c.PrintAll { 593 | shared.INFO(" Printing all data points ..") 594 | 595 | printSliceOfDataPoints(responseDPS, c) 596 | 597 | if len(responseERR) > 0 { 598 | fmt.Println(" ____ ERRORS ____") 599 | } 600 | for i := range responseERR { 601 | PrintTError(responseERR[i]) 602 | } 603 | if len(responseERR) > 0 { 604 | fmt.Println("") 605 | } 606 | } 607 | if len(responseDPS) == 0 { 608 | fmt.Println("No datapoints found") 609 | return 610 | } 611 | 612 | shared.INFO(" Analyzing data ..") 613 | fmt.Println("") 614 | analyzeLatencyTest(responseDPS, c) 615 | 616 | return nil 617 | } 618 | 619 | func AnalyzeTest(ctx context.Context, c shared.Config) (err error) { 620 | _, cancel := context.WithCancel(ctx) 621 | defer cancel() 622 | 623 | f, err := os.Open(c.File) 624 | if err != nil { 625 | return err 626 | } 627 | defer f.Close() 628 | 629 | dps := make([]shared.DP, 0) 630 | errors := make([]shared.TError, 0) 631 | 632 | s := bufio.NewScanner(f) 633 | for s.Scan() { 634 | b := s.Bytes() 635 | if bytes.HasPrefix(b[1:], shared.ErrorPoint.String()) { 636 | dperr := new(shared.TError) 637 | err := json.Unmarshal(b, dperr) 638 | if err != nil { 639 | return err 640 | } 641 | errors = append(errors, *dperr) 642 | } else if bytes.HasPrefix(b, shared.DataPoint.String()) { 643 | dp := new(shared.DP) 644 | err := json.Unmarshal(b[1:], dp) 645 | if err != nil { 646 | return err 647 | } 648 | dps = append(dps, *dp) 649 | } else { 650 | shared.DEBUG(ErrorStyle.Render("Unknown data point encountered: ", string(b))) 651 | } 652 | } 653 | 654 | if c.HostFilter != "" { 655 | dps = shared.HostFilter(c.HostFilter, dps) 656 | } 657 | 658 | if c.PrintStats { 659 | printSliceOfDataPoints(dps, c) 660 | } 661 | 662 | if c.PrintErrors { 663 | if len(errors) > 0 { 664 | fmt.Println(" ____ ERRORS ____") 665 | } 666 | for i := range errors { 667 | PrintTError(errors[i]) 668 | } 669 | if len(errors) > 0 { 670 | fmt.Println("") 671 | } 672 | } 673 | 674 | if len(dps) == 0 { 675 | fmt.Println("No datapoints found") 676 | return 677 | } 678 | 679 | switch dps[0].Type { 680 | case shared.RequestTest: 681 | analyzeLatencyTest(dps, c) 682 | case shared.StreamTest: 683 | fmt.Println("") 684 | fmt.Println("Detailed analysis for bandwidth testing is in development") 685 | } 686 | 687 | return nil 688 | } 689 | 690 | func analyzeLatencyTest(dps []shared.DP, c shared.Config) { 691 | shared.SortDataPoints(dps, c) 692 | 693 | dps10 := math.Ceil((float64(len(dps)) / 100) * 10) 694 | dps50 := math.Floor((float64(len(dps)) / 100) * 50) 695 | dps90 := math.Floor((float64(len(dps)) / 100) * 90) 696 | dps99 := math.Floor((float64(len(dps)) / 100) * 99) 697 | 698 | dps10s := make([]shared.DP, 0) 699 | dps50s := make([]shared.DP, 0) 700 | dps90s := make([]shared.DP, 0) 701 | dps99s := make([]shared.DP, 0) 702 | 703 | // count, sum, low, avg, high 704 | dps10stats := []int64{0, 0, math.MaxInt64, 0, 0} 705 | dps50stats := []int64{0, 0, math.MaxInt64, 0, 0} 706 | dps90stats := []int64{0, 0, math.MaxInt64, 0, 0} 707 | dps99stats := []int64{0, 0, math.MaxInt64, 0, 0} 708 | 709 | for i := range dps { 710 | if i >= int(dps10) { 711 | dps10s = append(dps10s, dps[i]) 712 | shared.UpdatePSStats(dps10stats, dps[i], c) 713 | } 714 | if i >= int(dps50) { 715 | dps50s = append(dps50s, dps[i]) 716 | shared.UpdatePSStats(dps50stats, dps[i], c) 717 | } 718 | if i >= int(dps90) { 719 | dps90s = append(dps90s, dps[i]) 720 | shared.UpdatePSStats(dps90stats, dps[i], c) 721 | } 722 | if i >= int(dps99) { 723 | dps99s = append(dps99s, dps[i]) 724 | shared.UpdatePSStats(dps99stats, dps[i], c) 725 | } 726 | } 727 | 728 | fmt.Println("") 729 | fmt.Println(" _____ P99 data points _____ ") 730 | fmt.Println("") 731 | printSliceOfDataPoints(dps99s, c) 732 | 733 | fmt.Println("") 734 | if c.Sort == "" { 735 | fmt.Println(" Sorting:", shared.SortDefault) 736 | } else { 737 | fmt.Println(" Sorting:", c.Sort) 738 | } 739 | if c.Micro { 740 | fmt.Println(" Time: Microseconds") 741 | } else { 742 | fmt.Println(" Time: Milliseconds") 743 | } 744 | fmt.Println("") 745 | PrintPercentiles(SuccessStyle, "P10", dps10stats, c) 746 | PrintPercentiles(WarningStyle, "P50", dps50stats, c) 747 | PrintPercentiles(ErrorStyle, "P90", dps90stats, c) 748 | PrintPercentiles(ErrorStyle, "P99", dps99stats, c) 749 | } 750 | 751 | func MakeCSV(ctx context.Context, c shared.Config) (err error) { 752 | byteValue, err := os.ReadFile(c.File) 753 | if err != nil { 754 | return err 755 | } 756 | 757 | file, err := os.Create(c.File + ".csv") 758 | if err != nil { 759 | return err 760 | } 761 | defer file.Close() 762 | 763 | fb := bytes.NewBuffer(byteValue) 764 | scanner := bufio.NewScanner(fb) 765 | 766 | writer := csv.NewWriter(file) 767 | defer writer.Flush() 768 | if err := writer.Write(getStructFields(new(shared.DP))); err != nil { 769 | return err 770 | } 771 | 772 | for scanner.Scan() { 773 | b := scanner.Bytes() 774 | if bytes.HasPrefix(b, shared.DataPoint.String()) { 775 | dp := new(shared.DP) 776 | err = json.Unmarshal(b[1:], dp) 777 | if err != nil { 778 | return err 779 | } 780 | 781 | if err := writer.Write(dpToSlice(dp)); err != nil { 782 | return err 783 | } 784 | } 785 | } 786 | 787 | return nil 788 | } 789 | 790 | // Function to get field names of the struct 791 | func getStructFields(s interface{}) []string { 792 | t := reflect.TypeOf(s).Elem() 793 | fields := make([]string, t.NumField()) 794 | for i := 0; i < t.NumField(); i++ { 795 | fields[i] = t.Field(i).Tag.Get("json") 796 | if fields[i] == "" { 797 | fields[i] = t.Field(i).Name 798 | } 799 | } 800 | return fields 801 | } 802 | 803 | func dpToSlice(dp *shared.DP) (data []string) { 804 | v := reflect.ValueOf(dp).Elem() 805 | data = make([]string, v.NumField()) 806 | for i := 0; i < v.NumField(); i++ { 807 | data[i] = fmt.Sprintf("%v", v.Field(i).Interface()) 808 | } 809 | return 810 | } 811 | 812 | func transformDataPointsToMilliseconds(dps []shared.DP) (clone []shared.DP) { 813 | clone = make([]shared.DP, len(dps)) 814 | copy(clone, dps) 815 | for i := range clone { 816 | clone[i].TTFBH = clone[i].TTFBH / 1000 817 | clone[i].TTFBL = clone[i].TTFBL / 1000 818 | clone[i].RMSH = clone[i].RMSH / 1000 819 | clone[i].RMSL = clone[i].RMSL / 1000 820 | } 821 | return 822 | } 823 | 824 | func printSliceOfDataPoints(dps []shared.DP, c shared.Config) { 825 | var data []shared.DP 826 | if !c.Micro { 827 | data = transformDataPointsToMilliseconds(dps) 828 | } else { 829 | data = dps 830 | } 831 | 832 | for i := range data { 833 | if i%20 == 0 { 834 | printDataPointHeaders(data[0].Type) 835 | } 836 | dp := data[i] 837 | printTableRow(BaseStyle, &dp, dp.Type) 838 | } 839 | } 840 | -------------------------------------------------------------------------------- /client/table.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package client 19 | 20 | import ( 21 | "fmt" 22 | "strconv" 23 | "strings" 24 | "time" 25 | 26 | "github.com/charmbracelet/lipgloss" 27 | "github.com/minio/hperf/shared" 28 | ) 29 | 30 | type header struct { 31 | label string 32 | width int 33 | } 34 | 35 | type column struct { 36 | value interface{} 37 | width int 38 | } 39 | 40 | var headerSlice = make([]header, header_length) 41 | 42 | type HeaderField int 43 | 44 | const ( 45 | IntNumber HeaderField = iota 46 | Created 47 | Local 48 | Remote 49 | RMSH 50 | RMSL 51 | TTFBH 52 | TTFBL 53 | TX 54 | TXH 55 | TXL 56 | TXT 57 | TXCount 58 | ErrCount 59 | DroppedPackets 60 | MemoryUsage 61 | MemoryHigh 62 | MemoryLow 63 | CPUUsage 64 | CPUHigh 65 | CPULow 66 | ID 67 | HumanTime 68 | header_length 69 | ) 70 | 71 | func initHeaders() { 72 | headerSlice[IntNumber] = header{"#", 5} 73 | headerSlice[Created] = header{"Created", 8} 74 | headerSlice[Local] = header{"Local", 15} 75 | headerSlice[Remote] = header{"Remote", 15} 76 | headerSlice[RMSH] = header{"RMS(high)", 9} 77 | headerSlice[RMSL] = header{"RMS(low)", 9} 78 | headerSlice[TTFBH] = header{"TTFB(high)", 9} 79 | headerSlice[TTFBL] = header{"TTFB(low)", 9} 80 | headerSlice[TX] = header{"TX", 10} 81 | headerSlice[TXL] = header{"TX(low)", 10} 82 | headerSlice[TXH] = header{"TX(high)", 10} 83 | headerSlice[TXT] = header{"TX(total)", 15} 84 | headerSlice[TXCount] = header{"#TX", 10} 85 | headerSlice[ErrCount] = header{"#ERR", 6} 86 | headerSlice[DroppedPackets] = header{"#Dropped", 9} 87 | headerSlice[MemoryUsage] = header{"Mem(used)", 9} 88 | headerSlice[MemoryHigh] = header{"Mem(high)", 9} 89 | headerSlice[MemoryLow] = header{"Mem(low)", 9} 90 | headerSlice[CPUUsage] = header{"CPU(used)", 9} 91 | headerSlice[CPUHigh] = header{"CPU(high)", 9} 92 | headerSlice[CPULow] = header{"CPU(low)", 9} 93 | headerSlice[ID] = header{"ID", 30} 94 | headerSlice[HumanTime] = header{"Time", 30} 95 | } 96 | 97 | func GenerateFormatString(columnCount int) (fs string) { 98 | for i := 0; i < columnCount; i++ { 99 | fs += "%-*s " 100 | } 101 | return 102 | } 103 | 104 | var ( 105 | ListHeaders = []HeaderField{IntNumber, ID, HumanTime} 106 | BandwidthHeaders = []HeaderField{Created, Local, Remote, TX, ErrCount, DroppedPackets, MemoryUsage, CPUUsage} 107 | LatencyHeaders = []HeaderField{Created, Local, Remote, RMSH, RMSL, TTFBH, TTFBL, TX, TXCount, ErrCount, DroppedPackets, MemoryUsage, CPUUsage} 108 | FullDataPointHeaders = []HeaderField{Created, Local, Remote, RMSH, RMSL, TTFBH, TTFBL, TX, TXCount, ErrCount, DroppedPackets, MemoryUsage, CPUUsage} 109 | 110 | RealTimeBandwidthHeaders = []HeaderField{ErrCount, TXCount, TXH, TXL, TXT, DroppedPackets, MemoryHigh, MemoryLow, CPUHigh, CPULow} 111 | RealTimeLatencyHeaders = []HeaderField{ErrCount, TXCount, TXH, TXL, TXT, RMSH, RMSL, TTFBH, TTFBL, DroppedPackets, MemoryHigh, MemoryLow, CPUHigh, CPULow} 112 | ) 113 | 114 | var ( 115 | HeaderStyle = lipgloss.NewStyle().Background(lipgloss.Color("#F2F2F2")).Foreground(lipgloss.Color("#000000")) 116 | BaseStyle = lipgloss.NewStyle().Background(lipgloss.Color("#000000")).Foreground(lipgloss.Color("#F2F2F2")) 117 | SuccessStyle = lipgloss.NewStyle().Background(lipgloss.Color("#009900")).Foreground(lipgloss.Color("#F2F2F2")) 118 | WarningStyle = lipgloss.NewStyle().Background(lipgloss.Color("#999900")).Foreground(lipgloss.Color("#F2F2F2")) 119 | ErrorStyle = lipgloss.NewStyle().Background(lipgloss.Color("#AA0000")).Foreground(lipgloss.Color("#FFFFFF")) 120 | ) 121 | 122 | func printHeader(fields []HeaderField) { 123 | if headerSlice[0].width == 0 { 124 | initHeaders() 125 | } 126 | fs := GenerateFormatString(len(fields)) 127 | hs := make([]interface{}, 0) 128 | for i := range fields { 129 | h := headerSlice[fields[i]] 130 | hs = append(hs, h.width, h.label) 131 | } 132 | 133 | fmt.Println(HeaderStyle.Render(fmt.Sprintf(fs, hs...))) 134 | } 135 | 136 | func PrintPercentilesHeader(style lipgloss.Style, tag string, dps []int64, c shared.Config) { 137 | fs := GenerateFormatString(6) 138 | hs := []interface{}{ 139 | 4, tag, 140 | 10, "count", 141 | 10, "sum", 142 | 10, "min", 143 | 10, "avg", 144 | 10, "max", 145 | } 146 | fmt.Println(style.Render( 147 | fmt.Sprintf(fs, hs...), 148 | )) 149 | } 150 | 151 | func PrintPercentiles(style lipgloss.Style, tag string, dps []int64, c shared.Config) { 152 | PrintPercentilesHeader(style, tag, dps, c) 153 | fs := GenerateFormatString(6) 154 | hs := make([]interface{}, 12) 155 | hs[0] = 4 156 | hs[1] = "" 157 | hs[2] = 10 158 | hs[3] = formatInt(dps[0]) 159 | hs[4] = 10 160 | hs[6] = 10 161 | hs[8] = 10 162 | hs[10] = 10 163 | 164 | if c.Micro { 165 | hs[5] = formatInt(dps[1]) 166 | hs[7] = formatInt(dps[2]) 167 | hs[9] = formatInt(dps[3]) 168 | hs[11] = formatInt(dps[4]) 169 | } else { 170 | hs[5] = formatInt(dps[1] / 1000) 171 | hs[7] = formatInt(dps[2] / 1000) 172 | hs[9] = formatInt(dps[3] / 1000) 173 | hs[11] = formatInt(dps[4] / 1000) 174 | } 175 | 176 | fmt.Println(BaseStyle.Render( 177 | fmt.Sprintf(fs, hs...), 178 | )) 179 | } 180 | 181 | func PrintColumns(style lipgloss.Style, columns ...column) { 182 | fs := GenerateFormatString(len(columns)) 183 | hs := make([]interface{}, 0) 184 | for i := range columns { 185 | hs = append(hs, columns[i].width, columns[i].value) 186 | } 187 | fmt.Println(style.Render( 188 | fmt.Sprintf(fs, hs...), 189 | )) 190 | } 191 | 192 | func printDataPointHeaders(t shared.TestType) { 193 | switch t { 194 | case shared.StreamTest: 195 | printHeader(BandwidthHeaders) 196 | case shared.RequestTest: 197 | printHeader(LatencyHeaders) 198 | default: 199 | printHeader(FullDataPointHeaders) 200 | } 201 | } 202 | 203 | func printRealTimeHeaders(t shared.TestType) { 204 | switch t { 205 | case shared.StreamTest: 206 | printHeader(RealTimeBandwidthHeaders) 207 | case shared.RequestTest: 208 | printHeader(RealTimeLatencyHeaders) 209 | default: 210 | } 211 | } 212 | 213 | func printRealTimeRow(style lipgloss.Style, entry *shared.TestOutput, t shared.TestType) { 214 | switch t { 215 | case shared.StreamTest: 216 | PrintColumns( 217 | style, 218 | column{formatInt(int64(entry.ErrCount)), headerSlice[ErrCount].width}, 219 | column{formatUint(entry.TXC), headerSlice[TXCount].width}, 220 | column{shared.BWToString(entry.TXH), headerSlice[TXH].width}, 221 | column{shared.BWToString(entry.TXL), headerSlice[TXL].width}, 222 | column{shared.BToString(entry.TXT), headerSlice[TXT].width}, 223 | column{formatInt(int64(entry.DP)), headerSlice[DroppedPackets].width}, 224 | column{formatInt(int64(entry.MH)), headerSlice[MemoryHigh].width}, 225 | column{formatInt(int64(entry.ML)), headerSlice[MemoryLow].width}, 226 | column{formatInt(int64(entry.CH)), headerSlice[CPUHigh].width}, 227 | column{formatInt(int64(entry.CL)), headerSlice[CPULow].width}, 228 | ) 229 | return 230 | case shared.RequestTest: 231 | PrintColumns( 232 | style, 233 | column{formatInt(int64(entry.ErrCount)), headerSlice[ErrCount].width}, 234 | column{formatUint(entry.TXC), headerSlice[TXCount].width}, 235 | column{shared.BWToString(entry.TXH), headerSlice[TXH].width}, 236 | column{shared.BWToString(entry.TXL), headerSlice[TXL].width}, 237 | column{shared.BToString(entry.TXT), headerSlice[TXT].width}, 238 | column{formatInt(entry.RMSH), headerSlice[RMSH].width}, 239 | column{formatInt(entry.RMSL), headerSlice[RMSL].width}, 240 | column{formatInt(entry.TTFBH), headerSlice[TTFBH].width}, 241 | column{formatInt(entry.TTFBL), headerSlice[TTFBL].width}, 242 | column{formatInt(int64(entry.DP)), headerSlice[DroppedPackets].width}, 243 | column{formatInt(int64(entry.MH)), headerSlice[MemoryHigh].width}, 244 | column{formatInt(int64(entry.ML)), headerSlice[MemoryLow].width}, 245 | column{formatInt(int64(entry.CH)), headerSlice[CPUHigh].width}, 246 | column{formatInt(int64(entry.CL)), headerSlice[CPULow].width}, 247 | ) 248 | default: 249 | shared.DEBUG("Unknown test type, not printing table") 250 | } 251 | } 252 | 253 | func printTableRow(style lipgloss.Style, entry *shared.DP, t shared.TestType) { 254 | switch t { 255 | case shared.StreamTest: 256 | PrintColumns( 257 | style, 258 | column{entry.Created.Format("15:04:05"), headerSlice[Created].width}, 259 | column{strings.Split(entry.Local, ":")[0], headerSlice[Local].width}, 260 | column{strings.Split(entry.Remote, ":")[0], headerSlice[Remote].width}, 261 | column{shared.BWToString(entry.TX), headerSlice[TX].width}, 262 | column{formatInt(int64(entry.ErrCount)), headerSlice[ErrCount].width}, 263 | column{formatInt(int64(entry.DroppedPackets)), headerSlice[DroppedPackets].width}, 264 | column{formatInt(int64(entry.MemoryUsedPercent)), headerSlice[MemoryUsage].width}, 265 | column{formatInt(int64(entry.CPUUsedPercent)), headerSlice[CPUUsage].width}, 266 | ) 267 | return 268 | case shared.RequestTest: 269 | PrintColumns( 270 | style, 271 | column{entry.Created.Format("15:04:05"), headerSlice[Created].width}, 272 | column{strings.Split(entry.Local, ":")[0], headerSlice[Local].width}, 273 | column{strings.Split(entry.Remote, ":")[0], headerSlice[Remote].width}, 274 | column{formatInt(entry.RMSH), headerSlice[RMSH].width}, 275 | column{formatInt(entry.RMSL), headerSlice[RMSL].width}, 276 | column{formatInt(entry.TTFBH), headerSlice[TTFBH].width}, 277 | column{formatInt(entry.TTFBL), headerSlice[TTFBH].width}, 278 | column{shared.BWToString(entry.TX), headerSlice[TX].width}, 279 | column{formatUint(entry.TXCount), headerSlice[TXCount].width}, 280 | column{formatInt(int64(entry.ErrCount)), headerSlice[ErrCount].width}, 281 | column{formatInt(int64(entry.DroppedPackets)), headerSlice[DroppedPackets].width}, 282 | column{formatInt(int64(entry.MemoryUsedPercent)), headerSlice[MemoryUsage].width}, 283 | column{formatInt(int64(entry.CPUUsedPercent)), headerSlice[CPUUsage].width}, 284 | ) 285 | default: 286 | shared.DEBUG("Unknown test type, not printing table") 287 | } 288 | } 289 | 290 | func collectDataPointv2(r *shared.DataReponseToClient) { 291 | if r == nil { 292 | return 293 | } 294 | 295 | responseLock.Lock() 296 | defer responseLock.Unlock() 297 | 298 | responseDPS = append(responseDPS, r.DPS...) 299 | responseERR = append(responseERR, r.Errors...) 300 | } 301 | 302 | func praseDataPoint(r *shared.DataReponseToClient, c *shared.Config) { 303 | if r == nil { 304 | return 305 | } 306 | 307 | responseLock.Lock() 308 | defer responseLock.Unlock() 309 | 310 | // This guarantees we are always printing the 311 | // same header types as the data point types. 312 | if len(r.DPS) > 0 { 313 | c.TestType = r.DPS[0].Type 314 | } 315 | if len(responseDPS) > 0 { 316 | if len(responseDPS)%10 == 0 { 317 | printDataPointHeaders(c.TestType) 318 | } 319 | } else { 320 | if len(r.DPS) > 0 { 321 | printDataPointHeaders(c.TestType) 322 | } 323 | } 324 | 325 | for i := range r.DPS { 326 | r.DPS[i].Received = time.Now() 327 | entry := r.DPS[i] 328 | printTableRow(BaseStyle, &entry, entry.Type) 329 | } 330 | 331 | for i := range r.Errors { 332 | PrintTError(r.Errors[i]) 333 | } 334 | 335 | responseDPS = append(responseDPS, r.DPS...) 336 | responseERR = append(responseERR, r.Errors...) 337 | } 338 | 339 | // Helper functions to format int/uint values for table display 340 | func formatInt(val int64) string { 341 | return strconv.FormatInt(val, 10) 342 | } 343 | 344 | func formatUint(val uint64) string { 345 | return strconv.FormatUint(val, 10) 346 | } 347 | -------------------------------------------------------------------------------- /cmd/hperf/analyze.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | ) 24 | 25 | var analyzeCMD = cli.Command{ 26 | Name: "analyze", 27 | Usage: "Analyze the give test", 28 | Action: runAnalyze, 29 | Flags: []cli.Flag{ 30 | dnsServerFlag, 31 | hostsFlag, 32 | portFlag, 33 | fileFlag, 34 | printStatsFlag, 35 | printErrFlag, 36 | sortFlag, 37 | microSecondsFlag, 38 | hostFilterFlag, 39 | }, 40 | CustomHelpTemplate: `NAME: 41 | {{.HelpName}} - {{.Usage}} 42 | 43 | USAGE: 44 | {{.HelpName}} [FLAGS] 45 | 46 | FLAGS: 47 | {{range .VisibleFlags}}{{.}} 48 | {{end}} 49 | EXAMPLES: 50 | 1. Analyze test results in file '/tmp/latency-test-1': 51 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1 --file latency-test-1 52 | 2. Analyze test results and print full output: 53 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1 --file latency-test-1 --print-full 54 | 3. Analyze test results with sorted output: 55 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1 --file latency-test-1 --sort RMSH 56 | 4. Analyze test results with sorted output: 57 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1 --file latency-test-1 --sort RMSH --host-filter 10.10.10.1 58 | `, 59 | } 60 | 61 | func runAnalyze(ctx *cli.Context) error { 62 | config, err := parseConfig(ctx) 63 | if err != nil { 64 | return err 65 | } 66 | return client.AnalyzeTest(GlobalContext, *config) 67 | } 68 | -------------------------------------------------------------------------------- /cmd/hperf/bandwidth.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "fmt" 22 | 23 | "github.com/minio/cli" 24 | "github.com/minio/hperf/client" 25 | "github.com/minio/hperf/shared" 26 | ) 27 | 28 | var bandwidthCMD = cli.Command{ 29 | Name: "bandwidth", 30 | Usage: "Start a test to measure bandwidth", 31 | Action: runBandwidth, 32 | Flags: []cli.Flag{ 33 | hostsFlag, 34 | portFlag, 35 | durationFlag, 36 | saveTestFlag, 37 | testIDFlag, 38 | concurrencyFlag, 39 | dnsServerFlag, 40 | microSecondsFlag, 41 | printAllFlag, 42 | }, 43 | CustomHelpTemplate: `NAME: 44 | {{.HelpName}} - {{.Usage}} 45 | 46 | USAGE: 47 | {{.HelpName}} [FLAGS] 48 | 49 | NOTES: 50 | When testing for bandwidth it is recommended to start with concurrency 10 and increase the count as needed. Normally 10 is enough to saturate a 100Gb NIC. 51 | 52 | FLAGS: 53 | {{range .VisibleFlags}}{{.}} 54 | {{end}} 55 | EXAMPLES: 56 | 1. Run a basic test which prints all data points when finished: 57 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --print-all 58 | 59 | 2. Run a test with custom concurrency: 60 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --concurrency 10 61 | 62 | 3. Run a 30 seconds bandwidth test: 63 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --duration 30 --id bandwidth-30 64 | `, 65 | } 66 | 67 | func runBandwidth(ctx *cli.Context) error { 68 | config, err := parseConfig(ctx) 69 | if err != nil { 70 | return err 71 | } 72 | 73 | config.TestType = shared.StreamTest 74 | config.BufferSize = 32000 75 | config.PayloadSize = 32000 76 | config.RequestDelay = 0 77 | config.RestartOnError = true 78 | 79 | fmt.Println("") 80 | shared.INFO(" Test ID:", config.TestID) 81 | fmt.Println("") 82 | 83 | err = client.RunTest(GlobalContext, *config) 84 | if err != nil { 85 | return err 86 | } 87 | 88 | fmt.Println("") 89 | shared.INFO(" Testing finished..") 90 | 91 | return client.AnalyzeBandwidthTest(GlobalContext, *config) 92 | } 93 | -------------------------------------------------------------------------------- /cmd/hperf/csv.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | ) 24 | 25 | var csvCMD = cli.Command{ 26 | Name: "csv", 27 | Usage: "Transform a test file to csv file", 28 | Action: runCSV, 29 | Flags: []cli.Flag{ 30 | fileFlag, 31 | }, 32 | CustomHelpTemplate: `NAME: 33 | {{.HelpName}} - {{.Usage}} 34 | 35 | USAGE: 36 | {{.HelpName}} [FLAGS] 37 | 38 | FLAGS: 39 | {{range .VisibleFlags}}{{.}} 40 | {{end}} 41 | EXAMPLES: 42 | 1. Transform a test file to csv file: 43 | {{.Prompt}} {{.HelpName}} --file /tmp/output-file 44 | `, 45 | } 46 | 47 | func runCSV(ctx *cli.Context) error { 48 | config, err := parseConfig(ctx) 49 | if err != nil { 50 | return err 51 | } 52 | 53 | return client.MakeCSV(GlobalContext, *config) 54 | } 55 | -------------------------------------------------------------------------------- /cmd/hperf/delete.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | ) 24 | 25 | var deleteCMD = cli.Command{ 26 | Name: "delete", 27 | Usage: "deletes one or all tests on the selected hosts", 28 | Action: runDelete, 29 | Flags: []cli.Flag{ 30 | dnsServerFlag, 31 | hostsFlag, 32 | portFlag, 33 | testIDFlag, 34 | }, 35 | CustomHelpTemplate: `NAME: 36 | {{.HelpName}} - {{.Usage}} 37 | 38 | USAGE: 39 | {{.HelpName}} [FLAGS] 40 | 41 | FLAGS: 42 | {{range .VisibleFlags}}{{.}} 43 | {{end}} 44 | EXAMPLES: 45 | 1. Delete all tests on hosts '10.10.10.1' and '10.10.10.2': 46 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 47 | 48 | 2. Delete test by ID on hosts '10.10.10.1' and '10.10.10.2': 49 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --id my_test_id 50 | `, 51 | } 52 | 53 | func runDelete(ctx *cli.Context) error { 54 | config, err := parseConfig(ctx) 55 | if err != nil { 56 | return err 57 | } 58 | return client.DeleteTests(GlobalContext, *config) 59 | } 60 | -------------------------------------------------------------------------------- /cmd/hperf/download.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | ) 24 | 25 | var statDownloadCMD = cli.Command{ 26 | Name: "download", 27 | Usage: "Download stats for tests by ID", 28 | Action: runDownload, 29 | Flags: []cli.Flag{ 30 | dnsServerFlag, 31 | hostsFlag, 32 | portFlag, 33 | testIDFlag, 34 | fileFlag, 35 | }, 36 | CustomHelpTemplate: `NAME: 37 | {{.HelpName}} - {{.Usage}} 38 | 39 | USAGE: 40 | {{.HelpName}} [FLAGS] 41 | 42 | FLAGS: 43 | {{range .VisibleFlags}}{{.}} 44 | {{end}} 45 | EXAMPLES: 46 | 1. Download test by ID for hosts '10.10.10.1' and '10.10.10.2': 47 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --id my_test_id --file /tmp/output-file 48 | `, 49 | } 50 | 51 | func runDownload(ctx *cli.Context) error { 52 | config, err := parseConfig(ctx) 53 | if err != nil { 54 | return err 55 | } 56 | 57 | return client.DownloadTest(GlobalContext, *config) 58 | } 59 | -------------------------------------------------------------------------------- /cmd/hperf/latency.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "fmt" 22 | 23 | "github.com/minio/cli" 24 | "github.com/minio/hperf/client" 25 | "github.com/minio/hperf/shared" 26 | ) 27 | 28 | var latency = cli.Command{ 29 | Name: "latency", 30 | Usage: "Start a latency test and analyze the results", 31 | Action: runLatency, 32 | Flags: []cli.Flag{ 33 | hostsFlag, 34 | portFlag, 35 | durationFlag, 36 | testIDFlag, 37 | saveTestFlag, 38 | dnsServerFlag, 39 | microSecondsFlag, 40 | printAllFlag, 41 | }, 42 | CustomHelpTemplate: `NAME: 43 | {{.HelpName}} - {{.Usage}} 44 | 45 | USAGE: 46 | {{.HelpName}} [FLAGS] 47 | 48 | FLAGS: 49 | {{range .VisibleFlags}}{{.}} 50 | {{end}} 51 | EXAMPLES: 52 | 1. Run a 30 second latency test and show all data points after the test finishes: 53 | {{.Prompt}} {{.HelpName}} --duration 30 --hosts 10.10.10.1,10.10.10.2 --print-all 54 | 55 | 2. Run a 30 second latency test with custom id: 56 | {{.Prompt}} {{.HelpName}} --duration 60 --hosts 10.10.10.1,10.10.10.2 --id latency-60 57 | `, 58 | } 59 | 60 | func runLatency(ctx *cli.Context) error { 61 | config, err := parseConfig(ctx) 62 | if err != nil { 63 | return err 64 | } 65 | config.TestType = shared.RequestTest 66 | config.BufferSize = 1000 67 | config.PayloadSize = 1000 68 | config.Concurrency = 1 69 | config.RequestDelay = 200 70 | config.RestartOnError = true 71 | 72 | fmt.Println("") 73 | shared.INFO(" Test ID:", config.TestID) 74 | fmt.Println("") 75 | 76 | err = client.RunTest(GlobalContext, *config) 77 | if err != nil { 78 | return err 79 | } 80 | fmt.Println("") 81 | shared.INFO(" Testing finished ..") 82 | 83 | return client.AnalyzeLatencyTest(GlobalContext, *config) 84 | } 85 | -------------------------------------------------------------------------------- /cmd/hperf/list.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | ) 24 | 25 | var listTestsCMD = cli.Command{ 26 | Name: "list", 27 | Usage: "list all tests on the selected hosts", 28 | Action: runList, 29 | Flags: []cli.Flag{ 30 | dnsServerFlag, 31 | hostsFlag, 32 | portFlag, 33 | testIDFlag, 34 | }, 35 | CustomHelpTemplate: `NAME: 36 | {{.HelpName}} - {{.Usage}} 37 | 38 | USAGE: 39 | {{.HelpName}} [FLAGS] 40 | 41 | FLAGS: 42 | {{range .VisibleFlags}}{{.}} 43 | {{end}} 44 | EXAMPLES: 45 | 1. List all test on the '10.10.10.1' host: 46 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1 47 | `, 48 | } 49 | 50 | func runList(ctx *cli.Context) error { 51 | config, err := parseConfig(ctx) 52 | if err != nil { 53 | return err 54 | } 55 | return client.ListTests(GlobalContext, *config) 56 | } 57 | -------------------------------------------------------------------------------- /cmd/hperf/listen.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | ) 24 | 25 | var listenCMD = cli.Command{ 26 | Name: "listen", 27 | Usage: "receive live data from one or all active tests on the selected hosts", 28 | Action: runListen, 29 | Flags: []cli.Flag{ 30 | dnsServerFlag, 31 | hostsFlag, 32 | portFlag, 33 | testIDFlag, 34 | }, 35 | CustomHelpTemplate: `NAME: 36 | {{.HelpName}} - {{.Usage}} 37 | 38 | USAGE: 39 | {{.HelpName}} [FLAGS] 40 | 41 | FLAGS: 42 | {{range .VisibleFlags}}{{.}} 43 | {{end}} 44 | EXAMPLES: 45 | 1. Listen to a specific test on specific hosts: 46 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --id my_test_id 47 | 48 | 2. Listen to all active tests: 49 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 50 | `, 51 | } 52 | 53 | func runListen(ctx *cli.Context) error { 54 | config, err := parseConfig(ctx) 55 | if err != nil { 56 | return err 57 | } 58 | config.Duration = 0 59 | return client.Listen(GlobalContext, *config) 60 | } 61 | -------------------------------------------------------------------------------- /cmd/hperf/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "bytes" 22 | "context" 23 | "encoding/json" 24 | "errors" 25 | "fmt" 26 | "os" 27 | "os/signal" 28 | "runtime" 29 | "strconv" 30 | "syscall" 31 | "time" 32 | 33 | "github.com/minio/cli" 34 | "github.com/minio/hperf/client" 35 | "github.com/minio/hperf/shared" 36 | ) 37 | 38 | var version = "0.0.0-dev" 39 | 40 | // Help template for mc 41 | var mcHelpTemplate = `NAME: 42 | {{.Name}} - {{.Usage}} 43 | 44 | USAGE: 45 | {{.Name}} {{if .VisibleFlags}}[FLAGS] {{end}}COMMAND{{if .VisibleFlags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...] 46 | 47 | COMMANDS: 48 | {{range .VisibleCommands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} 49 | {{end}}{{if .VisibleFlags}} 50 | GLOBAL FLAGS: 51 | {{range .VisibleFlags}}{{.}} 52 | {{end}}{{end}} 53 | ` 54 | 55 | func main() { 56 | CreateApp().Run(os.Args) 57 | } 58 | 59 | func InvalidFlagValueError(value interface{}, name string) error { 60 | return fmt.Errorf("Invalid flag value (%s) for flag (%s)", value, name) 61 | } 62 | 63 | var ( 64 | debug = false 65 | insecure = false 66 | globalFlags = []cli.Flag{ 67 | hostsFlag, 68 | portFlag, 69 | insecureFlag, 70 | concurrencyFlag, 71 | delayFlag, 72 | durationFlag, 73 | bufferSizeFlag, 74 | payloadSizeFlag, 75 | restartOnErrorFlag, 76 | testIDFlag, 77 | saveTestFlag, 78 | dnsServerFlag, 79 | } 80 | hostsFlag = cli.StringFlag{ 81 | Name: "hosts", 82 | EnvVar: "HPERF_HOSTS", 83 | Usage: "list of hosts for the current command", 84 | } 85 | portFlag = cli.StringFlag{ 86 | Name: "port", 87 | Value: "9010", 88 | EnvVar: "HPERF_PORT", 89 | Usage: "port used to communicate with hosts", 90 | } 91 | insecureFlag = cli.BoolTFlag{ 92 | Name: "insecure", 93 | EnvVar: "HPERF_INSECURE", 94 | Usage: "use http instead of https", 95 | } 96 | debugFlag = cli.BoolFlag{ 97 | Name: "debug", 98 | EnvVar: "HPERF_DEBUG", 99 | Usage: "enable debug output logs for client and server for a command", 100 | } 101 | concurrencyFlag = cli.IntFlag{ 102 | Name: "concurrency", 103 | EnvVar: "HPERF_CONCURRENCY", 104 | Value: runtime.GOMAXPROCS(0) * 2, 105 | Usage: "this flags controls how many concurrent requests to run per host", 106 | } 107 | delayFlag = cli.IntFlag{ 108 | Name: "request-delay", 109 | Value: 0, 110 | EnvVar: "HPERF_REQUEST_DELAY", 111 | Usage: "adds a delay (in milliseconds) before sending http requests from host to host", 112 | } 113 | durationFlag = cli.IntFlag{ 114 | Name: "duration", 115 | Value: 30, 116 | EnvVar: "HPERF_DURATION", 117 | Usage: "controls how long a test will run in seconds", 118 | } 119 | bufferSizeFlag = cli.IntFlag{ 120 | Name: "buffer-size", 121 | Value: 32000, 122 | EnvVar: "HPERF_BUFFER_SIZE", 123 | Usage: "buffer size in bytes", 124 | } 125 | payloadSizeFlag = cli.IntFlag{ 126 | Name: "payload-size", 127 | Value: 1000000, 128 | EnvVar: "HPERF_PAYLOAD_SIZE", 129 | Usage: "payload size in bytes", 130 | } 131 | restartOnErrorFlag = cli.BoolTFlag{ 132 | Name: "restart-on-error", 133 | EnvVar: "HPERF_RESTART_ON_ERROR", 134 | Usage: "restart tests/clients upon error", 135 | } 136 | testIDFlag = cli.StringFlag{ 137 | Name: "id", 138 | Usage: "specify custom ID per test", 139 | } 140 | fileFlag = cli.StringFlag{ 141 | Name: "file", 142 | Usage: "input file path", 143 | } 144 | saveTestFlag = cli.BoolTFlag{ 145 | Name: "save", 146 | EnvVar: "HPERF_SAVE", 147 | Usage: "save tests results on the server for retrieve later", 148 | } 149 | dnsServerFlag = cli.StringFlag{ 150 | Name: "dns-server", 151 | EnvVar: "HPERF_DNS_SERVER", 152 | Usage: "use a custom DNS server to resolve hosts", 153 | } 154 | printStatsFlag = cli.BoolFlag{ 155 | Name: "print-stats", 156 | Usage: "Print data points", 157 | } 158 | printAllFlag = cli.BoolFlag{ 159 | Name: "print-all", 160 | Usage: "Print all data points", 161 | } 162 | microSecondsFlag = cli.BoolFlag{ 163 | Name: "micro", 164 | Usage: "Display timers in microseconds instead of milliseconds", 165 | } 166 | sortFlag = cli.StringFlag{ 167 | Name: "sort", 168 | Usage: "Sort datapoints using columns", 169 | } 170 | printErrFlag = cli.BoolFlag{ 171 | Name: "print-errors", 172 | Usage: "Print errors", 173 | } 174 | hostFilterFlag = cli.StringFlag{ 175 | Name: "host-filter", 176 | Usage: "Filter analysis datapoints based on host", 177 | } 178 | ) 179 | 180 | var ( 181 | baseFlags = []cli.Flag{ 182 | debugFlag, 183 | insecureFlag, 184 | } 185 | Commands = []cli.Command{ 186 | analyzeCMD, 187 | bandwidthCMD, 188 | csvCMD, 189 | deleteCMD, 190 | latency, 191 | listenCMD, 192 | listTestsCMD, 193 | requestsCMD, 194 | serverCMD, 195 | statDownloadCMD, 196 | stopCMD, 197 | } 198 | ) 199 | 200 | func CreateApp() *cli.App { 201 | cli.HelpFlag = cli.BoolFlag{ 202 | Name: "help, h", 203 | Usage: "show help", 204 | } 205 | 206 | app := cli.NewApp() 207 | app.Action = func(ctx *cli.Context) error { 208 | showAppHelpAndExit(ctx) 209 | return exitStatus(0) 210 | } 211 | 212 | app.Before = before 213 | app.OnUsageError = func(context *cli.Context, err error, isSubcommand bool) error { 214 | fmt.Println(err) 215 | return nil 216 | } 217 | 218 | app.Name = "hperf" 219 | app.HideHelpCommand = true 220 | app.Usage = "MinIO network performance test utility for infrastructure at scale" 221 | app.Commands = Commands 222 | app.Author = "MinIO, Inc." 223 | app.Copyright = "(c) 2021-2024 MinIO, Inc." 224 | app.Version = version 225 | app.Flags = baseFlags 226 | app.CustomAppHelpTemplate = mcHelpTemplate 227 | app.EnableBashCompletion = false 228 | return app 229 | } 230 | 231 | var ( 232 | GlobalContext context.Context 233 | GlobalCancelFunc context.CancelCauseFunc 234 | ) 235 | 236 | func before(ctx *cli.Context) error { 237 | debug = ctx.Bool("debug") 238 | insecure = ctx.Bool("insecure") 239 | GlobalContext, GlobalCancelFunc = context.WithCancelCause(context.Background()) 240 | go handleOSSignal(GlobalCancelFunc) 241 | return nil 242 | } 243 | 244 | func parseConfig(ctx *cli.Context) (*shared.Config, error) { 245 | shared.DebugEnabled = debug 246 | 247 | concur := ctx.Int(concurrencyFlag.Name) 248 | if concur == 0 { 249 | concur = max(1, runtime.NumCPU()/2) 250 | if concur == 0 { 251 | concur = 1 252 | } 253 | } 254 | 255 | var config *shared.Config 256 | hosts, err := shared.ParseHosts( 257 | ctx.String(hostsFlag.Name), 258 | ctx.String(dnsServerFlag.Name), 259 | ) 260 | if err != nil { 261 | goto Error 262 | } 263 | 264 | config = &shared.Config{ 265 | DialTimeout: 0, 266 | Debug: debug, 267 | Hosts: hosts, 268 | Insecure: insecure, 269 | TestType: shared.RequestTest, 270 | Duration: ctx.Int(durationFlag.Name), 271 | RequestDelay: ctx.Int(delayFlag.Name), 272 | Concurrency: ctx.Int(concurrencyFlag.Name), 273 | PayloadSize: ctx.Int(payloadSizeFlag.Name), 274 | BufferSize: ctx.Int(bufferSizeFlag.Name), 275 | Port: ctx.String(portFlag.Name), 276 | Save: ctx.BoolT(saveTestFlag.Name), 277 | TestID: ctx.String(testIDFlag.Name), 278 | RestartOnError: ctx.BoolT(restartOnErrorFlag.Name), 279 | File: ctx.String(fileFlag.Name), 280 | PrintStats: ctx.Bool(printStatsFlag.Name), 281 | PrintAll: ctx.Bool(printAllFlag.Name), 282 | PrintErrors: ctx.Bool(printErrFlag.Name), 283 | Sort: shared.SortType(ctx.String(sortFlag.Name)), 284 | Micro: ctx.Bool(microSecondsFlag.Name), 285 | HostFilter: ctx.String(hostFilterFlag.Name), 286 | } 287 | 288 | switch ctx.Command.Name { 289 | case "latency", "bandwidth", "http", "get": 290 | if ctx.String("id") == "" { 291 | config.TestID = strconv.Itoa(int(time.Now().Unix())) 292 | } 293 | case "download": 294 | if ctx.String("id") == "" { 295 | err = errors.New("--id is required") 296 | } 297 | if ctx.String("file") == "" { 298 | err = errors.New("--file is required") 299 | } 300 | case "analyze": 301 | if ctx.String("file") == "" { 302 | err = errors.New("--file is required") 303 | } 304 | default: 305 | } 306 | 307 | Error: 308 | if err != nil { 309 | cli.ShowCommandHelp(ctx, ctx.Command.Name) 310 | fmt.Println("") 311 | fmt.Println(client.ErrorStyle.Render(" " + err.Error())) 312 | fmt.Println("") 313 | fmt.Println("") 314 | } 315 | 316 | prettyprint(config, "CONFIG") 317 | return config, err 318 | } 319 | 320 | func prettyprint(data *shared.Config, title string) { 321 | if !data.Debug { 322 | return 323 | } 324 | dataB, err := json.Marshal(data) 325 | if err != nil { 326 | fmt.Println(err) 327 | } 328 | var out bytes.Buffer 329 | err = json.Indent(&out, dataB, "", " ") 330 | if err != nil { 331 | fmt.Println(err) 332 | } 333 | fmt.Println(title, " ==============================") 334 | // outData := out.Bytes() 335 | fmt.Println(string(out.Bytes())) 336 | fmt.Println("=================") 337 | } 338 | 339 | func exitStatus(status int) error { 340 | return cli.NewExitError("", status) 341 | } 342 | 343 | func showAppHelpAndExit(cliCtx *cli.Context) { 344 | cli.ShowAppHelp(cliCtx) 345 | os.Exit(1) 346 | } 347 | 348 | func handleOSSignal(cancel context.CancelCauseFunc) { 349 | signalCh := make(chan os.Signal, 1) 350 | signal.Notify(signalCh, 351 | syscall.SIGHUP, 352 | syscall.SIGINT, 353 | syscall.SIGTERM, 354 | syscall.SIGQUIT) 355 | sig := <-signalCh 356 | cancel(fmt.Errorf("OS Signal caugh: %d", sig)) 357 | } 358 | -------------------------------------------------------------------------------- /cmd/hperf/requests.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | "github.com/minio/hperf/shared" 24 | ) 25 | 26 | var requestsCMD = cli.Command{ 27 | Name: "requests", 28 | Usage: "Start a test which uses multiple http requests to measure performance", 29 | Action: runLatency, 30 | Flags: []cli.Flag{ 31 | hostsFlag, 32 | portFlag, 33 | concurrencyFlag, 34 | delayFlag, 35 | durationFlag, 36 | bufferSizeFlag, 37 | payloadSizeFlag, 38 | restartOnErrorFlag, 39 | testIDFlag, 40 | saveTestFlag, 41 | dnsServerFlag, 42 | microSecondsFlag, 43 | }, 44 | CustomHelpTemplate: `NAME: 45 | {{.HelpName}} - {{.Usage}} 46 | 47 | USAGE: 48 | {{.HelpName}} [FLAGS] 49 | 50 | FLAGS: 51 | {{range .VisibleFlags}}{{.}} 52 | {{end}} 53 | EXAMPLES: 54 | 1. Run a basic test: 55 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 56 | 57 | 2. Run a slow moving test to probe latency: 58 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --request-delay 100 --concurrency 1 59 | 60 | 3. Run a high throughput test to probe bandwidth: 61 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --request-delay 0 --concurrency 10 62 | 63 | 4. Run a high throughput test with 1MB payload size: 64 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --request-delay 0 --concurrency 10 --payload-size 1000000 65 | `, 66 | } 67 | 68 | func runRequests(ctx *cli.Context) error { 69 | config, err := parseConfig(ctx) 70 | if err != nil { 71 | return err 72 | } 73 | config.TestType = shared.RequestTest 74 | return client.RunTest(GlobalContext, *config) 75 | } 76 | -------------------------------------------------------------------------------- /cmd/hperf/server.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "os" 22 | 23 | "github.com/minio/cli" 24 | "github.com/minio/hperf/server" 25 | "github.com/minio/hperf/shared" 26 | ) 27 | 28 | func getPWD() string { 29 | pwd, _ := os.Getwd() 30 | return pwd 31 | } 32 | 33 | var ( 34 | addressFlag = cli.StringFlag{ 35 | Name: "address", 36 | EnvVar: "HPERF_ADDRESS", 37 | Value: "0.0.0.0:9010", 38 | Usage: "bind to the specified address", 39 | } 40 | realIPFlag = cli.StringFlag{ 41 | Name: "real-ip", 42 | EnvVar: "HPERF_REAL_IP", 43 | Value: "", 44 | Usage: "The real IP used to connect to other servers. If the --address is bound to the real IP then this flag can be skipped.", 45 | } 46 | storagePathFlag = cli.StringFlag{ 47 | Name: "storage-path", 48 | EnvVar: "HPERF_STORAGE_PATH", 49 | Value: getPWD(), 50 | Usage: "all test results will be saved in this directory", 51 | } 52 | 53 | serverCMD = cli.Command{ 54 | Name: "server", 55 | Usage: "start an interactive server", 56 | Action: runServer, 57 | Flags: []cli.Flag{addressFlag, realIPFlag, storagePathFlag, debugFlag}, 58 | CustomHelpTemplate: `NAME: 59 | {{.HelpName}} - {{.Usage}} 60 | 61 | USAGE: 62 | {{.HelpName}} [FLAGS] 63 | 64 | FLAGS: 65 | {{range .VisibleFlags}}{{.}} 66 | {{end}} 67 | EXAMPLES: 68 | 1. Run HPerf server with defaults: 69 | {{.Prompt}} {{.HelpName}} 70 | 71 | 2. Run HPerf server with custom file path 72 | {{.Prompt}} {{.HelpName}} --storage-path /path/on/disk 73 | 74 | 3. Run HPerf server with custom file path and custom address 75 | {{.Prompt}} {{.HelpName}} --storage-path /path/on/disk --address 0.0.0.0:9000 76 | 77 | 4. Run HPerf server with custom file path and floating(real) ip 78 | {{.Prompt}} {{.HelpName}} --storage-path /path/on/disk --address 0.0.0.0:9000 --real-ip 152.121.12.4 79 | `, 80 | } 81 | ) 82 | 83 | func runServer(ctx *cli.Context) error { 84 | shared.DebugEnabled = debug 85 | return server.RunServer( 86 | GlobalContext, 87 | ctx.String("address"), 88 | ctx.String("real-ip"), 89 | ctx.String("storage-path"), 90 | ) 91 | } 92 | -------------------------------------------------------------------------------- /cmd/hperf/stop.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | ) 24 | 25 | var stopCMD = cli.Command{ 26 | Name: "stop", 27 | Usage: "stop a specific test or all test on the selected hosts", 28 | Action: runStop, 29 | Flags: []cli.Flag{ 30 | dnsServerFlag, 31 | hostsFlag, 32 | portFlag, 33 | testIDFlag, 34 | }, 35 | CustomHelpTemplate: `NAME: 36 | {{.HelpName}} - {{.Usage}} 37 | 38 | USAGE: 39 | {{.HelpName}} [FLAGS] 40 | 41 | FLAGS: 42 | {{range .VisibleFlags}}{{.}} 43 | {{end}} 44 | EXAMPLES: 45 | 1. Stop all tests on hosts '10.10.10.1' and '10.10.10.2': 46 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 47 | 48 | 2. Stop test by ID on hosts '10.10.10.1' and '10.10.10.2': 49 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --id my_test_id 50 | `, 51 | } 52 | 53 | func runStop(ctx *cli.Context) error { 54 | config, err := parseConfig(ctx) 55 | if err != nil { 56 | return err 57 | } 58 | return client.Stop(GlobalContext, *config) 59 | } 60 | -------------------------------------------------------------------------------- /cmd/hperf/stream.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/minio/cli" 22 | "github.com/minio/hperf/client" 23 | "github.com/minio/hperf/shared" 24 | ) 25 | 26 | var streamCMD = cli.Command{ 27 | Name: "stream", 28 | Usage: "Start a test which uses an HTTP body stream to measure bandwidth", 29 | Action: runStream, 30 | Flags: []cli.Flag{ 31 | hostsFlag, 32 | portFlag, 33 | concurrencyFlag, 34 | durationFlag, 35 | testIDFlag, 36 | bufferSizeFlag, 37 | payloadSizeFlag, 38 | restartOnErrorFlag, 39 | dnsServerFlag, 40 | saveTestFlag, 41 | }, 42 | CustomHelpTemplate: `NAME: 43 | {{.HelpName}} - {{.Usage}} 44 | 45 | USAGE: 46 | {{.HelpName}} [FLAGS] 47 | 48 | NOTE: 49 | Matching concurrency with your thread count can often lead to 50 | improved performance, it is even better to run concurrency at 51 | 50% of the GOMAXPROCS. 52 | 53 | FLAGS: 54 | {{range .VisibleFlags}}{{.}} 55 | {{end}} 56 | EXAMPLES: 57 | 1. Run a basic test: 58 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 59 | 60 | 2. Run a test with custom concurrency: 61 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --concurrency 24 62 | 63 | 3. Run a test with custom buffer and payload size: 64 | {{.Prompt}} {{.HelpName}} --hosts 10.10.10.1,10.10.10.2 --bufferSize 9000 --payloadSize 9000 65 | `, 66 | } 67 | 68 | func runStream(ctx *cli.Context) error { 69 | config, err := parseConfig(ctx) 70 | if err != nil { 71 | return err 72 | } 73 | config.TestType = shared.StreamTest 74 | return client.RunTest(GlobalContext, *config) 75 | } 76 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/minio/hperf 2 | 3 | go 1.24.2 4 | 5 | require ( 6 | github.com/charmbracelet/lipgloss v0.13.0 7 | github.com/fasthttp/websocket v1.5.10 8 | github.com/gofiber/contrib/websocket v1.3.2 9 | github.com/gofiber/fiber/v2 v2.52.5 10 | github.com/google/uuid v1.6.0 11 | github.com/minio/cli v1.24.2 12 | github.com/minio/pkg/v3 v3.0.20 13 | github.com/shirou/gopsutil v3.21.11+incompatible 14 | golang.org/x/sys v0.26.0 15 | ) 16 | 17 | require ( 18 | github.com/andybalholm/brotli v1.1.0 // indirect 19 | github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect 20 | github.com/charmbracelet/x/ansi v0.1.4 // indirect 21 | github.com/go-ole/go-ole v1.3.0 // indirect 22 | github.com/klauspost/compress v1.17.9 // indirect 23 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 24 | github.com/mattn/go-colorable v0.1.13 // indirect 25 | github.com/mattn/go-isatty v0.0.20 // indirect 26 | github.com/mattn/go-runewidth v0.0.16 // indirect 27 | github.com/muesli/termenv v0.15.2 // indirect 28 | github.com/rivo/uniseg v0.4.7 // indirect 29 | github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 // indirect 30 | github.com/tklauser/go-sysconf v0.3.14 // indirect 31 | github.com/tklauser/numcpus v0.8.0 // indirect 32 | github.com/valyala/bytebufferpool v1.0.0 // indirect 33 | github.com/valyala/fasthttp v1.55.0 // indirect 34 | github.com/valyala/tcplisten v1.0.0 // indirect 35 | github.com/yusufpapurcu/wmi v1.2.4 // indirect 36 | golang.org/x/net v0.29.0 // indirect 37 | ) 38 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 2 | github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= 3 | github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= 4 | github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= 5 | github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= 6 | github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA/SsA3cjw= 7 | github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY= 8 | github.com/charmbracelet/x/ansi v0.1.4 h1:IEU3D6+dWwPSgZ6HBH+v6oUuZ/nVawMiWj5831KfiLM= 9 | github.com/charmbracelet/x/ansi v0.1.4/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= 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/fasthttp/websocket v1.5.10 h1:bc7NIGyrg1L6sd5pRzCIbXpro54SZLEluZCu0rOpcN4= 13 | github.com/fasthttp/websocket v1.5.10/go.mod h1:BwHeuXGWzCW1/BIKUKD3+qfCl+cTdsHu/f243NcAI/Q= 14 | github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= 15 | github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= 16 | github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= 17 | github.com/gofiber/contrib/websocket v1.3.2 h1:AUq5PYeKwK50s0nQrnluuINYeep1c4nRCJ0NWsV3cvg= 18 | github.com/gofiber/contrib/websocket v1.3.2/go.mod h1:07u6QGMsvX+sx7iGNCl5xhzuUVArWwLQ3tBIH24i+S8= 19 | github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo= 20 | github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ= 21 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 22 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 23 | github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= 24 | github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= 25 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 26 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 27 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= 28 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= 29 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 30 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 31 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 32 | github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= 33 | github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 34 | github.com/minio/cli v1.24.2 h1:J+fCUh9mhPLjN3Lj/YhklXvxj8mnyE/D6FpFduXJ2jg= 35 | github.com/minio/cli v1.24.2/go.mod h1:bYxnK0uS629N3Bq+AOZZ+6lwF77Sodk4+UL9vNuXhOY= 36 | github.com/minio/pkg/v3 v3.0.20 h1:iZSWNIXOpbVXkLhxbVQofIIJgDwh62FJf4O+ttMobLE= 37 | github.com/minio/pkg/v3 v3.0.20/go.mod h1:LwYm9J2+ZMgnrVvnxxFKss1QCuY86X85ec6CQNv2a4k= 38 | github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= 39 | github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= 40 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 41 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 42 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 43 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= 44 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 45 | github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 h1:D0vL7YNisV2yqE55+q0lFuGse6U8lxlg7fYTctlT5Gc= 46 | github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38/go.mod h1:sM7Mt7uEoCeFSCBM+qBrqvEo+/9vdmj19wzp3yzUhmg= 47 | github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= 48 | github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= 49 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 50 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 51 | github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU= 52 | github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY= 53 | github.com/tklauser/numcpus v0.8.0 h1:Mx4Wwe/FjZLeQsK/6kt2EOepwwSl7SmJrK5bV/dXYgY= 54 | github.com/tklauser/numcpus v0.8.0/go.mod h1:ZJZlAY+dmR4eut8epnzf0u/VwodKmryxR8txiloSqBE= 55 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 56 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 57 | github.com/valyala/fasthttp v1.55.0 h1:Zkefzgt6a7+bVKHnu/YaYSOPfNYNisSVBo/unVCf8k8= 58 | github.com/valyala/fasthttp v1.55.0/go.mod h1:NkY9JtkrpPKmgwV3HTaS2HWaJss9RSIsRVfcxxoHiOM= 59 | github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= 60 | github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= 61 | github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= 62 | github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= 63 | golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= 64 | golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= 65 | golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 66 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 67 | golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 68 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 69 | golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= 70 | golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 71 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 72 | gopkg.in/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0= 73 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 74 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 75 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 76 | -------------------------------------------------------------------------------- /helm-reindex.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | helm package helm/hperf -d helm-releases/ 4 | -------------------------------------------------------------------------------- /helm/hperf/.helmignore: -------------------------------------------------------------------------------- 1 | # Patterns to ignore when building packages. 2 | # This supports shell glob matching, relative path matching, and 3 | # negation (prefixed with !). Only one pattern per line. 4 | .DS_Store 5 | # Common VCS dirs 6 | .git/ 7 | .gitignore 8 | .bzr/ 9 | .bzrignore 10 | .hg/ 11 | .hgignore 12 | .svn/ 13 | # Common backup files 14 | *.swp 15 | *.bak 16 | *.tmp 17 | *.orig 18 | *~ 19 | # Various IDEs 20 | .project 21 | .idea/ 22 | *.tmproj 23 | .vscode/ 24 | -------------------------------------------------------------------------------- /helm/hperf/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | name: hperf 3 | description: Nperf is a tool for active measurements of the maximum achievable bandwidth between N peers, measuring RX/TX bandwidth for each peers. 4 | 5 | # A chart can be either an 'application' or a 'library' chart. 6 | # 7 | # Application charts are a collection of templates that can be packaged into versioned archives 8 | # to be deployed. 9 | # 10 | # Library charts provide useful utilities or functions for the chart developer. They're included as 11 | # a dependency of application charts to inject those utilities and functions into the rendering 12 | # pipeline. Library charts do not define any templates and therefore cannot be deployed. 13 | type: application 14 | 15 | # This is the chart version. This version number should be incremented each time you make changes 16 | # to the chart and its templates, including the app version. 17 | # Versions are expected to follow Semantic Versioning (https://semver.org/) 18 | version: v4.0.5 19 | 20 | # This is the version number of the application being deployed. This version number should be 21 | # incremented each time you make changes to the application. Versions are not expected to 22 | # follow Semantic Versioning. They should reflect the version the application is using. 23 | # It is recommended to use it with quotes. 24 | appVersion: "4.0.5" 25 | -------------------------------------------------------------------------------- /helm/hperf/templates/NOTES.txt: -------------------------------------------------------------------------------- 1 | --- 2 | Look for `hperf` results with `kubectl logs` 3 | 4 | kubectl logs --namespace {{ .Release.Namespace }} --max-log-requests {{ .Values.replicaCount }} -l "app=hperf" -f 5 | -------------------------------------------------------------------------------- /helm/hperf/templates/_helpers.tpl: -------------------------------------------------------------------------------- 1 | {{/* 2 | Expand the name of the chart. 3 | */}} 4 | {{- define "hperf.name" -}} 5 | {{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} 6 | {{- end }} 7 | 8 | {{/* 9 | Create a default fully qualified app name. 10 | We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). 11 | If release name contains chart name it will be used as a full name. 12 | */}} 13 | {{- define "hperf.fullname" -}} 14 | {{- if .Values.fullnameOverride }} 15 | {{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} 16 | {{- else }} 17 | {{- $name := default .Chart.Name .Values.nameOverride }} 18 | {{- if contains $name .Release.Name }} 19 | {{- .Release.Name | trunc 63 | trimSuffix "-" }} 20 | {{- else }} 21 | {{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} 22 | {{- end }} 23 | {{- end }} 24 | {{- end }} 25 | 26 | {{/* 27 | Create chart name and version as used by the chart label. 28 | */}} 29 | {{- define "hperf.chart" -}} 30 | {{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} 31 | {{- end }} 32 | 33 | {{/* 34 | Common labels 35 | */}} 36 | {{- define "hperf.labels" -}} 37 | helm.sh/chart: {{ include "hperf.chart" . }} 38 | {{ include "hperf.selectorLabels" . }} 39 | {{- if .Chart.AppVersion }} 40 | app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} 41 | {{- end }} 42 | app.kubernetes.io/managed-by: {{ .Release.Service }} 43 | {{- end }} 44 | 45 | {{/* 46 | Selector labels 47 | */}} 48 | {{- define "hperf.selectorLabels" -}} 49 | app.kubernetes.io/name: {{ include "hperf.name" . }} 50 | app.kubernetes.io/instance: {{ .Release.Name }} 51 | {{- end }} 52 | 53 | {{/* 54 | Create the name of the service account to use 55 | */}} 56 | {{- define "hperf.serviceAccountName" -}} 57 | {{- if .Values.serviceAccount.create }} 58 | {{- default (include "hperf.fullname" .) .Values.serviceAccount.name }} 59 | {{- else }} 60 | {{- default "default" .Values.serviceAccount.name }} 61 | {{- end }} 62 | {{- end }} 63 | -------------------------------------------------------------------------------- /helm/hperf/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ template "hperf.fullname" . }} 5 | labels: 6 | app: hperf 7 | spec: 8 | publishNotReadyAddresses: true 9 | clusterIP: None 10 | ports: 11 | - port: 9999 12 | name: http1 13 | selector: 14 | app: hperf 15 | -------------------------------------------------------------------------------- /helm/hperf/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | {{- if .Values.serviceAccount.create -}} 2 | apiVersion: v1 3 | kind: ServiceAccount 4 | metadata: 5 | name: {{ include "hperf.serviceAccountName" . }} 6 | labels: 7 | {{- include "hperf.labels" . | nindent 4 }} 8 | {{- with .Values.serviceAccount.annotations }} 9 | annotations: 10 | {{- toYaml . | nindent 4 }} 11 | {{- end }} 12 | {{- end }} 13 | -------------------------------------------------------------------------------- /helm/hperf/templates/statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | name: {{ template "hperf.fullname" . }} 5 | namespace: {{ .Release.Namespace | quote }} 6 | labels: 7 | app: hperf 8 | spec: 9 | serviceName: {{ template "hperf.fullname" . }} 10 | replicas: {{ .Values.replicaCount }} 11 | podManagementPolicy: Parallel 12 | selector: 13 | matchLabels: 14 | app: hperf 15 | template: 16 | metadata: 17 | name: hperf 18 | labels: 19 | app: hperf 20 | spec: 21 | {{- with .Values.imagePullSecrets }} 22 | imagePullSecrets: 23 | {{- toYaml . | nindent 8 }} 24 | {{- end }} 25 | serviceAccountName: {{ include "hperf.serviceAccountName" . }} 26 | securityContext: 27 | {{- toYaml .Values.podSecurityContext | nindent 8 }} 28 | containers: 29 | - name: hperf 30 | securityContext: 31 | {{- toYaml .Values.securityContext | nindent 12 }} 32 | image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" 33 | imagePullPolicy: {{ .Values.image.pullPolicy }} 34 | args: 35 | {{- range $i := until ($.Values.replicaCount | int)}} 36 | - {{ template "hperf.fullname" $ }}-{{ $i }}.{{ template "hperf.fullname" $ }}.{{ $.Release.Namespace }}.svc.{{ $.Values.clusterDomain }} 37 | {{ end }} 38 | ports: 39 | - name: http1 40 | containerPort: 9999 41 | {{- with .Values.nodeSelector }} 42 | nodeSelector: 43 | {{- toYaml . | nindent 8 }} 44 | {{- end }} 45 | affinity: 46 | podAntiAffinity: 47 | requiredDuringSchedulingIgnoredDuringExecution: 48 | - labelSelector: 49 | matchExpressions: 50 | - key: app 51 | operator: In 52 | values: 53 | - hperf 54 | topologyKey: "kubernetes.io/hostname" 55 | {{- with .Values.tolerations }} 56 | tolerations: 57 | {{- toYaml . | nindent 8 }} 58 | {{- end }} 59 | -------------------------------------------------------------------------------- /helm/hperf/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for hperf. 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 6 6 | 7 | image: 8 | repository: quay.io/minio/hperf 9 | pullPolicy: Always 10 | # Overrides the image tag whose default is the chart appVersion. 11 | tag: v4.0.5 12 | 13 | imagePullSecrets: [] 14 | 15 | ## Provide a name in place of minio for `app:` labels 16 | ## 17 | nameOverride: "" 18 | 19 | ## Provide a name to substitute for the full names of resources 20 | ## 21 | fullnameOverride: "" 22 | 23 | ## set kubernetes cluster domain where minio is running 24 | ## 25 | clusterDomain: cluster.local 26 | 27 | serviceAccount: 28 | # Specifies whether a service account should be created 29 | create: true 30 | # Annotations to add to the service account 31 | annotations: {} 32 | # The name of the service account to use. 33 | # If not set and create is true, a name is generated using the fullname template 34 | name: "" 35 | 36 | podAnnotations: {} 37 | 38 | podSecurityContext: {} 39 | # fsGroup: 2000 40 | 41 | securityContext: {} 42 | # capabilities: 43 | # drop: 44 | # - ALL 45 | # readOnlyRootFilesystem: true 46 | # runAsNonRoot: true 47 | # runAsUser: 1000 48 | 49 | resources: {} 50 | # We usually recommend not to specify default resources and to leave this as a conscious 51 | # choice for the user. This also increases chances charts run on environments with little 52 | # resources, such as Minikube. If you do want to specify resources, uncomment the following 53 | # lines, adjust them as necessary, and remove the curly braces after 'resources:'. 54 | # limits: 55 | # cpu: 100m 56 | # memory: 128Mi 57 | # requests: 58 | # cpu: 100m 59 | # memory: 128Mi 60 | 61 | nodeSelector: {} 62 | 63 | tolerations: [] 64 | 65 | affinity: {} 66 | -------------------------------------------------------------------------------- /server/file.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package server 19 | 20 | import ( 21 | "bufio" 22 | "os" 23 | "path/filepath" 24 | "strconv" 25 | "strings" 26 | 27 | "github.com/gofiber/contrib/websocket" 28 | "github.com/minio/hperf/shared" 29 | ) 30 | 31 | func streamTestFilesToWebsocket(con *websocket.Conn, testID string) (err error) { 32 | var files []string 33 | files, err = filepath.Glob(filepath.Join(basePath, testID+".*")) 34 | if err != nil { 35 | return 36 | } 37 | msg := new(shared.WebsocketSignal) 38 | for _, path := range files { 39 | f, err := os.Open(path) 40 | if err != nil { 41 | return err 42 | } 43 | s := bufio.NewScanner(f) 44 | for s.Scan() { 45 | msg.Data = s.Bytes() 46 | msg.SType = shared.GetTest 47 | msg.Code = 200 48 | err = con.WriteJSON(msg) 49 | if err != nil { 50 | return err 51 | } 52 | } 53 | if s.Err() != nil { 54 | return s.Err() 55 | } 56 | } 57 | 58 | return nil 59 | } 60 | 61 | func deleteTestsFromDisk(con *websocket.Conn, signal shared.WebsocketSignal) (err error) { 62 | defer SendDone(con) 63 | 64 | if signal.Config.TestID == "" { 65 | err = os.RemoveAll(basePath) 66 | if err != nil { 67 | SendError(con, err) 68 | } 69 | } 70 | 71 | var files []string 72 | files, err = filepath.Glob(filepath.Join(basePath, signal.Config.TestID+".*")) 73 | if err != nil { 74 | SendError(con, err) 75 | return 76 | } 77 | 78 | for _, path := range files { 79 | err = os.Remove(path) 80 | if err != nil { 81 | SendError(con, err) 82 | } 83 | } 84 | 85 | return 86 | } 87 | 88 | func listTestsFromDisk() (finalList []shared.TestInfo, err error) { 89 | var files []string 90 | files, err = filepath.Glob(filepath.Join(basePath, "*.1")) 91 | if err != nil { 92 | return 93 | } 94 | 95 | finalList = make([]shared.TestInfo, 0) 96 | for _, path := range files { 97 | var stat os.FileInfo 98 | stat, err = os.Stat(path) 99 | if err != nil { 100 | return 101 | } 102 | trimPath := strings.TrimSuffix(path, ".1") 103 | finalPath := strings.Split(trimPath, string(os.PathSeparator)) 104 | finalList = append(finalList, shared.TestInfo{ 105 | ID: finalPath[len(finalPath)-1], 106 | Time: stat.ModTime(), 107 | }) 108 | } 109 | return 110 | } 111 | 112 | func resetTestFiles(t *test) (err error) { 113 | var files []string 114 | files, err = filepath.Glob(filepath.Join(basePath, t.ID+"*")) 115 | if err != nil { 116 | return 117 | } 118 | 119 | for _, match := range files { 120 | err = os.Remove(match) 121 | if err != nil { 122 | return 123 | } 124 | } 125 | return 126 | } 127 | 128 | func newTestFile(t *test) (f *os.File, err error) { 129 | if t.DataFile != nil { 130 | t.DataFile.Close() 131 | } 132 | 133 | err = os.MkdirAll(basePath, 0o777) 134 | if err != nil { 135 | return 136 | } 137 | t.DataFileIndex++ 138 | t.DataFile, err = os.Create(basePath + t.ID + "." + strconv.Itoa(t.DataFileIndex)) 139 | if err != nil { 140 | return 141 | } 142 | 143 | return 144 | } 145 | -------------------------------------------------------------------------------- /server/helpers_linux.go: -------------------------------------------------------------------------------- 1 | //go:build linux 2 | // +build linux 3 | 4 | // Copyright (c) 2015-2024 MinIO, Inc. 5 | // 6 | // This file is part of MinIO Object Storage stack 7 | // 8 | // This program is free software: you can redistribute it and/or modify 9 | // it under the terms of the GNU Affero General Public License as published by 10 | // the Free Software Foundation, either version 3 of the License, or 11 | // (at your option) any later version. 12 | // 13 | // This program is distributed in the hope that it will be useful 14 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | // GNU Affero General Public License for more details. 17 | // 18 | // You should have received a copy of the GNU Affero General Public License 19 | // along with this program. If not, see . 20 | 21 | package server 22 | 23 | import ( 24 | "syscall" 25 | 26 | "golang.org/x/sys/unix" 27 | ) 28 | 29 | func setTCPParametersFn() func(network, address string, c syscall.RawConn) error { 30 | return func(network, address string, c syscall.RawConn) error { 31 | c.Control(func(fdPtr uintptr) { 32 | // got socket file descriptor to set parameters. 33 | fd := int(fdPtr) 34 | 35 | _ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) 36 | _ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_REUSEPORT, 1) 37 | 38 | { 39 | // Enable big buffers 40 | // _ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_SNDBUF, 65535) 41 | // _ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_RCVBUF, 65535) 42 | } 43 | _ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.TCP_NODELAY, 1) 44 | 45 | // Enable TCP open 46 | // https://lwn.net/Articles/508865/ - 32k queue size. 47 | _ = syscall.SetsockoptInt(fd, syscall.SOL_TCP, unix.TCP_FASTOPEN, 32*1024) 48 | 49 | // Enable TCP fast connect 50 | // TCPFastOpenConnect sets the underlying socket to use 51 | // the TCP fast open connect. This feature is supported 52 | // since Linux 4.11. 53 | _ = syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, unix.TCP_FASTOPEN_CONNECT, 1) 54 | 55 | // Enable TCP quick ACK, John Nagle says 56 | // "Set TCP_QUICKACK. If you find a case where that makes things worse, let me know." 57 | _ = syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, unix.TCP_QUICKACK, 1) 58 | 59 | /// Enable keep-alive 60 | { 61 | _ = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1) 62 | 63 | // The time (in seconds) the connection needs to remain idle before 64 | // TCP starts sending keepalive probes 65 | _ = syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE, 15) 66 | 67 | // Number of probes. 68 | // ~ cat /proc/sys/net/ipv4/tcp_keepalive_probes (defaults to 9, we reduce it to 5) 69 | _ = syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPCNT, 5) 70 | 71 | // Wait time after successful probe in seconds. 72 | // ~ cat /proc/sys/net/ipv4/tcp_keepalive_intvl (defaults to 75 secs, we reduce it to 15 secs) 73 | _ = syscall.SetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, 15) 74 | } 75 | }) 76 | return nil 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /server/helpers_others.go: -------------------------------------------------------------------------------- 1 | //go:build !linux 2 | // +build !linux 3 | 4 | // Copyright (c) 2015-2024 MinIO, Inc. 5 | // 6 | // This file is part of MinIO Object Storage stack 7 | // 8 | // This program is free software: you can redistribute it and/or modify 9 | // it under the terms of the GNU Affero General Public License as published by 10 | // the Free Software Foundation, either version 3 of the License, or 11 | // (at your option) any later version. 12 | // 13 | // This program is distributed in the hope that it will be useful 14 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | // GNU Affero General Public License for more details. 17 | // 18 | // You should have received a copy of the GNU Affero General Public License 19 | // along with this program. If not, see . 20 | 21 | package server 22 | 23 | import "syscall" 24 | 25 | //nolint:unused 26 | func setTCPParametersFn() func(network, address string, c syscall.RawConn) error { 27 | return func(network, address string, c syscall.RawConn) error { 28 | return nil 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /server/server.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package server 19 | 20 | import ( 21 | "bytes" 22 | "context" 23 | "encoding/json" 24 | "errors" 25 | "fmt" 26 | "io" 27 | "log" 28 | "math" 29 | "net" 30 | "net/http" 31 | "os" 32 | "runtime" 33 | "runtime/debug" 34 | "strconv" 35 | "strings" 36 | "sync" 37 | "sync/atomic" 38 | "time" 39 | 40 | "github.com/gofiber/contrib/websocket" 41 | "github.com/gofiber/fiber/v2" 42 | "github.com/google/uuid" 43 | "github.com/minio/hperf/shared" 44 | "github.com/shirou/gopsutil/cpu" 45 | "github.com/shirou/gopsutil/mem" 46 | ) 47 | 48 | var ( 49 | httpServer = fiber.New(fiber.Config{ 50 | StreamRequestBody: true, 51 | ServerHeader: "hperf", 52 | AppName: "hperf", 53 | DisableStartupMessage: true, 54 | ReadBufferSize: 1000000, 55 | WriteBufferSize: 1000000, 56 | }) 57 | bindAddress = "0.0.0.0:9000" 58 | realIP = "" 59 | testFolderSuffix = "hperf-tests" 60 | basePath = "./" 61 | tests = make([]*test, 0) 62 | testLock = sync.Mutex{} 63 | ) 64 | 65 | type test struct { 66 | ID string 67 | Config shared.Config 68 | Started time.Time 69 | 70 | ctx context.Context 71 | cancel context.CancelCauseFunc 72 | 73 | Readers []*netPerfReader 74 | errors []shared.TError 75 | errMap map[string]struct{} 76 | errIndex atomic.Int32 77 | DPS []shared.DP 78 | M sync.Mutex 79 | 80 | DataFile *os.File 81 | DataFileIndex int 82 | cons map[string]*websocket.Conn 83 | } 84 | 85 | func (t *test) AddError(err error, id string) { 86 | t.M.Lock() 87 | defer t.M.Unlock() 88 | if err == nil { 89 | return 90 | } 91 | _, ok := t.errMap[id] 92 | if ok { 93 | return 94 | } 95 | if t.Config.Debug { 96 | fmt.Println("ERR:", err) 97 | } 98 | t.errors = append(t.errors, shared.TError{Error: err.Error(), Created: time.Now()}) 99 | t.errMap[id] = struct{}{} 100 | } 101 | 102 | func RunServer(ctx context.Context, address string, rIP string, storagePath string) (err error) { 103 | cancelContext, cancel := context.WithCancel(ctx) 104 | defer cancel() 105 | 106 | if storagePath == "" { 107 | basePath, err = os.Getwd() 108 | if err != nil { 109 | return 110 | } 111 | } else { 112 | basePath = storagePath 113 | err = os.MkdirAll(storagePath, 0o777) 114 | if err != nil { 115 | return err 116 | } 117 | } 118 | shared.DEBUG("Storage path:", storagePath) 119 | 120 | if basePath[len(basePath)-1] != byte(os.PathSeparator) { 121 | basePath += string(os.PathSeparator) + testFolderSuffix + string(os.PathSeparator) 122 | } else { 123 | basePath += testFolderSuffix + string(os.PathSeparator) 124 | } 125 | shared.DEBUG("Base path:", basePath) 126 | 127 | err = os.MkdirAll(basePath, 0o777) 128 | if err != nil { 129 | return err 130 | } 131 | 132 | bindAddress = address 133 | realIP = rIP 134 | shared.INFO("starting 'hperf' server on:", bindAddress) 135 | err = startAPIandWS(cancelContext) 136 | if err != nil { 137 | return 138 | } 139 | 140 | return nil 141 | } 142 | 143 | func startAPIandWS(ctx context.Context) (err error) { 144 | httpServer.Get("/", func(c *fiber.Ctx) error { 145 | return c.SendString("Hello, World!") 146 | }) 147 | 148 | httpServer.Use("/ws", func(c *fiber.Ctx) error { 149 | if websocket.IsWebSocketUpgrade(c) { 150 | c.Locals("allowed", true) 151 | return c.Next() 152 | } 153 | return fiber.ErrUpgradeRequired 154 | }) 155 | 156 | httpServer.Get("/ws/:id", websocket.New(func(con *websocket.Conn) { 157 | var ( 158 | msg []byte 159 | err error 160 | ) 161 | 162 | err = SendPing(con) 163 | if err != nil { 164 | shared.DEBUG("Error accepting client socket:", err) 165 | if con != nil { 166 | con.Close() 167 | } 168 | return 169 | } 170 | 171 | for { 172 | if ctx.Err() != nil { 173 | shared.DEBUG("Ctx done, closing websocket read loop:", err) 174 | return 175 | } 176 | if _, msg, err = con.ReadMessage(); err != nil { 177 | shared.DEBUG("Error reading websocket message:", err) 178 | break 179 | } 180 | 181 | signal := new(shared.WebsocketSignal) 182 | err := json.Unmarshal(msg, signal) 183 | if err != nil { 184 | if signal.Config.Debug { 185 | log.Println("Unable to parse signal:", err) 186 | } 187 | continue 188 | } 189 | if signal.Config.Debug { 190 | fmt.Printf("WebsocketSignal: %+v\n", signal) 191 | } 192 | 193 | switch signal.SType { 194 | case shared.RunTest: 195 | go createAndRunTest(con, *signal) 196 | case shared.ListenTest: 197 | go listenToLiveTests(con, *signal) 198 | case shared.ListTests: 199 | go listAllTests(con, *signal) 200 | case shared.GetTest: 201 | go getTestOnServer(con, *signal) 202 | case shared.Ping: 203 | go replyToPing(con) 204 | case shared.DeleteTests: 205 | go deleteTestsFromDisk(con, *signal) 206 | case shared.StopAllTests: 207 | go stopAllTests(con, *signal) 208 | case shared.Exit: 209 | os.Exit(1) 210 | default: 211 | if signal.Config.Debug { 212 | fmt.Println("unrecognized command") 213 | } 214 | } 215 | 216 | } 217 | })) 218 | 219 | httpServer.Put("/requests", func(c *fiber.Ctx) error { 220 | io.Copy(io.Discard, bytes.NewBuffer(c.Body())) 221 | return c.SendStatus(200) 222 | }) 223 | 224 | httpServer.Put("/stream", func(c *fiber.Ctx) error { 225 | io.Copy(io.Discard, c.Request().BodyStream()) 226 | return c.SendStatus(200) 227 | }) 228 | 229 | go func() { 230 | err = httpServer.Listen(bindAddress) 231 | if err != nil { 232 | fmt.Println(err) 233 | } 234 | }() 235 | 236 | routineMonitor <- 1 237 | 238 | for { 239 | select { 240 | case id := <-routineMonitor: 241 | if id == 1 { 242 | go getServerStats(id) 243 | } 244 | default: 245 | } 246 | if ctx.Err() != nil { 247 | httpServer.Shutdown() 248 | return 249 | } 250 | time.Sleep(1 * time.Second) 251 | } 252 | } 253 | 254 | var ( 255 | currentMemoryStat *mem.VirtualMemoryStat 256 | droppedPackets int 257 | cpuPercent float64 258 | ) 259 | 260 | func getServerStats(id byte) { 261 | defer func() { 262 | r := recover() 263 | if r != nil { 264 | log.Println(r, string(debug.Stack())) 265 | } 266 | time.Sleep(1 * time.Second) 267 | routineMonitor <- id 268 | }() 269 | 270 | var err error 271 | currentMemoryStat, err = mem.VirtualMemory() 272 | if err != nil { 273 | fmt.Println(err) 274 | } 275 | 276 | droppedPackets, err = GetDroppedPackets() 277 | if err != nil { 278 | fmt.Println(err) 279 | } 280 | percent, err := cpu.Percent(time.Second, false) 281 | if err != nil { 282 | fmt.Println(err) 283 | } 284 | if len(percent) > 0 { 285 | cpuPercent = percent[0] 286 | } 287 | } 288 | 289 | func GetDroppedPackets() (total int, err error) { 290 | if runtime.GOOS != "linux" { 291 | return 0, nil 292 | } 293 | data, err := os.ReadFile("/proc/net/dev") 294 | if err != nil { 295 | return 0, err 296 | } 297 | lines := strings.Split(string(data), "\n") 298 | for _, line := range lines[2:] { 299 | fields := strings.Fields(line) 300 | if len(fields) < 5 { 301 | continue 302 | } 303 | dropped, err := strconv.Atoi(fields[4]) // Field 4 is for dropped packets 304 | if err != nil { 305 | return 0, err 306 | } 307 | total += dropped 308 | } 309 | return 310 | } 311 | 312 | var routineMonitor = make(chan byte, 100) 313 | 314 | func replyToPing(c *websocket.Conn) { 315 | msg := new(shared.WebsocketSignal) 316 | msg.SType = shared.Pong 317 | _ = c.WriteJSON(msg) 318 | } 319 | 320 | func SendError(c *websocket.Conn, e error) error { 321 | if e == nil { 322 | return nil 323 | } 324 | msg := new(shared.WebsocketSignal) 325 | msg.SType = shared.Err 326 | msg.Error = e.Error() 327 | return c.WriteJSON(msg) 328 | } 329 | 330 | func stopAllTests(con *websocket.Conn, s shared.WebsocketSignal) { 331 | defer SendDone(con) 332 | for i := range tests { 333 | if s.Config.TestID != "" && s.Config.TestID != tests[i].ID { 334 | continue 335 | } 336 | if s.Config.Debug { 337 | fmt.Println("Stopping:", tests[i].ID) 338 | } 339 | tests[i].cancel(fmt.Errorf("Client called StopAllTests")) 340 | } 341 | } 342 | 343 | func SendPing(c *websocket.Conn) error { 344 | msg := new(shared.WebsocketSignal) 345 | msg.SType = shared.Ping 346 | msg.Code = shared.OK 347 | return c.WriteJSON(msg) 348 | } 349 | 350 | func SendOK(c *websocket.Conn, t shared.SignalType) error { 351 | msg := new(shared.WebsocketSignal) 352 | msg.SType = t 353 | msg.Code = shared.OK 354 | return c.WriteJSON(msg) 355 | } 356 | 357 | func SendDone(c *websocket.Conn) error { 358 | msg := new(shared.WebsocketSignal) 359 | msg.SType = shared.Done 360 | msg.Code = shared.OK 361 | return c.WriteJSON(msg) 362 | } 363 | 364 | func newTest(c *shared.Config) (t *test, err error) { 365 | testLock.Lock() 366 | defer testLock.Unlock() 367 | 368 | t = new(test) 369 | t.errMap = make(map[string]struct{}) 370 | t.cons = make(map[string]*websocket.Conn) 371 | t.Started = time.Now() 372 | t.Config = *c 373 | t.DPS = make([]shared.DP, 0) 374 | t.ID = c.TestID 375 | t.ctx, t.cancel = context.WithCancelCause(context.Background()) 376 | 377 | if c.Save { 378 | resetTestFiles(t) 379 | newTestFile(t) 380 | } 381 | 382 | t.Readers = make([]*netPerfReader, 0) 383 | readersCreated := 0 384 | 385 | for i := range c.Hosts { 386 | 387 | joinedHostPort := net.JoinHostPort(c.Hosts[i], c.Port) 388 | if realIP != "" && strings.Contains(joinedHostPort, realIP) { 389 | continue 390 | } 391 | if joinedHostPort == bindAddress { 392 | continue 393 | } 394 | t.Readers = append(t.Readers, 395 | newPerformanceReaderForASingleHost(c, c.Hosts[i], c.Port), 396 | ) 397 | readersCreated++ 398 | 399 | } 400 | 401 | if readersCreated == 0 { 402 | return nil, fmt.Errorf("No performance readers were created, please revise your config") 403 | } 404 | 405 | tests = append(tests, t) 406 | return t, nil 407 | } 408 | 409 | type netPerfReader struct { 410 | hasStats bool 411 | m sync.Mutex 412 | 413 | buf []byte 414 | 415 | addr string 416 | ip string 417 | client *http.Client 418 | 419 | TXCount atomic.Uint64 420 | TX atomic.Uint64 421 | 422 | concurrency chan int 423 | 424 | TTFBH int64 425 | TTFBL int64 426 | RMSH int64 427 | RMSL int64 428 | 429 | lastDataPointTime time.Time 430 | } 431 | 432 | type asyncReader struct { 433 | pr *netPerfReader 434 | i int64 // current reading index 435 | prevRune int // index of previous rune; or < 0 436 | ttfbRegistered bool 437 | start time.Time 438 | ctx context.Context 439 | c *shared.Config 440 | } 441 | 442 | func (a *asyncReader) Read(b []byte) (n int, err error) { 443 | a.pr.m.Lock() 444 | if !a.ttfbRegistered { 445 | since := time.Since(a.start).Microseconds() 446 | a.ttfbRegistered = true 447 | if since > a.pr.TTFBH { 448 | a.pr.TTFBH = since 449 | } 450 | if since < a.pr.TTFBL { 451 | a.pr.TTFBL = since 452 | } 453 | } 454 | a.pr.hasStats = true 455 | a.pr.m.Unlock() 456 | 457 | if a.ctx.Err() != nil { 458 | return 0, io.EOF 459 | } 460 | 461 | if a.c.TestType == shared.StreamTest { 462 | n = copy(b, a.pr.buf) 463 | a.pr.TX.Add(uint64(n)) 464 | return n, nil 465 | } 466 | 467 | if a.i >= int64(len(a.pr.buf)) { 468 | return 0, io.EOF 469 | } 470 | n = copy(b, a.pr.buf[a.i:]) 471 | a.i += int64(n) 472 | a.pr.TX.Add(uint64(n)) 473 | return n, nil 474 | } 475 | 476 | func createAndRunTest(con *websocket.Conn, signal shared.WebsocketSignal) { 477 | defer SendDone(con) 478 | 479 | test, err := newTest(signal.Config) 480 | if err != nil { 481 | SendError(con, err) 482 | return 483 | } 484 | if signal.Config.Debug { 485 | defer func() { 486 | fmt.Println("Test exiting:", test.ID) 487 | }() 488 | } 489 | defer test.cancel(fmt.Errorf("testing finished")) 490 | 491 | start := time.Now() 492 | for i := range test.Readers { 493 | go startPerformanceReader(test, test.Readers[i]) 494 | } 495 | 496 | conUID := uuid.NewString() 497 | test.cons[conUID] = con 498 | 499 | for { 500 | if test.ctx.Err() != nil { 501 | return 502 | } 503 | 504 | if time.Since(start).Seconds() > float64(test.Config.Duration) { 505 | break 506 | } 507 | time.Sleep(1 * time.Second) 508 | if signal.Config.Debug { 509 | fmt.Println("Duration: ", signal.Config.TestID, time.Since(start).Seconds()) 510 | } 511 | 512 | generateDataPoints(test) 513 | _ = sendAndSaveData(test) 514 | } 515 | } 516 | 517 | func listenToLiveTests(con *websocket.Conn, s shared.WebsocketSignal) { 518 | uid := uuid.NewString() 519 | 520 | for i := range tests { 521 | if s.Config.TestID != "" && tests[i].ID != s.Config.TestID { 522 | continue 523 | } 524 | if s.Config.Debug { 525 | fmt.Println("Listen:", tests[i].ID, "DPS:", len(tests[i].DPS), "ERR:", len(tests[i].errors)) 526 | } 527 | 528 | tests[i].cons[uid] = con 529 | } 530 | } 531 | 532 | type DataPointPaginator struct { 533 | DPIndex int 534 | ErrIndex int 535 | After time.Time 536 | } 537 | 538 | func sendAndSaveData(t *test) (err error) { 539 | defer func() { 540 | r := recover() 541 | if r != nil { 542 | log.Println(r, string(debug.Stack())) 543 | } 544 | }() 545 | 546 | wss := new(shared.WebsocketSignal) 547 | wss.SType = shared.Stats 548 | wss.DataPoint = new(shared.DataReponseToClient) 549 | 550 | if t.DataFile == nil && t.Config.Save { 551 | newTestFile(t) 552 | } 553 | 554 | for i := range t.DPS { 555 | wss.DataPoint.DPS = append(wss.DataPoint.DPS, t.DPS[i]) 556 | if t.Config.Save { 557 | fileb, err := json.Marshal(t.DPS[i]) 558 | if err != nil { 559 | t.AddError(err, "datapoint-marshaling") 560 | } 561 | t.DataFile.Write(shared.DataPoint.String()) 562 | t.DataFile.Write(fileb) 563 | t.DataFile.Write([]byte{10}) 564 | } 565 | } 566 | t.DPS = make([]shared.DP, 0) 567 | 568 | t.M.Lock() 569 | errorsClone := make([]shared.TError, 0) 570 | for _, v := range t.errors { 571 | errorsClone = append(errorsClone, v) 572 | } 573 | t.errors = make([]shared.TError, 0) 574 | t.errMap = make(map[string]struct{}) 575 | t.M.Unlock() 576 | 577 | for i := range errorsClone { 578 | wss.DataPoint.Errors = append(wss.DataPoint.Errors, errorsClone[i]) 579 | if t.Config.Save { 580 | fileb, err := json.Marshal(errorsClone[i]) 581 | if err != nil { 582 | t.AddError(err, "error-marshaling") 583 | } 584 | t.DataFile.Write(shared.ErrorPoint.String()) 585 | t.DataFile.Write(fileb) 586 | t.DataFile.Write([]byte{10}) 587 | } 588 | } 589 | 590 | for i := range t.cons { 591 | if t.cons[i] == nil { 592 | continue 593 | } 594 | 595 | err = t.cons[i].WriteJSON(wss) 596 | if err != nil { 597 | if t.Config.Debug { 598 | fmt.Println("Unable to send data point:", err) 599 | } 600 | t.cons[i].Close() 601 | delete(t.cons, i) 602 | continue 603 | } 604 | } 605 | return 606 | } 607 | 608 | func generateDataPoints(t *test) { 609 | for ri, rv := range t.Readers { 610 | if rv == nil { 611 | continue 612 | } 613 | 614 | if !rv.hasStats { 615 | continue 616 | } 617 | 618 | r := t.Readers[ri] 619 | 620 | tx := r.TX.Swap(0) 621 | totalSecs := time.Since(r.lastDataPointTime).Seconds() 622 | r.lastDataPointTime = time.Now() 623 | txtotal := float64(tx) / totalSecs 624 | 625 | d := shared.DP{ 626 | Type: t.Config.TestType, 627 | TestID: t.ID, 628 | Created: time.Now(), 629 | TX: uint64(txtotal), 630 | TXTotal: tx, 631 | TXCount: r.TXCount.Load(), 632 | Remote: r.addr, 633 | TTFBL: r.TTFBL, 634 | TTFBH: r.TTFBH, 635 | RMSL: r.RMSL, 636 | RMSH: r.RMSH, 637 | ErrCount: len(t.errors), 638 | DroppedPackets: droppedPackets, 639 | MemoryUsedPercent: int(currentMemoryStat.UsedPercent), 640 | CPUUsedPercent: int(cpuPercent), 641 | } 642 | 643 | if realIP != "" { 644 | d.Local = realIP 645 | } else { 646 | d.Local = bindAddress 647 | } 648 | 649 | r.m.Lock() 650 | r.hasStats = false 651 | r.TTFBH = 0 652 | r.TTFBL = math.MaxInt64 653 | r.RMSH = 0 654 | r.RMSL = math.MaxInt64 655 | r.m.Unlock() 656 | 657 | t.DPS = append(t.DPS, d) 658 | } 659 | return 660 | } 661 | 662 | func newTransport(c *shared.Config) *http.Transport { 663 | return &http.Transport{ 664 | Proxy: http.ProxyFromEnvironment, 665 | DialContext: newDialContext(10 * time.Second), 666 | MaxIdleConnsPerHost: 1024, 667 | WriteBufferSize: c.BufferSize, 668 | ReadBufferSize: c.BufferSize, 669 | IdleConnTimeout: 15 * time.Second, 670 | ResponseHeaderTimeout: 15 * time.Minute, 671 | TLSHandshakeTimeout: 10 * time.Second, 672 | DisableCompression: true, 673 | } 674 | } 675 | 676 | func newDialContext(dialTimeout time.Duration) dialContext { 677 | d := &net.Dialer{ 678 | Timeout: dialTimeout, 679 | Control: setTCPParametersFn(), 680 | } 681 | return func(ctx context.Context, network, addr string) (net.Conn, error) { 682 | return d.DialContext(ctx, network, addr) 683 | } 684 | } 685 | 686 | // DialContext is a function to make custom Dial for internode communications 687 | type dialContext func(ctx context.Context, network, address string) (net.Conn, error) 688 | 689 | func newPerformanceReaderForASingleHost(c *shared.Config, host string, port string) (r *netPerfReader) { 690 | r = new(netPerfReader) 691 | r.lastDataPointTime = time.Now() 692 | r.addr = net.JoinHostPort(host, port) 693 | r.ip = host 694 | r.buf = make([]byte, c.PayloadSize) 695 | r.TTFBL = math.MaxInt64 696 | r.RMSL = math.MaxInt64 697 | r.client = &http.Client{ 698 | Transport: newTransport(c), 699 | } 700 | r.concurrency = make(chan int, c.Concurrency) 701 | for i := 1; i <= c.Concurrency; i++ { 702 | r.concurrency <- i 703 | } 704 | return 705 | } 706 | 707 | func startPerformanceReader(t *test, r *netPerfReader) { 708 | defer func() { 709 | r := recover() 710 | if r != nil { 711 | log.Println(r, string(debug.Stack())) 712 | } 713 | }() 714 | for { 715 | var cid int 716 | select { 717 | case cid = <-r.concurrency: 718 | go sendRequestToHost(t, r, cid) 719 | case _ = <-t.ctx.Done(): 720 | return 721 | } 722 | } 723 | } 724 | 725 | func sendRequestToHost(t *test, r *netPerfReader, cid int) { 726 | defer func() { 727 | rec := recover() 728 | if rec != nil { 729 | log.Println(rec, string(debug.Stack())) 730 | } 731 | r.concurrency <- cid 732 | }() 733 | 734 | if t.Config.RequestDelay > 0 { 735 | time.Sleep(time.Duration(t.Config.RequestDelay) * time.Millisecond) 736 | } 737 | 738 | if t.ctx.Err() != nil { 739 | return 740 | } 741 | 742 | AR := new(asyncReader) 743 | AR.ctx = t.ctx 744 | AR.pr = r 745 | AR.c = &t.Config 746 | AR.start = time.Now() 747 | 748 | var req *http.Request 749 | var resp *http.Response 750 | var err error 751 | 752 | proto := "https://" 753 | if t.Config.Insecure { 754 | proto = "http://" 755 | } 756 | 757 | route := "/404" 758 | var body io.Reader 759 | method := http.MethodPut 760 | switch t.Config.TestType { 761 | case shared.StreamTest: 762 | route = "/stream" 763 | body = io.NopCloser(AR) 764 | case shared.RequestTest: 765 | route = "/requests" 766 | body = AR 767 | default: 768 | t.AddError(fmt.Errorf("Unknown test type: %d", t.Config.TestType), "unknown-signal") 769 | } 770 | 771 | req, err = http.NewRequestWithContext( 772 | t.ctx, 773 | method, 774 | proto+r.addr+route, 775 | body, 776 | ) 777 | if err != nil { 778 | t.AddError(err, "network-new-request") 779 | return 780 | } 781 | 782 | if t.Config.TestType == shared.StreamTest { 783 | req.ContentLength = -1 784 | } 785 | 786 | sent := time.Now() 787 | r.TXCount.Add(1) 788 | resp, err = r.client.Do(req) 789 | if err != nil { 790 | if errors.Is(err, context.Canceled) { 791 | return 792 | } 793 | t.AddError(err, "network-error") 794 | return 795 | } 796 | 797 | if resp.StatusCode != http.StatusOK { 798 | t.AddError(fmt.Errorf("Status code was %d, expected 200 from host %s", resp.StatusCode, r.addr), "invalid-status-code") 799 | return 800 | } 801 | 802 | done := time.Since(sent).Microseconds() 803 | 804 | r.m.Lock() 805 | if done > r.RMSH { 806 | r.RMSH = done 807 | } 808 | 809 | if done < r.RMSL { 810 | r.RMSL = done 811 | } 812 | r.hasStats = true 813 | r.m.Unlock() 814 | 815 | io.Copy(io.Discard, resp.Body) 816 | resp.Body.Close() 817 | 818 | return 819 | } 820 | 821 | func listAllTests(con *websocket.Conn, s shared.WebsocketSignal) { 822 | defer SendDone(con) 823 | 824 | var err error 825 | s.TestList, err = listTestsFromDisk() 826 | if err != nil { 827 | SendError(con, err) 828 | return 829 | } 830 | 831 | s.Code = 200 832 | s.SType = shared.ListTests 833 | err = con.WriteJSON(s) 834 | if err != nil { 835 | fmt.Println(err) 836 | } 837 | } 838 | 839 | func getTestOnServer(con *websocket.Conn, s shared.WebsocketSignal) { 840 | defer SendDone(con) 841 | err := streamTestFilesToWebsocket(con, s.Config.TestID) 842 | if err != nil { 843 | SendError(con, err) 844 | } 845 | } 846 | 847 | func sendAllDataPoints(con *websocket.Conn, t *test) error { 848 | wss := new(shared.WebsocketSignal) 849 | wss.SType = shared.Stats 850 | dataResponse := new(shared.DataReponseToClient) 851 | 852 | for i := range t.DPS { 853 | dataResponse.DPS = append(dataResponse.DPS, t.DPS[i]) 854 | } 855 | 856 | for i := range t.errors { 857 | dataResponse.Errors = append(dataResponse.Errors, t.errors[i]) 858 | } 859 | 860 | wss.DataPoint = dataResponse 861 | err := con.WriteJSON(wss) 862 | if err != nil { 863 | return err 864 | } 865 | return nil 866 | } 867 | -------------------------------------------------------------------------------- /shared/shared.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2024 MinIO, Inc. 2 | // 3 | // This file is part of MinIO Object Storage stack 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | package shared 19 | 20 | import ( 21 | "bytes" 22 | "encoding/json" 23 | "errors" 24 | "fmt" 25 | "net" 26 | "os" 27 | "strconv" 28 | "strings" 29 | "time" 30 | 31 | "github.com/minio/pkg/v3/ellipses" 32 | ) 33 | 34 | var DebugEnabled = false 35 | 36 | type WebsocketSignal struct { 37 | SType SignalType 38 | Code SignalCode 39 | Error string 40 | 41 | // Type specific fields 42 | Data []byte 43 | Config *Config 44 | DataPoint *DataReponseToClient 45 | TestList []TestInfo 46 | } 47 | 48 | type TestInfo struct { 49 | ID string 50 | Time time.Time 51 | } 52 | 53 | type TestOutput struct { 54 | ErrCount int 55 | TXC uint64 56 | TXL uint64 57 | TXH uint64 58 | TXT uint64 59 | RMSL int64 60 | RMSH int64 61 | TTFBL int64 62 | TTFBH int64 63 | DP int 64 | ML int 65 | MH int 66 | CL int 67 | CH int 68 | } 69 | 70 | type ( 71 | SignalType int 72 | SignalCode int 73 | TestType int 74 | FilePrefix byte 75 | ) 76 | 77 | const ( 78 | DataPoint FilePrefix = iota 79 | ErrorPoint 80 | ) 81 | 82 | func (f FilePrefix) String() []byte { 83 | return []byte(strconv.Itoa(int(f))) 84 | } 85 | 86 | const ( 87 | Err SignalType = iota 88 | RunTest 89 | ListenTest 90 | ListTests 91 | GetTest 92 | DeleteTests 93 | Ping 94 | Pong 95 | Exit 96 | StopAllTests 97 | Stats 98 | Done 99 | ) 100 | 101 | const ( 102 | Unknown TestType = iota 103 | RequestTest 104 | StreamTest 105 | ) 106 | 107 | const ( 108 | OK SignalCode = iota 109 | Fail 110 | Retry 111 | ) 112 | 113 | type TError struct { 114 | Error string 115 | Created time.Time 116 | } 117 | 118 | type DP struct { 119 | Type TestType 120 | TestID string 121 | Created time.Time 122 | Local string 123 | Remote string 124 | RMSH int64 125 | RMSL int64 126 | TTFBH int64 127 | TTFBL int64 128 | TX uint64 129 | TXTotal uint64 130 | TXCount uint64 131 | ErrCount int 132 | DroppedPackets int 133 | MemoryUsedPercent int 134 | CPUUsedPercent int 135 | 136 | // Client only 137 | Received time.Time `json:"-"` 138 | } 139 | 140 | type DataReponseToClient struct { 141 | DPS []DP 142 | Errors []TError 143 | } 144 | 145 | type Config struct { 146 | Debug bool `json:"Debug"` 147 | Port string `json:"Port"` 148 | Concurrency int `json:"Concurrency"` 149 | PayloadSize int `json:"PayloadMB"` 150 | BufferSize int `json:"BufferKB"` 151 | Duration int `json:"Duration"` 152 | RequestDelay int `json:"RequestDelay"` 153 | Hosts []string `json:"Hosts"` 154 | RestartOnError bool `json:"RestartOnError"` 155 | DialTimeout time.Duration `json:"DialTimeout"` 156 | TestID string `json:"TestID"` 157 | Save bool `json:"Save"` 158 | Insecure bool `json:"Insecure"` 159 | TestType TestType `json:"TestType"` 160 | File string `json:"File"` 161 | // AllowLocalInterface bool `json:"AllowLocalInterfaces"` 162 | 163 | // Client Only 164 | ResolveHosts string `json:"-"` 165 | PrintStats bool `json:"-"` 166 | PrintAll bool `json:"-"` 167 | PrintErrors bool `json:"-"` 168 | Sort SortType `json:"-"` 169 | Micro bool `json:"-"` 170 | HostFilter string `json:"-"` 171 | } 172 | 173 | func INFO(items ...any) { 174 | fmt.Println(items...) 175 | } 176 | 177 | func DEBUG(items ...any) { 178 | if DebugEnabled { 179 | fmt.Println(items...) 180 | } 181 | } 182 | 183 | func BToString(b uint64) string { 184 | if b <= 999 { 185 | intS := strconv.FormatUint(b, 10) 186 | return intS + " B" 187 | } else if b <= 999_999 { 188 | intF := float64(b) 189 | return fmt.Sprintf("%.2f KB", intF/1000) 190 | } else if b <= 999_999_999 { 191 | intF := float64(b) 192 | return fmt.Sprintf("%.2f MB", intF/1_000_000) 193 | } else if b <= 999_999_999_999 { 194 | intF := float64(b) 195 | return fmt.Sprintf("%.2f GB", intF/1_000_000_000) 196 | } else if b <= 999_999_999_999_999 { 197 | intF := float64(b) 198 | return fmt.Sprintf("%.2f TB", intF/1_000_000_000_000) 199 | } 200 | 201 | return "???" 202 | } 203 | 204 | func BWToString(b uint64) string { 205 | if b <= 999 { 206 | intS := strconv.FormatUint(b, 10) 207 | return intS + " B/s" 208 | } else if b <= 999_999 { 209 | intF := float64(b) 210 | return fmt.Sprintf("%.2f KB/s", intF/1000) 211 | } else if b <= 999_999_999 { 212 | intF := float64(b) 213 | return fmt.Sprintf("%.2f MB/s", intF/1_000_000) 214 | } else if b <= 999_999_999_999 { 215 | intF := float64(b) 216 | return fmt.Sprintf("%.2f GB/s", intF/1_000_000_000) 217 | } else if b <= 999_999_999_999_999 { 218 | intF := float64(b) 219 | return fmt.Sprintf("%.2f TB/s", intF/1_000_000_000_000) 220 | } 221 | 222 | return "???" 223 | } 224 | 225 | func ParseHosts(hosts string, dnsServer string) (list []string, err error) { 226 | list = make([]string, 0) 227 | 228 | if dnsServer != "" { 229 | DEBUG("Using DNS server: ", dnsServer) 230 | } 231 | if strings.Contains(hosts, "file:") { 232 | DEBUG("Parsing hosts from file: ", hosts) 233 | 234 | fs := strings.Split(hosts, ":") 235 | if len(fs) < 2 { 236 | err = errors.New("When using a file for hosts, please use the format( file:path ) example( file:~/hosts.txt )") 237 | return 238 | } 239 | 240 | var hb []byte 241 | hb, err = os.ReadFile(fs[1]) 242 | if err != nil { 243 | err = errors.New("Could not open file:" + fs[1]) 244 | return 245 | } 246 | 247 | // this is just to trip out carrage return 248 | hb = bytes.Replace(hb, []byte{13}, []byte{}, -1) 249 | 250 | var splitLines [][]byte 251 | if bytes.Contains(hb, []byte(",")) { 252 | splitLines = bytes.Split(hb, []byte(",")) 253 | } else if bytes.Contains(hb, []byte{10}) { 254 | splitLines = bytes.Split(hb, []byte{10}) 255 | } 256 | 257 | if len(splitLines) < 1 { 258 | err = errors.New("Hosts within the file ( " + fs[1] + " ) should be per line or comma seperated") 259 | return 260 | } 261 | 262 | for _, v := range splitLines { 263 | // to account to accidental empty lines or commas 264 | if len(v) == 0 { 265 | continue 266 | } 267 | list = append(list, string(v)) 268 | } 269 | 270 | } else { 271 | 272 | splitHosts := strings.Split(hosts, ",") 273 | hostList := make([]ellipses.ArgPattern, 0) 274 | for _, v := range splitHosts { 275 | if !ellipses.HasEllipses(v) { 276 | list = append(list, v) 277 | continue 278 | } 279 | 280 | x, e := ellipses.FindEllipsesPatterns(v) 281 | if e != nil { 282 | err = e 283 | return 284 | } 285 | hostList = append(hostList, x) 286 | } 287 | 288 | for _, host := range hostList { 289 | for _, pattern := range host { 290 | for _, seq := range pattern.Seq { 291 | list = append(list, pattern.Prefix+seq) 292 | } 293 | } 294 | } 295 | 296 | } 297 | 298 | for i, host := range list { 299 | if net.ParseIP(host) == nil && dnsServer != "" { 300 | var ips []net.IP 301 | ips, err = net.LookupIP(host) 302 | if err != nil { 303 | return 304 | } 305 | if len(ips) == 0 { 306 | err = errors.New("Could not look up " + host + ", err: did not find any IPs on record") 307 | return 308 | } 309 | 310 | list[i] = ips[0].String() 311 | continue 312 | } 313 | } 314 | 315 | DEBUG("Final host list") 316 | DEBUG(list) 317 | 318 | return 319 | } 320 | 321 | func GetInterfaceAddresses() (list []string, err error) { 322 | list = make([]string, 0) 323 | 324 | interfaces, err := net.Interfaces() 325 | if err != nil { 326 | return nil, err 327 | } 328 | for _, intf := range interfaces { 329 | addrs, err := intf.Addrs() 330 | if err != nil { 331 | return nil, err 332 | } 333 | for _, addr := range addrs { 334 | sa := strings.Split(addr.String(), "/") 335 | list = append(list, sa[0]) 336 | } 337 | } 338 | 339 | return 340 | } 341 | 342 | func WriteStructAndNewLineToFile(f *os.File, prefix FilePrefix, s interface{}) (int, error) { 343 | outb, err := json.Marshal(s) 344 | if err != nil { 345 | return 0, err 346 | } 347 | n, err := f.Write(prefix.String()) 348 | if err != nil { 349 | return n, err 350 | } 351 | n, err = f.Write(outb) 352 | if err != nil { 353 | return n, err 354 | } 355 | n, err = f.Write([]byte{10}) 356 | return n, err 357 | } 358 | -------------------------------------------------------------------------------- /shared/sorting.go: -------------------------------------------------------------------------------- 1 | package shared 2 | 3 | import ( 4 | "slices" 5 | "strings" 6 | ) 7 | 8 | type SortType string 9 | 10 | const ( 11 | SortDefault SortType = "RMSH" 12 | SortRMSH SortType = "RMSH" 13 | SortTTFBH SortType = "TTFBH" 14 | ) 15 | 16 | func HostFilter(host string, dps []DP) (filtered []DP) { 17 | filtered = make([]DP, 0) 18 | for _, v := range dps { 19 | if strings.Contains(v.Local, host) { 20 | filtered = append(filtered, v) 21 | } else if strings.Contains(v.Remote, host) { 22 | filtered = append(filtered, v) 23 | } 24 | } 25 | 26 | return 27 | } 28 | 29 | func SortDataPoints(dps []DP, c Config) { 30 | switch c.Sort { 31 | case SortRMSH: 32 | SortDataPointRMSH(dps) 33 | case SortTTFBH: 34 | SortDataPointTTFBH(dps) 35 | default: 36 | c.Sort = SortDefault 37 | SortDataPointRMSH(dps) 38 | } 39 | } 40 | 41 | func SortDataPointRMSH(dps []DP) { 42 | slices.SortFunc(dps, func(a DP, b DP) int { 43 | if a.RMSH < b.RMSH { 44 | return -1 45 | } else { 46 | return 1 47 | } 48 | }) 49 | } 50 | 51 | func SortDataPointTTFBH(dps []DP) { 52 | slices.SortFunc(dps, func(a DP, b DP) int { 53 | if a.TTFBH < b.TTFBH { 54 | return -1 55 | } else { 56 | return 1 57 | } 58 | }) 59 | } 60 | -------------------------------------------------------------------------------- /shared/stats.go: -------------------------------------------------------------------------------- 1 | package shared 2 | 3 | func UpdatePSStats(b []int64, dp DP, c Config) { 4 | switch c.Sort { 5 | case SortRMSH: 6 | UpdatePSStatsRMHS(b, dp) 7 | case SortTTFBH: 8 | UpdatePSStatsTTFBH(b, dp) 9 | default: 10 | c.Sort = SortRMSH 11 | UpdatePSStatsRMHS(b, dp) 12 | } 13 | } 14 | 15 | func UpdatePSStatsRMHS(b []int64, dp DP) { 16 | b[0]++ 17 | b[1] += dp.RMSH 18 | if dp.RMSH < b[2] { 19 | b[2] = dp.RMSH 20 | } 21 | b[3] = b[1] / b[0] 22 | if dp.RMSH > b[4] { 23 | b[4] = dp.RMSH 24 | } 25 | } 26 | 27 | func UpdatePSStatsTTFBH(b []int64, dp DP) { 28 | b[0]++ 29 | b[1] += dp.TTFBH 30 | if dp.TTFBH < b[2] { 31 | b[2] = dp.TTFBH 32 | } 33 | b[3] = b[1] / b[0] 34 | if dp.TTFBH > b[4] { 35 | b[4] = dp.TTFBH 36 | } 37 | } 38 | --------------------------------------------------------------------------------