software.amazon.awssdk.services.cloudwatch.model.MetricDatum Java Examples

The following examples show how to use software.amazon.awssdk.services.cloudwatch.model.MetricDatum. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CloudWatchReporter.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
/**
 * The {@link Snapshot} values of {@link Histogram} are reported as {@link StatisticSet} raw. In other words, the
 * conversion using the duration factor does NOT apply.
 * <p>
 * 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
 *
 * @see Histogram#getSnapshot
 */
private void processHistogram(final String metricName, final Histogram histogram, final List<MetricDatum> metricData) {
    final Snapshot snapshot = histogram.getSnapshot();

    if (builder.withZeroValuesSubmission || snapshot.size() > 0) {
        for (final Percentile percentile : builder.percentiles) {
            final double value = snapshot.getValue(percentile.getQuantile());
            stageMetricDatum(true, metricName, value, StandardUnit.NONE, percentile.getDesc(), metricData);
        }
    }

    // prevent empty snapshot from causing InvalidParameterValueException
    if (snapshot.size() > 0) {
        stageMetricDatum(builder.withArithmeticMean, metricName, snapshot.getMean(), StandardUnit.NONE, DIMENSION_SNAPSHOT_MEAN, metricData);
        stageMetricDatum(builder.withStdDev, metricName, snapshot.getStdDev(), StandardUnit.NONE, DIMENSION_SNAPSHOT_STD_DEV, metricData);
        stageMetricDatumWithRawSnapshot(builder.withStatisticSet, metricName, snapshot, StandardUnit.NONE, metricData);
    }
}
 
Example #2
Source File: CloudWatchMetricsPublisherTest.java    From amazon-kinesis-client with Apache License 2.0 6 votes vote down vote up
public List<Map<String, MetricDatum>> constructMetricDatumListMap(List<MetricDatumWithKey<CloudWatchMetricKey>> data) {
    int batchSize = 20;
    List<Map<String, MetricDatum>> dataList = new ArrayList<Map<String, MetricDatum>>();

    int expectedRequestcount = (int) Math.ceil(data.size() / 20.0);

    for (int i = 0; i < expectedRequestcount; i++) {
        dataList.add(i, new HashMap<>());
    }

    int batchIndex = 1;
    int listIndex = 0;
    for (MetricDatumWithKey<CloudWatchMetricKey> metricDatumWithKey : data) {
        if (batchIndex > batchSize) {
            batchIndex = 1;
            listIndex++;
        }
        batchIndex++;
        dataList.get(listIndex).put(metricDatumWithKey.datum.metricName(), metricDatumWithKey.datum);
    }
    return dataList;
}
 
Example #3
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
protected void publish() {
    boolean interrupted = false;
    try {
        for (List<MetricDatum> batch : MetricDatumPartition.partition(metricData(), config.batchSize())) {
            try {
                sendMetricData(batch);
            } catch (InterruptedException ex) {
                interrupted = true;
            }
        }
    }
    finally {
        if (interrupted) {
            Thread.currentThread().interrupt();
        }
    }
}
 
Example #4
Source File: CloudWatchMetricsPublisherTest.java    From amazon-kinesis-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsPublisher() {
    final CompletableFuture<PutMetricDataResponse> putResponseFuture = new CompletableFuture<>();
    putResponseFuture.complete(PutMetricDataResponse.builder().build());
    when(cloudWatchClient.putMetricData(any(PutMetricDataRequest.class))).thenReturn(putResponseFuture);

    List<MetricDatumWithKey<CloudWatchMetricKey>> dataToPublish = constructMetricDatumWithKeyList(25);
    List<Map<String, MetricDatum>> expectedData = constructMetricDatumListMap(dataToPublish);
    publisher.publishMetrics(dataToPublish);
    
    ArgumentCaptor<PutMetricDataRequest> argument = ArgumentCaptor.forClass(PutMetricDataRequest.class);
    Mockito.verify(cloudWatchClient, Mockito.atLeastOnce()).putMetricData(argument.capture());

    List<PutMetricDataRequest> requests = argument.getAllValues();
    Assert.assertEquals(expectedData.size(), requests.size());

    for (int i = 0; i < requests.size(); i++) {
        assertMetricData(expectedData.get(i), requests.get(i));
    }

}
 
Example #5
Source File: MetricsPublisherImplTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublishInvocationMetric() {
    final MetricsPublisherImpl providerMetricsPublisher = new MetricsPublisherImpl(providerCloudWatchProvider, loggerProxy,
                                                                                   awsAccountId, resourceTypeName);
    providerMetricsPublisher.refreshClient();

    final Instant instant = Instant.parse("2019-06-04T17:50:00Z");
    providerMetricsPublisher.publishInvocationMetric(instant, Action.UPDATE);

    final ArgumentCaptor<PutMetricDataRequest> argument1 = ArgumentCaptor.forClass(PutMetricDataRequest.class);
    verify(providerCloudWatchClient).putMetricData(argument1.capture());

    final PutMetricDataRequest request = argument1.getValue();
    assertThat(request.namespace())
        .isEqualTo(String.format("%s/%s/%s", "AWS/CloudFormation", awsAccountId, "AWS/Test/TestModel"));

    assertThat(request.metricData()).hasSize(1);
    final MetricDatum metricDatum = request.metricData().get(0);
    assertThat(metricDatum.metricName()).isEqualTo("HandlerInvocationCount");
    assertThat(metricDatum.unit()).isEqualTo(StandardUnit.COUNT);
    assertThat(metricDatum.value()).isEqualTo(1.0);
    assertThat(metricDatum.timestamp()).isEqualTo(Instant.parse("2019-06-04T17:50:00Z"));
    assertThat(metricDatum.dimensions()).containsExactlyInAnyOrder(Dimension.builder().name("Action").value("UPDATE").build(),
        Dimension.builder().name("ResourceType").value(resourceTypeName).build());
}
 
Example #6
Source File: MetricsPublisherImplTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublishDurationMetric() {
    final MetricsPublisherImpl providerMetricsPublisher = new MetricsPublisherImpl(providerCloudWatchProvider, loggerProxy,
                                                                                   awsAccountId, resourceTypeName);
    providerMetricsPublisher.refreshClient();

    final Instant instant = Instant.parse("2019-06-04T17:50:00Z");
    providerMetricsPublisher.publishDurationMetric(instant, Action.UPDATE, 123456);

    final ArgumentCaptor<PutMetricDataRequest> argument1 = ArgumentCaptor.forClass(PutMetricDataRequest.class);
    verify(providerCloudWatchClient).putMetricData(argument1.capture());

    final PutMetricDataRequest request = argument1.getValue();
    assertThat(request.namespace())
        .isEqualTo(String.format("%s/%s/%s", "AWS/CloudFormation", awsAccountId, "AWS/Test/TestModel"));

    assertThat(request.metricData()).hasSize(1);
    final MetricDatum metricDatum = request.metricData().get(0);
    assertThat(metricDatum.metricName()).isEqualTo("HandlerInvocationDuration");
    assertThat(metricDatum.unit()).isEqualTo(StandardUnit.MILLISECONDS);
    assertThat(metricDatum.value()).isEqualTo(123456);
    assertThat(metricDatum.timestamp()).isEqualTo(Instant.parse("2019-06-04T17:50:00Z"));
    assertThat(metricDatum.dimensions()).containsExactlyInAnyOrder(Dimension.builder().name("Action").value("UPDATE").build(),
        Dimension.builder().name("ResourceType").value(resourceTypeName).build());
}
 
Example #7
Source File: MetricAccumulatingQueue.java    From amazon-kinesis-client with Apache License 2.0 6 votes vote down vote up
/**
 * We use a queue and a map in this method. The reason for this is because, the queue will keep our metrics in
 * FIFO order and the map will provide us with constant time lookup to get the appropriate MetricDatum.
 * 
 * @param key metric key to be inserted into queue
 * @param datum metric to be inserted into queue
 * @return a boolean depending on whether the datum was inserted into the queue
 */
public synchronized boolean offer(KeyType key, MetricDatum datum) {
    MetricDatumWithKey<KeyType> metricDatumWithKey = map.get(key);

    if (metricDatumWithKey == null) {
        metricDatumWithKey = new MetricDatumWithKey<>(key, datum);
        boolean offered = queue.offer(metricDatumWithKey);
        if (offered) {
            map.put(key, metricDatumWithKey);
        }

        return offered;
    } else {
        accumulate(metricDatumWithKey, datum);
        return true;
    }
}
 
Example #8
Source File: PutMetricData.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void putMetData(CloudWatchClient cw, Double dataPoint ) {

        try {
            Dimension dimension = Dimension.builder()
                .name("UNIQUE_PAGES")
                .value("URLS").build();

            MetricDatum datum = MetricDatum.builder()
                .metricName("PAGES_VISITED")
                .unit(StandardUnit.NONE)
                .value(dataPoint)
                .dimensions(dimension).build();

            PutMetricDataRequest request = PutMetricDataRequest.builder()
                .namespace("SITE/TRAFFIC")
                .metricData(datum).build();

            PutMetricDataResponse response = cw.putMetricData(request);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.printf("Successfully put data point %f", dataPoint);
        // snippet-end:[cloudwatch.java2.put_metric_data.main]
    }
 
Example #9
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
private MetricDatum metricDatumByDimensionFromCapturedRequest(final String dimensionValue) {
    final PutMetricDataRequest putMetricDataRequest = metricDataRequestCaptor.getValue();
    final List<MetricDatum> metricData = putMetricDataRequest.metricData();

    final Optional<MetricDatum> metricDatumOptional =
            metricData
                    .stream()
                    .filter(metricDatum -> metricDatum.dimensions()
                            .contains(Dimension.builder().name(DIMENSION_NAME_TYPE).value(dimensionValue).build()))
                    .findFirst();

    if (metricDatumOptional.isPresent()) {
        return metricDatumOptional.get();
    }

    throw new IllegalStateException("Could not find MetricDatum for Dimension value: " + dimensionValue);
}
 
Example #10
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
@Test
public void shouldNotReportCounterValueDeltaWhenReportingRawCountValue() throws Exception {
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    final CloudWatchReporter cloudWatchReporter = reporterBuilder.withReportRawCountValue().build();

    cloudWatchReporter.report();
    MetricDatum metricDatum = firstMetricDatumFromCapturedRequest();
    assertThat(metricDatum.value().intValue()).isEqualTo(2);
    metricDataRequestCaptor.getAllValues().clear();

    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();

    cloudWatchReporter.report();
    metricDatum = firstMetricDatumFromCapturedRequest();
    assertThat(metricDatum.value().intValue()).isEqualTo(8);

    verify(mockAmazonCloudWatchAsyncClient, times(2)).putMetricData(any(PutMetricDataRequest.class));
}
 
Example #11
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
@Test
public void shouldReportCounterValueDelta() throws Exception {
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    final CloudWatchReporter cloudWatchReporter = reporterBuilder.build();

    cloudWatchReporter.report();
    MetricDatum metricDatum = firstMetricDatumFromCapturedRequest();
    assertThat(metricDatum.value().intValue()).isEqualTo(2);
    metricDataRequestCaptor.getAllValues().clear();

    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();

    cloudWatchReporter.report();
    metricDatum = firstMetricDatumFromCapturedRequest();
    assertThat(metricDatum.value().intValue()).isEqualTo(6);

    verify(mockAmazonCloudWatchAsyncClient, times(2)).putMetricData(any(PutMetricDataRequest.class));
}
 
Example #12
Source File: CloudWatchMeterRegistryTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void batchSizeShouldWorkOnMetricDatum() throws InterruptedException {
    List<Meter> meters = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
        Timer timer = Timer.builder("timer." + i).register(this.registry);
        meters.add(timer);
    }
    when(this.registry.getMeters()).thenReturn(meters);
    doNothing().when(this.registry).sendMetricData(any());
    this.registry.publish();
    @SuppressWarnings("unchecked")
    ArgumentCaptor<List<MetricDatum>> argumentCaptor = ArgumentCaptor.forClass(List.class);
    verify(this.registry, times(2)).sendMetricData(argumentCaptor.capture());
    List<List<MetricDatum>> allValues = argumentCaptor.getAllValues();
    assertThat(allValues.get(0)).hasSize(20);
    assertThat(allValues.get(1)).hasSize(20);
}
 
Example #13
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
@Test
public void reportMetersCountersGaugesWithZeroValuesOnlyWhenConfigured() throws Exception {
    metricRegistry.register(ARBITRARY_GAUGE_NAME, (Gauge<Long>) () -> 0L);
    metricRegistry.meter(ARBITRARY_METER_NAME).mark(0);
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc(0);
    metricRegistry.timer(ARBITRARY_TIMER_NAME).update(-1L, TimeUnit.NANOSECONDS);

    buildReportWithSleep(reporterBuilder
            .withArithmeticMean()
            .withOneMinuteMeanRate()
            .withFiveMinuteMeanRate()
            .withFifteenMinuteMeanRate()
            .withZeroValuesSubmission()
            .withMeanRate());

    verify(mockAmazonCloudWatchAsyncClient, times(1)).putMetricData(metricDataRequestCaptor.capture());

    final PutMetricDataRequest putMetricDataRequest = metricDataRequestCaptor.getValue();
    final List<MetricDatum> metricData = putMetricDataRequest.metricData();
    for (final MetricDatum metricDatum : metricData) {
        assertThat(metricDatum.value()).isEqualTo(0.0);
    }
}
 
Example #14
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
@Test
public void shouldReportSnapshotValuesWithoutConversionWhenReportingHistogram() throws Exception {
    metricRegistry.histogram(CloudWatchReporterTest.ARBITRARY_HISTOGRAM_NAME).update(1);
    metricRegistry.histogram(CloudWatchReporterTest.ARBITRARY_HISTOGRAM_NAME).update(2);
    metricRegistry.histogram(CloudWatchReporterTest.ARBITRARY_HISTOGRAM_NAME).update(3);
    metricRegistry.histogram(CloudWatchReporterTest.ARBITRARY_HISTOGRAM_NAME).update(30);
    reporterBuilder.withStatisticSet().build().report();

    final MetricDatum metricData = metricDatumByDimensionFromCapturedRequest(DIMENSION_SNAPSHOT_SUMMARY);

    assertThat(metricData.statisticValues().sum().intValue()).isEqualTo(36);
    assertThat(metricData.statisticValues().maximum().intValue()).isEqualTo(30);
    assertThat(metricData.statisticValues().minimum().intValue()).isEqualTo(1);
    assertThat(metricData.statisticValues().sampleCount().intValue()).isEqualTo(4);
    assertThat(metricData.unit()).isEqualTo(StandardUnit.NONE);
}
 
Example #15
Source File: CloudWatchAsyncStabilityTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class)
public void putMetrics_lowTpsLongInterval() {
    List<MetricDatum> metrics = new ArrayList<>();
    for (int i = 0; i < 20 ; i++) {
        metrics.add(MetricDatum.builder()
                               .metricName("test")
                               .values(RandomUtils.nextDouble(1d, 1000d))
                               .build());
    }

    IntFunction<CompletableFuture<?>> futureIntFunction = i ->
        cloudWatchAsyncClient.putMetricData(b -> b.namespace(namespace)
                                                  .metricData(metrics));

    runCloudWatchTest("putMetrics_lowTpsLongInterval", futureIntFunction);
}
 
Example #16
Source File: CloudWatchReporter.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
private void processCounter(final String metricName, final Counting counter, final List<MetricDatum> metricData) {
    long currentCount = counter.getCount();
    Long lastCount = lastPolledCounts.get(counter);
    lastPolledCounts.put(counter, currentCount);

    if (lastCount == null) {
        lastCount = 0L;
    }

    final long reportValue;
    if (builder.withReportRawCountValue) {
        reportValue = currentCount;
    } else {
        // Only submit metrics that have changed - let's save some money!
        reportValue = currentCount - lastCount;
    }

    stageMetricDatum(true, metricName, reportValue, StandardUnit.COUNT, DIMENSION_COUNT, metricData);
}
 
Example #17
Source File: CloudWatchReporter.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
/**
 * 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 DimensionedName dimensionedName = DimensionedName.decode(metricName);

        final Set<Dimension> dimensions = new LinkedHashSet<>(builder.globalDimensions);
        dimensions.add(Dimension.builder().name(DIMENSION_NAME_TYPE).value(dimensionValue).build());
        dimensions.addAll(dimensionedName.getDimensions());

        metricData.add(MetricDatum.builder()
                .timestamp(Instant.ofEpochMilli(builder.clock.getTime()))
                .value(cleanMetricValue(metricValue))
                .metricName(dimensionedName.getName())
                .dimensions(dimensions)
                .storageResolution(highResolution ? HIGH_RESOLUTION : STANDARD_RESOLUTION)
                .unit(standardUnit)
                .build());
    }
}
 
Example #18
Source File: CloudWatchReporter.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 6 votes vote down vote up
/**
 * The {@link Snapshot} values of {@link Timer} are reported as {@link StatisticSet} after conversion. The
 * conversion is done using the duration factor, which is deduced from the set duration unit.
 * <p>
 * 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
 *
 * @see Timer#getSnapshot
 * @see #getDurationUnit
 * @see #convertDuration(double)
 */
private void processTimer(final String metricName, final Timer timer, final List<MetricDatum> metricData) {
    final Snapshot snapshot = timer.getSnapshot();

    if (builder.withZeroValuesSubmission || snapshot.size() > 0) {
        for (final Percentile percentile : builder.percentiles) {
            final double convertedDuration = convertDuration(snapshot.getValue(percentile.getQuantile()));
            stageMetricDatum(true, metricName, convertedDuration, durationUnit, percentile.getDesc(), metricData);
        }
    }

    // prevent empty snapshot from causing InvalidParameterValueException
    if (snapshot.size() > 0) {
        final String formattedDuration = String.format(" [in-%s]", getDurationUnit());
        stageMetricDatum(builder.withArithmeticMean, metricName, convertDuration(snapshot.getMean()), durationUnit, DIMENSION_SNAPSHOT_MEAN + formattedDuration, metricData);
        stageMetricDatum(builder.withStdDev, metricName, convertDuration(snapshot.getStdDev()), durationUnit, DIMENSION_SNAPSHOT_STD_DEV + formattedDuration, metricData);
        stageMetricDatumWithConvertedSnapshot(builder.withStatisticSet, metricName, snapshot, durationUnit, metricData);
    }
}
 
Example #19
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Nullable
private MetricDatum metricDatum(Meter.Id id, @Nullable String suffix, StandardUnit standardUnit, double value) {
    if (Double.isNaN(value)) {
        return null;
    }

    List<Tag> tags = id.getConventionTags(config().namingConvention());
    return MetricDatum.builder()
            .storageResolution(config.highResolution() ? 1 : 60)
            .metricName(getMetricName(id, suffix))
            .dimensions(toDimensions(tags))
            .timestamp(timestamp)
            .value(CloudWatchUtils.clampMetricValue(value))
            .unit(standardUnit)
            .build();
}
 
Example #20
Source File: MetricsPublisherImplTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublishExceptionMetric() {
    final MetricsPublisherImpl providerMetricsPublisher = new MetricsPublisherImpl(providerCloudWatchProvider, loggerProxy,
                                                                                   awsAccountId, resourceTypeName);
    providerMetricsPublisher.refreshClient();

    final Instant instant = Instant.parse("2019-06-03T17:50:00Z");
    final RuntimeException e = new RuntimeException("some error");
    providerMetricsPublisher.publishExceptionMetric(instant, Action.CREATE, e, HandlerErrorCode.InternalFailure);

    final ArgumentCaptor<PutMetricDataRequest> argument1 = ArgumentCaptor.forClass(PutMetricDataRequest.class);
    verify(providerCloudWatchClient).putMetricData(argument1.capture());

    final PutMetricDataRequest request = argument1.getValue();
    assertThat(request.namespace())
        .isEqualTo(String.format("%s/%s/%s", "AWS/CloudFormation", awsAccountId, "AWS/Test/TestModel"));

    assertThat(request.metricData()).hasSize(1);
    final MetricDatum metricDatum = request.metricData().get(0);
    assertThat(metricDatum.metricName()).isEqualTo("HandlerException");
    assertThat(metricDatum.unit()).isEqualTo(StandardUnit.COUNT);
    assertThat(metricDatum.value()).isEqualTo(1.0);
    assertThat(metricDatum.timestamp()).isEqualTo(Instant.parse("2019-06-03T17:50:00Z"));
    assertThat(metricDatum.dimensions()).containsExactlyInAnyOrder(Dimension.builder().name("Action").value("CREATE").build(),
        Dimension.builder().name("ExceptionType").value("class java.lang.RuntimeException").build(),
        Dimension.builder().name("ResourceType").value(resourceTypeName).build(),
        Dimension.builder().name("HandlerErrorCode").value("InternalFailure").build());
}
 
Example #21
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 5 votes vote down vote up
private List<Dimension> allDimensionsFromCapturedRequest() {
    final PutMetricDataRequest putMetricDataRequest = metricDataRequestCaptor.getValue();
    final List<MetricDatum> metricData = putMetricDataRequest.metricData();
    final List<Dimension> all = new LinkedList<>();
    for (final MetricDatum metricDatum : metricData) {
        all.addAll(metricDatum.dimensions());
    }
    return all;
}
 
Example #22
Source File: CloudWatchMetricsPublisherTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
public static void assertMetricData(Map<String, MetricDatum> expected, PutMetricDataRequest actual) {
    List<MetricDatum> actualData = actual.metricData();
    for (MetricDatum actualDatum : actualData) {
        String metricName = actualDatum.metricName();
        Assert.assertNotNull(expected.get(metricName));
        Assert.assertTrue(expected.get(metricName).equals(actualDatum));
        expected.remove(metricName);
    }

    Assert.assertTrue(expected.isEmpty());
}
 
Example #23
Source File: AccumulatingMetricsScopeTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
public void assertMetrics(MetricDatum... expectedData) {
    for (MetricDatum expected : expectedData) {
        MetricDatum actual = data.remove(expected.metricName());
        Assert.assertEquals(expected, actual);
    }

    Assert.assertEquals("Data should be empty at the end of assertMetrics", 0, data.size());
}
 
Example #24
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 5 votes vote down vote up
@Test
public void settingHighResolutionGeneratesMetricsWithStorageResolutionSetToOne() throws Exception {
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    reporterBuilder.withHighResolution().build().report();

    final MetricDatum firstMetricDatum = firstMetricDatumFromCapturedRequest();

    assertThat(firstMetricDatum.storageResolution()).isEqualTo(1);
}
 
Example #25
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 5 votes vote down vote up
@Test
public void notSettingHighResolutionGeneratesMetricsWithStorageResolutionSetToSixty() throws Exception {
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    reporterBuilder.build().report();

    final MetricDatum firstMetricDatum = firstMetricDatumFromCapturedRequest();
    
    assertThat(firstMetricDatum.storageResolution()).isEqualTo(60);
}
 
Example #26
Source File: CloudWatchReporter.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 5 votes vote down vote up
private void stageMetricDatumWithRawSnapshot(final boolean metricConfigured,
                                             final String metricName,
                                             final Snapshot snapshot,
                                             final StandardUnit standardUnit,
                                             final List<MetricDatum> metricData) {
    if (metricConfigured) {
        final DimensionedName dimensionedName = DimensionedName.decode(metricName);
        double total = LongStream.of(snapshot.getValues()).sum();
        final StatisticSet statisticSet =StatisticSet
                .builder()
                .sum(total)
                .sampleCount((double) snapshot.size())
                .minimum((double) snapshot.getMin())
                .maximum((double) snapshot.getMax())
                .build();

        final Set<Dimension> dimensions = new LinkedHashSet<>(builder.globalDimensions);
        dimensions.add(Dimension.builder().name(DIMENSION_NAME_TYPE).value(DIMENSION_SNAPSHOT_SUMMARY).build());
        dimensions.addAll(dimensionedName.getDimensions());

        metricData.add(MetricDatum
                .builder()
                .timestamp(Instant.ofEpochMilli(builder.clock.getTime()))
                .metricName(dimensionedName.getName())
                .dimensions(dimensions)
                .statisticValues(statisticSet)
                .storageResolution(highResolution ? HIGH_RESOLUTION : STANDARD_RESOLUTION)
                .unit(standardUnit)
                .build());
    }
}
 
Example #27
Source File: CloudWatchReporter.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 5 votes vote down vote up
private void stageMetricDatumWithConvertedSnapshot(final boolean metricConfigured,
                                                   final String metricName,
                                                   final Snapshot snapshot,
                                                   final StandardUnit standardUnit,
                                                   final List<MetricDatum> metricData) {
    if (metricConfigured) {
        final DimensionedName dimensionedName = DimensionedName.decode(metricName);
        double scaledSum = convertDuration(LongStream.of(snapshot.getValues()).sum());
        final StatisticSet statisticSet = StatisticSet.builder()
                .sum(scaledSum)
                .sampleCount((double) snapshot.size())
                .minimum(convertDuration(snapshot.getMin()))
                .maximum(convertDuration(snapshot.getMax()))
                .build();

        final Set<Dimension> dimensions = new LinkedHashSet<>(builder.globalDimensions);
        dimensions.add(Dimension.builder().name(DIMENSION_NAME_TYPE).value(DIMENSION_SNAPSHOT_SUMMARY).build());
        dimensions.addAll(dimensionedName.getDimensions());

        metricData.add(MetricDatum
                .builder()
                .timestamp(Instant.ofEpochMilli(builder.clock.getTime()))
                .metricName(dimensionedName.getName())
                .dimensions(dimensions)
                .statisticValues(statisticSet)
                .storageResolution(highResolution ? HIGH_RESOLUTION : STANDARD_RESOLUTION)
                .unit(standardUnit)
                .build());
    }
}
 
Example #28
Source File: TestHelper.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
public static MetricDatum constructDatum(String name,
                                         StandardUnit unit,
                                         double maximum,
                                         double minimum,
                                         double sum,
                                         double count) {
    return MetricDatum.builder().metricName(name)
            .unit(unit)
            .statisticValues(StatisticSet.builder().maximum(maximum)
                    .minimum(minimum)
                    .sum(sum)
                    .sampleCount(count).build()).build();
}
 
Example #29
Source File: CloudWatchPublisherRunnableTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
private MetricDatumWithKey<CloudWatchMetricKey> constructDatum(int value) {
    MetricDatum datum = TestHelper.constructDatum("datum-" + Integer.toString(value),
            StandardUnit.COUNT,
            value,
            value,
            value,
            1);

    return new MetricDatumWithKey<CloudWatchMetricKey>(new CloudWatchMetricKey(datum), datum);
}
 
Example #30
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 5 votes vote down vote up
@Test
public void shouldReportExpectedCounterValue() throws Exception {
    metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc();
    reporterBuilder.build().report();

    final MetricDatum metricDatum = firstMetricDatumFromCapturedRequest();

    assertThat(metricDatum.value()).isWithin(1.0);
    assertThat(metricDatum.unit()).isEqualTo(StandardUnit.COUNT);
}