├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── calculator ├── calculator.go └── calculator_test.go ├── ci ├── create-release.sh ├── package.sh ├── package.yml ├── unit-test.sh └── unit-test.yml ├── flags ├── head_room.go ├── head_room_test.go ├── jvm_options.go ├── jvm_options_test.go ├── loaded_class_count.go ├── loaded_class_count_test.go ├── thread_count.go ├── thread_count_test.go ├── total_memory.go ├── total_memory_test.go └── validatable.go ├── go.mod ├── go.sum ├── main.go └── memory ├── max_direct_memory.go ├── max_direct_memory_test.go ├── max_heap.go ├── max_heap_test.go ├── max_metaspace.go ├── max_metaspace_test.go ├── reserved_code_cache.go ├── reserved_code_cache_test.go ├── size.go ├── size_test.go ├── stack.go └── stack_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Copyright 2015-2018 the original author or authors. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | .idea/ 16 | bin/ 17 | *.iml -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Cloud Foundry Java Buildpack Memory Calculator 2 | 3 | Copyright (c) 2015-Present CloudFoundry.org Foundation, Inc. All Rights Reserved. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Buildpack Memory Calculator 2 | 3 | The Java Buildpack Memory Calculator calculates a holistic JVM memory configuration with the goal of ensuring that applications perform well while not exceeding a container's memory limit and being recycled. 4 | 5 | In order to perform this calculation, the Memory Calculator requires the following input: 6 | * `--total-memory`: total memory available to the application, typically expressed with size classification (`B`, `K`, `M`, `G`, `T`) 7 | * `--loaded-class-count`: the number of classes that will be loaded when the application is running 8 | * `--thread-count`: the number of user threads 9 | * `--jvm-options`: JVM Options, typically `JAVA_OPTS` 10 | * `--head-room`: percentage of total memory available which will be left unallocated to cover JVM overhead 11 | 12 | The Memory Calculator prints the calculated JVM configuration flags (_excluding_ any that the user has specified in `--jvm-options`). If a valid configuration cannot be calculated (e.g. more memory must be allocated than is available), an error is printed and a non-zero exit code is returned. In order to **override** a calculated value, users should pass any of the standard JVM configuration flags into `--jvm-options`. The calculation will take these as fixed values and adjust the non-fixed values accordingly. 13 | 14 | ## Install 15 | 16 | ```sh 17 | $ go get -v github.com/cloudfoundry/java-buildpack-memory-calculator 18 | ``` 19 | 20 | ## Algorithm 21 | 22 | The following algorithm is used to generate the holistic JVM memory configuration: 23 | 24 | 1. `Headroom amount` is calculated as `total memory * (head room / 100)`. 25 | 1. If `-XX:MaxDirectMemorySize` is configured it is used for the amount of direct memory. If not configured, `10M` (in the absence of any reasonable heuristic) is used. 26 | 1. If `-XX:MaxMetaspaceSize` is configured it is used for the amount of metaspace. If not configured, then the value is calculated as `(5800B * loaded class count) + 14000000b`. 27 | 1. If `-XX:ReservedCodeCacheSize` is configured it is used for the amount of reserved code cache. If not configured, `240M` (the JVM default) is used. 28 | 1. If `-Xss` is configured it is used for the size of each thread stack. If not configured, `1M` (the JVM default) is used. 29 | 1. If `-Xmx` is configured it is used for the size of the heap. If not configured, then the value is calculated as 30 | 31 | ``` 32 | total memory - (headroom amount + direct memory + metaspace + reserved code cache + (thread stack * thread count)) 33 | ``` 34 | 35 | Broadly, this means that for a constant application (same number of classes), the non-heap overhead is a fixed value. Any changes to the total memory will be directly reflected in the size of the heap. Adjustments to the non-heap memory configuration (e.g. stack size, reserved code cache) _can_ result in larger heap sizes, but can also have negative runtime side effects that must be taken into account. 36 | 37 | For example, with a 1G memory limit, you have a heap size of `1G - (0 headroom + 10M direct + X metaspace + 240M + 250 threads * 1M thread memory)` which means you have `heap space = 524M - X metaspace`. Metaspace is often around 100M for a typical Spring Boot app, so in that situation it leaves us with around 424M of heap space. If you shift your memory limit to 768M then you end up with `heap space = 268M - X metaspace` or 168M with a typical Spring Boot app (100M metaspace). As you can see, when the memory limit goes below 1G, the formula used by the memory calculator prioritizes the non-heap space and heap space suffers. 38 | 39 | Every application is different, but for best results, it is recommended that when running with a memory limit below 1G the user apply some manual adjustments to the memory limits. For example, you can lower the thread stack size, the number of threads, or the reserved code cache size. This will allow you to save more room for the heap. Just be aware that each of these tunings has a trade-off for your application in terms of scalability (threads) or performance (code cache), and this is why the memory calculator prioritizes these settings over the heap. As a human, you need to test/evaluate the trade-offs for a given application and decide what works best for the application. 40 | 41 | ### Compressed class space size 42 | 43 | According to the [HotSpot GC Tuning Guide][h]: 44 | 45 | > The MaxMetaspaceSize applies to the sum of the committed compressed class space and the space for the other class metadata. 46 | 47 | Therefore the memory calculator does not set the compressed class space size (`-XX:CompressedClassSpaceSize`) since the memory for the compressed class space is bounded by the maximum metaspace size (`-XX:MaxMetaspaceSize`). 48 | 49 | [h]: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/considerations.html 50 | 51 | ## License 52 | The Java Buildpack Memory Calculator is Open Source software released under the [Apache 2.0 license][a]. 53 | 54 | [a]: http://www.apache.org/licenses/LICENSE-2.0.html 55 | -------------------------------------------------------------------------------- /calculator/calculator.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package calculator 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/flags" 23 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 24 | ) 25 | 26 | type Calculator struct { 27 | HeadRoom *flags.HeadRoom 28 | JvmOptions *flags.JVMOptions 29 | LoadedClassCount *flags.LoadedClassCount 30 | ThreadCount *flags.ThreadCount 31 | TotalMemory *flags.TotalMemory 32 | } 33 | 34 | func (c Calculator) Calculate() ([]fmt.Stringer, error) { 35 | var options []fmt.Stringer 36 | 37 | j := c.JvmOptions 38 | if j == nil { 39 | j = &flags.JVMOptions{} 40 | } 41 | 42 | headRoom := c.headRoom() 43 | 44 | directMemory := j.MaxDirectMemory 45 | if directMemory == nil { 46 | d := memory.DefaultMaxDirectMemory 47 | directMemory = &d 48 | options = append(options, *directMemory) 49 | } 50 | 51 | metaspace := j.MaxMetaspace 52 | if metaspace == nil { 53 | m := c.metaspace() 54 | metaspace = &m 55 | options = append(options, *metaspace) 56 | } 57 | 58 | reservedCodeCache := j.ReservedCodeCache 59 | if reservedCodeCache == nil { 60 | r := memory.DefaultReservedCodeCache 61 | reservedCodeCache = &r 62 | options = append(options, *reservedCodeCache) 63 | } 64 | 65 | stack := j.Stack 66 | if stack == nil { 67 | s := memory.DefaultStack 68 | stack = &s 69 | options = append(options, *stack) 70 | } 71 | 72 | overhead := c.overhead(headRoom, directMemory, metaspace, reservedCodeCache, stack) 73 | available := memory.Size(*c.TotalMemory) 74 | 75 | if overhead > available { 76 | return nil, fmt.Errorf("required memory %s is greater than %s available for allocation: %s, %s, %s, %s x %d threads", 77 | overhead, available, directMemory, metaspace, reservedCodeCache, stack, *c.ThreadCount) 78 | } 79 | 80 | heap := j.MaxHeap 81 | if heap == nil { 82 | h := c.heap(overhead) 83 | heap = &h 84 | options = append(options, *heap) 85 | } 86 | 87 | if overhead+memory.Size(*heap) > available { 88 | return nil, fmt.Errorf("required memory %s is greater than %s available for allocation: %s, %s, %s, %s, %s x %d threads", 89 | overhead+memory.Size(*heap), available, directMemory, heap, metaspace, reservedCodeCache, stack, *c.ThreadCount) 90 | } 91 | 92 | return options, nil 93 | } 94 | 95 | func (c Calculator) headRoom() memory.Size { 96 | return memory.Size(float64(*c.TotalMemory) * (float64(*c.HeadRoom) / 100)) 97 | } 98 | 99 | func (c Calculator) heap(overhead memory.Size) memory.MaxHeap { 100 | return memory.MaxHeap(memory.Size(*c.TotalMemory) - overhead) 101 | } 102 | 103 | func (c Calculator) metaspace() memory.MaxMetaspace { 104 | return memory.MaxMetaspace((*c.LoadedClassCount * 5800) + 14000000) 105 | } 106 | 107 | func (c Calculator) overhead(headRoom memory.Size, directMemory *memory.MaxDirectMemory, metaspace *memory.MaxMetaspace, reservedCodeCache *memory.ReservedCodeCache, stack *memory.Stack) memory.Size { 108 | return headRoom + 109 | memory.Size(*directMemory) + 110 | memory.Size(*metaspace) + 111 | memory.Size(*reservedCodeCache) + 112 | memory.Size(int64(*stack)*int64(*c.ThreadCount)) 113 | } 114 | -------------------------------------------------------------------------------- /calculator/calculator_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package calculator_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/calculator" 23 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/flags" 24 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 25 | . "github.com/onsi/gomega" 26 | "github.com/sclevine/spec" 27 | ) 28 | 29 | func TestCalculator(t *testing.T) { 30 | spec.Run(t, "Calculator", func(t *testing.T, _ spec.G, it spec.S) { 31 | 32 | g := NewGomegaWithT(t) 33 | 34 | var c calculator.Calculator 35 | 36 | it.Before(func() { 37 | h := flags.HeadRoom(0) 38 | j := flags.JVMOptions{} 39 | l := flags.LoadedClassCount(1000) 40 | t := flags.ThreadCount(10) 41 | m := flags.TotalMemory(500 * memory.Mibi) 42 | 43 | c = calculator.Calculator{HeadRoom: &h, JvmOptions: &j, LoadedClassCount: &l, ThreadCount: &t, TotalMemory: &m} 44 | }) 45 | 46 | it("uses default and calculated values", func() { 47 | g.Expect(c.Calculate()).To(ConsistOf( 48 | memory.DefaultMaxDirectMemory, 49 | memory.MaxMetaspace(19800000), 50 | memory.DefaultReservedCodeCache, 51 | memory.DefaultStack, 52 | memory.MaxHeap(231858240), 53 | )) 54 | }) 55 | 56 | it("uses configured direct memory", func() { 57 | d := memory.MaxDirectMemory(memory.Mibi) 58 | c.JvmOptions.MaxDirectMemory = &d 59 | 60 | g.Expect(c.Calculate()).To(ConsistOf( 61 | memory.MaxMetaspace(19800000), 62 | memory.DefaultReservedCodeCache, 63 | memory.DefaultStack, 64 | memory.MaxHeap(241295424), 65 | )) 66 | }) 67 | 68 | it("uses configured metaspace", func() { 69 | m := memory.MaxMetaspace(memory.Mibi) 70 | c.JvmOptions.MaxMetaspace = &m 71 | 72 | g.Expect(c.Calculate()).To(ConsistOf( 73 | memory.DefaultMaxDirectMemory, 74 | memory.DefaultReservedCodeCache, 75 | memory.DefaultStack, 76 | memory.MaxHeap(250609664), 77 | )) 78 | }) 79 | 80 | it("uses configured reserved code cache", func() { 81 | r := memory.ReservedCodeCache(memory.Mibi) 82 | c.JvmOptions.ReservedCodeCache = &r 83 | 84 | g.Expect(c.Calculate()).To(ConsistOf( 85 | memory.DefaultMaxDirectMemory, 86 | memory.MaxMetaspace(19800000), 87 | memory.DefaultStack, 88 | memory.MaxHeap(482467904), 89 | )) 90 | }) 91 | 92 | it("uses configured stack", func() { 93 | s := memory.Stack(memory.Mibi) 94 | c.JvmOptions.Stack = &s 95 | 96 | g.Expect(c.Calculate()).To(ConsistOf( 97 | memory.DefaultMaxDirectMemory, 98 | memory.MaxMetaspace(19800000), 99 | memory.DefaultReservedCodeCache, 100 | memory.MaxHeap(231858240), 101 | )) 102 | }) 103 | 104 | it("uses configured heap", func() { 105 | h := memory.MaxHeap(memory.Mibi) 106 | c.JvmOptions.MaxHeap = &h 107 | 108 | g.Expect(c.Calculate()).To(ConsistOf( 109 | memory.DefaultMaxDirectMemory, 110 | memory.MaxMetaspace(19800000), 111 | memory.DefaultReservedCodeCache, 112 | memory.DefaultStack, 113 | )) 114 | }) 115 | 116 | it("returns error if overhead is too large", func() { 117 | m := memory.MaxMetaspace(500 * memory.Mibi) 118 | c.JvmOptions.MaxMetaspace = &m 119 | 120 | _, err := c.Calculate() 121 | g.Expect(err).To(HaveOccurred()) 122 | }) 123 | 124 | it("returns error if configured heap is too large", func() { 125 | h := memory.MaxHeap(500 * memory.Mibi) 126 | c.JvmOptions.MaxHeap = &h 127 | 128 | _, err := c.Calculate() 129 | g.Expect(err).To(HaveOccurred()) 130 | }) 131 | }) 132 | } 133 | -------------------------------------------------------------------------------- /ci/create-release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | 5 | RELEASE=$1 6 | SNAPSHOT=$2 7 | 8 | update_version() { 9 | sed -E -i '' "s|(^[ ]*VERSION:[ ]*).+$|\1${1}|" ci/package.yml 10 | } 11 | 12 | update_version ${RELEASE} 13 | git add . 14 | git commit --message "v${RELEASE} Release" 15 | git tag -s v${RELEASE} -m "v${RELEASE}" 16 | 17 | git reset --hard HEAD^1 18 | update_version ${SNAPSHOT} 19 | git add . 20 | git commit --message "v${SNAPSHOT} Development" 21 | -------------------------------------------------------------------------------- /ci/package.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | 5 | if [[ -d $PWD/go-module-cache && ! -d ${GOPATH}/pkg/mod ]]; then 6 | mkdir -p ${GOPATH}/pkg 7 | ln -s $PWD/go-module-cache ${GOPATH}/pkg/mod 8 | fi 9 | 10 | TARGET="${PWD}/artifactory/org/cloudfoundry/java-buildpack-memory-calculator/${VERSION}/java-buildpack-memory-calculator-$(echo ${VERSION} | sed "s|SNAPSHOT|$(date '+%Y%m%d.%H%M%S')-1|").tgz" 11 | 12 | cd "$(dirname "${BASH_SOURCE[0]}")/.." 13 | go build -ldflags='-s -w' -o bin/java-buildpack-memory-calculator main.go 14 | 15 | cd bin 16 | mkdir -p $(dirname ${TARGET}) 17 | tar czf ${TARGET} java-buildpack-memory-calculator 18 | -------------------------------------------------------------------------------- /ci/package.yml: -------------------------------------------------------------------------------- 1 | --- 2 | platform: linux 3 | 4 | image_resource: 5 | type: registry-image 6 | source: 7 | repository: golang 8 | tag: latest 9 | 10 | inputs: 11 | - name: java-buildpack-memory-calculator 12 | 13 | outputs: 14 | - name: artifactory 15 | 16 | caches: 17 | - path: go-module-cache 18 | 19 | run: 20 | path: java-buildpack-memory-calculator/ci/package.sh 21 | 22 | params: 23 | VERSION: 4.3.0-SNAPSHOT 24 | -------------------------------------------------------------------------------- /ci/unit-test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | 5 | if [[ -d $PWD/go-module-cache && ! -d ${GOPATH}/pkg/mod ]]; then 6 | mkdir -p ${GOPATH}/pkg 7 | ln -s $PWD/go-module-cache ${GOPATH}/pkg/mod 8 | fi 9 | 10 | cd "$(dirname "${BASH_SOURCE[0]}")/.." 11 | go test ./... 12 | -------------------------------------------------------------------------------- /ci/unit-test.yml: -------------------------------------------------------------------------------- 1 | --- 2 | platform: linux 3 | 4 | image_resource: 5 | type: registry-image 6 | source: 7 | repository: golang 8 | tag: latest 9 | 10 | inputs: 11 | - name: java-buildpack-memory-calculator 12 | 13 | caches: 14 | - path: go-module-cache 15 | 16 | run: 17 | path: java-buildpack-memory-calculator/ci/unit-test.sh 18 | -------------------------------------------------------------------------------- /flags/head_room.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags 18 | 19 | import ( 20 | "fmt" 21 | "strconv" 22 | ) 23 | 24 | const ( 25 | DefaultHeadRoom = HeadRoom(0) 26 | FlagHeadRoom = "head-room" 27 | ) 28 | 29 | type HeadRoom int 30 | 31 | func (h *HeadRoom) Set(s string) error { 32 | f, err := strconv.ParseInt(s, 10, 64) 33 | if err != nil { 34 | return err 35 | } 36 | 37 | *h = HeadRoom(f) 38 | return nil 39 | } 40 | 41 | func (h *HeadRoom) String() string { 42 | return strconv.FormatInt(int64(*h), 10) 43 | } 44 | 45 | func (h *HeadRoom) Type() string { 46 | return "int" 47 | } 48 | 49 | func (h *HeadRoom) Validate() error { 50 | if *h < 0 || *h > 100 { 51 | return fmt.Errorf("--%s must be a valid percentage: %d", FlagHeadRoom, *h) 52 | } 53 | 54 | return nil 55 | } 56 | -------------------------------------------------------------------------------- /flags/head_room_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/flags" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestHeadRoom(t *testing.T) { 28 | spec.Run(t, "HeadRoom", func(t *testing.T, _ spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("is invalid less than 0", func() { 33 | h := flags.HeadRoom(-1) 34 | 35 | g.Expect(h.Validate()).NotTo(Succeed()) 36 | }) 37 | 38 | it("is invalid more than 100", func() { 39 | h := flags.HeadRoom(101) 40 | 41 | g.Expect(h.Validate()).NotTo(Succeed()) 42 | }) 43 | 44 | it("is valid between 0 and 100", func() { 45 | h := flags.HeadRoom(50) 46 | 47 | g.Expect(h.Validate()).To(Succeed()) 48 | }) 49 | 50 | it("parses value", func() { 51 | var h flags.HeadRoom 52 | 53 | g.Expect(h.Set("50")).To(Succeed()) 54 | g.Expect(h).To(Equal(flags.HeadRoom(50))) 55 | }) 56 | 57 | }) 58 | } 59 | -------------------------------------------------------------------------------- /flags/jvm_options.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags 18 | 19 | import ( 20 | "strings" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 23 | ) 24 | 25 | var DefaultJVMOptions = JVMOptions{} 26 | 27 | const FlagJVMOptions = "jvm-options" 28 | 29 | type JVMOptions struct { 30 | MaxDirectMemory *memory.MaxDirectMemory 31 | MaxHeap *memory.MaxHeap 32 | MaxMetaspace *memory.MaxMetaspace 33 | ReservedCodeCache *memory.ReservedCodeCache 34 | Stack *memory.Stack 35 | } 36 | 37 | func (j *JVMOptions) Set(s string) error { 38 | for _, c := range strings.Split(s, " ") { 39 | if memory.IsMaxDirectMemory(c) { 40 | m, err := memory.ParseMaxDirectMemory(c) 41 | if err != nil { 42 | return err 43 | } 44 | 45 | j.MaxDirectMemory = &m 46 | } else if memory.IsMaxHeap(c) { 47 | m, err := memory.ParseMaxHeap(c) 48 | if err != nil { 49 | return err 50 | } 51 | 52 | j.MaxHeap = &m 53 | } else if memory.IsMaxMetaspace(c) { 54 | m, err := memory.ParseMaxMetaspace(c) 55 | if err != nil { 56 | return err 57 | } 58 | 59 | j.MaxMetaspace = &m 60 | } else if memory.IsReservedCodeCache(c) { 61 | r, err := memory.ParseReservedCodeCache(c) 62 | if err != nil { 63 | return err 64 | } 65 | 66 | j.ReservedCodeCache = &r 67 | } else if memory.IsStack(c) { 68 | s, err := memory.ParseStack(c) 69 | if err != nil { 70 | return err 71 | } 72 | 73 | j.Stack = &s 74 | } 75 | } 76 | 77 | return nil 78 | } 79 | 80 | func (j *JVMOptions) String() string { 81 | var values []string 82 | 83 | if j.MaxDirectMemory != nil { 84 | values = append(values, j.MaxDirectMemory.String()) 85 | } 86 | 87 | if j.MaxHeap != nil { 88 | values = append(values, j.MaxHeap.String()) 89 | } 90 | 91 | if j.MaxMetaspace != nil { 92 | values = append(values, j.MaxMetaspace.String()) 93 | } 94 | 95 | if j.ReservedCodeCache != nil { 96 | values = append(values, j.ReservedCodeCache.String()) 97 | } 98 | 99 | if j.Stack != nil { 100 | values = append(values, j.Stack.String()) 101 | } 102 | 103 | return strings.Join(values, " ") 104 | } 105 | 106 | func (j *JVMOptions) Type() string { 107 | return "string" 108 | } 109 | 110 | func (j *JVMOptions) Validate() error { 111 | return nil 112 | } 113 | -------------------------------------------------------------------------------- /flags/jvm_options_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/flags" 23 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 24 | . "github.com/onsi/gomega" 25 | "github.com/sclevine/spec" 26 | ) 27 | 28 | func TestJVMOptions(t *testing.T) { 29 | spec.Run(t, "JVMOptions", func(t *testing.T, _ spec.G, it spec.S) { 30 | 31 | g := NewGomegaWithT(t) 32 | 33 | it("it is always valid", func() { 34 | j := flags.JVMOptions{} 35 | 36 | g.Expect(j.Validate()).To(Succeed()) 37 | }) 38 | 39 | it("creates string", func() { 40 | d := memory.MaxDirectMemory(memory.Kibi) 41 | h := memory.MaxHeap(memory.Kibi) 42 | m := memory.MaxMetaspace(memory.Kibi) 43 | r := memory.ReservedCodeCache(memory.Kibi) 44 | s := memory.Stack(memory.Kibi) 45 | 46 | j := flags.JVMOptions{MaxDirectMemory: &d, MaxHeap: &h, MaxMetaspace: &m, ReservedCodeCache: &r, Stack: &s} 47 | 48 | g.Expect(j.String()).To(Equal("-XX:MaxDirectMemorySize=1K -Xmx1K -XX:MaxMetaspaceSize=1K -XX:ReservedCodeCacheSize=1K -Xss1K")) 49 | }) 50 | 51 | it("parses value", func() { 52 | d := memory.MaxDirectMemory(memory.Kibi) 53 | h := memory.MaxHeap(memory.Kibi) 54 | m := memory.MaxMetaspace(memory.Kibi) 55 | r := memory.ReservedCodeCache(memory.Kibi) 56 | s := memory.Stack(memory.Kibi) 57 | 58 | e := flags.JVMOptions{MaxDirectMemory: &d, MaxHeap: &h, MaxMetaspace: &m, ReservedCodeCache: &r, Stack: &s} 59 | 60 | var j flags.JVMOptions 61 | 62 | g.Expect(j.Set("-XX:MaxDirectMemorySize=1K -Xmx1K -XX:MaxMetaspaceSize=1K -XX:ReservedCodeCacheSize=1K -Xss1K")).To(Succeed()) 63 | g.Expect(j).To(Equal(e)) 64 | }) 65 | 66 | }) 67 | } 68 | -------------------------------------------------------------------------------- /flags/loaded_class_count.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags 18 | 19 | import ( 20 | "fmt" 21 | "strconv" 22 | ) 23 | 24 | const ( 25 | DefaultLoadedClassCount = LoadedClassCount(0) 26 | FlagLoadedClassCount = "loaded-class-count" 27 | ) 28 | 29 | type LoadedClassCount int 30 | 31 | func (l *LoadedClassCount) Set(s string) error { 32 | i, err := strconv.ParseInt(s, 10, 64) 33 | if err != nil { 34 | return err 35 | } 36 | 37 | *l = LoadedClassCount(i) 38 | return nil 39 | } 40 | 41 | func (l *LoadedClassCount) String() string { 42 | return strconv.FormatInt(int64(*l), 10) 43 | } 44 | 45 | func (l *LoadedClassCount) Type() string { 46 | return "int" 47 | } 48 | 49 | func (l *LoadedClassCount) Validate() error { 50 | if *l == 0 { 51 | return fmt.Errorf("--%s must be specified", FlagLoadedClassCount) 52 | } 53 | 54 | if *l < 0 { 55 | return fmt.Errorf("--%s must be positive: %d", FlagLoadedClassCount, *l) 56 | } 57 | 58 | return nil 59 | } 60 | -------------------------------------------------------------------------------- /flags/loaded_class_count_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/flags" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestLoadedClassCount(t *testing.T) { 28 | spec.Run(t, "LoadedClassCount", func(t *testing.T, _ spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("is invalid less than 0", func() { 33 | l := flags.LoadedClassCount(-1) 34 | 35 | g.Expect(l.Validate()).NotTo(Succeed()) 36 | }) 37 | 38 | it("is invalid at 0", func() { 39 | l := flags.LoadedClassCount(0) 40 | 41 | g.Expect(l.Validate()).NotTo(Succeed()) 42 | }) 43 | 44 | it("is valid more than 0", func() { 45 | l := flags.LoadedClassCount(1) 46 | 47 | g.Expect(l.Validate()).To(Succeed()) 48 | }) 49 | 50 | it("parses value", func() { 51 | var l flags.LoadedClassCount 52 | 53 | g.Expect(l.Set("1")).To(Succeed()) 54 | g.Expect(l).To(Equal(flags.LoadedClassCount(1))) 55 | }) 56 | }) 57 | } 58 | -------------------------------------------------------------------------------- /flags/thread_count.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags 18 | 19 | import ( 20 | "fmt" 21 | "strconv" 22 | ) 23 | 24 | const ( 25 | DefaultThreadCount = ThreadCount(0) 26 | FlagThreadCount = "thread-count" 27 | ) 28 | 29 | type ThreadCount int 30 | 31 | func (t *ThreadCount) Set(s string) error { 32 | i, err := strconv.ParseInt(s, 10, 64) 33 | if err != nil { 34 | return err 35 | } 36 | 37 | *t = ThreadCount(i) 38 | return nil 39 | } 40 | 41 | func (t *ThreadCount) String() string { 42 | return strconv.FormatInt(int64(*t), 10) 43 | } 44 | 45 | func (t *ThreadCount) Type() string { 46 | return "int" 47 | } 48 | 49 | func (t *ThreadCount) Validate() error { 50 | if *t == 0 { 51 | return fmt.Errorf("--%s must be specified", FlagThreadCount) 52 | } 53 | 54 | if *t < 0 { 55 | return fmt.Errorf("--%s must be positive: %d", FlagThreadCount, *t) 56 | } 57 | 58 | return nil 59 | } 60 | -------------------------------------------------------------------------------- /flags/thread_count_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/flags" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestThreadCount(t *testing.T) { 28 | spec.Run(t, "ThreadCount", func(t *testing.T, _ spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("is invalid less than 0", func() { 33 | t := flags.ThreadCount(-1) 34 | 35 | g.Expect(t.Validate()).NotTo(Succeed()) 36 | }) 37 | 38 | it("is invalid at 0", func() { 39 | t := flags.ThreadCount(0) 40 | 41 | g.Expect(t.Validate()).NotTo(Succeed()) 42 | }) 43 | 44 | it("is valid more than 0", func() { 45 | t := flags.ThreadCount(1) 46 | 47 | g.Expect(t.Validate()).To(Succeed()) 48 | }) 49 | 50 | it("parses value", func() { 51 | var t flags.ThreadCount 52 | 53 | g.Expect(t.Set("1")).To(Succeed()) 54 | g.Expect(t).To(Equal(flags.ThreadCount(1))) 55 | }) 56 | }) 57 | } 58 | -------------------------------------------------------------------------------- /flags/total_memory.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 23 | ) 24 | 25 | const ( 26 | DefaultTotalMemory = TotalMemory(0) 27 | FlagTotalMemory = "total-memory" 28 | ) 29 | 30 | const min = memory.Size(1024) 31 | 32 | type TotalMemory memory.Size 33 | 34 | func (t *TotalMemory) Set(s string) error { 35 | m, err := memory.ParseSize(s) 36 | if err != nil { 37 | return err 38 | } 39 | 40 | *t = TotalMemory(m) 41 | return nil 42 | } 43 | 44 | func (t *TotalMemory) String() string { 45 | return memory.Size(*t).String() 46 | } 47 | 48 | func (t *TotalMemory) Type() string { 49 | return "int64" 50 | } 51 | 52 | func (t *TotalMemory) Validate() error { 53 | if *t == 0 { 54 | return fmt.Errorf("--%s must be specified", FlagTotalMemory) 55 | } 56 | 57 | if *t < 0 { 58 | return fmt.Errorf("--%s must be positive: %d", FlagTotalMemory, *t) 59 | } 60 | 61 | if memory.Size(*t) < min { 62 | return fmt.Errorf("--%s must be greater than %d: %d", FlagTotalMemory, min, *t) 63 | } 64 | 65 | return nil 66 | } 67 | -------------------------------------------------------------------------------- /flags/total_memory_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/flags" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestTotalMemory(t *testing.T) { 28 | spec.Run(t, "TotalMemory", func(t *testing.T, _ spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("is invalid less than 0", func() { 33 | t := flags.TotalMemory(-1) 34 | 35 | g.Expect(t.Validate()).NotTo(Succeed()) 36 | }) 37 | 38 | it("is invalid at 0", func() { 39 | t := flags.TotalMemory(0) 40 | 41 | g.Expect(t.Validate()).NotTo(Succeed()) 42 | }) 43 | 44 | it("is invalid less than 1K", func() { 45 | t := flags.TotalMemory(1023) 46 | 47 | g.Expect(t.Validate()).NotTo(Succeed()) 48 | }) 49 | 50 | it("is valid more than 1K", func() { 51 | t := flags.TotalMemory(1024) 52 | 53 | g.Expect(t.Validate()).To(Succeed()) 54 | }) 55 | 56 | it("parses value", func() { 57 | var t flags.TotalMemory 58 | 59 | g.Expect(t.Set("1K")).To(Succeed()) 60 | g.Expect(t).To(Equal(flags.TotalMemory(1024))) 61 | }) 62 | }) 63 | } 64 | -------------------------------------------------------------------------------- /flags/validatable.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package flags 18 | 19 | type Validatable interface { 20 | Validate() error 21 | } 22 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/cloudfoundry/java-buildpack-memory-calculator/v4 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/onsi/gomega v1.10.1 7 | github.com/sclevine/spec v1.4.0 8 | github.com/spf13/pflag v1.0.5 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= 2 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 3 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 4 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= 5 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= 6 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= 7 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= 8 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= 9 | github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= 10 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= 11 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 12 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 13 | github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= 14 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 15 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 16 | github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= 17 | github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= 18 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 19 | github.com/onsi/ginkgo v1.12.1 h1:mFwc4LvZ0xpSvDZ3E+k8Yte0hLOMxXUlP+yXtJqkYfQ= 20 | github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= 21 | github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= 22 | github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= 23 | github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= 24 | github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8= 25 | github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= 26 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 27 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 28 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 29 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 30 | golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7 h1:AeiKBIuRw3UomYXSbLy0Mc2dDLfdtbT/IVn4keq83P0= 31 | golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= 32 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 33 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 34 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 35 | golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 36 | golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 37 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= 38 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 39 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= 40 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 41 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= 42 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 43 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= 44 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= 45 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= 46 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= 47 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= 48 | google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= 49 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 50 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 51 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 52 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 53 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= 54 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 55 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 56 | gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= 57 | gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 58 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "os" 22 | "strings" 23 | 24 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/calculator" 25 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/flags" 26 | flag "github.com/spf13/pflag" 27 | ) 28 | 29 | func main() { 30 | h := flags.DefaultHeadRoom 31 | j := flags.DefaultJVMOptions 32 | l := flags.DefaultLoadedClassCount 33 | t := flags.DefaultThreadCount 34 | m := flags.DefaultTotalMemory 35 | 36 | c := calculator.Calculator{HeadRoom: &h, JvmOptions: &j, LoadedClassCount: &l, ThreadCount: &t, TotalMemory: &m} 37 | 38 | flag.Var(c.HeadRoom, flags.FlagHeadRoom, "percentage of total memory available which will be left unallocated to cover JVM overhead") 39 | flag.Var(c.JvmOptions, flags.FlagJVMOptions, "JVM options, typically JAVA_OPTS") 40 | flag.Var(c.LoadedClassCount, flags.FlagLoadedClassCount, "the number of classes that will be loaded when the application is running") 41 | flag.Var(c.ThreadCount, flags.FlagThreadCount, "the number of user threads") 42 | flag.Var(c.TotalMemory, "total-memory", "total memory available to the application, typically expressed with size classification (B, K, M, G, T)") 43 | flag.Parse() 44 | 45 | if !validate(c.HeadRoom, c.JvmOptions, c.LoadedClassCount, c.ThreadCount, c.TotalMemory) { 46 | _, _ = fmt.Fprintln(os.Stderr, "") 47 | flag.Usage() 48 | os.Exit(1) 49 | } 50 | 51 | o, err := c.Calculate() 52 | if err != nil { 53 | _, _ = fmt.Fprintf(os.Stderr, err.Error()) 54 | os.Exit(2) 55 | } 56 | 57 | s := make([]string, len(o)) 58 | for i, t := range o { 59 | s[i] = t.String() 60 | } 61 | 62 | fmt.Println(output(o)) 63 | } 64 | 65 | func output(o []fmt.Stringer) string { 66 | s := make([]string, len(o)) 67 | 68 | for i, t := range o { 69 | s[i] = t.String() 70 | } 71 | 72 | return strings.Join(s, " ") 73 | } 74 | 75 | func validate(vs ...flags.Validatable) bool { 76 | valid := true 77 | 78 | for _, v := range vs { 79 | if err := v.Validate(); err != nil { 80 | _, _ = fmt.Fprintln(os.Stderr, err) 81 | valid = false 82 | } 83 | } 84 | 85 | return valid 86 | } 87 | -------------------------------------------------------------------------------- /memory/max_direct_memory.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory 18 | 19 | import ( 20 | "fmt" 21 | "regexp" 22 | "strings" 23 | ) 24 | 25 | const DefaultMaxDirectMemory = MaxDirectMemory(10 * Mibi) 26 | 27 | var maxDirectMemoryRE = regexp.MustCompile(fmt.Sprintf("^-XX:MaxDirectMemorySize=(%s)$", sizePattern)) 28 | 29 | type MaxDirectMemory Size 30 | 31 | func IsMaxDirectMemory(s string) bool { 32 | return maxDirectMemoryRE.MatchString(strings.TrimSpace(s)) 33 | } 34 | 35 | func ParseMaxDirectMemory(s string) (MaxDirectMemory, error) { 36 | t := strings.TrimSpace(s) 37 | 38 | if !maxDirectMemoryRE.MatchString(t) { 39 | return MaxDirectMemory(0), fmt.Errorf("max direct memory does not match pattern '%s': %s", maxDirectMemoryRE.String(), t) 40 | } 41 | 42 | groups := maxDirectMemoryRE.FindStringSubmatch(t) 43 | size, err := ParseSize(groups[1]) 44 | if err != nil { 45 | return MaxDirectMemory(0), err 46 | } 47 | 48 | return MaxDirectMemory(size), nil 49 | } 50 | 51 | func (m MaxDirectMemory) String() string { 52 | return fmt.Sprintf("-XX:MaxDirectMemorySize=%s", Size(m)) 53 | } 54 | -------------------------------------------------------------------------------- /memory/max_direct_memory_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestMaxDirectMemory(t *testing.T) { 28 | spec.Run(t, "MaxDirectMemory", func(t *testing.T, when spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("formats", func() { 33 | g.Expect(memory.MaxDirectMemory(memory.Kibi).String()).To(Equal("-XX:MaxDirectMemorySize=1K")) 34 | }) 35 | 36 | it("matches -XX:MaxDirectMemorySize", func() { 37 | g.Expect(memory.IsMaxDirectMemory("-XX:MaxDirectMemorySize=1K")).To(BeTrue()) 38 | }) 39 | 40 | it("does not match non -XX:MaxDirectMemorySize", func() { 41 | g.Expect(memory.IsMaxDirectMemory("-Xss1K")).To(BeFalse()) 42 | }) 43 | 44 | it("parses", func() { 45 | g.Expect(memory.ParseMaxDirectMemory("-XX:MaxDirectMemorySize=1K")).To(Equal(memory.MaxDirectMemory(memory.Kibi))) 46 | }) 47 | 48 | }) 49 | } 50 | -------------------------------------------------------------------------------- /memory/max_heap.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory 18 | 19 | import ( 20 | "fmt" 21 | "regexp" 22 | "strings" 23 | ) 24 | 25 | var maxHeapRE = regexp.MustCompile(fmt.Sprintf("^-Xmx(%s)$", sizePattern)) 26 | 27 | type MaxHeap Size 28 | 29 | func IsMaxHeap(s string) bool { 30 | return maxHeapRE.MatchString(strings.TrimSpace(s)) 31 | } 32 | 33 | func ParseMaxHeap(s string) (MaxHeap, error) { 34 | t := strings.TrimSpace(s) 35 | 36 | if !maxHeapRE.MatchString(t) { 37 | return MaxHeap(0), fmt.Errorf("max heap does not match pattern '%s': %s", maxHeapRE.String(), t) 38 | } 39 | 40 | groups := maxHeapRE.FindStringSubmatch(t) 41 | size, err := ParseSize(groups[1]) 42 | if err != nil { 43 | return MaxHeap(0), err 44 | } 45 | 46 | return MaxHeap(size), nil 47 | } 48 | 49 | func (m MaxHeap) String() string { 50 | return fmt.Sprintf("-Xmx%s", Size(m)) 51 | } 52 | -------------------------------------------------------------------------------- /memory/max_heap_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestMaxHeap(t *testing.T) { 28 | spec.Run(t, "MaxHeap", func(t *testing.T, when spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("formats", func() { 33 | g.Expect(memory.MaxHeap(memory.Kibi).String()).To(Equal("-Xmx1K")) 34 | }) 35 | 36 | it("matches -Xmx", func() { 37 | g.Expect(memory.IsMaxHeap("-Xmx1K")).To(BeTrue()) 38 | }) 39 | 40 | it("does not match non -Xmx", func() { 41 | g.Expect(memory.IsMaxHeap("-Xss1K")).To(BeFalse()) 42 | }) 43 | 44 | it("parses", func() { 45 | g.Expect(memory.ParseMaxHeap("-Xmx1K")).To(Equal(memory.MaxHeap(memory.Kibi))) 46 | }) 47 | 48 | }) 49 | } 50 | -------------------------------------------------------------------------------- /memory/max_metaspace.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory 18 | 19 | import ( 20 | "fmt" 21 | "regexp" 22 | "strings" 23 | ) 24 | 25 | var maxMetaspaceRE = regexp.MustCompile(fmt.Sprintf("^-XX:MaxMetaspaceSize=(%s)$", sizePattern)) 26 | 27 | type MaxMetaspace Size 28 | 29 | func IsMaxMetaspace(s string) bool { 30 | return maxMetaspaceRE.MatchString(strings.TrimSpace(s)) 31 | } 32 | 33 | func ParseMaxMetaspace(s string) (MaxMetaspace, error) { 34 | t := strings.TrimSpace(s) 35 | 36 | if !maxMetaspaceRE.MatchString(t) { 37 | return MaxMetaspace(0), fmt.Errorf("max metaspace does not match pattern '%s': %s", maxMetaspaceRE.String(), t) 38 | } 39 | 40 | groups := maxMetaspaceRE.FindStringSubmatch(t) 41 | size, err := ParseSize(groups[1]) 42 | if err != nil { 43 | return MaxMetaspace(0), err 44 | } 45 | 46 | return MaxMetaspace(size), nil 47 | } 48 | 49 | func (m MaxMetaspace) String() string { 50 | return fmt.Sprintf("-XX:MaxMetaspaceSize=%s", Size(m)) 51 | } 52 | -------------------------------------------------------------------------------- /memory/max_metaspace_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestMaxMetaspace(t *testing.T) { 28 | spec.Run(t, "MaxMetaspace", func(t *testing.T, when spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("formats", func() { 33 | g.Expect(memory.MaxMetaspace(memory.Kibi).String()).To(Equal("-XX:MaxMetaspaceSize=1K")) 34 | }) 35 | 36 | it("matches -XX:MaxMetaspaceSize", func() { 37 | g.Expect(memory.IsMaxMetaspace("-XX:MaxMetaspaceSize=1K")).To(BeTrue()) 38 | }) 39 | 40 | it("does not match non -XX:MaxMetaspaceSize", func() { 41 | g.Expect(memory.IsMaxMetaspace("-Xss1K")).To(BeFalse()) 42 | }) 43 | 44 | it("parses", func() { 45 | g.Expect(memory.ParseMaxMetaspace("-XX:MaxMetaspaceSize=1K")).To(Equal(memory.MaxMetaspace(memory.Kibi))) 46 | }) 47 | 48 | }) 49 | } 50 | -------------------------------------------------------------------------------- /memory/reserved_code_cache.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory 18 | 19 | import ( 20 | "fmt" 21 | "regexp" 22 | "strings" 23 | ) 24 | 25 | const DefaultReservedCodeCache = ReservedCodeCache(240 * Mibi) 26 | 27 | var reservedCodeCacheRE = regexp.MustCompile(fmt.Sprintf("^-XX:ReservedCodeCacheSize=(%s)$", sizePattern)) 28 | 29 | type ReservedCodeCache Size 30 | 31 | func IsReservedCodeCache(s string) bool { 32 | return reservedCodeCacheRE.MatchString(strings.TrimSpace(s)) 33 | } 34 | 35 | func ParseReservedCodeCache(s string) (ReservedCodeCache, error) { 36 | t := strings.TrimSpace(s) 37 | 38 | if !reservedCodeCacheRE.MatchString(t) { 39 | return ReservedCodeCache(0), fmt.Errorf("reserved code cache does not match pattern '%s': %s", reservedCodeCacheRE.String(), t) 40 | } 41 | 42 | groups := reservedCodeCacheRE.FindStringSubmatch(t) 43 | size, err := ParseSize(groups[1]) 44 | if err != nil { 45 | return ReservedCodeCache(0), err 46 | } 47 | 48 | return ReservedCodeCache(size), nil 49 | } 50 | 51 | func (r ReservedCodeCache) String() string { 52 | return fmt.Sprintf("-XX:ReservedCodeCacheSize=%s", Size(r)) 53 | } 54 | -------------------------------------------------------------------------------- /memory/reserved_code_cache_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestReservedCodeCache(t *testing.T) { 28 | spec.Run(t, "ReservedCodeCache", func(t *testing.T, when spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("formats", func() { 33 | g.Expect(memory.ReservedCodeCache(memory.Kibi).String()).To(Equal("-XX:ReservedCodeCacheSize=1K")) 34 | }) 35 | 36 | it("matches -XX:ReservedCodeCacheSize", func() { 37 | g.Expect(memory.IsReservedCodeCache("-XX:ReservedCodeCacheSize=1K")).To(BeTrue()) 38 | }) 39 | 40 | it("does not match non -XX:ReservedCodeCacheSize", func() { 41 | g.Expect(memory.IsReservedCodeCache("-Xss1K")).To(BeFalse()) 42 | }) 43 | 44 | it("parses", func() { 45 | g.Expect(memory.ParseReservedCodeCache("-XX:ReservedCodeCacheSize=1K")).To(Equal(memory.ReservedCodeCache(memory.Kibi))) 46 | }) 47 | 48 | }) 49 | } 50 | -------------------------------------------------------------------------------- /memory/size.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory 18 | 19 | import ( 20 | "fmt" 21 | "regexp" 22 | "strconv" 23 | "strings" 24 | ) 25 | 26 | const ( 27 | Kibi = 1024 28 | Mibi = 1024 * Kibi 29 | Gibi = 1024 * Mibi 30 | Tibi = 1024 * Gibi 31 | ) 32 | 33 | const sizePattern = "[\\d]+[bkmgtBKMGT]?" 34 | 35 | var sizeRE = regexp.MustCompile("^([\\d]+)([bkmgtBKMGT]?)$") 36 | 37 | type Size int64 38 | 39 | func ParseSize(s string) (Size, error) { 40 | t := strings.TrimSpace(s) 41 | 42 | if !sizeRE.MatchString(t) { 43 | return Size(0), fmt.Errorf("memory size does not match pattern '%s': %s", sizeRE.String(), t) 44 | } 45 | 46 | groups := sizeRE.FindStringSubmatch(t) 47 | size, err := strconv.ParseInt(groups[1], 10, 64) 48 | if err != nil { 49 | return Size(0), fmt.Errorf("memory size is not an integer: %s", groups[1]) 50 | } 51 | 52 | switch strings.ToLower(groups[2]) { 53 | case "k": 54 | size *= Kibi 55 | case "m": 56 | size *= Mibi 57 | case "g": 58 | size *= Gibi 59 | case "t": 60 | size *= Tibi 61 | } 62 | 63 | return Size(size), nil 64 | } 65 | 66 | func (s Size) String() string { 67 | b := int64(s) / Kibi 68 | 69 | if b == 0 { 70 | return "0" 71 | } 72 | 73 | if b%Gibi == 0 { 74 | return fmt.Sprintf("%dT", b/Gibi) 75 | } 76 | 77 | if b%Mibi == 0 { 78 | return fmt.Sprintf("%dG", b/Mibi) 79 | } 80 | 81 | if b%Kibi == 0 { 82 | return fmt.Sprintf("%dM", b/Kibi) 83 | } 84 | 85 | return fmt.Sprintf("%dK", b) 86 | } 87 | -------------------------------------------------------------------------------- /memory/size_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestMemorySize(t *testing.T) { 28 | spec.Run(t, "Size", func(t *testing.T, when spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | when("format", func() { 33 | 34 | it("formats bytes", func() { 35 | g.Expect(memory.Size(1023).String()).To(Equal("0")) 36 | }) 37 | 38 | it("formats Kibi", func() { 39 | g.Expect(memory.Size(memory.Kibi + 1023).String()).To(Equal("1K")) 40 | }) 41 | 42 | it("formats Mibi", func() { 43 | g.Expect(memory.Size(memory.Mibi + 1023).String()).To(Equal("1M")) 44 | }) 45 | 46 | it("formats Gibi", func() { 47 | g.Expect(memory.Size(memory.Gibi + 1023).String()).To(Equal("1G")) 48 | }) 49 | 50 | it("formats Tibi", func() { 51 | g.Expect(memory.Size(memory.Tibi + 1023).String()).To(Equal("1T")) 52 | }) 53 | 54 | it("formats larger than Tibi", func() { 55 | g.Expect(memory.Size((memory.Tibi * 1024) + 1023).String()).To(Equal("1024T")) 56 | }) 57 | }) 58 | 59 | when("parse", func() { 60 | 61 | it("parses bytes", func() { 62 | g.Expect(memory.ParseSize("1")).To(Equal(memory.Size(1))) 63 | g.Expect(memory.ParseSize("1b")).To(Equal(memory.Size(1))) 64 | }) 65 | 66 | it("parses Kibi", func() { 67 | g.Expect(memory.ParseSize("1k")).To(Equal(memory.Size(memory.Kibi))) 68 | g.Expect(memory.ParseSize("1K")).To(Equal(memory.Size(memory.Kibi))) 69 | }) 70 | 71 | it("parses Mibi", func() { 72 | g.Expect(memory.ParseSize("1m")).To(Equal(memory.Size(memory.Mibi))) 73 | g.Expect(memory.ParseSize("1M")).To(Equal(memory.Size(memory.Mibi))) 74 | }) 75 | 76 | it("parses Gibi", func() { 77 | g.Expect(memory.ParseSize("1g")).To(Equal(memory.Size(memory.Gibi))) 78 | g.Expect(memory.ParseSize("1G")).To(Equal(memory.Size(memory.Gibi))) 79 | }) 80 | 81 | it("parses Tibi", func() { 82 | g.Expect(memory.ParseSize("1t")).To(Equal(memory.Size(memory.Tibi))) 83 | g.Expect(memory.ParseSize("1T")).To(Equal(memory.Size(memory.Tibi))) 84 | }) 85 | 86 | it("parses zero", func() { 87 | g.Expect(memory.ParseSize("0")).To(Equal(memory.Size(0))) 88 | }) 89 | 90 | it("trims whitespace", func() { 91 | g.Expect(memory.ParseSize("\t\r\n 1")).To(Equal(memory.Size(1))) 92 | g.Expect(memory.ParseSize("1 \t\r\n")).To(Equal(memory.Size(1))) 93 | }) 94 | 95 | it("does not parse empty value", func() { 96 | _, err := memory.ParseSize("") 97 | g.Expect(err).To(HaveOccurred()) 98 | }) 99 | 100 | it("does not parse negative value", func() { 101 | _, err := memory.ParseSize("-1") 102 | g.Expect(err).To(HaveOccurred()) 103 | }) 104 | 105 | it("does not parse unknown units", func() { 106 | _, err := memory.ParseSize("1A") 107 | g.Expect(err).To(HaveOccurred()) 108 | }) 109 | 110 | it("does not parse non-decimal value", func() { 111 | _, err := memory.ParseSize("0x1") 112 | g.Expect(err).To(HaveOccurred()) 113 | }) 114 | 115 | it("does not parse non-integral value", func() { 116 | _, err := memory.ParseSize("1.0") 117 | g.Expect(err).To(HaveOccurred()) 118 | }) 119 | 120 | it("does not parse embedded whitespace", func() { 121 | _, err := memory.ParseSize("1 0") 122 | g.Expect(err).To(HaveOccurred()) 123 | }) 124 | }) 125 | }) 126 | } 127 | -------------------------------------------------------------------------------- /memory/stack.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory 18 | 19 | import ( 20 | "fmt" 21 | "regexp" 22 | "strings" 23 | ) 24 | 25 | const DefaultStack = Stack(Mibi) 26 | 27 | var stackRE = regexp.MustCompile(fmt.Sprintf("^-Xss(%s)$", sizePattern)) 28 | 29 | type Stack Size 30 | 31 | func IsStack(s string) bool { 32 | return stackRE.MatchString(strings.TrimSpace(s)) 33 | } 34 | 35 | func ParseStack(s string) (Stack, error) { 36 | t := strings.TrimSpace(s) 37 | 38 | if !stackRE.MatchString(t) { 39 | return Stack(0), fmt.Errorf("stack size does not match pattern '%s': %s", stackRE.String(), t) 40 | } 41 | 42 | groups := stackRE.FindStringSubmatch(t) 43 | size, err := ParseSize(groups[1]) 44 | if err != nil { 45 | return Stack(0), err 46 | } 47 | 48 | return Stack(size), nil 49 | } 50 | 51 | func (s Stack) String() string { 52 | return fmt.Sprintf("-Xss%s", Size(s)) 53 | } 54 | -------------------------------------------------------------------------------- /memory/stack_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015-2019 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package memory_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/cloudfoundry/java-buildpack-memory-calculator/v4/memory" 23 | . "github.com/onsi/gomega" 24 | "github.com/sclevine/spec" 25 | ) 26 | 27 | func TestStack(t *testing.T) { 28 | spec.Run(t, "Stack", func(t *testing.T, when spec.G, it spec.S) { 29 | 30 | g := NewGomegaWithT(t) 31 | 32 | it("formats", func() { 33 | g.Expect(memory.Stack(memory.Kibi).String()).To(Equal("-Xss1K")) 34 | }) 35 | 36 | it("matches -Xss", func() { 37 | g.Expect(memory.IsStack("-Xss1K")).To(BeTrue()) 38 | }) 39 | 40 | it("does not match non -Xss", func() { 41 | g.Expect(memory.IsStack("-Xmx1K")).To(BeFalse()) 42 | }) 43 | 44 | it("parses", func() { 45 | g.Expect(memory.ParseStack("-Xss1K")).To(Equal(memory.Stack(memory.Kibi))) 46 | }) 47 | 48 | }) 49 | } 50 | --------------------------------------------------------------------------------