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

The following examples show how to use software.amazon.awssdk.services.cloudwatch.model.StandardUnit. 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
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 #2
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 #3
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 #4
Source File: MetricsPublisherImpl.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
private void publishMetric(final String metricName,
                           final Map<String, String> dimensionData,
                           final StandardUnit unit,
                           final Double value,
                           final Instant timestamp) {
    assert cloudWatchClient != null : "CloudWatchEventsClient was not initialised. You must call refreshClient() first.";

    List<Dimension> dimensions = new ArrayList<>();
    for (Map.Entry<String, String> kvp : dimensionData.entrySet()) {
        Dimension dimension = Dimension.builder().name(kvp.getKey()).value(kvp.getValue()).build();
        dimensions.add(dimension);
    }

    MetricDatum metricDatum = MetricDatum.builder().metricName(metricName).unit(unit).value(value).dimensions(dimensions)
        .timestamp(timestamp).build();

    PutMetricDataRequest putMetricDataRequest = PutMetricDataRequest.builder()
        .namespace(String.format("%s/%s/%s", Metric.METRIC_NAMESPACE_ROOT, providerAccountId, resourceNamespace))
        .metricData(metricDatum).build();

    try {
        this.cloudWatchClient.putMetricData(putMetricDataRequest);
    } catch (final Exception e) {
        log(String.format("An error occurred while publishing metrics: %s", e.getMessage()));
    }
}
 
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 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 #6
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 #7
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 #8
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 #9
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 #10
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 5 votes vote down vote up
@Test
public void shouldReportHistogramSubsequentSnapshotValues_SumMaxMinValues() throws Exception {
    CloudWatchReporter reporter = reporterBuilder.withStatisticSet().build();

    final Histogram slidingWindowHistogram = new Histogram(new SlidingWindowReservoir(4));
    metricRegistry.register("SlidingWindowHistogram", slidingWindowHistogram);

    slidingWindowHistogram.update(1);
    slidingWindowHistogram.update(2);
    slidingWindowHistogram.update(30);
    reporter.report();

    final MetricDatum metricData = metricDatumByDimensionFromCapturedRequest(DIMENSION_SNAPSHOT_SUMMARY);

    assertThat(metricData.statisticValues().maximum().intValue()).isEqualTo(30);
    assertThat(metricData.statisticValues().minimum().intValue()).isEqualTo(1);
    assertThat(metricData.statisticValues().sampleCount().intValue()).isEqualTo(3);
    assertThat(metricData.statisticValues().sum().intValue()).isEqualTo(33);
    assertThat(metricData.unit()).isEqualTo(StandardUnit.NONE);

    slidingWindowHistogram.update(4);
    slidingWindowHistogram.update(100);
    slidingWindowHistogram.update(5);
    slidingWindowHistogram.update(6);
    reporter.report();

    final MetricDatum secondMetricData = metricDatumByDimensionFromCapturedRequest(DIMENSION_SNAPSHOT_SUMMARY);

    assertThat(secondMetricData.statisticValues().maximum().intValue()).isEqualTo(100);
    assertThat(secondMetricData.statisticValues().minimum().intValue()).isEqualTo(4);
    assertThat(secondMetricData.statisticValues().sampleCount().intValue()).isEqualTo(4);
    assertThat(secondMetricData.statisticValues().sum().intValue()).isEqualTo(115);
    assertThat(secondMetricData.unit()).isEqualTo(StandardUnit.NONE);
}
 
Example #11
Source File: AccumulatingMetricsScope.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
/**
 * Adds data points to an IMetricsScope. Multiple calls to IMetricsScopes that have the 
 * same key will have their data accumulated.
 * 
 * @param key
 *        data point key
 * @param name
 *        data point name
 * @param value
 *        data point value
 * @param unit
 *        data point unit
 */
public void addData(KeyType key, String name, double value, StandardUnit unit) {
    super.addData(name, value, unit);

    final MetricDatum datum = data.get(key);
    final MetricDatum metricDatum;
    if (datum == null) {
        metricDatum = MetricDatum.builder().metricName(name).unit(unit)
                .statisticValues(
                        StatisticSet.builder().maximum(value).minimum(value).sampleCount(1.0).sum(value).build())
                .build();
    } else {
        if (!datum.unit().equals(unit)) {
            throw new IllegalArgumentException("Cannot add to existing metric with different unit");
        }

        final StatisticSet oldStatisticSet = datum.statisticValues();
        final StatisticSet statisticSet = oldStatisticSet.toBuilder()
                .maximum(Math.max(value, oldStatisticSet.maximum()))
                .minimum(Math.min(value, oldStatisticSet.minimum())).sampleCount(oldStatisticSet.sampleCount() + 1)
                .sum(oldStatisticSet.sum() + value).build();

        metricDatum = datum.toBuilder().statisticValues(statisticSet).build();
    }

    data.put(key, metricDatum);
}
 
Example #12
Source File: MetricsPublisherImpl.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void publishExceptionMetric(final Instant timestamp,
                                   final Action action,
                                   final Throwable e,
                                   final HandlerErrorCode handlerErrorCode) {
    Map<String, String> dimensions = new HashMap<>();
    dimensions.put(Metric.DIMENSION_KEY_ACTION_TYPE, action == null ? "NO_ACTION" : action.name());
    dimensions.put(Metric.DIMENSION_KEY_EXCEPTION_TYPE, e.getClass().toString());
    dimensions.put(Metric.DIMENSION_KEY_RESOURCE_TYPE, this.getResourceTypeName());
    dimensions.put(Metric.DIMENSION_KEY_HANDLER_ERROR_CODE, handlerErrorCode.name());

    publishMetric(Metric.METRIC_NAME_HANDLER_EXCEPTION, dimensions, StandardUnit.COUNT, 1.0, timestamp);
}
 
Example #13
Source File: PutMetricAlarm.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void putMetricAlarm(CloudWatchClient cw, String alarmName, String instanceId) {

        try {
            Dimension dimension = Dimension.builder()
                .name("InstanceId")
                .value(instanceId).build();

            PutMetricAlarmRequest request = PutMetricAlarmRequest.builder()
                .alarmName(alarmName)
                .comparisonOperator(
                        ComparisonOperator.GREATER_THAN_THRESHOLD)
                .evaluationPeriods(1)
                .metricName("CPUUtilization")
                .namespace("AWS/EC2")
                .period(60)
                .statistic(Statistic.AVERAGE)
                .threshold(70.0)
                .actionsEnabled(false)
                .alarmDescription(
                        "Alarm when server CPU utilization exceeds 70%")
                .unit(StandardUnit.SECONDS)
                .dimensions(dimension)
                .build();

            PutMetricAlarmResponse response = cw.putMetricAlarm(request);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

       System.out.printf(
                "Successfully created alarm with name %s", alarmName);
        // snippet-end:[cloudwatch.java2.put_metric_alarm.main]
    }
 
Example #14
Source File: MetricsUtil.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
public static void addLatency(@NonNull final MetricsScope metricsScope, final String dimension,
                              final long startTime, @NonNull final MetricsLevel metricsLevel) {
    final String metricName = StringUtils.isEmpty(dimension) ? TIME_METRIC
            : String.format("%s.%s", dimension, TIME_METRIC);
    metricsScope.addData(metricName, System.currentTimeMillis() - startTime, StandardUnit.MILLISECONDS,
            metricsLevel);
}
 
Example #15
Source File: CloudWatchReporterTest.java    From codahale-aggregated-metrics-cloudwatch-reporter with MIT License 5 votes vote down vote up
@Test
public void shouldReportStdDevWithoutConversionWhenReportingHistogram() 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.withStdDev().build().report();

    final MetricDatum metricData = metricDatumByDimensionFromCapturedRequest(DIMENSION_SNAPSHOT_STD_DEV);

    assertThat(metricData.value().intValue()).isEqualTo(12);
    assertThat(metricData.unit()).isEqualTo(StandardUnit.NONE);
}
 
Example #16
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
Stream<MetricDatum> functionTimerData(FunctionTimer timer) {
    // we can't know anything about max and percentiles originating from a function timer
    double sum = timer.totalTime(getBaseTimeUnit());
    if (!Double.isFinite(sum)) {
        return Stream.empty();
    }
    Stream.Builder<MetricDatum> metrics = Stream.builder();
    double count = timer.count();
    metrics.add(metricDatum(timer.getId(), "count", StandardUnit.COUNT, count));
    metrics.add(metricDatum(timer.getId(), "sum", sum));
    if (count > 0) {
        metrics.add(metricDatum(timer.getId(), "avg", timer.mean(getBaseTimeUnit())));
    }
    return metrics.build();
}
 
Example #17
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
Stream<MetricDatum> summaryData(DistributionSummary summary) {
    Stream.Builder<MetricDatum> metrics = Stream.builder();
    metrics.add(metricDatum(summary.getId(), "sum", summary.totalAmount()));
    long count = summary.count();
    metrics.add(metricDatum(summary.getId(), "count", StandardUnit.COUNT, count));
    if (count > 0) {
        metrics.add(metricDatum(summary.getId(), "avg", summary.mean()));
        metrics.add(metricDatum(summary.getId(), "max", summary.max()));
    }
    return metrics.build();
}
 
Example #18
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
Stream<MetricDatum> functionCounterData(FunctionCounter counter) {
    MetricDatum metricDatum = metricDatum(counter.getId(), "count", StandardUnit.COUNT, counter.count());
    if (metricDatum == null) {
        return Stream.empty();
    }
    return Stream.of(metricDatum);
}
 
Example #19
Source File: FilteringMetricsScope.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the data to the metrics scope if the given level is equal to above the enabled metrics
 * level.
 * @param name Metrics data name.
 * @param value Value of the metrics.
 * @param unit Unit of the metrics.
 * @param level Metrics level for the data.
 */
@Override
public void addData(String name, double value, StandardUnit unit, MetricsLevel level) {
    if (level.getValue() < metricsLevel.getValue()) {
        // Drop the data.
        return;
    }
    super.addData(name, value, unit);
}
 
Example #20
Source File: ProcessTask.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
/**
 * Scans a list of records to filter out records up to and including the most recent checkpoint value and to get the
 * greatest extended sequence number from the retained records. Also emits metrics about the records.
 *
 * @param scope
 *            metrics scope to emit metrics into
 * @param records
 *            list of records to scan and change in-place as needed
 * @param lastCheckpointValue
 *            the most recent checkpoint value
 * @param lastLargestPermittedCheckpointValue
 *            previous largest permitted checkpoint value
 * @return the largest extended sequence number among the retained records
 */
private ExtendedSequenceNumber filterAndGetMaxExtendedSequenceNumber(final MetricsScope scope,
                                                                     final List<KinesisClientRecord> records,
                                                                     final ExtendedSequenceNumber lastCheckpointValue,
                                                                     final ExtendedSequenceNumber lastLargestPermittedCheckpointValue) {
    ExtendedSequenceNumber largestExtendedSequenceNumber = lastLargestPermittedCheckpointValue;
    ListIterator<KinesisClientRecord> recordIterator = records.listIterator();
    while (recordIterator.hasNext()) {
        KinesisClientRecord record = recordIterator.next();
        ExtendedSequenceNumber extendedSequenceNumber = new ExtendedSequenceNumber(record.sequenceNumber(),
                record.subSequenceNumber());

        if (extendedSequenceNumber.compareTo(lastCheckpointValue) <= 0) {
            recordIterator.remove();
            log.debug("removing record with ESN {} because the ESN is <= checkpoint ({})", extendedSequenceNumber,
                    lastCheckpointValue);
            continue;
        }

        if (largestExtendedSequenceNumber == null
                || largestExtendedSequenceNumber.compareTo(extendedSequenceNumber) < 0) {
            largestExtendedSequenceNumber = extendedSequenceNumber;
        }

        scope.addData(DATA_BYTES_PROCESSED_METRIC, record.data().limit(), StandardUnit.BYTES,
                MetricsLevel.SUMMARY);
    }
    return largestExtendedSequenceNumber;
}
 
Example #21
Source File: MetricAccumulatingQueueTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAccumulation() {
    Collection<Dimension> dimensionsA = Collections.singleton(dim("name","a"));
    Collection<Dimension> dimensionsB = Collections.singleton(dim("name","b"));
    String keyA = "a";
    String keyB = "b";

    MetricDatum datum1 =
            TestHelper.constructDatum(keyA, StandardUnit.COUNT, 10, 5, 15, 2).toBuilder().dimensions(dimensionsA).build();
    queue.offer(new CloudWatchMetricKey(datum1), datum1);
    MetricDatum datum2 =
            TestHelper.constructDatum(keyA, StandardUnit.COUNT, 1, 1, 2, 2).toBuilder().dimensions(dimensionsA).build();
    queue.offer(new CloudWatchMetricKey(datum2), datum2);

    MetricDatum datum3 =
            TestHelper.constructDatum(keyA, StandardUnit.COUNT, 1, 1, 2, 2).toBuilder().dimensions(dimensionsB).build();
    queue.offer(new CloudWatchMetricKey(datum3), datum3);

    MetricDatum datum4 = TestHelper.constructDatum(keyA, StandardUnit.COUNT, 1, 1, 2, 2);
    queue.offer(new CloudWatchMetricKey(datum4), datum4);
    queue.offer(new CloudWatchMetricKey(datum4), datum4);

    MetricDatum datum5 =
            TestHelper.constructDatum(keyB, StandardUnit.COUNT, 100, 10, 110, 2).toBuilder().dimensions(dimensionsA).build();
    queue.offer(new CloudWatchMetricKey(datum5), datum5);

    Assert.assertEquals(4, queue.size());
    List<MetricDatumWithKey<CloudWatchMetricKey>> items = queue.drain(4);

    Assert.assertEquals(items.get(0).datum, TestHelper.constructDatum(keyA, StandardUnit.COUNT, 10, 1, 17, 4)
            .toBuilder().dimensions(dimensionsA).build());
    Assert.assertEquals(items.get(1).datum, datum3);
    Assert.assertEquals(items.get(2).datum, TestHelper.constructDatum(keyA, StandardUnit.COUNT, 1, 1, 4, 4));
    Assert.assertEquals(items.get(3).datum, TestHelper.constructDatum(keyB, StandardUnit.COUNT, 100, 10, 110, 2)
            .toBuilder().dimensions(dimensionsA).build());
}
 
Example #22
Source File: FilteringMetricsScopeTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultAddAll() {
    TestScope scope = new TestScope();
    scope.addData("detailedDataName", 2.0, StandardUnit.COUNT, MetricsLevel.DETAILED);
    scope.addData("noLevelDataName", 3.0, StandardUnit.MILLISECONDS);
    scope.addDimension("dimensionName", "dimensionValue");

    // By default all metrics and dimensions should be allowed.
    scope.assertMetrics(
            TestHelper.constructDatum("detailedDataName", StandardUnit.COUNT, 2.0, 2.0, 2.0, 1),
            TestHelper.constructDatum("noLevelDataName", StandardUnit.MILLISECONDS, 3.0, 3.0, 3.0, 1.0));
    scope.assertDimensions(TestHelper.constructDimension("dimensionName", "dimensionValue"));
}
 
Example #23
Source File: FilteringMetricsScopeTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetricsLevel() {
    TestScope scope = new TestScope(MetricsLevel.SUMMARY, null);
    scope.addData("summaryDataName", 2.0, StandardUnit.COUNT, MetricsLevel.SUMMARY);
    scope.addData("summaryDataName", 10.0, StandardUnit.COUNT, MetricsLevel.SUMMARY);
    scope.addData("detailedDataName", 4.0, StandardUnit.BYTES, MetricsLevel.DETAILED);
    scope.addData("noLevelDataName", 3.0, StandardUnit.MILLISECONDS);

    scope.assertMetrics(TestHelper.constructDatum("summaryDataName", StandardUnit.COUNT, 10.0, 2.0, 12.0, 2.0));
}
 
Example #24
Source File: FilteringMetricsScopeTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetricsLevelNone() {
    TestScope scope = new TestScope(MetricsLevel.NONE, null);
    scope.addData("summaryDataName", 2.0, StandardUnit.COUNT, MetricsLevel.SUMMARY);
    scope.addData("summaryDataName", 10.0, StandardUnit.COUNT, MetricsLevel.SUMMARY);
    scope.addData("detailedDataName", 4.0, StandardUnit.BYTES, MetricsLevel.DETAILED);
    scope.addData("noLevelDataName", 3.0, StandardUnit.MILLISECONDS);

    // No metrics should be emitted.
    scope.assertMetrics();
}
 
Example #25
Source File: CloudWatchMetricsPublisherTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
public static List<MetricDatumWithKey<CloudWatchMetricKey>> constructMetricDatumWithKeyList(int value) {
    List<MetricDatumWithKey<CloudWatchMetricKey>> data = new ArrayList<MetricDatumWithKey<CloudWatchMetricKey>>();
    for (int i = 1; i <= value; i++) {
        MetricDatum datum =
                TestHelper.constructDatum("datum" + Integer.toString(i), StandardUnit.COUNT, i, i, i, 1);
        data.add(new MetricDatumWithKey<CloudWatchMetricKey>(new CloudWatchMetricKey(datum), datum));
    }

    return data;
}
 
Example #26
Source File: AccumulatingMetricsScopeTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleAdd() {
    TestScope scope = new TestScope();

    scope.addData("name", 2.0, StandardUnit.COUNT);
    scope.assertMetrics(TestHelper.constructDatum("name", StandardUnit.COUNT, 2.0, 2.0, 2.0, 1));
}
 
Example #27
Source File: AccumulatingMetricsScopeTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAccumulate() {
    TestScope scope = new TestScope();

    scope.addData("name", 2.0, StandardUnit.COUNT);
    scope.addData("name", 3.0, StandardUnit.COUNT);
    scope.assertMetrics(TestHelper.constructDatum("name", StandardUnit.COUNT, 3.0, 2.0, 5.0, 2));
}
 
Example #28
Source File: AccumulatingMetricsScopeTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testAccumulateWrongUnit() {
    TestScope scope = new TestScope();

    scope.addData("name", 2.0, StandardUnit.COUNT);
    scope.addData("name", 3.0, StandardUnit.MEGABITS);
}
 
Example #29
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 #30
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);
}