通过Java客户端获取运行AWS实例的CPU利用率指标

时间:2019-09-24 05:41:31

标签: java amazon-web-services aws-sdk-java-2.0

我已经从创建的AMI启动了新实例。然后,我对该实例启用了云监视监视。

我想要的是通过Java客户端获取该特定实例的CPU利用率。我只想通过传递凭据和instanceid来检索该信息。我将附加下面编写的代码。

我遇到的问题是我无法检索CPU利用率指标。我在这里想念东西吗?

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()); }
         */
    }
}

使用上面的代码,我总是获得零数据点和0.0作为cpu利用率,而在aws控制台上,对于给定的日期范围,我看到了一些cpu峰值。

1 个答案:

答案 0 :(得分:0)

EC2实例是特定于区域的,因此指向正确的区域可以解决我的问题。我们需要在select: function(e) { let tv = $("#treeview-right").data("kendoTreeView"), text = e.sender.dataItem(e.node).text; tv.dataSource.filter({ field: "type", operator: "eq", value: text }); } 中传递正确的区域值。