Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/IMPLEMENTING_JRES.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ export PATH=$JAVA_HOME/bin:$PATH
Downloads `java-buildpack-memory-calculator` binary. At application start it computes JVM heap/metaspace/stack settings from `$MEMORY_LIMIT`:

```
-Xmx512M -Xms512M -XX:MaxMetaspaceSize=128M -Xss1M -XX:ReservedCodeCacheSize=32M
-Xmx512M -XX:MaxMetaspaceSize=128M -Xss1M -XX:ReservedCodeCacheSize=32M
```

User customization — prefer `JBP_CONFIG_<JRE>_JRE` for structured config (covers all three knobs):
Expand All @@ -293,8 +293,9 @@ cf set-env myapp JBP_CONFIG_OPEN_JDK_JRE \
`stack_threads` — number of user threads (default: 250); affects `-Xss` heap budget.
`class_count` — estimated loaded classes (default: auto-detected); affects `-XX:MaxMetaspaceSize`.
`headroom` — percent of total memory to leave unallocated (default: 0).
`xms_equals_xmx` — experimental: set `-Xms` equal to the maximum heap (default: false). Not available as a `MEMORY_CALCULATOR_*` env var.

`MEMORY_CALCULATOR_*` env vars are a simpler alternative, but only cover two of the three knobs. They take precedence over `JBP_CONFIG_*` when both are set:
`MEMORY_CALCULATOR_*` env vars are a simpler alternative, but only cover some of the knobs. They take precedence over `JBP_CONFIG_*` when both are set:

```bash
cf set-env myapp MEMORY_CALCULATOR_STACK_THREADS 300
Expand Down
14 changes: 13 additions & 1 deletion docs/jre-open_jdk_jre.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ The total available memory for the application's container is specified when an
The Java buildpack uses this value to control the JRE's use of various
regions of memory and logs the JRE memory settings when the application starts or restarts.
These settings can be influenced by configuring
the `stack_threads` and/or `class_count` mappings (both part of the `memory_calculator` mapping),
the `stack_threads`, `class_count`, `headroom` and/or `xms_equals_xmx` mappings (all part of the `memory_calculator` mapping),
and/or Java options relating to memory.

Note: If the total available memory is scaled up or down, the Java buildpack will re-calculate the JRE memory settings the next time the application is started.
Expand Down Expand Up @@ -119,6 +119,18 @@ stack_threads: 500

Note that the default value of 250 threads is optimized for a default Tomcat configuration. If you are using another container, especially something non-blocking like Netty, it's more appropriate to use a significantly smaller value. Typically 25 threads would cover the needs of both the server (Netty) and the threads started by the JVM itself.

#### Initial Heap

By default the memory calculator sets only the maximum heap size (`-Xmx`) and the JVM chooses the initial heap size, which grows under load. To set the initial heap size (`-Xms`) equal to the maximum heap size, enable the experimental `xms_equals_xmx` option:

```yaml
xms_equals_xmx: true
```

An explicit `-Xms` in the Java options takes precedence. If an explicit `-Xms` is larger than the maximum heap, the application fails to start with an error from the memory calculator.

Setting the initial heap equal to the maximum heap avoids heap growth, but increases the initially committed memory and can affect memory-based autoscaling. Compare latency, GC pauses, CPU and container memory under a representative workload before enabling it in production.

#### Java Options

If the JRE memory settings need to be fine-tuned, the user can set one or more Java memory options to
Expand Down
56 changes: 56 additions & 0 deletions src/integration/spring_boot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io"
"net/http"
"strings"
"testing"

"github.com/cloudfoundry/switchblade"
Expand All @@ -13,6 +14,26 @@ import (
. "github.com/onsi/gomega"
)

type heapOptions struct {
Xms string
Xmx string
}

func heapOptionsOf(inputArguments string) heapOptions {
var heap heapOptions
for _, argument := range strings.FieldsFunc(inputArguments, func(r rune) bool {
return r == '"' || r == ',' || r == '[' || r == ']' || r == ' ' || r == '\n'
}) {
if value, found := strings.CutPrefix(argument, "-Xms"); found {
heap.Xms = value
}
if value, found := strings.CutPrefix(argument, "-Xmx"); found {
heap.Xmx = value
}
}
return heap
}

func testSpringBoot(platform switchblade.Platform, fixtures string, sb3JarPath, sb4JarPath string) func(*testing.T, spec.G, spec.S) {
return func(t *testing.T, context spec.G, it spec.S) {
var (
Expand Down Expand Up @@ -77,6 +98,41 @@ func testSpringBoot(platform switchblade.Platform, fixtures string, sb3JarPath,
})
})

// https://github.com/cloudfoundry/java-buildpack/issues/1377
context("with the memory calculator", func() {
it("sets the initial heap equal to the maximum heap when xms_equals_xmx is true", func() {
deployment, logs, err := platform.Deploy.
WithEnv(map[string]string{
"BP_JAVA_VERSION": defaultJavaVersion,
"JBP_CONFIG_OPEN_JDK_JRE": "{ memory_calculator: { xms_equals_xmx: true } }",
}).
Execute(name, requireJar(t, sb4JarPath))
Expect(err).NotTo(HaveOccurred(), logs.String)

Eventually(deployment).Should(matchers.Serve(
WithTransform(heapOptionsOf, Satisfy(func(heap heapOptions) bool {
return heap.Xmx != "" && heap.Xms == heap.Xmx
})),
).WithEndpoint("/input-arguments"))
})

it("does not set an initial heap by default", func() {
deployment, logs, err := platform.Deploy.
WithEnv(map[string]string{
"BP_JAVA_VERSION": defaultJavaVersion,
}).
Execute(name, requireJar(t, sb4JarPath))
Expect(err).NotTo(HaveOccurred(), logs.String)

Eventually(deployment).Should(matchers.Serve(
WithTransform(heapOptionsOf, And(
HaveField("Xmx", Not(BeEmpty())),
HaveField("Xms", BeEmpty()),
)),
).WithEndpoint("/input-arguments"))
})
})

context("with JAVA_OPTS configuration", func() {
it("applies configured JAVA_OPTS with from_environment=false and verifies at runtime", func() {
deployment, logs, err := platform.Deploy.
Expand Down
10 changes: 10 additions & 0 deletions src/java/jres/memory_calculator.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type MemoryCalculator struct {
classCount int
stackThreads int
headroom int
xmsEqualsXmx bool
configLoaded bool
classCountUserSet bool
stackThreadsUserSet bool
Expand Down Expand Up @@ -124,6 +125,9 @@ func (m *MemoryCalculator) Supply() error {

m.ctx.Log.Info("Memory Calculator installed: Loaded Classes: %s, Threads: %s, Headroom: %s",
m.classCountDisplay(), m.stackThreadsDisplay(), m.headroomDisplay())
if m.xmsEqualsXmx {
m.ctx.Log.Info("Memory Calculator: initial heap (-Xms) equals maximum heap (-Xmx)")
}

// Clean up temp directory
os.RemoveAll(tempDir)
Expand Down Expand Up @@ -296,6 +300,10 @@ func (m *MemoryCalculator) GetCalculatorCommand() string {
classCount = int(float64(DefaultClassCount) * 0.35) // Apply same 35% factor
}

if m.xmsEqualsXmx {
args = append(args, "--xms-equals-xmx")
}

args = append(args,
fmt.Sprintf("--loaded-class-count=%d", classCount),
fmt.Sprintf("--thread-count=%d", m.stackThreads),
Expand Down Expand Up @@ -330,6 +338,7 @@ type memoryCalculatorConfig struct {
StackThreads int `yaml:"stack_threads"`
ClassCount int `yaml:"class_count"`
Headroom int `yaml:"headroom"`
XmsEqualsXmx bool `yaml:"xms_equals_xmx"`
}

// LoadConfig loads memory calculator configuration from the JRE-specific env var
Expand Down Expand Up @@ -383,6 +392,7 @@ func (m *MemoryCalculator) LoadConfig() {
m.headroom = mc.Headroom
m.headroomUserSet = true
}
m.xmsEqualsXmx = mc.XmsEqualsXmx
}
}

Expand Down
61 changes: 61 additions & 0 deletions src/java/jres/memory_calculator_issues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,4 +280,65 @@ var _ = Describe("Memory Calculator Issues", func() {
"MALLOC_ARENA_MAX must be exported to reach the exec-ed JVM.\nCommand:\n%s", cmd)
})
})

// -------------------------------------------------------------------------
// https://github.com/cloudfoundry/java-buildpack/issues/1377
// Opt-in memory_calculator.xms_equals_xmx forwards --xms-equals-xmx to the calculator.
// Calculator versions before the one that introduced the flag exit with
// "unknown flag", so the flag must only be passed when the user opts in.
// -------------------------------------------------------------------------
Describe("#1377: xms_equals_xmx", func() {
commandFor := func(jreName string) string {
fakeBinary("4.2.0")
mc := jres.NewMemoryCalculator(ctx, jreDir, "17.0.9", 17, jreName)
Expect(mc.Finalize()).To(Succeed())
return mc.GetCalculatorCommand()
}

It("does not pass --xms-equals-xmx by default", func() {
Expect(commandFor("openjdk")).NotTo(ContainSubstring("xms-equals-xmx"))
})

It("passes --xms-equals-xmx when JBP_CONFIG_OPEN_JDK_JRE sets xms_equals_xmx: true", func() {
DeferCleanup(os.Unsetenv, "JBP_CONFIG_OPEN_JDK_JRE")
Expect(os.Setenv("JBP_CONFIG_OPEN_JDK_JRE", "{ memory_calculator: { xms_equals_xmx: true } }")).To(Succeed())

Expect(commandFor("openjdk")).To(ContainSubstring("--xms-equals-xmx"))
})

It("does not pass --xms-equals-xmx when xms_equals_xmx: false", func() {
DeferCleanup(os.Unsetenv, "JBP_CONFIG_OPEN_JDK_JRE")
Expect(os.Setenv("JBP_CONFIG_OPEN_JDK_JRE", "{ memory_calculator: { xms_equals_xmx: false } }")).To(Succeed())

Expect(commandFor("openjdk")).NotTo(ContainSubstring("xms-equals-xmx"))
})

It("passes --xms-equals-xmx for another JRE through its own JBP_CONFIG variable", func() {
DeferCleanup(os.Unsetenv, "JBP_CONFIG_ZULU_JRE")
Expect(os.Setenv("JBP_CONFIG_ZULU_JRE", "{ memory_calculator: { xms_equals_xmx: true } }")).To(Succeed())

Expect(commandFor("zulu")).To(ContainSubstring("--xms-equals-xmx"))
})

It("passes the flag together with the other memory_calculator settings", func() {
DeferCleanup(os.Unsetenv, "JBP_CONFIG_OPEN_JDK_JRE")
Expect(os.Setenv("JBP_CONFIG_OPEN_JDK_JRE",
"{ memory_calculator: { xms_equals_xmx: true, headroom: 5, stack_threads: 50 } }")).To(Succeed())

cmd := commandFor("openjdk")

Expect(cmd).To(ContainSubstring("--xms-equals-xmx"))
Expect(cmd).To(ContainSubstring("--head-room=5"))
Expect(cmd).To(ContainSubstring("--thread-count=50"))
})

It("accepts xms_equals_xmx without an unknown-field WARNING", func() {
DeferCleanup(os.Unsetenv, "JBP_CONFIG_OPEN_JDK_JRE")
Expect(os.Setenv("JBP_CONFIG_OPEN_JDK_JRE", "{ memory_calculator: { xms_equals_xmx: true } }")).To(Succeed())

commandFor("openjdk")

Expect(logBuffer.String()).NotTo(ContainSubstring("WARNING"))
})
})
})