Profile a Java application on Amazon EC2
Install the CloudWatch agent and the AWS Distro for OpenTelemetry (ADOT) Java agent on an Amazon EC2 instance, and send continuous profiles from a sample Java application to Amazon CloudWatch Profiles.
When you finish, a sample Java application named example-java-service runs
on an Amazon Linux 2023 instance with the ADOT Java agent. The async-profiler that's embedded in
the ADOT Java agent sends one profile every 60 seconds to the CloudWatch agent on the same
instance. The CloudWatch agent signs each request to the CloudWatch profiles endpoint with AWS
Signature Version 4 (SigV4), using the credentials of the instance role. You then find the
service and its flame graphs in CloudWatch.
Time to complete: About 20 minutes
Cost to complete: There is no charge for Amazon CloudWatch Profiles during the preview. Standard Amazon EC2 charges apply for the instance that you run.
Prerequisites
Before you begin, make sure that you have the following:
-
An Amazon EC2 instance that runs Amazon Linux 2023 on the x86_64 or arm64 architecture, and a user on that instance that can run
sudo. -
An IAM role attached to the instance with the
CloudWatchAgentServerPolicymanaged policy. This policy includes thecloudwatch:PutProfileRecordspermission that the signing identity needs. For more information, see IAM permissions required. For instructions, see Create an IAM role for Amazon EC2 instances and Attach an IAM role to an Amazon EC2 instance. -
Credentials with the
cloudwatch:GetProfileRecordspermission to view the profile data in Step 5: Verify that profiles arrive in CloudWatch. TheCloudWatchAgentServerPolicypolicy doesn't include this permission. For more information, see IAM permissions required.
Step 1: Install and configure the CloudWatch agent
The CloudWatch agent doesn't use a separate configuration key for profiles. When you
configure the otlp source under opentelemetry.collect, the agent
also forwards the profile data that it receives on the same OpenTelemetry Protocol (OTLP)
port. The agent signs each request with the credentials of the instance role.
To install and configure the CloudWatch agent
-
Connect to your instance.
-
Install the CloudWatch agent. Profiles need the CloudWatch agent version 1.300075.0 or later, which is the first release with OTLP profiles support.
sudo dnf install -y amazon-cloudwatch-agentAlternatively, download the agent package from Amazon S3 and install it. On an arm64 instance, replace
amd64witharm64in the URL.curl -sSLO https://amazoncloudwatch-agent.s3.amazonaws.com/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm sudo rpm -U ./amazon-cloudwatch-agent.rpm -
Create the agent configuration file
/opt/aws/amazon-cloudwatch-agent/etc/profiles-getting-started.jsonwith the following content. Replaceregionwith the AWS Region where you want to store the profile data, for example,us-east-1.sudo tee /opt/aws/amazon-cloudwatch-agent/etc/profiles-getting-started.json >/dev/null <<'EOF' { "agent": { "region": "region" }, "opentelemetry": { "collect": { "otlp": { "http_endpoint": "127.0.0.1:4318" } } } } EOFThis configuration makes the agent listen for OTLP data over HTTP on port
4318. The127.0.0.1address accepts data only from processes on the same instance. The ADOT Java agent sends profiles over HTTP, so you don't need a gRPC endpoint. -
Load the configuration and start the agent.
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \ -a fetch-config -m ec2 -s \ -c file:/opt/aws/amazon-cloudwatch-agent/etc/profiles-getting-started.jsonThe
fetch-configaction replaces any earlier agent configuration, and the-soption restarts the agent.
Step 2: Confirm that the agent is ready to receive profiles
Before you start the application, confirm that the agent runs, that it listens on port
4318, and that it built a profiles pipeline. An agent version without profiles
support accepts the same configuration without an error, but it doesn't forward profile
data.
To confirm that the agent is ready
-
Check the agent status.
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a statusThe output shows
"status": "running". -
Check that the agent listens on port
4318.ss -ltn | grep 4318The output shows a listening socket on
127.0.0.1:4318. The agent might take a few seconds to open the port after it starts. -
Check the agent log for the startup messages.
sudo grep -E 'Starting HTTP server|Everything is ready' \ /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log | tail -n 4The output includes a line that contains
"msg":"Starting HTTP server"and"endpoint":"127.0.0.1:4318", and a line that contains"msg":"Everything is ready. Begin running and processing data.". The log keeps lines from earlier runs, so look at the most recent lines. -
Confirm that the agent built a profiles pipeline.
sudo grep 'profiles/otlp' /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.yamlThe output includes
profiles/otlp. If the command returns nothing, your agent version doesn't support profiles. Install a version that supports profiles, and then repeat Step 1.
Step 3: Install Java and the ADOT Java agent
The sample application runs on Amazon Corretto 21. Version 2.32.0 and later of the ADOT Java agent embed async-profiler, so you don't install a separate profiler.
To install Java and the ADOT Java agent
-
Install Amazon Corretto 21.
sudo dnf install -y java-21-amazon-corretto-headlessThe headless package is enough to run the sample application.
-
Create a directory for the ADOT Java agent.
sudo mkdir -p /opt/aws-opentelemetry-agent -
Download the ADOT Java agent version 2.32.0 to the directory.
sudo curl -sSfLo /opt/aws-opentelemetry-agent/aws-opentelemetry-agent.jar \ https://github.com/aws-observability/aws-otel-java-instrumentation/releases/download/v2.32.0/aws-opentelemetry-agent.jar -
Verify the checksum of the file.
(cd /opt/aws-opentelemetry-agent && \ curl -sSfL https://github.com/aws-observability/aws-otel-java-instrumentation/releases/download/v2.32.0/aws-opentelemetry-agent.jar.sha256 \ | sha256sum -c -)The output shows
aws-opentelemetry-agent.jar: OK.This check detects a corrupted or incomplete download. The checksum comes from the same GitHub release as the agent. If you change the ADOT Java agent version, change it in both URLs.
Step 4: Run the sample application with profiling turned on
The sample application does CPU-bound work and allocates memory in a loop until you
stop it. Most of its CPU time goes to the computePrimes and
isPrime methods. The allocateBuffers and
hashStrings methods allocate memory. In production, use your own application
and service name instead.
To run the sample application
-
Create a directory for the sample application, and change to it.
mkdir -p ~/profiles-sample && cd ~/profiles-sample -
Create a file named
Main.javawith the following content.// Sample for CloudWatch Profiles. Runs until stopped. import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws Exception { System.out.println("example-java-service started. Press Ctrl+C to stop."); long checksum = 0; while (true) { checksum += computePrimes(); checksum += hashStrings(); checksum += allocateBuffers(); if (checksum == 42) System.out.println(checksum); // keeps the JIT from removing the work } } // Uses most of the CPU time: look for Main.computePrimes and Main.isPrime. static long computePrimes() { long count = 0; for (int n = 2; n < 200_000; n++) { if (isPrime(n)) count++; } return count; } static boolean isPrime(int n) { for (int d = 2; (long) d * d <= n; d++) { if (n % d == 0) return false; } return true; } // Allocates strings: look for Main.hashStrings in the memory profiles. static long hashStrings() { long h = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100_000; i++) { sb.setLength(0); sb.append("example-").append(i); h += sb.toString().hashCode(); } return h; } // Allocates byte arrays: look for Main.allocateBuffers in the memory profiles. static long allocateBuffers() { List<byte[]> buffers = new ArrayList<>(); for (int i = 0; i < 2_000; i++) { buffers.add(new byte[16 * 1024]); } return buffers.size(); } } -
Start the application with the ADOT Java agent and the profiler turned on.
OTEL_SERVICE_NAME="example-java-service" \ OTEL_AWS_PROFILER_ENABLED="true" \ OTEL_AWS_PROFILER_MEMORY_ENABLED="true" \ OTEL_TRACES_EXPORTER="none" \ OTEL_METRICS_EXPORTER="none" \ OTEL_LOGS_EXPORTER="none" \ java -javaagent:/opt/aws-opentelemetry-agent/aws-opentelemetry-agent.jar Main.javaThe application prints
example-java-service started. Press Ctrl+C to stop.and keeps running. The output also includes a line that containsStarted async-profiler. Leave the application running while you complete the next step.
The command uses the following environment variables:
-
OTEL_SERVICE_NAME– The service name that the ADOT Java agent adds to each profile as theservice.nameresource attribute. You find the profile data by this name. -
OTEL_AWS_PROFILER_ENABLED– Turns on the profiler that's embedded in the ADOT Java agent. -
OTEL_AWS_PROFILER_MEMORY_ENABLED– Turns on memory profiling, which the ADOT Java agent leaves off by default and the Kubernetes paths turn on. -
OTEL_TRACES_EXPORTER,OTEL_METRICS_EXPORTER, andOTEL_LOGS_EXPORTER– This tutorial sends only profiles, so these variables turn off the export of traces, metrics, and logs. If you also want to send traces, metrics, and logs through the CloudWatch agent, remove these variables.
You don't need to set an endpoint. By default, the profiler sends profiles to
http://localhost:4318/v1development/profiles, which matches the HTTP endpoint
in the agent configuration from Step 1.
With these settings, the profiler collects wall-clock profiles, which sample threads both on and off the CPU, and memory allocation profiles. For more information about how to change the profiling mode, the sampling intervals, or the profile length, see the ADOT Java agent variables in Profile your application.
Step 5: Verify that profiles arrive in CloudWatch
The first profiles arrive about 1–3 minutes after the application starts. To
find the service and its flame graphs, follow the steps in Verify that profile data is arriving. Look for the service
example-java-service and the following profile types:
-
wall:wall:nanoseconds:wall:nanoseconds– The flame graph includesMain.computePrimesandMain.isPrime. It also shows idle threads, because the wall-clock mode also samples threads that aren't running. -
memory:alloc_objects:count:alloc_objects:count– The flame graph showsMain.allocateBuffersandMain.hashStrings. -
memory:alloc_space:bytes:alloc_space:bytes– The flame graph showsMain.allocateBuffersandMain.hashStrings.
The flame graphs also include frames such as
com/sun/tools/javac/launcher/Main.main. These frames appear when you run a
single source file with java Main.java, because Java compiles the file when
it starts. A packaged application doesn't show them.
Step 6: Clean up
To stop sending profile data, stop the sample application. If you don't use the CloudWatch agent for other data, you can also stop the agent. To avoid further charges, delete the files that you created, and terminate the instance if you launched it only for this tutorial.
To clean up
-
In the terminal where the sample application runs, press Ctrl+C.
-
(Optional) Stop the CloudWatch agent.
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a stopThe agent configuration from Step 1 replaced any earlier configuration. If the agent sent other data before this tutorial, load your earlier configuration again instead of stopping the agent.
-
(Optional) Delete the sample application and the ADOT Java agent.
rm -rf ~/profiles-sample sudo rm -rf /opt/aws-opentelemetry-agent -
(Optional) If you launched the instance only for this tutorial, terminate the instance to stop Amazon EC2 charges.
Troubleshoot profiling on Amazon EC2
The following issues can occur when you set up profiling on Amazon EC2.
-
The profiler doesn't start
When the profiler starts, the ADOT Java agent writes a line that contains
Started async-profilerto the output of the application. If this line doesn't appear, check thatOTEL_AWS_PROFILER_ENABLEDis set totrueand that the-javaagentpath points to the ADOT Java agent version 2.32.0 or later. Profiling supports HotSpot Java virtual machines (JVMs) on Linux x64 and arm64. -
No profile data in CloudWatch
Check the following causes:
-
The agent has no profiles pipeline. If
grep 'profiles/otlp'on/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.yamlreturns nothing, your agent version doesn't support profiles. Install a version that supports profiles, and load the configuration again. -
The agent isn't running. Run
amazon-cloudwatch-agent-ctl -a status, and check/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.logfor errors. -
The profiler endpoint doesn't match the agent configuration. The profiler sends to
http://localhost:4318/v1development/profilesby default. If you changed thehttp_endpointport in the agent configuration, or setOTEL_AWS_PROFILER_ENDPOINT, make sure that both use the same HTTP port. -
The application output shows that the profiler data directory isn't writable. Set
OTEL_AWS_PROFILER_DATA_DIRto a directory that the user who runs the application can write to, and restart the application. -
Not enough time has passed. The profiler sends the first profile after the first 60-second window. Wait 2–3 minutes, and then check again.
-
-
You get an access denied error when you view profile data
The credentials that you use need the
cloudwatch:GetProfileRecordspermission. TheCloudWatchAgentServerPolicypolicy doesn't include it. For more information, see IAM permissions required.
Next steps
Now that profile data arrives in CloudWatch, you can do the following:
-
Profile your own application. Start it with the same
-javaagentoption and environment variables, and setOTEL_SERVICE_NAMEto the name of your service. For more information about the ADOT Java agent, see Profile your application. -
Change the agent configuration for your environment. For more information, see Use the CloudWatch agent.
-
Explore your profile data. For more information, see Query profile data in Amazon CloudWatch.
Related topics
For more information, see the following topics: