├── .github └── workflows │ └── release.yml ├── .gitignore ├── .goreleaser.yml ├── LICENSE ├── Makefile ├── README.md ├── docs ├── examples.md ├── index.md └── usage.md ├── go.mod ├── main.go ├── mkdocs.yml └── test └── main.go /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | on: 4 | push: 5 | tags: ["*"] 6 | 7 | jobs: 8 | create-release: 9 | 10 | runs-on: macos-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v1 14 | - name: Create a release 15 | run: make release 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | .DS_Store 17 | /test/test 18 | /results.json 19 | /site 20 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | project_name: rsg 2 | release: 3 | github: 4 | owner: mhausenblas 5 | name: right-size-guide 6 | builds: 7 | - id: right-size-guide 8 | goos: 9 | - linux 10 | - darwin 11 | goarch: 12 | - amd64 13 | - arm 14 | - arm64 15 | env: 16 | - CGO_ENABLED=0 17 | - GO111MODULE=on 18 | main: . 19 | archives: 20 | - id: right-size-guide 21 | builds: 22 | - right-size-guide 23 | name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}" 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | release_version:= v0.96 2 | 3 | export GO111MODULE=on 4 | 5 | .PHONY: bin 6 | bin: 7 | go build -o bin/rsg github.com/mhausenblas/right-size-guide 8 | 9 | .PHONY: release 10 | release: 11 | curl -sL https://git.io/goreleaser | bash -s -- --rm-dist --config .goreleaser.yml 12 | 13 | .PHONY: publish 14 | publish: 15 | git tag ${release_version} 16 | git push --tags -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Go to the [official docs](https://mhausenblas.info/right-size-guide/). -------------------------------------------------------------------------------- /docs/examples.md: -------------------------------------------------------------------------------- 1 | In this section we show how to apply `rsg` findings in the context of container 2 | orchestrators or other related environments, such as serverless compute engines. 3 | 4 | ### Kubernetes 5 | 6 | In Kubernetes, the [Quality of Service (QoS) ](https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/) 7 | of a pod is defined via the resource requests and limits. The former being an 8 | input for the scheduler to find a fitting node to launch the pod and the latter 9 | can be a cause to terminate any container in a pod. For example, 10 | if a container [consumes memory beyond its limit](https://kubernetes.io/docs/tasks/configure-pod-container/assign-memory-resource/) 11 | it is [OOM](https://www.kernel.org/doc/gorman/html/understand/understand016.html) killed. 12 | 13 | But how to arrive at "good" values for the resource requests and limits, which should 14 | be the same BTW if you want to have deterministic behavior? `rsg` to the rescue … 15 | 16 | Let's say you run `rsg` on your app and get the following results (made up, but hey): 17 | 18 | ```json 19 | { 20 | "idle": { 21 | "memory_in_bytes": 10123456, 22 | "cpuuser_in_usec": 2000, 23 | "cpusys_in_usec": 13000 24 | }, 25 | "peak": { 26 | "memory_in_bytes": 25042987, 27 | "cpuuser_in_usec": 4000, 28 | "cpusys_in_usec": 87666 29 | } 30 | } 31 | ``` 32 | 33 | You would then plug it into the Kubernetes manifest like so: 34 | 35 | ```yaml 36 | ... 37 | spec: 38 | containers: 39 | - name: someapp 40 | image: theimage:sometag 41 | resources: 42 | limits: 43 | memory: "30M" 44 | cpu: "900m" 45 | requests: 46 | memory: "30M" 47 | cpu: "900m" 48 | ``` 49 | 50 | !!! tip 51 | Above we used the peak value of the `rsg` finding `memory_in_bytes` which is 52 | `25,042,987` and padded it a little, arriving at `30M`, which is the [Kubernetes 53 | way of saying](https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#meaning-of-memory) 54 | "can I have 30 MB please". 55 | 56 | 57 | ### AWS Fargate 58 | 59 | In EKS on Fargate, one must observe the [pod resource allocations](https://docs.aws.amazon.com/eks/latest/userguide/fargate-pod-configuration.html). 60 | You can see what happens if you don't do this in [this Gist](https://gist.github.com/mhausenblas/56db56d63dad78fc4e81108da49f28b2). 61 | 62 | _TBD_ 63 | 64 | ### Amazon ECS 65 | 66 | _TBD_ -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | The right size guide (`rsg`) is a simple CLI tool that provides you with memory and 2 | CPU recommendations for your application. While, in containerized setups and 3 | there especially in Kubernetes-land, components such as the 4 | [VPA](https://github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler) 5 | exist that could be used to extract similar recommendations, they are: 6 | 7 | 1. limited to a certain orchestrator (Kubernetes), and 8 | 1. rather complicated to use, since they come with a number of dependencies. 9 | 10 | With `rsg` we want to do the opposite: an easy to use tool with zero dependencies 11 | that can be used with and for any container orchestrator, including Kubernetes, 12 | Amazon ECS, HashiCorp Nomad, and even good old Apache Mesos+Marathon. 13 | 14 | 15 | ## Install it 16 | 17 | Download the [latest binary](https://github.com/mhausenblas/right-size-guide/releases/latest) 18 | for Linux (Intel or Arm) and macOS. 19 | 20 | For example, to install `rsg` from binary on macOS you could do the following: 21 | 22 | ```sh 23 | curl -L https://github.com/mhausenblas/right-size-guide/releases/latest/download/rsg_darwin_amd64.tar.gz \ 24 | -o rsg.tar.gz && \ 25 | tar xvzf rsg.tar.gz rsg && \ 26 | mv rsg /usr/local/bin && \ 27 | rm rsg* 28 | ``` 29 | 30 | ## Prior art 31 | 32 | Based on an [informal query on Twitter](https://twitter.com/mhausenblas/status/1225855388584730624) these tools already provide similar functionality: 33 | 34 | - [time](http://man7.org/linux/man-pages/man1/time.1.html) 35 | - [perf](http://www.brendangregg.com/perf.html) 36 | - [DTrace](http://www.brendangregg.com/DTrace/cputimes) 37 | - Facebook [senpai](https://github.com/facebookincubator/senpai) 38 | - Kubernetes [VPA](https://github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler) 39 | -------------------------------------------------------------------------------- /docs/usage.md: -------------------------------------------------------------------------------- 1 | You can use `rsg` for both idle and peak resource usage assessment. The findings 2 | are presented in a simple JSON format, friendly for usage in a pipeline or 3 | in [OpenMetrics](https://openmetrics.io/) for ingestion in Prometheus. Status 4 | updates are written to `stderr` so you can suppress them if you like. 5 | 6 | ```sh 7 | $ rsg -h 8 | Usage: 9 | rsg --target $BINARY 10 | [--api-path $HTTP_URL_PATH --api-port $HTTP_PORT --peak-delay $TIME_MS --sampletime-idle $TIME_SEC --sampletime-peak $TIME_SEC --export-findings $FILE --output json|openmetrics] 11 | Example usage: 12 | rsg --target test/test --api-path /ping --api-port 8080 2>/dev/null 13 | Arguments: 14 | -api-path string 15 | [OPTIONAL] The URL path component of the HTTP API to use for peak resource usage assessment 16 | -api-port string 17 | [OPTIONAL] The TCP port of the HTTP API to use for peak resource usage assessment 18 | -delay-peak int 19 | [OPTIONAL] The time in milliseconds to wait between two consecutive HTTP GET requests for peak resource usage assessment (default 10) 20 | -export-findings string 21 | [OPTIONAL] The filesystem path to export findings to; if not provided the results will be written to stdout 22 | -output string 23 | [OPTIONAL] The output format, valid values are 'json' and 'openmetrics' (default "json") 24 | -sampletime-idle int 25 | [OPTIONAL] The time in seconds to perform idle resource usage assessment (default 2) 26 | -sampletime-peak int 27 | [OPTIONAL] The time in seconds to perform peak resource usage assessment (default 10) 28 | -target string 29 | The filesystem path of the binary or script to assess 30 | -version 31 | Print the version of rsg and exit 32 | ``` 33 | 34 | ### Assessing the idle resource usage 35 | 36 | Let's see how much `/usr/bin/yes` uses: 37 | 38 | ```sh 39 | $ rsg --target /usr/bin/yes 40 | 2020/02/15 16:14:37 Launching /usr/bin/yes for idle state resource usage assessment 41 | 2020/02/15 16:14:37 Trying to determine idle state resource usage (no external traffic) 42 | 2020/02/15 16:14:39 Idle state assessment of /usr/bin/yes completed 43 | 2020/02/15 16:14:39 Found idle state resource usage. MEMORY: 786kB CPU: 986ms (user)/9ms (sys) 44 | { 45 | "idle": { 46 | "memory_in_bytes": 786432, 47 | "cpuuser_in_usec": 986316, 48 | "cpusys_in_usec": 9140 49 | }, 50 | "peak": { 51 | "memory_in_bytes": 0, 52 | "cpuuser_in_usec": 0, 53 | "cpusys_in_usec": 0 54 | } 55 | } 56 | ``` 57 | 58 | ### Assessing the peak resource usage 59 | 60 | Now, imagine you have an application called `test` (as shown in [test/](https://github.com/mhausenblas/right-size-guide/blob/master/test/main.go)). 61 | It's a binary executable that exposes an HTTP API on `:8080/ping`. This is how 62 | you can use `rsg` to figure out how much memory and CPU this app server requires: 63 | 64 | ```sh 65 | $ rsg --target test/test --api-path /ping --api-port 8080 66 | 2020/02/15 16:20:24 Launching test/test for idle state resource usage assessment 67 | 2020/02/15 16:20:24 Trying to determine idle state resource usage (no external traffic) 68 | 2020/02/15 16:20:26 Idle state assessment of test/test completed 69 | 2020/02/15 16:20:26 Found idle state resource usage. MEMORY: 7757kB CPU: 8ms (user)/11ms (sys) 70 | 2020/02/15 16:20:26 Launching test/test for peak state resource usage assessment 71 | 2020/02/15 16:20:26 Trying to determine peak state resource usage using 127.0.0.1:8080/ping 72 | 2020/02/15 16:20:27 Starting to hammer the endpoint http://127.0.0.1:8080/ping every 10ms 73 | 2020/02/15 16:20:36 Peak state assessment of test/test completed 74 | 2020/02/15 16:20:36 Found peak state resource usage. MEMORY: 20209kB CPU: 191ms (user)/179ms (sys) 75 | { 76 | "idle": { 77 | "memory_in_bytes": 7757824, 78 | "cpuuser_in_usec": 8634, 79 | "cpusys_in_usec": 11988 80 | }, 81 | "peak": { 82 | "memory_in_bytes": 20209664, 83 | "cpuuser_in_usec": 191918, 84 | "cpusys_in_usec": 179626 85 | } 86 | } 87 | ``` 88 | 89 | You can also specify a file to export the findings to explicitly and suppress 90 | the status updates, like so: 91 | 92 | ```sh 93 | $ rsg --target test/test \ 94 | --api-path /ping --api-port 8080 \ 95 | --export-findings ./results.json 2>/dev/null 96 | ``` 97 | 98 | Then, you could pull out specific results, say, using `jq`: 99 | 100 | ```sh 101 | $ cat results.json | jq .peak.cpuuser_in_usec 102 | 76174 103 | ``` 104 | 105 | ### Emit OpenMetrics 106 | 107 | By default, `rsg` will output the findings in JSON, however it's super easy to 108 | emit OpenMetrics, like so: 109 | 110 | ```sh 111 | $ rsg --target test/test \ 112 | --api-path /ping --api-port 8080 \ 113 | --output openmetrics 114 | 2020/02/15 16:46:01 Launching test/test for idle state resource usage assessment 115 | 2020/02/15 16:46:01 Trying to determine idle state resource usage (no external traffic) 116 | 2020/02/15 16:46:03 Idle state assessment of test/test completed 117 | 2020/02/15 16:46:03 Found idle state resource usage. MEMORY: 7831kB CPU: 8ms (user)/8ms (sys) 118 | 2020/02/15 16:46:03 Launching test/test for peak state resource usage assessment 119 | 2020/02/15 16:46:03 Trying to determine peak state resource usage using 127.0.0.1:8080/ping 120 | 2020/02/15 16:46:04 Starting to hammer the endpoint http://127.0.0.1:8080/ping every 10ms 121 | 2020/02/15 16:46:13 Peak state assessment of test/test completed 122 | 2020/02/15 16:46:13 Found peak state resource usage. MEMORY: 20168kB CPU: 180ms (user)/168ms (sys) 123 | # HELP idle_memory The idle state memory consumption 124 | # TYPE idle_memory gauge 125 | idle_memory{unit="kB",target="test/test"} 7831552 126 | # HELP idle_cpu_user The idle state CPU consumption in user land 127 | # TYPE idle_cpu_user gauge 128 | idle_cpu_user{unit="microsec",target="test/test"} 8079 129 | # HELP idle_cpu_sys The idle state CPU consumption in the kernel 130 | # TYPE idle_cpu_sys gauge 131 | idle_cpu_sys{unit="microsec",target="test/test"} 8152 132 | # HELP peak_memory The peak state memory consumption 133 | # TYPE peak_memory gauge 134 | peak_memory{unit="kB",target="test/test"} 20168704 135 | # HELP peak_cpu_user The peak state CPU consumption in user land 136 | # TYPE peak_cpu_user gauge 137 | peak_cpu_user{unit="microsec",target="test/test"} 180770 138 | # HELP peak_cpu_sys The peak state CPU consumption in the kernel 139 | # TYPE peak_cpu_sys gauge 140 | peak_cpu_sys{unit="microsec",target="test/test"} 168892 141 | ``` -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/mhausenblas/right-size-guide 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/json" 7 | "flag" 8 | "fmt" 9 | "io/ioutil" 10 | "log" 11 | "net/http" 12 | "os" 13 | "os/exec" 14 | "strings" 15 | "syscall" 16 | "time" 17 | ) 18 | 19 | // Findings captures idle and peak resource usage 20 | type Findings struct { 21 | MemoryMaxRSS int64 `json:"memory_in_bytes"` 22 | CPUuser int64 `json:"cpuuser_in_usec"` 23 | CPUsys int64 `json:"cpusys_in_usec"` 24 | } 25 | 26 | var ( 27 | version = "dev" 28 | commit = "none" 29 | date = "unknown" 30 | ) 31 | var icmd, pcmd *exec.Cmd 32 | var idlef, peakf chan Findings 33 | 34 | func main() { 35 | // Define the CLI API: 36 | flag.Usage = func() { 37 | fmt.Printf("Usage:\n %s --target $BINARY \n [--api-path $HTTP_URL_PATH --api-port $HTTP_PORT --peak-delay $TIME_MS --sampletime-idle $TIME_SEC --sampletime-peak $TIME_SEC --export-findings $FILE --output json|openmetrics]\n", os.Args[0]) 38 | fmt.Println("Example usage:\n rsg --target test/test --api-path /ping --api-port 8080 2>/dev/null") 39 | fmt.Println("Arguments:") 40 | flag.PrintDefaults() 41 | } 42 | target := flag.String("target", "", "The filesystem path of the binary or script to assess") 43 | idlest := flag.Int("sampletime-idle", 2, "[OPTIONAL] The time in seconds to perform idle resource usage assessment") 44 | peakst := flag.Int("sampletime-peak", 10, "[OPTIONAL] The time in seconds to perform peak resource usage assessment") 45 | apibaseurl := flag.String("api-baseurl", "http://127.0.0.1", "[OPTIONAL] The base URL component of the HTTP API to use for peak resource usage assessment") 46 | apipath := flag.String("api-path", "", "[OPTIONAL] The URL path component of the HTTP API to use for peak resource usage assessment") 47 | apiport := flag.String("api-port", "", "[OPTIONAL] The TCP port of the HTTP API to use for peak resource usage assessment") 48 | peakdelay := flag.Int("delay-peak", 10, "[OPTIONAL] The time in milliseconds to wait between two consecutive HTTP GET requests for peak resource usage assessment") 49 | exportfile := flag.String("export-findings", "", "[OPTIONAL] The filesystem path to export findings to; if not provided the results will be written to stdout") 50 | outputformat := flag.String("output", "json", "[OPTIONAL] The output format, valid values are 'json' and 'openmetrics'") 51 | showversion := flag.Bool("version", false, "Print the version of rsg and exit") 52 | flag.Parse() 53 | 54 | if *showversion { 55 | fmt.Printf("%v, commit %v, built at %v\n", version, commit, date) 56 | os.Exit(0) 57 | } 58 | 59 | if len(os.Args) == 0 || *target == "" { 60 | fmt.Printf("Need at least the target program to proceed\n\n") 61 | flag.Usage() 62 | os.Exit(1) 63 | } 64 | 65 | // Set up testing parameters 66 | isampletime := time.Duration(*idlest) * time.Second 67 | psampletime := time.Duration(*peakst) * time.Second 68 | peakhammerpause := time.Duration(*peakdelay) * time.Millisecond 69 | 70 | // Set up global data structures and testing parameter 71 | idlef = make(chan Findings, 1) 72 | peakf = make(chan Findings, 1) 73 | icmd = exec.Command(*target) 74 | pcmd = exec.Command(*target) 75 | ifs := Findings{} 76 | pfs := Findings{} 77 | 78 | // Perform idle state assessment: 79 | go assessidle() 80 | <-time.After(isampletime) 81 | log.Printf("Idle state assessment of %v completed\n", *target) 82 | if icmd.Process != nil { 83 | err := icmd.Process.Signal(os.Interrupt) 84 | if err != nil { 85 | log.Fatalf("Can't stop process: %v\n", err) 86 | } 87 | } 88 | ifs = <-idlef 89 | log.Printf("Found idle state resource usage. MEMORY: %vkB CPU: %vms (user)/%vms (sys)", 90 | ifs.MemoryMaxRSS/1000, 91 | ifs.CPUuser/1000, 92 | ifs.CPUsys/1000) 93 | 94 | // Perform peak state assessment: 95 | if *apipath != "" && *apiport != "" { 96 | go assesspeak(*apibaseurl, *apiport, *apipath, peakhammerpause) 97 | <-time.After(psampletime) 98 | log.Printf("Peak state assessment of %v completed\n", *target) 99 | if pcmd.Process != nil { 100 | err := pcmd.Process.Signal(os.Interrupt) 101 | if err != nil { 102 | log.Fatalf("Can't stop process: %v\n", err) 103 | } 104 | } 105 | pfs = <-peakf 106 | log.Printf("Found peak state resource usage. MEMORY: %vkB CPU: %vms (user)/%vms (sys)", 107 | pfs.MemoryMaxRSS/1000, 108 | pfs.CPUuser/1000, 109 | pfs.CPUsys/1000) 110 | } 111 | // Handle export of findings: 112 | export(ifs, pfs, *exportfile, *outputformat, *target) 113 | } 114 | 115 | // assessidle performs the idle state resource usage assessment, that is, 116 | // the memory and CPU usage of the process without external traffic 117 | func assessidle() { 118 | log.Printf("Launching %v for idle state resource usage assessment", icmd.Path) 119 | log.Println("Trying to determine idle state resource usage (no external traffic)") 120 | icmd.Run() 121 | f := Findings{} 122 | if icmd.ProcessState != nil { 123 | f.MemoryMaxRSS = int64(icmd.ProcessState.SysUsage().(*syscall.Rusage).Maxrss) 124 | f.CPUuser = int64(icmd.ProcessState.SysUsage().(*syscall.Rusage).Utime.Usec) 125 | f.CPUsys = int64(icmd.ProcessState.SysUsage().(*syscall.Rusage).Stime.Usec) 126 | } 127 | idlef <- f 128 | } 129 | 130 | // assesspeak performs the peak state resource usage assessment, that is, 131 | // the memory and CPU usage of the process with external traffic applied 132 | func assesspeak(apibaseurl, apiport, apipath string, peakhammerpause time.Duration) { 133 | log.Printf("Launching %v for peak state resource usage assessment", pcmd.Path) 134 | log.Printf("Trying to determine peak state resource usage using %v:%v%v", apibaseurl, apiport, apipath) 135 | go stress(apibaseurl, apiport, apipath, peakhammerpause) 136 | pcmd.Run() 137 | f := Findings{} 138 | if pcmd.ProcessState != nil { 139 | f.MemoryMaxRSS = int64(pcmd.ProcessState.SysUsage().(*syscall.Rusage).Maxrss) 140 | f.CPUuser = int64(pcmd.ProcessState.SysUsage().(*syscall.Rusage).Utime.Usec) 141 | f.CPUsys = int64(pcmd.ProcessState.SysUsage().(*syscall.Rusage).Stime.Usec) 142 | } 143 | peakf <- f 144 | } 145 | 146 | // stress performs an HTTP GET stress test against the base URL/port/path provided 147 | func stress(apibaseurl, apiport, apipath string, peakhammerpause time.Duration) { 148 | time.Sleep(1 * time.Second) 149 | ep := fmt.Sprintf("%v:%v%v", apibaseurl, apiport, apipath) 150 | log.Printf("Starting to hammer %v every %v", ep, peakhammerpause) 151 | for { 152 | _, err := http.Get(ep) 153 | if err != nil { 154 | log.Println(err) 155 | } 156 | time.Sleep(peakhammerpause) 157 | } 158 | } 159 | 160 | // export writes the findings to a file or stdout, if exportfile is empty 161 | func export(ifs, pfs Findings, exportfile, outputformat, target string) { 162 | fs := map[string]Findings{ 163 | "idle": ifs, 164 | "peak": pfs, 165 | } 166 | data, err := json.MarshalIndent(fs, "", " ") 167 | if err != nil { 168 | log.Printf("Can't serialize findings: %v\n", err) 169 | } 170 | 171 | outputformat = strings.ToLower(outputformat) 172 | switch outputformat { 173 | case "json": 174 | switch { 175 | case exportfile != "": // use export file path provided 176 | log.Printf("Exporting findings as JSON to %v", exportfile) 177 | err := ioutil.WriteFile(exportfile, data, 0644) 178 | if err != nil { 179 | log.Printf("Can't export findings: %v\n", err) 180 | } 181 | default: // if no export file path set, write to stdout 182 | w := bufio.NewWriter(os.Stdout) 183 | _, err := w.Write(data) 184 | if err != nil { 185 | log.Printf("Can't export findings: %v\n", err) 186 | } 187 | w.Flush() 188 | } 189 | case "openmetrics": 190 | var buffer bytes.Buffer 191 | buffer.WriteString(emito("idle_memory", 192 | "gauge", 193 | "The idle state memory consumption", 194 | fmt.Sprintf("%d", ifs.MemoryMaxRSS), 195 | map[string]string{"target": target, "unit": "kB"})) 196 | buffer.WriteString(emito("idle_cpu_user", 197 | "gauge", 198 | "The idle state CPU consumption in user land", 199 | fmt.Sprintf("%d", ifs.CPUuser), 200 | map[string]string{"target": target, "unit": "microsec"})) 201 | buffer.WriteString(emito("idle_cpu_sys", 202 | "gauge", 203 | "The idle state CPU consumption in the kernel", 204 | fmt.Sprintf("%d", ifs.CPUsys), 205 | map[string]string{"target": target, "unit": "microsec"})) 206 | if pfs.MemoryMaxRSS != 0 { 207 | buffer.WriteString(emito("peak_memory", 208 | "gauge", 209 | "The peak state memory consumption", 210 | fmt.Sprintf("%d", pfs.MemoryMaxRSS), 211 | map[string]string{"target": target, "unit": "kB"})) 212 | buffer.WriteString(emito("peak_cpu_user", 213 | "gauge", 214 | "The peak state CPU consumption in user land", 215 | fmt.Sprintf("%d", pfs.CPUuser), 216 | map[string]string{"target": target, "unit": "microsec"})) 217 | buffer.WriteString(emito("peak_cpu_sys", 218 | "gauge", 219 | "The peak state CPU consumption in the kernel", 220 | fmt.Sprintf("%d", pfs.CPUsys), 221 | map[string]string{"target": target, "unit": "microsec"})) 222 | } 223 | switch { 224 | case exportfile != "": // use export file path provided 225 | log.Printf("Exporting findings in OpenMetrics format to %v", exportfile) 226 | err := ioutil.WriteFile(exportfile, buffer.Bytes(), 0644) 227 | if err != nil { 228 | log.Printf("Can't export findings: %v\n", err) 229 | } 230 | default: // if no export file path set, write to stdout 231 | w := bufio.NewWriter(os.Stdout) 232 | _, err := w.Write(buffer.Bytes()) 233 | if err != nil { 234 | log.Printf("Can't export findings: %v\n", err) 235 | } 236 | w.Flush() 237 | } 238 | default: 239 | log.Printf("Can't export findings, unknown output format selected, please use json or openmetrics") 240 | } 241 | } 242 | 243 | // emito creates an OpenMetrics compliant line, for example: 244 | // # HELP pod_count_all Number of pods in any state (running, terminating, etc.) 245 | // # TYPE pod_count_all gauge 246 | // pod_count_all{namespace="krs"} 4 1538675211 247 | func emito(metric, metrictype, metricdesc, value string, labels map[string]string) (line string) { 248 | line = fmt.Sprintf("# HELP %v %v\n", metric, metricdesc) 249 | line += fmt.Sprintf("# TYPE %v %v\n", metric, metrictype) 250 | // add labels: 251 | line += fmt.Sprintf("%v{", metric) 252 | for k, v := range labels { 253 | line += fmt.Sprintf("%v=\"%v\"", k, v) 254 | line += "," 255 | } 256 | // make sure that we get rid of trialing comma: 257 | line = strings.TrimSuffix(line, ",") 258 | // now add value and we're done: 259 | line += fmt.Sprintf("} %v\n", value) 260 | return 261 | } 262 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: rsg 2 | site_description: 'A tool that provides memory & CPU recommendations for apps' 3 | site_author: 'Michael Hausenblas' 4 | repo_name: 'mhausenblas/right-size-guide' 5 | repo_url: 'https://github.com/mhausenblas/right-size-guide' 6 | copyright: 'Copyright © 2020 Amazon' 7 | nav: 8 | - Home: index.md 9 | - Usage: usage.md 10 | - Examples: examples.md 11 | theme: 12 | name: 'material' 13 | logo: 14 | icon: 'memory' 15 | font: 16 | text: 'Lato' 17 | code: 'PT Mono' 18 | palette: 19 | primary: 'orange' 20 | accent: 'blue' 21 | highlightjs: true 22 | hljs_languages: 23 | - yaml 24 | - json 25 | - bash 26 | markdown_extensions: 27 | - toc: 28 | permalink: true 29 | - admonition 30 | - codehilite: 31 | linenums: true 32 | - pymdownx.details 33 | - pymdownx.superfences 34 | 35 | -------------------------------------------------------------------------------- /test/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "os" 8 | "os/signal" 9 | "syscall" 10 | ) 11 | 12 | func main() { 13 | srv := &http.Server{Addr: ":8080"} 14 | done := make(chan os.Signal, 1) 15 | signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) 16 | 17 | go func() { 18 | http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) { 19 | fmt.Fprintf(w, "pong") 20 | }) 21 | err := srv.ListenAndServe() 22 | if err != nil && err != http.ErrServerClosed { 23 | log.Fatalf("listen: %s\n", err) 24 | } 25 | }() 26 | log.Print("Server Started") 27 | <-done 28 | log.Print("Server Stopped") 29 | 30 | } 31 | --------------------------------------------------------------------------------