Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching CloudWatch metrics using the AWS Java SDK?

I'm trying to fetch CPU stats from an EC2 instance using the CloudWatch API:

http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/cloudwatch/AmazonCloudWatchClient.html

I have the following code but its returning an empty result, even though the instance Id, and AWS access and secret keys are correct.

I can see the CPU util for the instance on the CloudWatch UI, but can't seem to get it below?

I'm using version 1.9.0 of the AWS SDK.

Any help much appreciated.

import java.util.Date;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Datapoint;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;

public class AmazonCloudWatchFetchCpuUtilTest {

    public static void main(String[] args) {
        final String awsAccessKey = ...;
        final String awsSecretKey = ...;
        final String instanceId = ...;

        final AmazonCloudWatchClient client = client(awsAccessKey, awsSecretKey);
        final GetMetricStatisticsRequest request = request(instanceId); 
        final GetMetricStatisticsResult result = result(client, request);
        toStdOut(result, instanceId);   
    }

    private static AmazonCloudWatchClient client(final String awsAccessKey, final String awsSecretKey) {
        return new AmazonCloudWatchClient(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
    }

    private static GetMetricStatisticsRequest request(final String instanceId) {
        final long twentyFourHrs = 1000 * 60 * 60 * 24;
        final int oneHour = 60 * 60;
        return new GetMetricStatisticsRequest()
            .withStartTime(new Date(new Date().getTime()- twentyFourHrs))
            .withNamespace("AWS/EC2")
            .withPeriod(oneHour)
            .withDimensions(new Dimension().withName("InstanceId").withValue(instanceId))
            .withMetricName("CPUUtilization")
            .withStatistics("Average", "Maximum")
            .withEndTime(new Date());
    }

    private static GetMetricStatisticsResult result(
            final AmazonCloudWatchClient client, final GetMetricStatisticsRequest request) {
         return client.getMetricStatistics(request);
    }

    private static void toStdOut(final GetMetricStatisticsResult result, final String instanceId) {
        System.out.println(result); // outputs empty result: {Label: CPUUtilization,Datapoints: []}
        for (final Datapoint dataPoint : result.getDatapoints()) {
            System.out.printf("%s instance's average CPU utilization : %s%n", instanceId, dataPoint.getAverage());      
            System.out.printf("%s instance's max CPU utilization : %s%n", instanceId, dataPoint.getMaximum());
        }
    }
}
like image 331
Rory Avatar asked Jan 21 '15 11:01

Rory


People also ask

How do I get CloudWatch metrics in Lambda?

Create an IAM Role for the AWS Lambda Function Go back to the AWS Console to create an IAM role. The AWS Lambda function will use this to send metrics data to CloudWatch. To test our code locally, we created an IAM user and then configured our machine to use the credentials of the user.

How do you submit your metrics to Amazon CloudWatch?

You can publish your own metrics to CloudWatch using the AWS CLI or an API. You can view statistical graphs of your published metrics with the AWS Management Console. CloudWatch stores data about a metric as a series of data points. Each data point has an associated time stamp.


1 Answers

I was missing the endpoint setting on the client. Working now.

Changed this:

    private static AmazonCloudWatchClient client(final String awsAccessKey, final String awsSecretKey) {
        return new AmazonCloudWatchClient(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
    }

to this:

    private static AmazonCloudWatchClient client(final String awsAccessKey, final String awsSecretKey) {
        final AmazonCloudWatchClient client = new AmazonCloudWatchClient(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
        client.setEndpoint("http://monitoring.eu-west-1.amazonaws.com");
        return client;
    }
like image 195
Rory Avatar answered Oct 15 '22 04:10

Rory