Example usage for com.amazonaws.services.cloudwatch.model Metric getMetricName

List of usage examples for com.amazonaws.services.cloudwatch.model Metric getMetricName

Introduction

In this page you can find the example usage for com.amazonaws.services.cloudwatch.model Metric getMetricName.

Prototype


public String getMetricName() 

Source Link

Document

The name of the metric.

Usage

From source file:aws.example.cloudwatch.ListMetrics.java

License:Open Source License

public static void main(String[] args) {

    final String USAGE = "To run this example, supply a metric name and metric namespace\n"
            + "Ex: ListMetrics <metric-name> <metric-namespace>\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);//www  .jav  a 2  s.c om
    }

    String name = args[0];
    String namespace = args[1];

    final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient();

    boolean done = false;

    while (!done) {
        ListMetricsRequest request = new ListMetricsRequest().withMetricName(name).withNamespace(namespace);

        ListMetricsResult response = cw.listMetrics(request);

        for (Metric metric : response.getMetrics()) {
            System.out.printf("Retrieved metric %s", metric.getMetricName());
        }

        request.setNextToken(response.getNextToken());

        if (response.getNextToken() == null) {
            done = true;
        }
    }
}

From source file:cloudwatch.src.main.java.aws.example.cloudwatch.ListMetrics.java

License:Open Source License

public static void main(String[] args) {

    final String USAGE = "To run this example, supply a metric name and metric namespace\n"
            + "Ex: ListMetrics <metric-name> <metric-namespace>\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);//w  w w  .  ja  v a  2 s  .  com
    }

    String metricName = args[0];
    String metricNamespace = args[1];

    final AmazonCloudWatch cloudWatch = AmazonCloudWatchClientBuilder.defaultClient();

    boolean done = false;

    while (!done) {
        ListMetricsRequest request = new ListMetricsRequest().withMetricName(metricName)
                .withNamespace(metricNamespace);

        ListMetricsResult response = cloudWatch.listMetrics(request);

        for (Metric metric : response.getMetrics()) {
            System.out.printf("Retrieved metric %s", metric.getMetricName());
        }

        request.setNextToken(response.getNextToken());

        if (response.getNextToken() == null) {
            done = true;
        }
    }
}

From source file:com.appdynamics.extensions.cloudwatch.metricsmanager.MetricsManager.java

License:Apache License

/**
 * Helper method to gather metrics for a particular namespace using certain filter names
 * @param namespace     Name of the namespace
 * @param filterNames   List of filter names (used to filter metrics)
 * @return Map          Map containing metrics for a particular namespace
 *//*w w w . j  a v  a 2 s  .c om*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Map<String, Map<String, List<Datapoint>>> gatherMetricsHelper(final AmazonCloudWatch awsCloudWatch,
        final String namespace, String region, String... filterNames) {
    final Map<String, Map<String, List<Datapoint>>> metrics = new ConcurrentHashMap<String, Map<String, List<Datapoint>>>();

    List<Metric> metricsList = getMetrics(awsCloudWatch, namespace, filterNames);
    logger.info("Available metrics Size across all instances for NameSpace:" + namespace + " Region:" + region
            + " - " + metricsList.size());

    //Each metric is of the form {Namespace: AWS/EC2,MetricName: DiskWriteOps,Dimensions: [{Name: InstanceId,Value: i-b0b31ff2}]}
    if (logger.isDebugEnabled()) {
        logMetricPerInstance(metricsList, namespace, region);
    }

    int count = 0;
    ExecutorCompletionService ecs = new ExecutorCompletionService(workerPool);
    for (final Metric metric : metricsList) {
        List<Dimension> dimensions = metric.getDimensions();
        final String key = dimensions.get(0).getValue();

        if (!metrics.containsKey(key)) {
            metrics.put(key, new ConcurrentHashMap<String, List<Datapoint>>());
        }
        if (!metrics.get(key).containsKey(metric.getMetricName())) {
            final String metricName = metric.getMetricName();
            if (!amazonCloudWatchMonitor.isMetricDisabled(namespace, metricName)) {
                ecs.submit(new Callable() {
                    public Object call() throws Exception {
                        try {
                            GetMetricStatisticsRequest request = createGetMetricStatisticsRequest(namespace,
                                    metricName, getMetricType(namespace, metricName).getTypeName(),
                                    metric.getDimensions());
                            GetMetricStatisticsResult result = awsCloudWatch.getMetricStatistics(request);
                            if (logger.isDebugEnabled()) {
                                logger.debug("Fetching MetricStatistics for NameSpace = " + namespace
                                        + " Metric = " + metric + " Result = " + result);
                            }
                            List<Datapoint> dataPoints = result.getDatapoints();
                            if (dataPoints != null && !dataPoints.isEmpty()) {
                                metrics.get(key).put(metricName, dataPoints);
                            }
                        } catch (Exception e) {
                            //Better to log it here when we have the context rather than in get()
                            logger.error("Error while getting the MetricStatistics for NameSpace =" + namespace
                                    + " Metric " + metric, e);
                        }
                        return null;
                    }
                });
                ++count;
            }
        }
    }

    //Wait until its complete
    for (int i = 0; i < count; i++) {
        try {
            ecs.take().get();
        } catch (InterruptedException e) {
            logger.error("Interrupted exception", e);
        } catch (ExecutionException e) {
            // We are catching the exceptions b4hand, so this will not be executed
            logger.error("ExecutionException in MetricStatistics", e);
        }
    }

    // Logging metricName and datapoints corresponding to each instanceID
    if (logger.isDebugEnabled()) {
        logDataPointsPerInstance(metrics);
    }

    return metrics;
}

From source file:com.appdynamics.extensions.cloudwatch.metricsmanager.MetricsManager.java

License:Apache License

protected void logMetricPerInstance(List<Metric> metricsList, String namespace, String region) {
    Map<String, List<String>> metricsPerInstance = new HashMap<String, List<String>>();
    for (Metric metric : metricsList) {
        List<Dimension> dimensions = metric.getDimensions();

        String instanceId = null;

        if (dimensions != null && !dimensions.isEmpty()) {
            instanceId = dimensions.get(0).getValue();
        }/*w w  w. ja v a 2s .  c  om*/

        List<String> metricList = null;

        if (metricsPerInstance.containsKey(instanceId)) {
            metricList = metricsPerInstance.get(instanceId);

        } else {
            metricList = new ArrayList<String>();
        }

        metricList.add(metric.getMetricName());
        metricsPerInstance.put(instanceId, metricList);
    }

    for (String key : metricsPerInstance.keySet()) {
        logger.debug(" Metrics of " + key + " belonging to " + namespace + "," + region);
        for (String metricName : metricsPerInstance.get(key)) {
            logger.debug(metricName);
        }
    }
}

From source file:com.appdynamics.extensions.cloudwatch.metricsmanager.metricsmanagerimpl.EC2MetricsManager.java

License:Apache License

/**
  * Gather metrics for AWS/EC2//  www . j a  va 2 s  . c o m
  * @return   Map     Map containing metrics
  */
@Override
public Map<String, Map<String, List<Datapoint>>> gatherMetrics(final AmazonCloudWatch awsCloudWatch,
        String region) {
    final Map<String, Map<String, List<Datapoint>>> metrics = new ConcurrentHashMap<String, Map<String, List<Datapoint>>>();

    List<Metric> metricsList = getMetrics(awsCloudWatch, NAMESPACE, "InstanceId");
    logger.info("Available metrics Size across all instances for NameSpace:" + NAMESPACE + " Region:" + region
            + " - " + metricsList.size());

    //Each metric is of the form {Namespace: AWS/EC2,MetricName: DiskWriteOps,Dimensions: [{Name: InstanceId,Value: i-b0b31ff2}]}
    if (logger.isDebugEnabled()) {
        logMetricPerInstance(metricsList, NAMESPACE, region);
    }

    int count = 0;
    ExecutorCompletionService<Object> ecs = new ExecutorCompletionService<Object>(workerPool);
    for (final Metric metric : metricsList) {
        List<Dimension> dimensions = metric.getDimensions();
        final String key = getInstanceName(region, dimensions.get(0).getValue());

        if (!metrics.containsKey(key)) {
            metrics.put(key, new ConcurrentHashMap<String, List<Datapoint>>());
        }
        if (!metrics.get(key).containsKey(metric.getMetricName())) {
            final String metricName = metric.getMetricName();
            if (!amazonCloudWatchMonitor.isMetricDisabled(NAMESPACE, metricName)) {
                ecs.submit(new Callable<Object>() {
                    public Object call() throws Exception {
                        try {
                            GetMetricStatisticsRequest request = createGetMetricStatisticsRequest(NAMESPACE,
                                    metricName, getMetricType(NAMESPACE, metricName).getTypeName(),
                                    metric.getDimensions());
                            GetMetricStatisticsResult result = awsCloudWatch.getMetricStatistics(request);
                            if (logger.isDebugEnabled()) {
                                logger.debug("Fetching MetricStatistics for NameSpace = " + NAMESPACE
                                        + " Metric = " + metric + " Result = " + result);
                            }
                            List<Datapoint> dataPoints = result.getDatapoints();
                            if (dataPoints != null && !dataPoints.isEmpty()) {
                                metrics.get(key).put(metricName, dataPoints);
                            }
                        } catch (Exception e) {
                            //Better to log it here when we have the context rather than in get()
                            logger.error("Error while getting the MetricStatistics for NameSpace =" + NAMESPACE
                                    + " Metric " + metric, e);
                        }
                        return null;
                    }
                });
                ++count;
            }
        }
    }

    //Wait until its complete
    for (int i = 0; i < count; i++) {
        try {
            ecs.take().get();
        } catch (InterruptedException e) {
            logger.error("Interrupted exception", e);
        } catch (ExecutionException e) {
            // We are catching the exceptions b4hand, so this will not be executed
            logger.error("ExecutionException in MetricStatistics", e);
        }
    }

    // Logging metricName and datapoints corresponding to each instanceID
    if (logger.isDebugEnabled()) {
        logDataPointsPerInstance(metrics);
    }

    return metrics;

}

From source file:com.appdynamics.extensions.cloudwatch.metricsmanager.metricsmanagerimpl.ElastiCacheMetricsManager.java

License:Apache License

/**
 * Gather metrics for AWS/ElastiCache//from   ww  w  .j  a v a2s  .  com
 * @return   Map     Map containing metrics
 */
@Override
public Map gatherMetrics(AmazonCloudWatch awsCloudWatch, String region) {
    List<Metric> metricsList = getMetrics(awsCloudWatch, NAMESPACE, "CacheClusterId", "CacheNodeId");

    //Top level     -- Key = CacheClusterIds,       Value = HashMap of cache nodes
    //Mid level     -- Key = CacheNodeIds,          Value = HashMap of Metrics
    //Bottom level  -- Key = MetricName,            Value = List of datapoints
    Map<String, Map<String, Map<String, List<Datapoint>>>> cacheClusterMetrics = new HashMap<String, Map<String, Map<String, List<Datapoint>>>>();

    for (com.amazonaws.services.cloudwatch.model.Metric metric : metricsList) {
        List<Dimension> dimensions = metric.getDimensions();
        String cacheClusterId = dimensions.get(0).getValue();
        String cacheNodeId = dimensions.get(1).getValue();
        if (!cacheClusterMetrics.containsKey(cacheClusterId)) {
            cacheClusterMetrics.put(cacheClusterId, new HashMap<String, Map<String, List<Datapoint>>>());
        }
        if (!cacheClusterMetrics.get(cacheClusterId).containsKey(cacheNodeId)) {
            cacheClusterMetrics.get(cacheClusterId).put(cacheNodeId, new HashMap<String, List<Datapoint>>());
        }
        if (!cacheClusterMetrics.get(cacheClusterId).get(cacheNodeId).containsKey(metric.getMetricName())) {

            if (!amazonCloudWatchMonitor.isMetricDisabled(NAMESPACE, metric.getMetricName())) {
                GetMetricStatisticsRequest getMetricStatisticsRequest = createGetMetricStatisticsRequest(
                        NAMESPACE, metric.getMetricName(),
                        getMetricType(NAMESPACE, metric.getMetricName()).getTypeName(), dimensions);
                GetMetricStatisticsResult getMetricStatisticsResult = awsCloudWatch
                        .getMetricStatistics(getMetricStatisticsRequest);
                cacheClusterMetrics.get(cacheClusterId).get(cacheNodeId).put(metric.getMetricName(),
                        getMetricStatisticsResult.getDatapoints());
            }
        }
    }
    return cacheClusterMetrics;
}

From source file:com.appdynamics.extensions.cloudwatch.metricsmanager.metricsmanagerimpl.ELBMetricsManager.java

License:Apache License

/**
 * Gather metrics for AWS/ELB/*from w w w .  j a va  2  s  . com*/
 * @return   Map     Map containing metrics
 */
@Override
public Map gatherMetrics(final AmazonCloudWatch awsCloudWatch, String region) {
    List<com.amazonaws.services.cloudwatch.model.Metric> elbMetricsList = getMetrics(awsCloudWatch, NAMESPACE,
            "LoadBalancerName", "AvailabilityZone");

    //Top level     -- Key = LoadBalancerName,      Value = HashMap of availability zones
    //Mid level     -- Key = AvailabilityZoneName,  Value = HashMap of Metrics
    //Bottom level  -- Key = MetricName,            Value = List of datapoints
    final HashMap<String, HashMap<String, HashMap<String, List<Datapoint>>>> elbMetrics = new HashMap<String, HashMap<String, HashMap<String, List<Datapoint>>>>();

    int count = 0;
    ExecutorCompletionService<Object> ecs = new ExecutorCompletionService<Object>(workerPool);

    for (final com.amazonaws.services.cloudwatch.model.Metric metric : elbMetricsList) {
        final List<Dimension> dimensions = metric.getDimensions();
        final String loadBalancerName = dimensions.get(0).getValue();
        final String availabilityZone = dimensions.get(1).getValue();

        if (!elbMetrics.containsKey(loadBalancerName)) {
            elbMetrics.put(loadBalancerName, new HashMap<String, HashMap<String, List<Datapoint>>>());
        }

        if (!elbMetrics.get(loadBalancerName).containsKey(availabilityZone)) {
            elbMetrics.get(loadBalancerName).put(availabilityZone, new HashMap<String, List<Datapoint>>());
        }

        if (!elbMetrics.get(loadBalancerName).get(availabilityZone).containsKey(metric.getMetricName())) {

            if (!amazonCloudWatchMonitor.isMetricDisabled(NAMESPACE, metric.getMetricName())) {
                ecs.submit(new Callable<Object>() {
                    public Object call() throws Exception {
                        try {
                            GetMetricStatisticsRequest getMetricStatisticsRequest = createGetMetricStatisticsRequest(
                                    NAMESPACE, metric.getMetricName(),
                                    getMetricType(NAMESPACE, metric.getMetricName()).getTypeName(), dimensions);
                            GetMetricStatisticsResult getMetricStatisticsResult = awsCloudWatch
                                    .getMetricStatistics(getMetricStatisticsRequest);
                            elbMetrics.get(loadBalancerName).get(availabilityZone).put(metric.getMetricName(),
                                    getMetricStatisticsResult.getDatapoints());

                        } catch (Exception e) {
                            //Better to log it here when we have the context rather than in get()
                            logger.error("Error while getting the MetricStatistics for NameSpace =" + NAMESPACE
                                    + " Metric " + metric, e);
                        }
                        return null;
                    }
                });
                ++count;

            }
        }
    }

    //Wait until its complete
    for (int i = 0; i < count; i++) {
        try {
            ecs.take().get();
        } catch (InterruptedException e) {
            logger.error("Interrupted exception", e);
        } catch (ExecutionException e) {
            // We are catching the exceptions b4hand, so this will not be executed
            logger.error("ExecutionException in MetricStatistics", e);
        }
    }

    return elbMetrics;
}

From source file:com.appdynamics.extensions.cloudwatch.metricsmanager.metricsmanagerimpl.RedshiftMetricsManager.java

License:Apache License

/**
 * Gather metrics for AWS/Redshift//w ww.jav a2 s . c  o m
 * @return   Map     Map containing metrics
 */
@Override
public Map gatherMetrics(AmazonCloudWatch awsCloudWatch, String region) {
    HashMap<String, HashMap<String, HashMap<String, List<Datapoint>>>> redshiftMetrics = new HashMap<String, HashMap<String, HashMap<String, List<Datapoint>>>>();
    List<com.amazonaws.services.cloudwatch.model.Metric> metrics = getMetrics(awsCloudWatch, NAMESPACE,
            "ClusterIdentifier", "NodeID");
    for (com.amazonaws.services.cloudwatch.model.Metric metric : metrics) {
        List<Dimension> dimensions = metric.getDimensions();
        String clusterIdentifier = dimensions.get(1).getValue();
        String nodeID = dimensions.get(0).getValue();
        if (!redshiftMetrics.containsKey(clusterIdentifier)) {
            redshiftMetrics.put(clusterIdentifier, new HashMap<String, HashMap<String, List<Datapoint>>>());
        }
        if (!redshiftMetrics.get(clusterIdentifier).containsKey(nodeID)) {
            redshiftMetrics.get(clusterIdentifier).put(nodeID, new HashMap<String, List<Datapoint>>());
        }
        if (!redshiftMetrics.get(clusterIdentifier).get(nodeID).containsKey(metric.getMetricName())) {

            if (!amazonCloudWatchMonitor.isMetricDisabled(NAMESPACE, metric.getMetricName())) {
                GetMetricStatisticsRequest getMetricStatisticsRequest = createGetMetricStatisticsRequest(
                        NAMESPACE, metric.getMetricName(),
                        getMetricType(NAMESPACE, metric.getMetricName()).getTypeName(), dimensions);
                GetMetricStatisticsResult getMetricStatisticsResult = awsCloudWatch
                        .getMetricStatistics(getMetricStatisticsRequest);
                redshiftMetrics.get(clusterIdentifier).get(nodeID).put(metric.getMetricName(),
                        getMetricStatisticsResult.getDatapoints());
            }
        }
    }

    return redshiftMetrics;
}

From source file:com.blubb.andcw.ChartBuilder.java

License:Apache License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Metric m = new Metric().withMetricName((String) getIntent().getExtras().get("metric"))
            .withNamespace((String) getIntent().getExtras().get("namespace"));
    Dimension d = new Dimension().withName((String) getIntent().getExtras().get("dimension"))
            .withValue((String) getIntent().getExtras().get("dimensionvalue"));
    TimeSeries series = new TimeSeries(m.getMetricName() + " - " + d.getName() + " " + d.getValue());
    AWSCredentials awsc = getAWSCredentials();
    AmazonCloudWatchAsyncClient acw = new AmazonCloudWatchAsyncClient(awsc);
    long offset = new Date().getTime() - 1000 * 3600 * 24;
    GetMetricStatisticsRequest gmsr = new GetMetricStatisticsRequest().withStartTime(new Date(offset))
            .withMetricName(m.getMetricName()).withNamespace(m.getNamespace()).withDimensions(d).withPeriod(300)
            .withStatistics("Average").withEndTime(new Date());
    Log.i("AndCW req", gmsr.toString());
    Future<GetMetricStatisticsResult> res = acw.getMetricStatisticsAsync(gmsr);
    TreeSet<Datapoint> data = new TreeSet<Datapoint>(new Comparator<Datapoint>() {

        public int compare(Datapoint lhs, Datapoint rhs) {
            return lhs.getTimestamp().compareTo(rhs.getTimestamp());
        }/*from   w  ww  .  j  av  a2 s.com*/
    });
    try {
        data.addAll((List<Datapoint>) res.get().getDatapoints()); // FIXME
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    for (Datapoint dp : data) {
        series.add(dp.getTimestamp(), dp.getAverage());
    }
    XYSeriesRenderer renderer = new XYSeriesRenderer();
    mRenderer.addSeriesRenderer(renderer);
    renderer.setPointStyle(PointStyle.CIRCLE);
    renderer.setFillPoints(true);
    mDataset.addSeries(series);
    mRenderer.setApplyBackgroundColor(true);
    mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
    mRenderer.setAxisTitleTextSize(16);
    mRenderer.setChartTitleTextSize(20);
    mRenderer.setLabelsTextSize(15);
    mRenderer.setLegendTextSize(15);
    mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
    mRenderer.setZoomButtonsVisible(true);
    mRenderer.setPointSize(1);
    mChartView = ChartFactory.getTimeChartView(this, mDataset, mRenderer, null);
    setContentView(mChartView);

}

From source file:com.pinterest.arcee.autoscaling.AwsAlarmManager.java

License:Apache License

@Override
public List<String> listAwsMetrics(String groupName) throws Exception {
    DimensionFilter dimensionFilter = new DimensionFilter();
    dimensionFilter.setName(DIMENTION_NAME);
    dimensionFilter.setValue(groupName);
    ListMetricsRequest listMetricsRequest = new ListMetricsRequest();
    listMetricsRequest.withDimensions(dimensionFilter).withNamespace(METRIC_NAMESPACE);

    ListMetricsResult listMetricsResult = acwClient.listMetrics(listMetricsRequest);
    List<String> metricName = new ArrayList<>();
    for (Metric metric : listMetricsResult.getMetrics()) {
        metricName.add(metric.getMetricName());
    }/*from ww w .ja va 2s.  com*/
    return metricName;
}