A simple Go program for launching processes from a fixed configuration. This program replaces Gradle-generated Bash
launch scripts which are susceptible to attacks via injection of environment variables of the form JAVA_OPTS='$(rm -rf /)'.
The launcher accepts as configuration two YAML files as follows:
# StaticLauncherConfig - java version
# REQUIRED - The type of configuration, must be the string "java"
configType: java
# REQUIRED - The version of the configuration format, must be the integer 1
configVersion: 1
# REQUIRED - The name of the service, must match [a-z0-9-]+ and not be the name of a subProcess
serviceName: my-service
# REQUIRED - The main class to be run
mainClass: my.package.Main
# OPTIONAL - Path to the JRE or environment variable name (e.g. $JAVA_11_HOME). Defaults to the JAVA_HOME environment variable if unset,
# or if the specified environment variable is not set at runtime.
javaHome: /opt/palantir/jdk8/Contents/Home
# REQUIRED - The classpath entries; the final classpath is the ':'-concatenated list in the given order
classpath:
- ./foo.jar
# OPTIONAL - Environment Variables to be set in the environment (Note: cannot be referenced on args list)
env:
CUSTOM_VAR: CUSTOM_VALUE
# OPTIONAL - JVM options to be passed to the java command
jvmOpts:
- '-Xmx1g'
# OPTIONAL - Arguments passed to the main method of the main class
args:
- arg1
# OPTIONAL - A list of directories to be created before executing the command. Must be relative to CWD and over [A-Za-z0-9].
dirs:
- var/data/tmp
- var/log
# OPTIONAL - A map of configurations of subProcesses to launch
subProcesses:
SUB_PROCESS_NAME:
# another StaticLauncherConfig though it cannot have its own subProcesses, and uses its parent's configVersion
configType: executable
env:
CUSTOM_VAR: CUSTOM_VALUE
executable: "{{CWD}}/service/lib/envoy/envoy"
dirs:
- var/data/tmp
- var/log# StaticLauncherConfig - executable version
# REQUIRED - The type of configuration, must be the string "executable"
configType: executable
# REQUIRED - The version of the configuration format, must be the integer 1
configVersion: 1
# REQUIRED - The name of the service, must match [a-z0-9-]+ and not be the name of a subProcess
serviceName: my-service
# OPTIONAL - Environment Variables to be set in the environment (Note: cannot be referenced on args list)
env:
CUSTOM_VAR: CUSTOM_VALUE
# REQUIRED - The full path to the executable file, limited to whitelisted values (java, postgres, influxd, grafana-server)
executable: "{{CWD}}/service/bin/postgres"
# OPTIONAL - Arguments passed to the main method of the excutable or main class
args:
- arg1
# OPTIONAL - A list of directories to be created before executing the command. Must be relative to CWD and over [A-Za-z0-9].
dirs:
- var/data/tmp
- var/log
# OPTIONAL - A map of configurations of secondary processes to launch
subProcesses:
SUB_PROCESS_NAME:
# another StaticLauncherConfig though it cannot have its own subProcesses, and uses its parent's configVersion
configType: executable
env:
CUSTOM_VAR: CUSTOM_VALUE
executable: "{{CWD}}/service/lib/envoy/envoy"
dirs:
- var/data/tmp
- var/log# CustomLauncherConfig
# REQUIRED - The type of configuration, must be the string "java" or "executable"
configType: java
# REQUIRED - The version of the configuration format, must be the integer 1
configVersion: 1
# OPTIONAL - Environment Variables to be set in the environment, will override defaults in static config (Note: cannot be referenced on args list)
env:
CUSTOM_VAR: CUSTOM_VALUE
CUSTOM_PATH: '{{CWD}}/some/path'
# Additional JVM options to be passed to the java command. Ignored if configType is "executable"
jvmOpts:
- '-Xmx2g'
# OPTIONAL - A map of configurations of secondary processes to launch
subProcess:
SUB_PROCESS_NAME:
# another CustomLauncherConfig though it cannot have its own subProcesses, and uses its parent's configVersion
configType: executable
env:
CUSTOM_VAR: CUSTOM_VALUEThe launcher is invoked as:
go-java-launcher [<path to StaticLauncherConfig> [<path to CustomLauncherConfig>]]
where the static configuration file defaults to ./launcher-static.yml and the custom configuration file defaults to
./launcher-custom.yml. It assembles the configuration options and executes the following command (where <static.xyz>
and <custom.xyz> refer to the options from the two configuration files, respectively):
<javaHome>/bin/java \
<static.jvmOpts> \
<custom.jvmOpts> \
<computed container options> \
-classpath <classpath entries> \
<static.mainClass> \
<static.args>
Note that the custom jvmOpts appear after the static jvmOpts and thus typically take precedence; the exact
behaviour may depend on the Java distribution. When running in a container, some heap options are filtered out of
both and replaced by <computed container options>, see Java heap and container support.
If any subProcesses are defined, they will be launched as child processes of the main process, with all of these processes occupying their own process group. Additionally, a monitor subProcess will be launched, which terminates the group, should the main process die.
env block, both in static and custom configuration, supports restricted set of automatic expansions for values
assigned to environment variables. Variables are expanded if they are surrounded with {{ and }} as shown above
for CUSTOM_PATH. The following fixed expansions are supported:
{{CWD}}: The current working directory of the user which executed this process
Expansions are only performed on the values. No expansions are performed on the keys. Note that the JAVA_HOME
environment cannot be overwritten with this mechanism; use the javaHome mechanism in StaticLauncherConfig instead.
All output from go-java-launcher itself, and from the launch of all processes themselves is directed to stdout.
When starting a java process inside a container (as indicated by the presence of CONTAINER env
variable):
- Args with prefix
-Xmx|-Xmsin both static and custom jvm opts will be filtered out. - If neither
-XX:MaxRAMPercentage=nor-XX:InitialRAMPercentage=prefixes are present in either static or custom jvm opts,-Xmx|-Xmswill both be set to be 75% of the cgroups memory limit minus 3mb per processor, with a minimum value of 50% of the cgroups memory limit. - If the cgroups memory limit cannot be read (including when it is unlimited), or is unusually high (over 1,000,000
MiB, roughly 1TB), the launcher instead sets both
-XX:InitialRAMPercentage=and-XX:MaxRAMPercentage=to 75% (orheapPercentage, see below), unless either is already present. The JVM then discovers theMaxRAMvalue using Linux cgroups, and calculates the heap sizes as that percentage of it, e.g.max-heap-size = MaxRAM * MaxRAMPercentage.
To override the heap percentage, developers can set heapPercentage in launcher-custom.yml. This will use the cgroups memory limit to calculate the -Xmx|-Xms values, without the per processor adjustment. Setting -Xmx and -Xms to the same value ensures the heap will never shrink (unless allowHeapShrink is set, see below).
Alternatively, developers can override the heap percentage in containers by specifying both -XX:MaxRAMPercentage= and -XX:InitialRAMPercentage= and we recommend setting both to the same value. Note that setting -XX:MaxRAMPercentage= and -XX:InitialRAMPercentage= to the same value does not prevent the heap from shrinking.
If either -XX:MaxRAMPercentage= or -XX:InitialRAMPercentage= are set, heapPercentage will be ignored.
Developers can specify both MaxRAMPercentage|InitialRAMPercentage together with -Xmx|-Xms overrides
safely: when running inside a container, -Xmx|-Xms are always filtered out as per logic detailed above, so the
RAM percentage options take effect. Outside of a container, or with container support disabled, the options are
passed through unchanged.
By default, the cgroup-based heap sizing sets -Xms equal to -Xmx so the heap is fixed and never shrinks. To
instead let the JVM start with a small heap and grow or shrink it on demand, set allowHeapShrink in
launcher-custom.yml. The optional heap free ratios tune when the heap expands or shrinks:
configType: java
...
allowHeapShrink: true
minHeapFreeRatio: 20
maxHeapFreeRatio: 40When enabled, the launcher omits the generated -Xms flag (only -Xmx is set) and strips any
-XX:+AlwaysPreTouch from the JVM options. Each ratio is an integer in [0, 100] and independently replaces only
the matching jvmOpts entries, allowing installation-level ratio overrides without replacing product-level
jvmOpts. The JVM defaults are 40 for minimum and 70 for maximum. When both dedicated settings are present, the
launcher requires minHeapFreeRatio <= maxHeapFreeRatio; the JVM validates pairs that mix a dedicated setting with
jvmOpts.
These settings apply whenever the launcher can read the cgroups memory limit in a container, including when
-XX:MaxRAMPercentage= or -XX:InitialRAMPercentage= are set. They have no effect outside a container (no
CONTAINER env variable), when container support is disabled, when a -XX:MaxRAM= override is present, or when
the launcher falls back to percentage-based heap sizing because the limit can't be read or is unusually high.
This experimental option limits the number of parallel GC threads when G1 is explicitly enabled, based on
the number of available cores and the cgroup cpu.shares or cpu.weight. Available cores are capped
by both CPU affinity and the CPU quota, matching the JVM's container-aware default. This can reduce
unnecessarily large numbers of GC threads without exceeding that default.
experimental:
limitGcThreads: true
This can also be set with the envvar LAUNCHER_EXPERIMENTAL_LIMIT_GC_THREADS. A non-empty value overrides this
setting; an empty value is ignored.
It uses the sizing formula:
available_cores = min(host_cores, ceil(quota / period)) # host_cores if quota is unlimited
adjusted_cores = min(floor(requested_cores * 8), available_cores)
parallel_threads = adjusted_cores if adjusted_cores < 8 else 8 + ((adjusted_cores - 8) * 5 / 8)
The number of threads is also capped for smaller max heap sizes using a formula similar to the internal JVM default.
parallel_threads = min(parallel_threads, max(2, heap_bytes / 43620760))
In situations where memory percentages are used or memory arguments are omitted, this cap is not applied.
For G1 GC, concurrent GC threads are set to 1/4 the number of parallel threads by default.
The launcher does not set ConcGCThreads or validate explicit thread counts.
This only applies in JVM container mode (CONTAINER set), with container support enabled and no
-XX:MaxRAM=, -XX:ActiveProcessorCount=, -XX:ParallelGCThreads=, or -XX:ConcGCThreads= override.
An explicit parallel or concurrent GC thread count makes limitGcThreads inert: both CPU-based sizing
and the heap-based thread cap are skipped, leaving the supplied options unchanged.
Warning
This is experimental and may be either removed or promoted in the future.
glibc malloc keeps memory freed by the JVM (from JIT compilation, class loading, NIO, and other native allocations)
in its arenas rather than returning it to the OS, so a container's RSS can stay well above what the JVM is using. To
have the JVM periodically call malloc_trim via -XX:TrimNativeHeapInterval, set:
experimental:
trimNativeHeap: trueThis can also be set with the envvar LAUNCHER_EXPERIMENTAL_TRIM_NATIVE_HEAP. A non-empty value overrides this
setting; an empty value is ignored.
The trim runs every 5 seconds by default. To change the interval, set trimNativeHeapIntervalSeconds to a whole
number of seconds between 1 and 4294967:
experimental:
trimNativeHeap: true
trimNativeHeapIntervalSeconds: 15Shorter intervals keep peak RSS lower, especially during startup when class loading and JIT compilation allocate
heavily. Each trim briefly locks the malloc arena being trimmed, though, so a longer interval can help
latency-sensitive services. The interval has no effect unless trimNativeHeap is enabled.
The flag is only added when the cgroup CPU request (cpu.shares on cgroup v1, cpu.weight on cgroup v2,
converted to whole cores the same way as limitGcThreads) is at most 4 cores and the max heap chosen by the launcher
is at most 8 GiB. The savings are a roughly fixed amount per JVM, so they only matter relative to small containers. It
is also skipped if -XX:TrimNativeHeapInterval= is already in the JVM options.
The launcher doesn't check the Java version. The flag needs Java 17.0.12+, 21.0.3+ or 22.0.1+; earlier updates either lack it or declare it experimental, which fails startup.
This setting only takes effect in the cgroup-based heap sizing path.
This experimental option sets glibc.malloc.mmap_threshold=131072 in GLIBC_TUNABLES for small services.
experimental:
pinMallocMmapThreshold: true
This can also be set with the envvar LAUNCHER_EXPERIMENTAL_PIN_MALLOC_MMAP_THRESHOLD. A non-empty value overrides
this setting; an empty value is ignored.
glibc serves allocations at or above its mmap threshold with their own mmap, which is returned to the OS on
free. By default the threshold starts at 128 KiB but rises to the size of each large mmapped block that is freed
(up to 32 MiB), so later allocations of that size come from the malloc arenas and their memory stays resident after
they are freed. Setting the threshold explicitly turns that off, keeping it at glibc's own 128 KiB default. Each large
allocation then costs an mmap/munmap and fresh page faults, which mostly shows up as slightly more CPU during
startup.
The setting is only added when the cgroup CPU request (cpu.shares on cgroup v1, cpu.weight on cgroup v2) is
at most 200m and the max heap chosen by the launcher is at most 1 GiB. Other GLIBC_TUNABLES values from the
launcher configuration or the environment are kept, and an existing glibc.malloc.mmap_threshold is left
unchanged. It has no effect on musl. This setting only takes effect in the cgroup-based heap sizing path.
This behavior can be disabled by setting the following in launcher-custom.yml:
configType: java
...
dangerousDisableContainerSupport: trueAlternatively, the presence of -XX:MaxRAM= prefix in either static or custom jvm opts will also disable this
behavior.
Warning
Support for native images is experimental and may be either removed or promoted in the future. Use at your own risk.
Go-java-launcher supports running GraalVM Native Images. For example:
experimental:
executionMode: nativeThis requires a native image executable to be available at the path specified by nativeImageExecutablePath, which defaults to service/bin/native-executable.
Not all JVM options are supported by native image, so go-java-launcher will attempt to copy over applicable options from jvmOpts to the native image executable. The list of respected options is in AllowedNativeImageJVMOptions.
To add additional arguments (including native image options) to the native image executable, set nativeImageArguments.
Like Java processes, native images launched by go-java-launcher will also respect the heapPercentage option, which will be used to calculate the heap size of the native image executable.
This repository also publishes a binary called go-init that supports the commands start, status, and stop, in
adherence with the
Linux Standard Base
specification for init scripts. The binary reads configuration from (relative to its working directory)
service/bin/launcher-static.yml and var/conf/launcher-custom.yml in the same vein as go-java-launcher, but instead
outputs its own logging and that of the primary process to var/log/startup.log. Logs on the compilation of a
command used to launch a specific subProcesses, and its subsequent stdout and stderr streams are directed to
var/log/${SUB_PROCESS}-startup.log files. go-init does not launch each subProcess as a child process of the
primary process.
Note that while the specification states that the status command prints the status of the service, the exact wording
used to denote that status is not defined and subsequently subject to change without warning.
When running on windows go-init will not attempt to gracefully shutdown the process, due to signal limitations on detached processes.
This repository is made available under the Apache 2.0 License.