com.amazonaws.services.cloudwatch.model.PutMetricDataRequest Java Examples

The following examples show how to use com.amazonaws.services.cloudwatch.model.PutMetricDataRequest. 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: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 6 votes vote down vote up
private void addHistograms(SortedMap<String, Histogram> histograms, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    logger.debug("Adding Histograms...");
    for (String name : histograms.keySet()) {
        Histogram histogram = histograms.get(name);
        Snapshot snapshot = histogram.getSnapshot();
        checkAndAddDatum(MetricFilter.Stat.COUNT, name, histogram.getCount(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.MIN, name, snapshot.getMin(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.MAX, name, snapshot.getMax(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.MEAN, name, snapshot.getMean(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.STDDEV, name, snapshot.getStdDev(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.PERCENTILE_75, name, snapshot.get75thPercentile(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.PERCENTILE_95, name, snapshot.get95thPercentile(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.PERCENTILE_98, name, snapshot.get98thPercentile(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.PERCENTILE_99, name, snapshot.get99thPercentile(), requests, timestamp);
        checkAndAddDatum(MetricFilter.Stat.PERCENTILE_999, name, snapshot.get999thPercentile(), requests, timestamp);
    }
}
 
Example #2
Source File: CloudWatchScanCountListener.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
protected void runOneIteration() throws Exception {
    try {
        _cloudWatch.putMetricData(
                new PutMetricDataRequest()
                        .withNamespace(NAMESPACE)
                        .withMetricData(
                                new MetricDatum()
                                        .withTimestamp(new Date())
                                        .withMetricName(ACTIVE_AND_PENDING_SCANS)
                                        .withValue((double) (_activeScanCount + _pendingScanCount))
                                        .withUnit(StandardUnit.Count)
                                        .withDimensions(_dimensions)));
    } catch (AmazonClientException e) {
        _log.error("Failed to publish active and pending scans metric", e);
    }
}
 
Example #3
Source File: CloudWatch.java    From javamelody with Apache License 2.0 6 votes vote down vote up
@Override
public void send() throws IOException {
	final List<MetricDatum> datumList;
	synchronized (buffer) {
		datumList = new ArrayList<MetricDatum>(buffer);
		buffer.clear();
	}
	// note: Each PutMetricData request is limited to 40 KB in size for HTTP POST requests.
	// And the collection MetricData must not have a size greater than 20.
	final List<List<MetricDatum>> parts = partition(datumList, 20);
	for (final List<MetricDatum> part : parts) {
		final PutMetricDataRequest request = new PutMetricDataRequest()
				.withNamespace(cloudWatchNamespace).withMetricData(part);
		try {
			awsCloudWatch.putMetricData(request);
		} catch (final Exception e) {
			// pas catch (AmazonCloudWatchException) sinon ClassNotFoundException dans Jenkins par ex
			throw new IOException("Error connecting to AWS CloudWatch", e);
		}
	}
}
 
Example #4
Source File: DynamoDBReplicationEmitter.java    From dynamodb-cross-region-library with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void fail(final List<Record> records) {
    if (isShutdown) {
        if (records.isEmpty()) {
            // This is OK (but not expected)
            log.warn("Emitter fail method called after shutdown method was called. Continuing because list is empty");
            return;
        } else {
            throw new IllegalStateException("Emitter fail method called after shutdown method was called.");
        }
    }
    for (Record record : records) {
        log.error("Could not emit record: " + record);
    }
    final AmazonCloudWatchAsync cloudwatch = CLOUDWATCH.get();
    if (null != cloudwatch) {
        final double failed = records.size();
        final MetricDatum recordsProcessedFailedDatum = new MetricDatum().withMetricName(RECORDS_FAILED).withValue(failed).withUnit(StandardUnit.Count)
            .withTimestamp(new Date());
        final PutMetricDataRequest request = new PutMetricDataRequest().withNamespace(applicationName).withMetricData(recordsProcessedFailedDatum);
        cloudwatch.putMetricDataAsync(request);
    }
}
 
Example #5
Source File: CloudWatchReporterTest.java    From chassis with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(Object o) {
    if (!(o instanceof PutMetricDataRequest)) {
        errorText = "Invalid arg type " + o;
        return false;
    }
    PutMetricDataRequest request = (PutMetricDataRequest) o;
    if (validators.length != request.getMetricData().size()) {
        errorText = "Got " + request.getMetricData().size() + " data elements, but had only " + validators.length + " validators.";
        return false;
    }
    for (int i = 0; i < request.getMetricData().size(); i++) {
        try {
            validators[i].validate(request.getMetricData().get(i));
        } catch (Exception e) {
            errorText = e.getMessage();
            return false;
        }
    }
    return true;
}
 
Example #6
Source File: MetricsEmittingBasicClickEventsToKinesis.java    From aws-big-data-blog with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #7
Source File: DynamoDBBuffer.java    From dynamodb-cross-region-library with Apache License 2.0 5 votes vote down vote up
/**
 * Publish relevant CloudWatch metrics.
 */
protected void emitCloudWatchMetrics() {
    if (null != getCloudwatch()) {
        // TODO Emit CloudWatch metrics about the size of the queue of writes
        MetricDatum recordsProcessedDatum = new MetricDatum().withValue(getProcessedRecords());
        PutMetricDataRequest request = new PutMetricDataRequest().withMetricData(recordsProcessedDatum);
        getCloudwatch().putMetricData(request);
    }
}
 
Example #8
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private void addGauges(SortedMap<String, Gauge> gauges, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    logger.debug("Adding Gauges...");
    for (String name : gauges.keySet()) {
        Gauge<?> gauge = gauges.get(name);
        if (!(gauge.getValue() instanceof Number)) {
            logger.warn("Encountered Gauge with non-numeric value. Gauge:{}, Value:{}", name, gauge.getValue());
            continue;
        }
        Double value = ((Number) gauge.getValue()).doubleValue();
        addDatum(filter.getMatchingMetricDescriptor(name, Stat.ALL).getAlias(), value, requests, timestamp);
    }
}
 
Example #9
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 5 votes vote down vote up
private void addDatum(String name, double value, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    if (logger.isDebugEnabled()) {
        logger.debug("Adding Datum {} with value {} at {}", name, value, timestamp);
    }
    if (requests.isEmpty() || requests.getLast().getMetricData().size() == MAX_CLOUDWATCH_DATUM_PER_REQUEST) {
        requests.add(createRequest());
    }
    PutMetricDataRequest request = requests.getLast();
    MetricDatum datum = new MetricDatum().withTimestamp(timestamp).withValue(value).withMetricName(name).withUnit(StandardUnit.None).withDimensions(createDimensions());
    request.withMetricData(datum);
}
 
Example #10
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 5 votes vote down vote up
private void addTimers(SortedMap<String, Timer> timers, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    logger.debug("Adding Timers...");
    for (String name : timers.keySet()) {
        Timer timer = timers.get(name);
        checkAndAddDatum(MetricFilter.Stat.COUNT, name, timer.getCount(), requests, timestamp);
        addMetered(name, timer, requests, timestamp);
    }
}
 
Example #11
Source File: CloudWatchReporterTest.java    From chassis with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure all metrics are published event when the max number of cloudwatch metrics (per request) is exceeded.
 */
@Test
public void testPublishInMultipleCloudWatchRequests() throws InterruptedException {
    MetricRegistry metricRegistry = new MetricRegistry();

    StringBuilder filter = new StringBuilder();
    for (int i = 0; i < MetricsCloudWatchReporter.MAX_CLOUDWATCH_DATUM_PER_REQUEST + 1; i++) {
        String metric = "UnitTestCounter" + i;
        metricRegistry.counter(metric).inc();
        if (i > 0) {
            filter.append(",");
        }
        filter.append(metric).append("=").append(metric);
    }

    final AmazonCloudWatch amazonCloudWatch = Mockito.mock(AmazonCloudWatch.class);

    reporter =
            new MetricsCloudWatchReporter(
                    APP_NAME,
                    APP_VERSION,
                    APP_ENVIRONMENT,
                    filter.toString(),
                    2,
                    TimeUnit.SECONDS,
                    metricRegistry,
                    createCloudWatchFactory(amazonCloudWatch));

    reporter.start();

    Mockito.verify(amazonCloudWatch, Mockito.never()).putMetricData(Mockito.any(PutMetricDataRequest.class));

    Thread.sleep(3000);

    Mockito.verify(amazonCloudWatch, Mockito.times(2)).putMetricData(Mockito.any(PutMetricDataRequest.class));
}
 
Example #12
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 5 votes vote down vote up
private void addCounters(SortedMap<String, Counter> counters, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    logger.debug("Adding Counters...");
    for (String name : counters.keySet()) {
        Counter counter = counters.get(name);
        addDatum(filter.getMatchingMetricDescriptor(name, Stat.ALL).getAlias(), counter.getCount(), requests, timestamp);
    }
}
 
Example #13
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private void addMetricData(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    addGauges(gauges, requests, timestamp);
    addCounters(counters, requests, timestamp);
    addHistograms(histograms, requests, timestamp);
    addMeters(meters, requests, timestamp);
    addTimers(timers, requests, timestamp);
}
 
Example #14
Source File: PutCloudWatchMetric.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    MetricDatum datum = new MetricDatum();

    try {
        datum.setMetricName(context.getProperty(METRIC_NAME).evaluateAttributeExpressions(flowFile).getValue());
        datum.setValue(Double.parseDouble(context.getProperty(VALUE).evaluateAttributeExpressions(flowFile).getValue()));

        final String timestamp = context.getProperty(TIMESTAMP).evaluateAttributeExpressions(flowFile).getValue();
        if (timestamp != null) {
            datum.setTimestamp(new Date(Long.parseLong(timestamp)));
        }

        final String unit = context.getProperty(UNIT).evaluateAttributeExpressions(flowFile).getValue();
        if (unit != null) {
            datum.setUnit(unit);
        }

        final PutMetricDataRequest metricDataRequest = new PutMetricDataRequest()
                .withNamespace(context.getProperty(NAMESPACE).evaluateAttributeExpressions(flowFile).getValue())
                .withMetricData(datum);

        putMetricData(metricDataRequest);
        session.transfer(flowFile, REL_SUCCESS);
        getLogger().info("Successfully published cloudwatch metric for {}", new Object[]{flowFile});
    } catch (final Exception e) {
        getLogger().error("Failed to publish cloudwatch metric for {} due to {}", new Object[]{flowFile, e});
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
    }

}
 
Example #15
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
public void report(
        SortedMap<String, Gauge> gauges,
        SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms,
        SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {

    logger.info("Starting metrics publishing to AWS CloudWatch.");

    LinkedList<PutMetricDataRequest> requests = new LinkedList<>();

    addMetricData(gauges, counters, histograms, meters, timers, requests, new Date());

    if (requests.isEmpty()) {
        logger.debug("No metric data to send to AWS.");
        return;
    }

    for (PutMetricDataRequest request : requests) {
        try {
            for (MetricDatum datum : request.getMetricData()) {
                logger.debug("Sending metric " + datum);
            }
            cloudWatch.putMetricData(request);
        } catch (Exception e) {
            logger.error("Failed to log metrics to CloudWatch discarding metrics for this attempt...",e);
            return;
        }
    }
    logger.info("Finished metrics publishing to AWS CloudWatch.");
}
 
Example #16
Source File: KouplerMetrics.java    From koupler with MIT License 5 votes vote down vote up
public void run() {
    try {
        PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest();

        putMetricDataRequest.withMetricData(new MetricDatum()
                .withDimensions(hostDimension)
                .withMetricName("BytesPerEvent")
                .withValue(bytesHistogram.getSnapshot().getMean()));

        putMetricDataRequest.withMetricData(new MetricDatum()
                .withDimensions(hostDimension)
                .withMetricName("KplEventQueueCount")
                .withValue(producer.getKplQueueSize() * 1.0));

        putMetricDataRequest.withMetricData(new MetricDatum()
                .withDimensions(hostDimension)
                .withMetricName("InternalEventQueueCount")
                .withValue(producer.getInternalQueueSize() * 1.0));
        
        putMetricDataRequest.withMetricData(new MetricDatum()
                .withDimensions(hostDimension)
                .withMetricName("QueuedEventsPerSecond")
                .withValue(queuedMeter.getMeanRate()));

        putMetricDataRequest.withMetricData(new MetricDatum()
                .withDimensions(hostDimension)
                .withMetricName("CompletedEventsPerSecond")
                .withValue(completedMeter.getMeanRate()));

        putMetricDataRequest.withNamespace(appName);

        cloudWatch.putMetricData(putMetricDataRequest);

        LOGGER.debug("Published metrics to CloudWatch [{}].", this.toString());

    } catch (Exception e) {
        LOGGER.error("Problem posting or reading cloudwatch metrics.", e);
    }
}
 
Example #17
Source File: PutMetricData.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply a data point:\n" +
            "Ex: PutMetricData <data_point>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        Double data_point = Double.parseDouble(args[0]);

        final AmazonCloudWatch cw =
            AmazonCloudWatchClientBuilder.defaultClient();

        Dimension dimension = new Dimension()
            .withName("UNIQUE_PAGES")
            .withValue("URLS");

        MetricDatum datum = new MetricDatum()
            .withMetricName("PAGES_VISITED")
            .withUnit(StandardUnit.None)
            .withValue(data_point)
            .withDimensions(dimension);

        PutMetricDataRequest request = new PutMetricDataRequest()
            .withNamespace("SITE/TRAFFIC")
            .withMetricData(datum);

        PutMetricDataResult response = cw.putMetricData(request);

        System.out.printf("Successfully put data point %f", data_point);
    }
 
Example #18
Source File: MockPutCloudWatchMetric.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected PutMetricDataResult putMetricData(PutMetricDataRequest metricDataRequest) throws AmazonClientException {
    putMetricDataCallCount++;
    actualNamespace = metricDataRequest.getNamespace();
    actualMetricData = metricDataRequest.getMetricData();

    if (throwException != null) {
        throw throwException;
    }

    return result;
}
 
Example #19
Source File: CloudWatchMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
void sendMetricData(List<MetricDatum> metricData) throws InterruptedException {
    PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest()
            .withNamespace(config.namespace())
            .withMetricData(metricData);
    CountDownLatch latch = new CountDownLatch(1);
    amazonCloudWatchAsync.putMetricDataAsync(putMetricDataRequest, new AsyncHandler<PutMetricDataRequest, PutMetricDataResult>() {
        @Override
        public void onError(Exception exception) {
            if (exception instanceof AbortedException) {
                logger.warn("sending metric data was aborted: {}", exception.getMessage());
            } else {
                logger.error("error sending metric data.", exception);
            }
            latch.countDown();
        }

        @Override
        public void onSuccess(PutMetricDataRequest request, PutMetricDataResult result) {
            logger.debug("published metric with namespace:{}", request.getNamespace());
            latch.countDown();
        }
    });
    try {
        @SuppressWarnings("deprecation")
        long readTimeoutMillis = config.readTimeout().toMillis();
        latch.await(readTimeoutMillis, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        logger.warn("metrics push to cloudwatch took longer than expected");
        throw e;
    }
}
 
Example #20
Source File: CloudWatchAlertDispatcher.java    From s3mper with Apache License 2.0 5 votes vote down vote up
private void sendCloudWatchConsistencyAlert() {
    MetricDatum datum = new MetricDatum();
    datum.setMetricName(cloudWatchConsistencyMetric);
    datum.setUnit(StandardUnit.Count);
    datum.setValue(1.0);
    
    PutMetricDataRequest request = new PutMetricDataRequest();
    request.setNamespace(namespace);
    request.setMetricData(Collections.singleton(datum));
    
    cloudWatch.putMetricData(request);
}
 
Example #21
Source File: MockPutCloudWatchMetric.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
protected PutMetricDataResult putMetricData(PutMetricDataRequest metricDataRequest) throws AmazonClientException {
    putMetricDataCallCount++;
    actualNamespace = metricDataRequest.getNamespace();
    actualMetricData = metricDataRequest.getMetricData();

    if (throwException != null) {
        throw throwException;
    }

    return result;
}
 
Example #22
Source File: CloudWatchAlertDispatcher.java    From s3mper with Apache License 2.0 5 votes vote down vote up
private void sendCloudWatchTimeoutAlert() {
    MetricDatum datum = new MetricDatum();
    datum.setMetricName(cloudWatchTimeoutMetric);
    datum.setUnit(StandardUnit.Count);
    datum.setValue(1.0);
    
    PutMetricDataRequest request = new PutMetricDataRequest();
    request.setNamespace(namespace);
    request.setMetricData(Collections.singleton(datum));
    
    cloudWatch.putMetricData(request);
}
 
Example #23
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 4 votes vote down vote up
private PutMetricDataRequest createRequest() {
    return new PutMetricDataRequest().withNamespace(appName);
}
 
Example #24
Source File: PutCloudWatchMetric.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    MetricDatum datum = new MetricDatum();

    try {
        datum.setMetricName(context.getProperty(METRIC_NAME).evaluateAttributeExpressions(flowFile).getValue());
        final String valueString = context.getProperty(VALUE).evaluateAttributeExpressions(flowFile).getValue();
        if (valueString != null) {
            datum.setValue(Double.parseDouble(valueString));
        } else {
            StatisticSet statisticSet = new StatisticSet();
            statisticSet.setMaximum(Double.parseDouble(context.getProperty(MAXIMUM).evaluateAttributeExpressions(flowFile).getValue()));
            statisticSet.setMinimum(Double.parseDouble(context.getProperty(MINIMUM).evaluateAttributeExpressions(flowFile).getValue()));
            statisticSet.setSampleCount(Double.parseDouble(context.getProperty(SAMPLECOUNT).evaluateAttributeExpressions(flowFile).getValue()));
            statisticSet.setSum(Double.parseDouble(context.getProperty(SUM).evaluateAttributeExpressions(flowFile).getValue()));

            datum.setStatisticValues(statisticSet);
        }

        final String timestamp = context.getProperty(TIMESTAMP).evaluateAttributeExpressions(flowFile).getValue();
        if (timestamp != null) {
            datum.setTimestamp(new Date(Long.parseLong(timestamp)));
        }

        final String unit = context.getProperty(UNIT).evaluateAttributeExpressions(flowFile).getValue();
        if (unit != null) {
            datum.setUnit(unit);
        }

        // add dynamic properties as dimensions
        if (!dynamicPropertyNames.isEmpty()) {
            final List<Dimension> dimensions = new ArrayList<>(dynamicPropertyNames.size());
            for (String propertyName : dynamicPropertyNames) {
                final String propertyValue = context.getProperty(propertyName).evaluateAttributeExpressions(flowFile).getValue();
                if (StringUtils.isNotBlank(propertyValue)) {
                    dimensions.add(new Dimension().withName(propertyName).withValue(propertyValue));
                }
            }
            datum.withDimensions(dimensions);
        }

        final PutMetricDataRequest metricDataRequest = new PutMetricDataRequest()
                .withNamespace(context.getProperty(NAMESPACE).evaluateAttributeExpressions(flowFile).getValue())
                .withMetricData(datum);

        putMetricData(metricDataRequest);
        session.transfer(flowFile, REL_SUCCESS);
        getLogger().info("Successfully published cloudwatch metric for {}", new Object[]{flowFile});
    } catch (final Exception e) {
        getLogger().error("Failed to publish cloudwatch metric for {} due to {}", new Object[]{flowFile, e});
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
    }

}
 
Example #25
Source File: PutCloudWatchMetric.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected PutMetricDataResult putMetricData(PutMetricDataRequest metricDataRequest) throws AmazonClientException {
    final AmazonCloudWatchClient client = getClient();
    final PutMetricDataResult result = client.putMetricData(metricDataRequest);
    return result;
}
 
Example #26
Source File: CloudWatchReporterTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
/**
 * Ensure that a failed publication does not prevent subsequent attempts
 */
@Test
@Ignore("Fix the thread sleeps.")
public void testRecoverAfterFailedPublication() throws InterruptedException {
    MetricRegistry metricRegistry = new MetricRegistry();

    metricRegistry.counter("UnitTestCounter").inc();

    final AmazonCloudWatch amazonCloudWatch = Mockito.mock(AmazonCloudWatch.class);

    reporter =
            new MetricsCloudWatchReporter(
                    APP_NAME,
                    APP_VERSION,
                    APP_ENVIRONMENT,
                    "utc=UnitTestCounter",
                    2,
                    TimeUnit.SECONDS,
                    metricRegistry,
                    createCloudWatchFactory(amazonCloudWatch));

    Mockito.doThrow(new RuntimeException("CloudWatch request error")).when(amazonCloudWatch).putMetricData(Mockito.any(PutMetricDataRequest.class));

    reporter.start();

    //give the reporter a chance to publish
    Thread.sleep(3000);

    //verify that
    Mockito.verify(amazonCloudWatch, Mockito.times(1)).putMetricData(Mockito.any(PutMetricDataRequest.class));

    Mockito.reset(amazonCloudWatch);

    metricRegistry.counter("UnitTestCounter").inc();

    Thread.sleep(3000);

    PutMetricDataRequestMatcher matcher = new PutMetricDataRequestMatcher(
            new MetricDatumValidator("utc", APP_ENVIRONMENT, 2d));

    Mockito.verify(amazonCloudWatch, Mockito.times(2)).putMetricData(Mockito.argThat(matcher));
}
 
Example #27
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 4 votes vote down vote up
private void checkAndAddDatum(Stat stat, String name, double value, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    MetricDescriptor descriptor = filter.getMatchingMetricDescriptor(name, stat);
    if (descriptor != null) {
        addDatum(descriptor.getAlias() + "." + stat.getStringValue(), value, requests, timestamp);
    }
}
 
Example #28
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 4 votes vote down vote up
private void addMetered(String name, Metered metered, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    checkAndAddDatum(MetricFilter.Stat.RATE_1_MINUTE, name, metered.getOneMinuteRate(), requests, timestamp);
    checkAndAddDatum(MetricFilter.Stat.RATE_5_MINUTE, name, metered.getFiveMinuteRate(), requests, timestamp);
    checkAndAddDatum(MetricFilter.Stat.RATE_15_MINUTE, name, metered.getFifteenMinuteRate(), requests, timestamp);
    checkAndAddDatum(MetricFilter.Stat.MEAN, name, metered.getMeanRate(), requests, timestamp);
}
 
Example #29
Source File: MetricsCloudWatchReporter.java    From chassis with Apache License 2.0 4 votes vote down vote up
private void addMeters(SortedMap<String, Meter> meters, LinkedList<PutMetricDataRequest> requests, Date timestamp) {
    logger.debug("Adding Meters...");
    for (String name : meters.keySet()) {
        addMetered(name, meters.get(name), requests, timestamp);
    }
}
 
Example #30
Source File: CloudWatchReporterFactoryTest.java    From dropwizard-metrics-cloudwatch with Apache License 2.0 4 votes vote down vote up
@Test
public void verifySendingToCloudWatch() throws Exception {
    CloudWatchReporterFactory factory = new CloudWatchReporterFactory();

    MetricRegistry registry = new MetricRegistry();
    Counter counter = registry.counter(MetricRegistry.name(this.getClass(), "test machine=123*"));


    AmazonCloudWatchAsync mockClient = mock(AmazonCloudWatchAsync.class);

    final Future<Void> mockFuture = mock(Future.class);
    when(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class))).thenReturn(mockFuture);
    when(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class))).thenAnswer(new Answer<Future>() {
        @Override
        public Future answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();

            if (args.length > 0 && args[0] != null) {
                PutMetricDataRequest req = (PutMetricDataRequest) args[0];
                assertEquals(req.getNamespace(), "myspace");
                for (MetricDatum datum : req.getMetricData()) {
                    System.out.println(datum.toString());
                    assertTrue(datum.toString().contains("env"));
                }
            }

            return mockFuture;
        }
    });

    factory.setClient(mockClient);
    factory.setAwsAccessKeyId("fakeKey");
    factory.setAwsSecretKey("fakeSecret");
    factory.setNamespace("myspace");
    factory.setGlobalDimensions(Lists.newArrayList("env=dev"));
    ScheduledReporter reporter = factory.build(registry);

    for (int i = 0; i < 200; i++) {
        counter.inc();
    }
    reporter.report();
    verify(mockClient.putMetricDataAsync(any(PutMetricDataRequest.class)), times(1));
}