Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -0,0 +1,152 @@
package com.baeldung.metrics.core;
import com.codahale.metrics.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class MetricsIntegrationTest {
@Test
public void whenMarkMeter_thenCorrectRates() throws InterruptedException {
Meter meter = new Meter();
long initCount = meter.getCount();
assertThat(initCount, equalTo(0L));
meter.mark();
assertThat(meter.getCount(), equalTo(1L));
meter.mark(20);
assertThat(meter.getCount(), equalTo(21L));
// not use assert for these rate values because they change every time when this test is run
double meanRate = meter.getMeanRate();
double oneMinRate = meter.getOneMinuteRate();
double fiveMinRate = meter.getFiveMinuteRate();
double fifteenMinRate = meter.getFifteenMinuteRate();
System.out.println(meanRate);
System.out.println(oneMinRate);
System.out.println(fiveMinRate);
System.out.println(fifteenMinRate);
}
@Test
public void whenInitRatioGauge_thenCorrectRatio() {
Gauge<Double> ratioGauge = new AttendanceRatioGauge(15, 20);
assertThat(ratioGauge.getValue(), equalTo(0.75));
}
@Test
public void whenUseCacheGauge_thenCorrectGauge() {
Gauge<List<Long>> activeUsersGauge = new ActiveUsersGauge(15, TimeUnit.MINUTES);
List<Long> expected = new ArrayList<Long>();
expected.add(12L);
assertThat(activeUsersGauge.getValue(), equalTo(expected));
}
@Test
public void whenUseDerivativeGauge_thenCorrectGaugeFromBase() {
Gauge<List<Long>> activeUsersGauge = new ActiveUsersGauge(15, TimeUnit.MINUTES);
Gauge<Integer> activeUserCountGauge = new ActiveUserCountGauge(activeUsersGauge);
assertThat(activeUserCountGauge.getValue(), equalTo(1));
}
@Test
public void whenIncDecCounter_thenCorrectCount() {
Counter counter = new Counter();
long initCount = counter.getCount();
assertThat(initCount, equalTo(0L));
counter.inc();
assertThat(counter.getCount(), equalTo(1L));
counter.inc(11);
assertThat(counter.getCount(), equalTo(12L));
counter.dec();
assertThat(counter.getCount(), equalTo(11L));
counter.dec(6);
assertThat(counter.getCount(), equalTo(5L));
}
@Test
public void whenUpdateHistogram_thenCorrectDistributionData() {
Histogram histogram = new Histogram(new UniformReservoir());
histogram.update(5);
long count1 = histogram.getCount();
assertThat(count1, equalTo(1L));
Snapshot snapshot1 = histogram.getSnapshot();
assertThat(snapshot1.getValues().length, equalTo(1));
assertThat(snapshot1.getValues()[0], equalTo(5L));
assertThat(snapshot1.getMax(), equalTo(5L));
assertThat(snapshot1.getMin(), equalTo(5L));
assertThat(snapshot1.getMean(), equalTo(5.0));
assertThat(snapshot1.getMedian(), equalTo(5.0));
assertThat(snapshot1.getStdDev(), equalTo(0.0));
assertThat(snapshot1.get75thPercentile(), equalTo(5.0));
assertThat(snapshot1.get95thPercentile(), equalTo(5.0));
assertThat(snapshot1.get98thPercentile(), equalTo(5.0));
assertThat(snapshot1.get99thPercentile(), equalTo(5.0));
assertThat(snapshot1.get999thPercentile(), equalTo(5.0));
histogram.update(20);
long count2 = histogram.getCount();
assertThat(count2, equalTo(2L));
Snapshot snapshot2 = histogram.getSnapshot();
assertThat(snapshot2.getValues().length, equalTo(2));
assertThat(snapshot2.getValues()[0], equalTo(5L));
assertThat(snapshot2.getValues()[1], equalTo(20L));
assertThat(snapshot2.getMax(), equalTo(20L));
assertThat(snapshot2.getMin(), equalTo(5L));
assertThat(snapshot2.getMean(), equalTo(12.5));
assertThat(snapshot2.getMedian(), equalTo(12.5));
assertEquals(10.6, snapshot2.getStdDev(), 0.1);
assertThat(snapshot2.get75thPercentile(), equalTo(20.0));
assertThat(snapshot2.get95thPercentile(), equalTo(20.0));
assertThat(snapshot2.get98thPercentile(), equalTo(20.0));
assertThat(snapshot2.get99thPercentile(), equalTo(20.0));
assertThat(snapshot2.get999thPercentile(), equalTo(20.0));
}
@Test
public void whenUseTimer_thenCorrectTimerContexts() throws InterruptedException {
Timer timer = new Timer();
Timer.Context context1 = timer.time();
TimeUnit.SECONDS.sleep(5);
long elapsed1 = context1.stop();
assertEquals(5000000000L, elapsed1, 1000000000);
assertThat(timer.getCount(), equalTo(1L));
assertEquals(0.2, timer.getMeanRate(), 0.2);
Timer.Context context2 = timer.time();
TimeUnit.SECONDS.sleep(2);
context2.close();
assertThat(timer.getCount(), equalTo(2L));
assertEquals(0.3, timer.getMeanRate(), 0.2);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.metrics.core;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.codahale.metrics.*;
public class ReporterIntegrationTest {
@Test
public void whenConsoleReporter_thenOutputReport() {
MetricRegistry metricRegistry = new MetricRegistry();
Meter meter = metricRegistry.meter("meter");
meter.mark();
meter.mark(200);
Histogram histogram = metricRegistry.histogram("histogram");
histogram.update(12);
histogram.update(17);
histogram.update(20);
Counter counter = metricRegistry.counter("counter");
counter.inc();
counter.dec();
counter.inc();
counter.inc();
counter.inc();
counter.inc();
ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry).build();
reporter.start(5, TimeUnit.MICROSECONDS);
reporter.report();
}
}
@@ -0,0 +1,35 @@
package com.baeldung.metrics.healthchecks;
import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckRegistry;
import org.junit.Test;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class HealthCheckIntegrationTest {
@Test
public void whenUseHealthCheck_thenHealthChecked() {
HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
healthCheckRegistry.register("db", new DatabaseHealthCheck());
healthCheckRegistry.register("uc", new UserCenterHealthCheck());
assertThat(healthCheckRegistry.getNames().size(), equalTo(2));
Map<String, HealthCheck.Result> results = healthCheckRegistry.runHealthChecks();
assertFalse(results.isEmpty());
results.forEach((k, v) -> assertTrue(v.isHealthy()));
healthCheckRegistry.unregister("uc");
assertThat(healthCheckRegistry.getNames().size(), equalTo(1));
}
}
@@ -0,0 +1,295 @@
package com.baeldung.metrics.micrometer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import static org.assertj.core.api.Assertions.withinPercentage;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import io.micrometer.atlas.AtlasMeterRegistry;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.Measurement;
import io.micrometer.core.instrument.Meter.Type;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.micrometer.core.instrument.stats.hist.Histogram;
import io.micrometer.core.instrument.stats.quantile.WindowSketchQuantiles;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.assertj.core.data.Percentage;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import com.netflix.spectator.atlas.AtlasConfig;
/**
* @author aiet
*/
public class MicrometerAtlasIntegrationTest {
private AtlasConfig atlasConfig;
@Before
public void init() {
atlasConfig = new AtlasConfig() {
@Override
public Duration step() {
return Duration.ofSeconds(1);
}
@Override
public String get(String k) {
return null;
}
};
}
@Test
public void givenCompositeRegistries_whenRecordMeter_thenAllRegistriesRecorded() {
CompositeMeterRegistry compositeRegistry = new CompositeMeterRegistry();
SimpleMeterRegistry oneSimpleMeter = new SimpleMeterRegistry();
AtlasMeterRegistry atlasMeterRegistry = new AtlasMeterRegistry(atlasConfig, Clock.SYSTEM);
compositeRegistry.add(oneSimpleMeter);
compositeRegistry.add(atlasMeterRegistry);
compositeRegistry.gauge("baeldung.heat", 90);
Optional<Gauge> oneGauge = oneSimpleMeter
.find("baeldung.heat")
.gauge();
assertTrue(oneGauge.isPresent());
Iterator<Measurement> measurements = oneGauge
.get()
.measure()
.iterator();
assertTrue(measurements.hasNext());
assertThat(measurements
.next()
.getValue(), equalTo(90.00));
Optional<Gauge> atlasGauge = atlasMeterRegistry
.find("baeldung.heat")
.gauge();
assertTrue(atlasGauge.isPresent());
Iterator<Measurement> anotherMeasurements = atlasGauge
.get()
.measure()
.iterator();
assertTrue(anotherMeasurements.hasNext());
assertThat(anotherMeasurements
.next()
.getValue(), equalTo(90.00));
}
@Test
public void givenGlobalRegistry_whenIncrementAnywhere_thenCounted() {
class CountedObject {
private CountedObject() {
Metrics
.counter("objects.instance")
.increment(1.0);
}
}
Metrics.addRegistry(new SimpleMeterRegistry());
Metrics
.counter("objects.instance")
.increment();
new CountedObject();
Optional<Counter> counterOptional = Metrics.globalRegistry
.find("objects.instance")
.counter();
assertTrue(counterOptional.isPresent());
assertTrue(counterOptional
.get()
.count() == 2.0);
}
@Test
public void givenCounter_whenIncrement_thenValueChanged() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
Counter counter = Counter
.builder("objects.instance")
.description("indicates instance count of the object")
.tags("dev", "performance")
.register(registry);
counter.increment(2.0);
assertTrue(counter.count() == 2);
counter.increment(-1);
assertTrue(counter.count() == 2);
}
@Test
public void givenTimer_whenWrapTasks_thenTimeRecorded() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
Timer timer = registry.timer("app.event");
timer.record(() -> {
try {
TimeUnit.MILLISECONDS.sleep(15);
} catch (InterruptedException ignored) {
}
});
timer.record(30, TimeUnit.MILLISECONDS);
assertTrue(2 == timer.count());
assertThat(timer.totalTime(TimeUnit.MILLISECONDS)).isBetween(40.0, 55.0);
}
@Test
public void givenLongTimer_whenRunTasks_thenTimerRecorded() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
LongTaskTimer longTaskTimer = LongTaskTimer
.builder("3rdPartyService")
.register(registry);
long currentTaskId = longTaskTimer.start();
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException ignored) {
}
long timeElapsed = longTaskTimer.stop(currentTaskId);
assertEquals(2L, timeElapsed/((int) 1e6),1L);
}
@Test
public void givenGauge_whenMeterListSize_thenCurrentSizeMonitored() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
List<String> list = new ArrayList<>(4);
Gauge gauge = Gauge
.builder("cache.size", list, List::size)
.register(registry);
assertTrue(gauge.value() == 0.0);
list.add("1");
assertTrue(gauge.value() == 1.0);
}
@Test
public void givenDistributionSummary_whenRecord_thenSummarized() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
DistributionSummary distributionSummary = DistributionSummary
.builder("request.size")
.baseUnit("bytes")
.register(registry);
distributionSummary.record(3);
distributionSummary.record(4);
distributionSummary.record(5);
assertTrue(3 == distributionSummary.count());
assertTrue(12 == distributionSummary.totalAmount());
}
@Test
public void givenTimer_whenEnrichWithQuantile_thenQuantilesComputed() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
Timer timer = Timer
.builder("test.timer")
.quantiles(WindowSketchQuantiles
.quantiles(0.3, 0.5, 0.95)
.create())
.register(registry);
timer.record(2, TimeUnit.SECONDS);
timer.record(2, TimeUnit.SECONDS);
timer.record(3, TimeUnit.SECONDS);
timer.record(4, TimeUnit.SECONDS);
timer.record(8, TimeUnit.SECONDS);
timer.record(13, TimeUnit.SECONDS);
Map<String, Integer> quantileMap = extractTagValueMap(registry, Type.Gauge, 1e9);
assertThat(quantileMap, allOf(hasEntry("quantile=0.3", 2), hasEntry("quantile=0.5", 3), hasEntry("quantile=0.95", 8)));
}
private Map<String, Integer> extractTagValueMap(MeterRegistry registry, Type meterType, double valueDivisor) {
return registry
.getMeters()
.stream()
.filter(meter -> meter.getType() == meterType)
.collect(Collectors.toMap(meter -> {
Tag tag = meter
.getId()
.getTags()
.iterator()
.next();
return tag.getKey() + "=" + tag.getValue();
}, meter -> (int) (meter
.measure()
.iterator()
.next()
.getValue() / valueDivisor)));
}
@Test
public void givenDistributionSummary_whenEnrichWithHistograms_thenDataAggregated() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
DistributionSummary hist = DistributionSummary
.builder("summary")
.histogram(Histogram.linear(0, 10, 5))
.register(registry);
hist.record(3);
hist.record(8);
hist.record(20);
hist.record(40);
hist.record(13);
hist.record(26);
Map<String, Integer> histograms = extractTagValueMap(registry, Type.Counter, 1.0);
assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=10.0", 2), hasEntry("bucket=20.0", 2), hasEntry("bucket=30.0", 1), hasEntry("bucket=40.0", 1), hasEntry("bucket=Infinity", 0)));
}
@Test
public void givenTimer_whenEnrichWithTimescaleHistogram_thenTimeScaleDataCollected() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
Timer timer = Timer
.builder("timer")
.histogram(Histogram.linearTime(TimeUnit.MILLISECONDS, 0, 200, 3))
.register(registry);
timer.record(1000, TimeUnit.MILLISECONDS);
timer.record(23, TimeUnit.MILLISECONDS);
timer.record(450, TimeUnit.MILLISECONDS);
timer.record(341, TimeUnit.MILLISECONDS);
timer.record(500, TimeUnit.MILLISECONDS);
Map<String, Integer> histograms = extractTagValueMap(registry, Type.Counter, 1.0);
assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=2.0E8", 1), hasEntry("bucket=4.0E8", 1), hasEntry("bucket=Infinity", 3)));
}
}
@@ -0,0 +1,95 @@
package com.baeldung.metrics.servo;
import com.netflix.servo.DefaultMonitorRegistry;
import com.netflix.servo.monitor.BasicCounter;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.publish.BasicMetricFilter;
import com.netflix.servo.publish.MonitorRegistryMetricPoller;
import com.netflix.servo.publish.PollRunnable;
import com.netflix.servo.publish.PollScheduler;
import com.netflix.servo.publish.atlas.AtlasMetricObserver;
import com.netflix.servo.publish.atlas.BasicAtlasConfig;
import com.netflix.servo.tag.BasicTagList;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.HttpClients;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.http.client.methods.RequestBuilder.get;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
/**
* Atlas server needs to be up and running for this live test to work.
*/
public class AtlasObserverLiveTest {
private final String atlasUri = "http://localhost:7101/api/v1";
@Before
public void prepareScheduler() {
System.setProperty("servo.pollers", "1000");
System.setProperty("servo.atlas.batchSize", "1");
System.setProperty("servo.atlas.uri", atlasUri + "/publish");
AtlasMetricObserver observer = new AtlasMetricObserver(new BasicAtlasConfig(), BasicTagList.of("servo", "counter"));
PollRunnable task = new PollRunnable(new MonitorRegistryMetricPoller(), new BasicMetricFilter(true), observer);
PollScheduler
.getInstance()
.start();
PollScheduler
.getInstance()
.addPoller(task, 1, SECONDS);
}
@After
public void stopScheduler() {
if (PollScheduler
.getInstance()
.isStarted()) {
PollScheduler
.getInstance()
.stop();
}
}
private String atlasValuesOfTag(String tagname) throws Exception {
HttpEntity entity = HttpClients
.createDefault()
.execute(get()
.setUri(atlasUri + "/tags/" + tagname)
.build())
.getEntity();
return new BufferedReader(new InputStreamReader(entity.getContent())).readLine();
}
@Test
public void givenAtlasAndCounter_whenRegister_thenPublishedToAtlas() throws Exception {
Counter counter = new BasicCounter(MonitorConfig
.builder("test")
.withTag("servo", "counter")
.build());
DefaultMonitorRegistry
.getInstance()
.register(counter);
assertThat(atlasValuesOfTag("servo"), not(containsString("counter")));
for (int i = 0; i < 3; i++) {
counter.increment(RandomUtils.nextInt(10));
SECONDS.sleep(1);
counter.increment(-1 * RandomUtils.nextInt(10));
SECONDS.sleep(1);
}
assertThat(atlasValuesOfTag("servo"), containsString("counter"));
}
}
@@ -0,0 +1,53 @@
package com.baeldung.metrics.servo;
import com.netflix.servo.Metric;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.annotations.Monitor;
import com.netflix.servo.annotations.MonitorTags;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.tag.BasicTag;
import com.netflix.servo.tag.BasicTagList;
import com.netflix.servo.tag.TagList;
import org.junit.Test;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class MetricAnnotationManualTest extends MetricTestBase {
@Monitor(name = "integerCounter", type = DataSourceType.COUNTER, description = "Total number of update operations.")
private final AtomicInteger updateCount = new AtomicInteger(0);
@MonitorTags private TagList tags = new BasicTagList(newArrayList(new BasicTag("tag-key", "tag-value")));
@Test
public void givenAnnotatedMonitor_whenUpdated_thenDataCollected() throws Exception {
Monitors.registerObject("testObject", this);
assertTrue(Monitors.isObjectRegistered("testObject", this));
updateCount.incrementAndGet();
updateCount.incrementAndGet();
SECONDS.sleep(1);
List<List<Metric>> metrics = observer.getObservations();
System.out.println(metrics);
assertThat(metrics, hasSize(greaterThanOrEqualTo(1)));
Iterator<List<Metric>> metricIterator = metrics.iterator();
//skip first empty observation
metricIterator.next();
while (metricIterator.hasNext()) {
assertThat(metricIterator.next(), hasItem(hasProperty("config", hasProperty("name", is("integerCounter")))));
}
}
}
@@ -0,0 +1,72 @@
package com.baeldung.metrics.servo;
import com.netflix.servo.DefaultMonitorRegistry;
import com.netflix.servo.Metric;
import com.netflix.servo.monitor.BasicGauge;
import com.netflix.servo.monitor.DynamicCounter;
import com.netflix.servo.monitor.Gauge;
import com.netflix.servo.monitor.MonitorConfig;
import org.junit.Test;
import java.util.Iterator;
import java.util.List;
import static com.netflix.servo.annotations.DataSourceType.GAUGE;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class MetricObserverManualTest extends MetricTestBase {
@Test
public void givenMetrics_whenRegister_thenMonitored() throws InterruptedException {
Gauge<Double> gauge = new BasicGauge<>(MonitorConfig
.builder("test")
.build(), () -> 2.32);
assertEquals(2.32, gauge.getValue(), 0.01);
DefaultMonitorRegistry
.getInstance()
.register(gauge);
for (int i = 0; i < 2; i++) {
SECONDS.sleep(1);
}
List<List<Metric>> metrics = observer.getObservations();
assertThat(metrics, hasSize(greaterThanOrEqualTo(2)));
Iterator<List<Metric>> metricIterator = metrics.iterator();
//skip first empty observation
metricIterator.next();
while (metricIterator.hasNext()) {
assertThat(metricIterator.next(), hasItem(allOf(hasProperty("config", hasProperty("tags", hasItem(GAUGE))), hasProperty("value", is(2.32)))));
}
}
@Test
public void givenMetrics_whenRegisterDynamically_thenMonitored() throws Exception {
for (int i = 0; i < 2; i++) {
DynamicCounter.increment("monitor-name", "tag-key", "tag-value");
SECONDS.sleep(1);
}
List<List<Metric>> metrics = observer.getObservations();
assertThat(metrics, hasSize(greaterThanOrEqualTo(2)));
Iterator<List<Metric>> metricIterator = metrics.iterator();
//skip first empty observation
metricIterator.next();
while (metricIterator.hasNext()) {
assertThat(metricIterator.next(), hasItem(hasProperty("value", greaterThanOrEqualTo(1.0))));
}
}
}
@@ -0,0 +1,53 @@
package com.baeldung.metrics.servo;
import com.netflix.servo.Metric;
import com.netflix.servo.publish.BasicMetricFilter;
import com.netflix.servo.publish.JvmMetricPoller;
import com.netflix.servo.publish.MemoryMetricObserver;
import com.netflix.servo.publish.PollRunnable;
import com.netflix.servo.publish.PollScheduler;
import org.junit.Test;
import java.util.List;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
public class MetricPollerManualTest {
@Test
public void givenJvmPoller_whenMonitor_thenDataCollected() throws Exception {
MemoryMetricObserver observer = new MemoryMetricObserver();
PollRunnable pollRunnable = new PollRunnable(new JvmMetricPoller(), new BasicMetricFilter(true), observer);
PollScheduler
.getInstance()
.start();
PollScheduler
.getInstance()
.addPoller(pollRunnable, 1, SECONDS);
SECONDS.sleep(1);
PollScheduler
.getInstance()
.stop();
List<List<Metric>> metrics = observer.getObservations();
assertThat(metrics, hasSize(greaterThanOrEqualTo(1)));
List<String> args = metrics
.stream()
.filter(m -> !m.isEmpty())
.flatMap(ms -> ms
.stream()
.map(m -> m
.getConfig()
.getName()))
.collect(toList());
assertThat(args, hasItems("loadedClassCount", "initUsage", "maxUsage", "threadCount"));
}
}
@@ -0,0 +1,42 @@
package com.baeldung.metrics.servo;
import com.netflix.servo.publish.BasicMetricFilter;
import com.netflix.servo.publish.MemoryMetricObserver;
import com.netflix.servo.publish.MetricFilter;
import com.netflix.servo.publish.MonitorRegistryMetricPoller;
import com.netflix.servo.publish.PollRunnable;
import com.netflix.servo.publish.PollScheduler;
import org.junit.After;
import org.junit.Before;
import static java.util.concurrent.TimeUnit.SECONDS;
abstract class MetricTestBase {
MemoryMetricObserver observer;
@Before
public void prepareScheduler() {
System.setProperty("servo.pollers", "1000");
observer = new MemoryMetricObserver();
PollScheduler
.getInstance()
.start();
MetricFilter metricFilter = new BasicMetricFilter(true);
PollRunnable task = new PollRunnable(new MonitorRegistryMetricPoller(), metricFilter, observer);
PollScheduler
.getInstance()
.addPoller(task, 1, SECONDS);
}
@After
public void stopScheduler() {
if (PollScheduler
.getInstance()
.isStarted()) {
PollScheduler
.getInstance()
.stop();
}
}
}
@@ -0,0 +1,237 @@
package com.baeldung.metrics.servo;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toMap;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.netflix.servo.monitor.BasicCounter;
import com.netflix.servo.monitor.BasicGauge;
import com.netflix.servo.monitor.BasicInformational;
import com.netflix.servo.monitor.BasicTimer;
import com.netflix.servo.monitor.BucketConfig;
import com.netflix.servo.monitor.BucketTimer;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.Gauge;
import com.netflix.servo.monitor.MaxGauge;
import com.netflix.servo.monitor.Monitor;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.PeakRateCounter;
import com.netflix.servo.monitor.StatsTimer;
import com.netflix.servo.monitor.StepCounter;
import com.netflix.servo.monitor.Stopwatch;
import com.netflix.servo.stats.StatsConfig;
public class MetricTypeManualTest {
@Test
public void givenDefaultCounter_whenManipulate_thenCountValid() {
Counter counter = Monitors.newCounter("test");
assertEquals("counter should start with 0", 0, counter
.getValue()
.intValue());
counter.increment();
assertEquals("counter should have increased by 1", 1, counter
.getValue()
.intValue());
counter.increment(-1);
assertEquals("counter should have decreased by 1", 0, counter
.getValue()
.intValue());
}
@Test
public void givenBasicCounter_whenManipulate_thenCountValid() {
Counter counter = new BasicCounter(MonitorConfig
.builder("test")
.build());
assertEquals("counter should start with 0", 0, counter
.getValue()
.intValue());
counter.increment();
assertEquals("counter should have increased by 1", 1, counter
.getValue()
.intValue());
counter.increment(-1);
assertEquals("counter should have decreased by 1", 0, counter
.getValue()
.intValue());
}
@Ignore
@Test
public void givenStepCounter_whenManipulate_thenRateValid() throws Exception {
System.setProperty("servo.pollers", "1000");
Counter counter = new StepCounter(MonitorConfig
.builder("test")
.build());
assertEquals("counter should start with rate 0.0", 0.0, counter.getValue());
counter.increment();
SECONDS.sleep(1);
assertEquals("counter rate should have increased to 1.0", 1.0, counter.getValue());
}
@Test
public void givenPeakRateCounter_whenManipulate_thenPeakRateReturn() throws Exception {
Counter counter = new PeakRateCounter(MonitorConfig
.builder("test")
.build());
assertEquals("counter should start with 0", 0, counter
.getValue()
.intValue());
counter.increment();
SECONDS.sleep(1);
counter.increment();
counter.increment();
assertEquals("peak rate should have be 2", 2, counter
.getValue()
.intValue());
}
@Test
public void givenTimer_whenExecuteTask_thenTimerUpdated() throws Exception {
BasicTimer timer = new BasicTimer(MonitorConfig
.builder("test")
.build(), MILLISECONDS);
Stopwatch stopwatch = timer.start();
SECONDS.sleep(1);
timer.record(2, SECONDS);
stopwatch.stop();
assertEquals("timer should count 1 second", 1000, timer
.getValue()
.intValue(),1000);
assertEquals("timer should count 3 second in total", 3000, timer.getTotalTime()
.intValue(),1000);
assertEquals("timer should record 2 updates", 2, timer
.getCount()
.intValue());
assertEquals("timer should have max 2", 2000, timer.getMax(), 0.01);
}
@Test
public void givenBucketTimer_whenRecord_thenStatsCalculated() throws Exception {
BucketTimer timer = new BucketTimer(MonitorConfig
.builder("test")
.build(), new BucketConfig.Builder()
.withBuckets(new long[]{2L, 5L})
.withTimeUnit(SECONDS)
.build(), SECONDS);
timer.record(3);
timer.record(6);
assertEquals("timer should count 9 seconds in total", 9, timer
.getTotalTime()
.intValue());
final Map<String, Long> metricMap = timer
.getMonitors()
.stream()
.filter(monitor -> monitor
.getConfig()
.getTags()
.containsKey("servo.bucket"))
.collect(toMap(monior -> getMonitorTagValue(monior, "servo.bucket"), monitor -> (Long) monitor.getValue()));
assertThat(metricMap, allOf(hasEntry("bucket=2s", 0L), hasEntry("bucket=5s", 1L), hasEntry("bucket=overflow", 1L)));
}
private static String getMonitorTagValue(Monitor monitor, String tagKey) {
return monitor
.getConfig()
.getTags()
.getTag(tagKey)
.getValue();
}
@Test
public void givenStatsTimer_whenExecuteTask_thenStatsCalculated() throws Exception {
System.setProperty("netflix.servo", "1000");
StatsTimer timer = new StatsTimer(MonitorConfig
.builder("test")
.build(), new StatsConfig.Builder()
.withComputeFrequencyMillis(2000)
.withPercentiles(new double[]{99.0, 95.0, 90.0})
.withPublishMax(true)
.withPublishMin(true)
.withPublishCount(true)
.withPublishMean(true)
.withPublishStdDev(true)
.withPublishVariance(true)
.build(), MILLISECONDS);
Stopwatch stopwatch = timer.start();
SECONDS.sleep(1);
timer.record(3, SECONDS);
stopwatch.stop();
stopwatch = timer.start();
timer.record(6, SECONDS);
SECONDS.sleep(2);
stopwatch.stop();
assertEquals("timer should count 12 seconds in total", 12000, timer.getTotalTime(),500);
assertEquals("timer should count 12 seconds in total", 12000, timer.getTotalMeasurement(),500);
assertEquals("timer should record 4 updates", 4, timer.getCount());
assertEquals("stats timer value time-cost/update should be 2", 3000, timer
.getValue()
.intValue(),500);
final Map<String, Number> metricMap = timer
.getMonitors()
.stream()
.collect(toMap(monitor -> getMonitorTagValue(monitor, "statistic"), monitor -> (Number) monitor.getValue()));
assertThat(metricMap.keySet(), containsInAnyOrder("count", "totalTime", "max", "min", "variance", "stdDev", "avg", "percentile_99", "percentile_95", "percentile_90"));
}
@Test
public void givenGauge_whenCall_thenValueReturned() {
Gauge<Double> gauge = new BasicGauge<>(MonitorConfig
.builder("test")
.build(), () -> 2.32);
assertEquals(2.32, gauge.getValue(), 0.01);
}
@Test
public void givenMaxGauge_whenUpdateMultipleTimes_thenMaxReturned() {
MaxGauge gauge = new MaxGauge(MonitorConfig
.builder("test")
.build());
assertEquals(0, gauge
.getValue()
.intValue());
gauge.update(4);
assertEquals(4, gauge.getCurrentValue(0));
gauge.update(1);
assertEquals(4, gauge.getCurrentValue(0));
}
@Test
public void givenInformationalMonitor_whenRecord_thenInformationCollected() throws Exception {
BasicInformational informational = new BasicInformational(MonitorConfig
.builder("test")
.build());
informational.setValue("information collected");
assertEquals("information collected", informational.getValue());
}
}