Nataraj
Nataraj

Reputation: 93

Getting the CPU Utilization metric of running aws instance through java client

I have started a new instance from an AMI that I have created. Then I enabled cloud watch monitoring on that instance.

What I want is to get the CPU utilization of that particular instance through a java client. I just want to retrieve that information just by passing through the credentials and the instanceid. I am attaching the following code that I have written.

The problem that I am having is that I am unable to retrieve the CPU utilization metric. Am I missing something here?

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.http.impl.client.BasicCredentialsProvider;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder;
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;
import com.amazonaws.services.cloudwatch.model.ListMetricsResult;

import software.amazon.awssdk.services.cloudwatch.model.Metric;

/**
 * Lists CloudWatch metrics
 */

public class AwsCloudWatchMetrics {

    final static String InstanceId = "i-xxxxxxxxxxxxx";

    public static void main(String[] args) {

        MonitorCPU();

    }
    private static void MonitorCPU() {

        // AmazonCloudWatchClient cw = new AmazonCloudWatchClient(credentials);

        AWSCredentialsProvider awsp = new AWSCredentialsProvider() {

            @Override
            public void refresh() {
                // TODO Auto-generated method stub

            }

            @Override
            public AWSCredentials getCredentials() {
                AWSCredentials awsCredentials = null;
                try {
                    awsCredentials = new AWSCredentials() {

                        public String getAWSSecretKey() {
                            return "awssecretkeygoeshere";
                        }

                        public String getAWSAccessKeyId() {
                            return "awsaccesskeygoeshere";
                        }
                    };
                } catch (Exception e) {
                    throw new AmazonClientException(
                            "can not load your aws credentials, please check your credentials !!", e);
                }
                return awsCredentials;
            }
        };
        try{

            AmazonCloudWatch cw =  AmazonCloudWatchClientBuilder.standard()
                    .withCredentials(awsp).withRegion("us-east-2").build();
            long offsetInMilliseconds = 1000 * 60 * 60 * 24 ;

            Dimension dimension = new Dimension()
                    .withName("InstanceId")
                    .withValue("i-xxxxxxxxxxxxx");

            GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
                    .withStartTime(new Date(new Date().getTime() - offsetInMilliseconds)).withNamespace("AWS/EC2")
                    .withPeriod(60 * 60)
                    .withMetricName("CPUUtilization").withStatistics("Average").withEndTime(new Date())
                    .withDimensions(dimension);

            // Dimension().withName("InstanceType").withValue("r5.large"))
            // Dimension().withName("InstanceId").withValue("i-xxxxxxxxxxxxxxxxx")
                    // .withMeasureName("CPUUtilization")
                    //withMetricName("CPUUtilization")

            GetMetricStatisticsResult getMetricStatisticsResult = cw.getMetricStatistics(request);

            System.out.println("request " + request.toString());
            System.out.println("label : " + getMetricStatisticsResult.getLabel());
            System.out.println("DataPoint Size : " + getMetricStatisticsResult.getDatapoints().size());

            double avgCPUUtilization = 0;
            List<Datapoint> dataPoint = getMetricStatisticsResult.getDatapoints();
            for (Object aDataPoint : dataPoint) {
                Datapoint dp = (Datapoint) aDataPoint;
                System.out.println(" avgCPUUtilization " + avgCPUUtilization);
            }

        }catch(AmazonServiceException ase){

            ase.printStackTrace();
        }

        /*
         * TreeMap metricValues = new TreeMap<Long, Double>(); for (Datapoint dp
         * : getMetricStatisticsResult.getDatapoints()) {
         * metricValues.put(dp.getTimestamp().getTime(), dp.getAverage()); }
         * 
         * Set set = metricValues.entrySet(); Iterator i = set.iterator(); while
         * (i.hasNext()) { Map.Entry me = (Map.Entry) i.next();
         * System.out.print(me.getKey() + ": ");
         * System.out.println(me.getValue()); }
         */
    }
}

With above code, i always get zero datapoints and 0.0 as cpu utilization, where as on aws console , for the given date range i see some cpu spike.

Upvotes: 1

Views: 1196

Answers (1)

Nataraj
Nataraj

Reputation: 93

EC2 instances are region specific, hence pointing to right region sloved my problem. We need to pass correct region value in .withRegion().

Upvotes: 2

Related Questions