private double getInstanceAverageLoad(AmazonCloudWatchClient cloudWatchClient, String instanceId) { long offsetInMilliseconds = 1000 * 60 * 60; GetMetricStatisticsRequest request = new GetMetricStatisticsRequest() .withStartTime(new Date(new Date().getTime() - offsetInMilliseconds)) .withNamespace("AWS/EC2") .withPeriod(60 * 60) .withDimensions(new Dimension().withName("InstanceId").withValue(instanceId)) .withMetricName("CPUUtilization") .withStatistics("Average", "Maximum") .withEndTime(new Date()); GetMetricStatisticsResult getMetricStatisticsResult = cloudWatchClient.getMetricStatistics(request); double avgCPUUtilization = 0; List dataPoint = getMetricStatisticsResult.getDatapoints(); for (Object aDataPoint : dataPoint) { Datapoint dp = (Datapoint) aDataPoint; avgCPUUtilization = dp.getAverage(); } return avgCPUUtilization; }
/** * Add a metric event to be aggregated. * Events with the same name, unit, and dimensions will have their values * aggregated into {@link StatisticSet}s, with the aggregated data * available via {@link #flush}. * * @param context Metric context to use for dimension information * @param name Metric name * @param value Recorded value for the metric event * @param unit Unit for interpreting the value */ public void add( final TypedMap context, final Metric name, final double value, final StandardUnit unit) { //TODO: avoid doing this every time for a context - caching, or? List<Dimension> dimensions = dimensionMapper.getDimensions(name, context); DatumKey key = new DatumKey(name.toString(), unit, dimensions); statisticsMap.merge( key, new StatisticSet() .withMaximum(value) .withMinimum(value) .withSampleCount(1D) .withSum(value), MetricDataAggregator::sum); }
@Test public void one_global() throws Exception { Metric metric = Metric.define("BarMetric"); String id = UUID.randomUUID().toString(); TypedMap context = ContextData.withId(id) .add(StandardContext.SERVICE, "BarService") .build(); DimensionMapper mapper = new DimensionMapper.Builder() .addGlobalDimension(ContextData.ID) .build(); List<Dimension> dims = mapper.getDimensions(metric, context); assertEquals("Unexpected size of dimension list", 1, dims.size()); assertEquals("Unexpected name for dimension", ContextData.ID.name, dims.get(0).getName()); assertEquals("Unexpected value for dimension", id, dims.get(0).getValue()); }
private MetricDatum makeDatum( final String id, final String name, final double sum, final double min, final double max, final int count, final StandardUnit unit) { MetricDatum md = new MetricDatum().withMetricName(name).withUnit(unit); final StatisticSet statSet = new StatisticSet() .withSampleCount(Double.valueOf(count)) .withSum(sum) .withMinimum(min) .withMaximum(max); md.setStatisticValues(statSet); List<Dimension> dimensions = new ArrayList<>(1); Dimension trace = new Dimension().withName(ContextData.ID.name).withValue(id); dimensions.add(trace); md.setDimensions(dimensions); return md; }
/** * Please note, the reported values submitted only if they show some data (greater than zero) in order to: * <p> * 1. save some money * 2. prevent com.amazonaws.services.cloudwatch.model.InvalidParameterValueException if empty {@link Snapshot} * is submitted * <p> * If {@link Builder#withZeroValuesSubmission()} is {@code true}, then all values will be submitted */ private void stageMetricDatum(final boolean metricConfigured, final String metricName, final double metricValue, final StandardUnit standardUnit, final String dimensionValue, final List<MetricDatum> metricData) { // Only submit metrics that show some data, so let's save some money if (metricConfigured && (builder.withZeroValuesSubmission || metricValue > 0)) { final Set<Dimension> dimensions = new LinkedHashSet<>(builder.globalDimensions); dimensions.add(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(dimensionValue)); metricData.add(new MetricDatum() .withTimestamp(new Date(builder.clock.getTime())) .withValue(cleanMetricValue(metricValue)) .withMetricName(metricName) .withDimensions(dimensions) .withUnit(standardUnit)); } }
private void stageMetricDatumWithConvertedSnapshot(final boolean metricConfigured, final String metricName, final Snapshot snapshot, final StandardUnit standardUnit, final List<MetricDatum> metricData) { if (metricConfigured) { double scaledSum = convertDuration(LongStream.of(snapshot.getValues()).sum()); final StatisticSet statisticSet = new StatisticSet() .withSum(scaledSum) .withSampleCount((double) snapshot.size()) .withMinimum(convertDuration(snapshot.getMin())) .withMaximum(convertDuration(snapshot.getMax())); final Set<Dimension> dimensions = new LinkedHashSet<>(builder.globalDimensions); dimensions.add(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(DIMENSION_SNAPSHOT_SUMMARY)); metricData.add(new MetricDatum() .withTimestamp(new Date(builder.clock.getTime())) .withMetricName(metricName) .withDimensions(dimensions) .withStatisticValues(statisticSet) .withUnit(standardUnit)); } }
private void stageMetricDatumWithRawSnapshot(final boolean metricConfigured, final String metricName, final Snapshot snapshot, final StandardUnit standardUnit, final List<MetricDatum> metricData) { if (metricConfigured) { double total = LongStream.of(snapshot.getValues()).sum(); final StatisticSet statisticSet = new StatisticSet() .withSum(total) .withSampleCount((double) snapshot.size()) .withMinimum((double) snapshot.getMin()) .withMaximum((double) snapshot.getMax()); final Set<Dimension> dimensions = new LinkedHashSet<>(builder.globalDimensions); dimensions.add(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(DIMENSION_SNAPSHOT_SUMMARY)); metricData.add(new MetricDatum() .withTimestamp(new Date(builder.clock.getTime())) .withMetricName(metricName) .withDimensions(dimensions) .withStatisticValues(statisticSet) .withUnit(standardUnit)); } }
private MetricDatum metricDatumByDimensionFromCapturedRequest(final String dimensionValue) { final PutMetricDataRequest putMetricDataRequest = metricDataRequestCaptor.getValue(); final List<MetricDatum> metricData = putMetricDataRequest.getMetricData(); final Optional<MetricDatum> metricDatumOptional = metricData .stream() .filter(metricDatum -> metricDatum.getDimensions() .contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(dimensionValue))) .findFirst(); if (metricDatumOptional.isPresent()) { return metricDatumOptional.get(); } throw new IllegalStateException("Could not find MetricDatum for Dimension value: " + dimensionValue); }
private CloudWatchReporter(MetricRegistry registry, AmazonCloudWatchClient client, String namespace, TimeUnit rateUnit, TimeUnit durationUnit, boolean reportAggregates, MetricFilter filter, Map<String, String> dimensions) { super(registry, "cloudwatch-reporter", filter, rateUnit, durationUnit); this.client = client; this.namespace = namespace; this.dimensions = new ArrayList<>(); this.reportAggregates = reportAggregates; for (Map.Entry<String, String> me : dimensions.entrySet()) { this.dimensions.add(new Dimension().withName(me.getKey()).withValue(me.getValue())); } }
private void setDimension(MetricDatum metricDatum, Exchange exchange) { String name = exchange.getIn().getHeader(CwConstants.METRIC_DIMENSION_NAME, String.class); String value = exchange.getIn().getHeader(CwConstants.METRIC_DIMENSION_VALUE, String.class); if (name != null && value != null) { metricDatum.withDimensions(new Dimension().withName(name).withValue(value)); } else { Map<String, String> dimensions = exchange.getIn().getHeader(CwConstants.METRIC_DIMENSIONS, Map.class); if (dimensions != null) { Collection<Dimension> dimensionCollection = new ArrayList<Dimension>(); for (Map.Entry<String, String> dimensionEntry : dimensions.entrySet()) { Dimension dimension = new Dimension().withName(dimensionEntry.getKey()).withValue(dimensionEntry.getValue()); dimensionCollection.add(dimension); } metricDatum.withDimensions(dimensionCollection); } } }
@Test public void setsMeticDimensions() throws Exception { template.send("direct:start", ExchangePattern.InOnly, new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(CwConstants.METRIC_NAME, "errorCount"); Map<String, String> dimensionsMap = new LinkedHashMap<String, String>(); dimensionsMap.put("keyOne", "valueOne"); dimensionsMap.put("keyTwo", "valueTwo"); exchange.getIn().setHeader(CwConstants.METRIC_DIMENSIONS, dimensionsMap); } }); ArgumentCaptor<PutMetricDataRequest> argument = ArgumentCaptor.forClass(PutMetricDataRequest.class); verify(cloudWatchClient).putMetricData(argument.capture()); List<Dimension> dimensions = argument.getValue().getMetricData().get(0).getDimensions(); Dimension dimension = dimensions.get(0); assertThat(dimensions.size(), is(2)); assertEquals("keyOne", dimension.getName()); assertEquals("valueOne", dimension.getValue()); }
public void createAlarmIfNotAlreadyExist(String topicArn) { List<Dimension> dimensions = new ArrayList<>(); dimensions.add(new Dimension().withName("Currency").withValue("USD")); PutMetricAlarmRequest request = new PutMetricAlarmRequest(); request.setAlarmName("s3video Billing Alarm"); request.setAlarmActions(Arrays.asList(topicArn)); request.setMetricName("EstimatedCharges"); request.setNamespace("AWS/Billing"); request.setDimensions(dimensions); request.setThreshold(alarmThreshold); request.setPeriod(SIX_HOUR_IN_SECONDS); request.setStatistic("Maximum"); request.setComparisonOperator("GreaterThanThreshold"); request.setEvaluationPeriods(1); cloudWatchClient.putMetricAlarm(request); }
@Override public void run() { try { List<MetricDatum> metricData = new ArrayList<>(); Date now = new Date(); metricData.addAll(heartbeats.entrySet().stream().map(entry -> new MetricDatum().withMetricName("Heartbeats") .withDimensions(new Dimension().withName("Client").withValue(entry.getKey())) .withTimestamp(now) .withUnit(StandardUnit.Count) .withValue(entry.getValue().doubleValue())).collect(Collectors.toList())); heartbeats.clear(); for (List<MetricDatum> chunk :partitionList(metricData, 20)) { awsClient.putMetricData(new PutMetricDataRequest().withNamespace(namespace).withMetricData(chunk)); } } catch (Throwable e) { log.error("Failed to publish CloudWatch metrics: {}", e.toString()); } }
/** * @return a string representation of this object */ @Override public String toString() { StringBuilder sb = new StringBuilder("{ElapsedTimeAggregator: {"); String namespace = putMetricDataRequest.getNamespace(); sb.append("region: ").append(region).append(", "); sb.append("namespace: ").append(namespace).append(", "); sb.append("metrics: ["); String msep = ""; for (MetricDatum metricDatum : putMetricDataRequest.getMetricData()) { sb.append(msep).append("{metricName: ").append(metricDatum.getMetricName()).append(", "); sb.append("dimensions: ["); String dsep = ""; for (Dimension dimension : metricDatum.getDimensions()) { sb.append(dsep).append(dimension); dsep = ", "; } sb.append("]}"); msep = ", "; } sb.append("]}}"); return sb.toString(); }
@Test public void testDimensions() throws Exception { new CloudWatchCollector( "---\nregion: reg\nmetrics:\n- aws_namespace: AWS/ELB\n aws_metric_name: RequestCount\n aws_dimensions:\n - AvailabilityZone\n - LoadBalancerName", client).register(registry); Mockito.when(client.listMetrics((ListMetricsRequest)argThat( new ListMetricsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimensions("AvailabilityZone", "LoadBalancerName")))) .thenReturn(new ListMetricsResult().withMetrics( new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("a"), new Dimension().withName("LoadBalancerName").withValue("myLB")), new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("a"), new Dimension().withName("LoadBalancerName").withValue("myLB"), new Dimension().withName("ThisExtraDimensionIsIgnored").withValue("dummy")), new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("b"), new Dimension().withName("LoadBalancerName").withValue("myOtherLB")))); Mockito.when(client.getMetricStatistics((GetMetricStatisticsRequest)argThat( new GetMetricStatisticsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimension("AvailabilityZone", "a").Dimension("LoadBalancerName", "myLB")))) .thenReturn(new GetMetricStatisticsResult().withDatapoints( new Datapoint().withTimestamp(new Date()).withAverage(2.0))); Mockito.when(client.getMetricStatistics((GetMetricStatisticsRequest)argThat( new GetMetricStatisticsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimension("AvailabilityZone", "b").Dimension("LoadBalancerName", "myOtherLB")))) .thenReturn(new GetMetricStatisticsResult().withDatapoints( new Datapoint().withTimestamp(new Date()).withAverage(3.0))); assertEquals(2.0, registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "a", "myLB"}), .01); assertEquals(3.0, registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "b", "myOtherLB"}), .01); assertNull(registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name", "this_extra_dimension_is_ignored"}, new String[]{"aws_elb", "", "a", "myLB", "dummy"})); }
@Test public void testDimensionSelect() throws Exception { new CloudWatchCollector( "---\nregion: reg\nmetrics:\n- aws_namespace: AWS/ELB\n aws_metric_name: RequestCount\n aws_dimensions:\n - AvailabilityZone\n - LoadBalancerName\n aws_dimension_select:\n LoadBalancerName:\n - myLB", client).register(registry); Mockito.when(client.listMetrics((ListMetricsRequest)argThat( new ListMetricsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimensions("AvailabilityZone", "LoadBalancerName")))) .thenReturn(new ListMetricsResult().withMetrics( new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("a"), new Dimension().withName("LoadBalancerName").withValue("myLB")), new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("b"), new Dimension().withName("LoadBalancerName").withValue("myLB")), new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("a"), new Dimension().withName("LoadBalancerName").withValue("myOtherLB")))); Mockito.when(client.getMetricStatistics((GetMetricStatisticsRequest)argThat( new GetMetricStatisticsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimension("AvailabilityZone", "a").Dimension("LoadBalancerName", "myLB")))) .thenReturn(new GetMetricStatisticsResult().withDatapoints( new Datapoint().withTimestamp(new Date()).withAverage(2.0))); Mockito.when(client.getMetricStatistics((GetMetricStatisticsRequest)argThat( new GetMetricStatisticsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimension("AvailabilityZone", "b").Dimension("LoadBalancerName", "myLB")))) .thenReturn(new GetMetricStatisticsResult().withDatapoints( new Datapoint().withTimestamp(new Date()).withAverage(2.0))); assertEquals(2.0, registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "a", "myLB"}), .01); assertEquals(2.0, registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "b", "myLB"}), .01); assertNull(registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "a", "myOtherLB"})); }
@Test public void testDimensionSelectRegex() throws Exception { new CloudWatchCollector( "---\nregion: reg\nmetrics:\n- aws_namespace: AWS/ELB\n aws_metric_name: RequestCount\n aws_dimensions:\n - AvailabilityZone\n - LoadBalancerName\n aws_dimension_select_regex:\n LoadBalancerName:\n - myLB(.*)", client).register(registry); Mockito.when(client.listMetrics((ListMetricsRequest) argThat( new ListMetricsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimensions("AvailabilityZone", "LoadBalancerName")))) .thenReturn(new ListMetricsResult().withMetrics( new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("a"), new Dimension().withName("LoadBalancerName").withValue("myLB1")), new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("b"), new Dimension().withName("LoadBalancerName").withValue("myLB2")), new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("a"), new Dimension().withName("LoadBalancerName").withValue("myOtherLB")))); Mockito.when(client.getMetricStatistics((GetMetricStatisticsRequest) argThat( new GetMetricStatisticsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimension("AvailabilityZone", "a").Dimension("LoadBalancerName", "myLB1")))) .thenReturn(new GetMetricStatisticsResult().withDatapoints( new Datapoint().withTimestamp(new Date()).withAverage(2.0))); Mockito.when(client.getMetricStatistics((GetMetricStatisticsRequest) argThat( new GetMetricStatisticsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimension("AvailabilityZone", "b").Dimension("LoadBalancerName", "myLB2")))) .thenReturn(new GetMetricStatisticsResult().withDatapoints( new Datapoint().withTimestamp(new Date()).withAverage(2.0))); assertEquals(2.0, registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "a", "myLB1"}), .01); assertEquals(2.0, registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "b", "myLB2"}), .01); assertNull(registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "a", "myOtherLB"})); }
@Test public void testGetDimensionsUsesNextToken() throws Exception { new CloudWatchCollector( "---\nregion: reg\nmetrics:\n- aws_namespace: AWS/ELB\n aws_metric_name: RequestCount\n aws_dimensions:\n - AvailabilityZone\n - LoadBalancerName\n aws_dimension_select:\n LoadBalancerName:\n - myLB", client).register(registry); Mockito.when(client.listMetrics((ListMetricsRequest)argThat( new ListMetricsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimensions("AvailabilityZone", "LoadBalancerName")))) .thenReturn(new ListMetricsResult().withNextToken("ABC")); Mockito.when(client.listMetrics((ListMetricsRequest)argThat( new ListMetricsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimensions("AvailabilityZone", "LoadBalancerName").NextToken("ABC")))) .thenReturn(new ListMetricsResult().withMetrics( new Metric().withDimensions(new Dimension().withName("AvailabilityZone").withValue("a"), new Dimension().withName("LoadBalancerName").withValue("myLB")))); Mockito.when(client.getMetricStatistics((GetMetricStatisticsRequest)argThat( new GetMetricStatisticsRequestMatcher().Namespace("AWS/ELB").MetricName("RequestCount").Dimension("AvailabilityZone", "a").Dimension("LoadBalancerName", "myLB")))) .thenReturn(new GetMetricStatisticsResult().withDatapoints( new Datapoint().withTimestamp(new Date()).withAverage(2.0))); assertEquals(2.0, registry.getSampleValue("aws_elb_request_count_average", new String[]{"job", "instance", "availability_zone", "load_balancer_name"}, new String[]{"aws_elb", "", "a", "myLB"}), .01); }
@Override public void execute(Context context) throws Exception { String asGroupName = resource.asGroup.remoteASGroup.getAutoScalingGroupName(); String policyARN = AWS.as.createPolicy(new PutScalingPolicyRequest() .withPolicyName(resource.id) .withAutoScalingGroupName(asGroupName) .withScalingAdjustment(resource.adjustmentPercentage) .withAdjustmentType("PercentChangeInCapacity") .withMinAdjustmentStep(1) .withCooldown(300)); AWS.cloudWatch.createAlarm(new PutMetricAlarmRequest() .withAlarmName(context.env.name + ":" + resource.id + "-alarm") .withMetricName("CPUUtilization") .withComparisonOperator(resource.comparisonOperator) .withThreshold(resource.cpuUtilizationPercentage) .withPeriod(60) .withEvaluationPeriods(resource.lastMinutes) .withStatistic(Statistic.Average) .withNamespace("AWS/EC2") .withDimensions(new Dimension().withName("AutoScalingGroupName").withValue(asGroupName)) .withAlarmActions(policyARN)); }
public void monitorCPUUsage() { AmazonCloudWatchClient cloudClient = new AmazonCloudWatchClient( getAwsCredentials()); GetMetricStatisticsRequest request = new GetMetricStatisticsRequest(); Calendar cal = Calendar.getInstance(); request.setEndTime(cal.getTime()); cal.add(Calendar.MINUTE, -5); request.setStartTime(cal.getTime()); request.setNamespace("AWS/EC2"); List<String> statistics = new ArrayList<String>(); statistics.add("Maximium"); statistics.add("Average"); request.setStatistics(statistics); request.setMetricName("CPUUtilization"); request.setPeriod(300); Dimension dimension = new Dimension(); dimension.setName("InstanceId"); dimension.setValue("i-d93fa2a4"); List<Dimension> dimensions = new ArrayList<Dimension>(); dimensions.add(dimension); request.setDimensions(dimensions); GetMetricStatisticsResult result = cloudClient .getMetricStatistics(request); List<Datapoint> dataPoints = result.getDatapoints(); for (Datapoint dataPoint : dataPoints) { System.out.println(dataPoint.getAverage()); } }
@Override protected void runOnce() throws Exception { ClickEvent event = inputQueue.take(); String partitionKey = event.getSessionId(); ByteBuffer data = ByteBuffer.wrap( event.getPayload().getBytes("UTF-8")); recordsPut.getAndIncrement(); PutRecordResult res = kinesis.putRecord( STREAM_NAME, data, partitionKey); MetricDatum d = new MetricDatum() .withDimensions( new Dimension().withName("StreamName").withValue(STREAM_NAME), new Dimension().withName("ShardId").withValue(res.getShardId()), new Dimension().withName("Host").withValue( InetAddress.getLocalHost().toString())) .withValue(1.0) .withMetricName("RecordsPut"); cw.putMetricData(new PutMetricDataRequest() .withMetricData(d) .withNamespace("MySampleProducer")); }
public DatumKey( final String name, final StandardUnit unit, final List<Dimension> dimensions) { this.name = name; this.unit = unit; this.dimensions = dimensions; }
@Test public void one_global_empty_context() throws Exception { Metric metric = Metric.define("MetricBaz"); TypedMap context = TypedMap.empty(); DimensionMapper mapper = new DimensionMapper.Builder() .addGlobalDimension(ContextData.ID) .build(); List<Dimension> dims = mapper.getDimensions(metric, context); assertEquals("Unexpected size of dimension list", 1, dims.size()); assertEquals("Unexpected name for dimension", ContextData.ID.name, dims.get(0).getName()); assertEquals("Unexpected value for missing dimension", "null", dims.get(0).getValue()); }
public GetMetricStatisticsResult getCpuUtilization(String name) { Dimension instanceDimension = new Dimension(); if (namespace.endsWith("EC2")) { instanceDimension.setName("InstanceId"); } else { instanceDimension.setName("DBInstanceIdentifier"); } instanceDimension.setValue(name); Calendar startCal = Calendar.getInstance(); Calendar endCal = Calendar.getInstance(); startCal.add(Calendar.MINUTE, -10); startCal.set(Calendar.SECOND, 0); GetMetricStatisticsRequest request = new GetMetricStatisticsRequest() .withStartTime(startCal.getTime()) .withEndTime(endCal.getTime()) .withNamespace(namespace) .withPeriod(60) .withMetricName("CPUUtilization") .withStatistics("Average") .withStatistics("Maximum") .withDimensions(Arrays.asList(instanceDimension)); GetMetricStatisticsResult result = sort(cloudWatch.getMetricStatistics(request).getDatapoints()); if (logger.isDebugEnabled()) { if (result.getDatapoints() != null && result.getDatapoints().size() > 0) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.debug("[{}:{}] {}, {} ~ {}", new Object[] {namespace, pulse.getId(), result, sdf.format(startCal.getTime()), sdf.format(endCal.getTime())}); } } return result; }
public GetMetricStatisticsResult getRequestCount(String name) { Dimension instanceDimension = new Dimension(); String ns = null; if (pulse.getType().equals("application")) { ns = "AWS/ApplicationELB"; instanceDimension.setName("LoadBalancer"); } else { ns = "AWS/ELB"; instanceDimension.setName("LoadBalancerName"); } instanceDimension.setValue(name); Calendar startCal = Calendar.getInstance(); Calendar endCal = Calendar.getInstance(); startCal.add(Calendar.MINUTE, -10); startCal.set(Calendar.SECOND, 0); GetMetricStatisticsRequest request = new GetMetricStatisticsRequest() .withStartTime(startCal.getTime()) .withEndTime(endCal.getTime()) .withNamespace(ns) .withPeriod(60) .withMetricName("RequestCount") .withStatistics("Sum") .withDimensions(Arrays.asList(instanceDimension)); GetMetricStatisticsResult result = sort(cloudWatch.getMetricStatistics(request).getDatapoints()); if (logger.isDebugEnabled()) { if (result.getDatapoints() != null && result.getDatapoints().size() > 0) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.debug("[{}:{}] {}, {} ~ {}", new Object[] {namespace, pulse.getId(), result, sdf.format(startCal.getTime()), sdf.format(endCal.getTime())}); } } return result; }
public static GetMetricStatisticsRequest createGetMetricStatisticsRequest(String namespace, String metricName, String statisticsType, List<Dimension> dimensions) { GetMetricStatisticsRequest getMetricStatisticsRequest = new GetMetricStatisticsRequest() .withStartTime(DateTime.now(DateTimeZone.UTC).minusMinutes(1).toDate()).withNamespace(namespace).withDimensions(dimensions) .withPeriod(60).withMetricName(metricName).withStatistics(statisticsType) .withEndTime(DateTime.now(DateTimeZone.UTC).minusMinutes(0).toDate()); return getMetricStatisticsRequest; }
@Test public void shouldReportWithoutGlobalDimensionsWhenGlobalDimensionsNotConfigured() throws Exception { metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc(); reporterBuilder.build().report(); // When 'withGlobalDimensions' was not called final List<Dimension> dimensions = firstMetricDatumDimensionsFromCapturedRequest(); assertThat(dimensions).hasSize(1); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(DIMENSION_COUNT)); }
@Test public void reportedCounterShouldContainExpectedDimension() throws Exception { metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc(); reporterBuilder.build().report(); final List<Dimension> dimensions = firstMetricDatumDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(DIMENSION_COUNT)); }
@Test public void reportedGaugeShouldContainExpectedDimension() throws Exception { metricRegistry.register(ARBITRARY_GAUGE_NAME, (Gauge<Long>) () -> 1L); reporterBuilder.build().report(); final List<Dimension> dimensions = firstMetricDatumDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(DIMENSION_GAUGE)); }
@Test public void reportedMeterShouldContainExpectedOneMinuteMeanRateDimension() throws Exception { metricRegistry.meter(ARBITRARY_METER_NAME).mark(1); buildReportWithSleep(reporterBuilder.withOneMinuteMeanRate()); final List<Dimension> dimensions = allDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue("1-min-mean-rate [per-second]")); }
@Test public void reportedMeterShouldContainExpectedFiveMinuteMeanRateDimension() throws Exception { metricRegistry.meter(ARBITRARY_METER_NAME).mark(1); buildReportWithSleep(reporterBuilder.withFiveMinuteMeanRate()); final List<Dimension> dimensions = allDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue("5-min-mean-rate [per-second]")); }
@Test public void reportedMeterShouldContainExpectedFifteenMinuteMeanRateDimension() throws Exception { metricRegistry.meter(ARBITRARY_METER_NAME).mark(1); buildReportWithSleep(reporterBuilder.withFifteenMinuteMeanRate()); final List<Dimension> dimensions = allDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue("15-min-mean-rate [per-second]")); }
@Test public void reportedMeterShouldContainExpectedMeanRateDimension() throws Exception { metricRegistry.meter(ARBITRARY_METER_NAME).mark(1); reporterBuilder.withMeanRate().build().report(); final List<Dimension> dimensions = allDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue("mean-rate [per-second]")); }
@Test public void reportedHistogramShouldContainExpectedArithmeticMeanDimension() throws Exception { metricRegistry.histogram(ARBITRARY_HISTOGRAM_NAME).update(1); reporterBuilder.withArithmeticMean().build().report(); final List<Dimension> dimensions = allDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(DIMENSION_SNAPSHOT_MEAN)); }
@Test public void reportedHistogramShouldContainExpectedStdDevDimension() throws Exception { metricRegistry.histogram(CloudWatchReporterTest.ARBITRARY_HISTOGRAM_NAME).update(1); metricRegistry.histogram(CloudWatchReporterTest.ARBITRARY_HISTOGRAM_NAME).update(2); reporterBuilder.withStdDev().build().report(); final List<Dimension> dimensions = allDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue(DIMENSION_SNAPSHOT_STD_DEV)); }
@Test public void reportedTimerShouldContainExpectedArithmeticMeanDimension() throws Exception { metricRegistry.timer(ARBITRARY_TIMER_NAME).update(3, TimeUnit.MILLISECONDS); reporterBuilder.withArithmeticMean().build().report(); final List<Dimension> dimensions = allDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue("snapshot-mean [in-milliseconds]")); }
@Test public void reportedTimerShouldContainExpectedStdDevDimension() throws Exception { metricRegistry.timer(ARBITRARY_TIMER_NAME).update(1, TimeUnit.MILLISECONDS); metricRegistry.timer(ARBITRARY_TIMER_NAME).update(3, TimeUnit.MILLISECONDS); reporterBuilder.withStdDev().build().report(); final List<Dimension> dimensions = allDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName(DIMENSION_NAME_TYPE).withValue("snapshot-std-dev [in-milliseconds]")); }
@Test public void shouldReportExpectedSingleGlobalDimension() throws Exception { metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc(); reporterBuilder.withGlobalDimensions("Region=us-west-2").build().report(); final List<Dimension> dimensions = firstMetricDatumDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName("Region").withValue("us-west-2")); }
@Test public void shouldReportExpectedMultipleGlobalDimensions() throws Exception { metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc(); reporterBuilder.withGlobalDimensions("Region=us-west-2", "Instance=stage").build().report(); final List<Dimension> dimensions = firstMetricDatumDimensionsFromCapturedRequest(); assertThat(dimensions).contains(new Dimension().withName("Region").withValue("us-west-2")); assertThat(dimensions).contains(new Dimension().withName("Instance").withValue("stage")); }
@Test public void shouldNotReportDuplicateGlobalDimensions() throws Exception { metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc(); reporterBuilder.withGlobalDimensions("Region=us-west-2", "Region=us-west-2").build().report(); final List<Dimension> dimensions = firstMetricDatumDimensionsFromCapturedRequest(); assertThat(dimensions).containsNoDuplicates(); }