0

I have a java agent that I want to be automatically enabled for any arbitrary java process running on the host.

I cannot rely on aliases or environment variables like PATH, JVM_OPTS etc as I want any JVM process to pick the agent even if run directly as /usr/bin/java -jar my-app.jar.

One (rather dirty) way of doing it is physically replacing java binary with my custom bash script like this:

#!/bin/bash 
$(dirname "$0")/java.original "-javaagent:path/to/my-agent.jar" "$@"

It works, but that approach requires renaming the original java binary file which I would like to avoid doing.

Question: Is there any better way how to achieve the same behavior without touching the java binary? Are there any global Java specific config file where I could instruct Java to always run with the given agent?

Alex Vayda
  • 101
  • 3

1 Answers1

0

There is a JAVA_TOOL_OPTIONS environment variable, that can be set in the /etc/profile.d for all users.

export JAVA_TOOL_OPTIONS=-javaagent:path/to/my-agent.jar

Every java process will then pick it up, regardless the way it is started.

From the official documentation:

This environment variable allows you to specify the initialization of tools, specifically the launching of native or Java programming language agents using the -agentlib or -javaagent options. In the following example the environment variable is set so that the HPROF profiler is launched when the application is started:

$ export JAVA_TOOL_OPTIONS="-agentlib:hprof"

This variable can also be used to augment the command line with other options for diagnostic purposes. For example, you can supply the -XX:OnError option to specify a script or command to be executed when a fatal error occurs.

There is also undocumented _JAVA_OPTIONS variable that takes precedence over the JAVA_TOOL_OPTIONS and the command line arguments, that might be handy in some cases. But because it's deprecated and might not be supported in all Java distributions it's not recommended to use.

Alex Vayda
  • 101
  • 3