public static void main(String[] args) { final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient(); boolean done = false; DescribeAlarmsRequest request = new DescribeAlarmsRequest(); while(!done) { DescribeAlarmsResult response = cw.describeAlarms(request); for(MetricAlarm alarm : response.getMetricAlarms()) { System.out.printf("Retrieved alarm %s", alarm.getAlarmName()); } request.setNextToken(response.getNextToken()); if(response.getNextToken() == null) { done = true; } } }
/** * describerAlarmsTest to get the data points * * @return MetricAlarm */ protected final MetricAlarm describerAlarmsTest() { MetricAlarm metricAlarm = null; DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest(); DescribeAlarmsResult result = amazonCloudWatchClient.describeAlarms(describeAlarmsRequest); if (result != null && !result.getMetricAlarms().isEmpty()) { metricAlarm = result.getMetricAlarms().get(0); } return metricAlarm; }
/** * * @param email * @param jobId */ public void removeWatch(String email, String jobId) { String alarmName = getAlarmName(email, jobId); for (MetricAlarm a : asynchCloudWatchClient.describeAlarms().getMetricAlarms()) { if (a.getAlarmName().equalsIgnoreCase(alarmName)) { DeleteAlarmsRequest req = new DeleteAlarmsRequest().withAlarmNames(alarmName); asynchCloudWatchClient.deleteAlarmsAsync(req); } } }
/** * * @param instances * @param email * @param jobId */ public void addWatch(Collection<String> instances, String email, String jobId) { String alarmName = getAlarmName(email, jobId); for (MetricAlarm a : asynchCloudWatchClient.describeAlarms().getMetricAlarms()) { if (a.getAlarmName().equalsIgnoreCase(alarmName)) { logger.info("Alarm for job " + jobId + " and email " + email + " already exists."); return; } } List<Dimension> dimensions = new ArrayList<Dimension>(); for (String instanceId : instances) { Dimension d = new Dimension().withName("InstanceId").withValue(instanceId); dimensions.add(d); } PutMetricAlarmRequest request = new PutMetricAlarmRequest() .withActionsEnabled(true).withAlarmName(alarmName) .withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold) .withDimensions(dimensions) .withAlarmActions(getOrCreateNotification(email)) .withEvaluationPeriods(1) .withPeriod(60) .withThreshold(60.0D) .withStatistic(Statistic.Average) .withMetricName("CPUUtilization") .withNamespace("AWS/EC2"); asynchCloudWatchClient.putMetricAlarm(request); logger.info("Created alarm " + alarmName); }
/** * Test GetMetricAlarm. */ @Test(timeout = TIMEOUT_LEVEL1) public final void GetMetricAlarm() { log.info("Start GetMetricAlarm Cloudwatch test"); MetricAlarm metricAlarm = describerAlarmsTest(); Assert.assertNotNull("metricAlarm should not be null", metricAlarm); Assert.assertNotNull("metricAlarm Name should not be null", metricAlarm.getAlarmName()); }