diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java b/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java index 6e1ae83a80..8ba76104fb 100644 --- a/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java +++ b/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java @@ -58,31 +58,31 @@ public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry regi if (delegate instanceof ThreadPoolExecutor) { ThreadPoolExecutor executor = (ThreadPoolExecutor) delegate; - registry.register(MetricRegistry.name(name, "pool.size"), - (Gauge) executor::getPoolSize); - registry.register(MetricRegistry.name(name, "pool.core"), - (Gauge) executor::getCorePoolSize); - registry.register(MetricRegistry.name(name, "pool.max"), - (Gauge) executor::getMaximumPoolSize); + registry.registerGauge(MetricRegistry.name(name, "pool.size"), + executor::getPoolSize); + registry.registerGauge(MetricRegistry.name(name, "pool.core"), + executor::getCorePoolSize); + registry.registerGauge(MetricRegistry.name(name, "pool.max"), + executor::getMaximumPoolSize); final BlockingQueue queue = executor.getQueue(); - registry.register(MetricRegistry.name(name, "tasks.active"), - (Gauge) executor::getActiveCount); - registry.register(MetricRegistry.name(name, "tasks.completed"), - (Gauge) executor::getCompletedTaskCount); - registry.register(MetricRegistry.name(name, "tasks.queued"), - (Gauge) queue::size); - registry.register(MetricRegistry.name(name, "tasks.capacity"), - (Gauge) queue::remainingCapacity); + registry.registerGauge(MetricRegistry.name(name, "tasks.active"), + executor::getActiveCount); + registry.registerGauge(MetricRegistry.name(name, "tasks.completed"), + executor::getCompletedTaskCount); + registry.registerGauge(MetricRegistry.name(name, "tasks.queued"), + queue::size); + registry.registerGauge(MetricRegistry.name(name, "tasks.capacity"), + queue::remainingCapacity); } else if (delegate instanceof ForkJoinPool) { ForkJoinPool forkJoinPool = (ForkJoinPool) delegate; - registry.register(MetricRegistry.name(name, "tasks.stolen"), - (Gauge) forkJoinPool::getStealCount); - registry.register(MetricRegistry.name(name, "tasks.queued"), - (Gauge) forkJoinPool::getQueuedTaskCount); - registry.register(MetricRegistry.name(name, "threads.active"), - (Gauge) forkJoinPool::getActiveThreadCount); - registry.register(MetricRegistry.name(name, "threads.running"), - (Gauge) forkJoinPool::getRunningThreadCount); + registry.registerGauge(MetricRegistry.name(name, "tasks.stolen"), + forkJoinPool::getStealCount); + registry.registerGauge(MetricRegistry.name(name, "tasks.queued"), + forkJoinPool::getQueuedTaskCount); + registry.registerGauge(MetricRegistry.name(name, "threads.active"), + forkJoinPool::getActiveThreadCount); + registry.registerGauge(MetricRegistry.name(name, "threads.running"), + forkJoinPool::getRunningThreadCount); } } diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java index 2d748a07b9..bd84a65c7b 100644 --- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java +++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java @@ -68,6 +68,25 @@ protected ConcurrentMap buildMap() { return new ConcurrentHashMap<>(); } + /** + * See {@link #registerGauge(MetricName, Gauge)} + */ + public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { + return register(MetricName.build(name), metric); + } + + /** + * Given a {@link Gauge}, registers it under the given name and returns it + * + * @param name the name of the gauge + * @param the type of the gauge's value + * @return the registered {@link Gauge} + * @since 4.2.10 + */ + public Gauge registerGauge(MetricName name, Gauge metric) throws IllegalArgumentException { + return register(name, metric); + } + /** * See {@link #register(MetricName, Metric)} */ @@ -91,7 +110,7 @@ public T register(MetricName name, T metric) throws IllegalAr } if (metric instanceof MetricRegistry) { - final MetricRegistry childRegistry = (MetricRegistry)metric; + final MetricRegistry childRegistry = (MetricRegistry) metric; final MetricName childName = name; childRegistry.addListener(new MetricRegistryListener() { @Override diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java index 309d9230a3..a083f89ff2 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java @@ -664,4 +664,18 @@ public void registerNullMetric() { assertThatThrownBy(() -> registry.register("any_name", null)) .hasMessage("metric == null"); } + + @Test + public void infersGaugeType() { + Gauge gauge = registry.registerGauge(GAUGE, () -> 10_000_000_000L); + + assertThat(gauge.getValue()).isEqualTo(10_000_000_000L); + } + + @Test + public void registersGaugeAsLambda() { + registry.registerGauge(GAUGE, () -> 3.14); + + assertThat(registry.gauge(GAUGE).getValue()).isEqualTo(3.14); + } } diff --git a/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcache.java b/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcache.java index b4a51cc7eb..d437ff1a33 100644 --- a/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcache.java +++ b/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcache.java @@ -1,6 +1,5 @@ package io.dropwizard.metrics5.ehcache; -import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.Timer; @@ -12,6 +11,8 @@ import java.io.Serializable; +import static io.dropwizard.metrics5.MetricRegistry.name; + /** * An instrumented {@link Ehcache} instance. */ @@ -116,57 +117,57 @@ public class InstrumentedEhcache extends EhcacheDecoratorAdapter { */ public static Ehcache instrument(MetricRegistry registry, final Ehcache cache) { - final MetricName prefix = MetricRegistry.name(cache.getClass(), cache.getName()); - registry.register(prefix.resolve("hits"), - (Gauge) () -> cache.getStatistics().cacheHitCount()); + final MetricName prefix = name(cache.getClass(), cache.getName()); + registry.registerGauge(prefix.resolve("hits"), + () -> cache.getStatistics().cacheHitCount()); - registry.register(prefix.resolve("in-memory-hits"), - (Gauge) () -> cache.getStatistics().localHeapHitCount()); + registry.registerGauge(prefix.resolve("in-memory-hits"), + () -> cache.getStatistics().localHeapHitCount()); - registry.register(prefix.resolve("off-heap-hits"), - (Gauge) () -> cache.getStatistics().localOffHeapHitCount()); + registry.registerGauge(prefix.resolve("off-heap-hits"), + () -> cache.getStatistics().localOffHeapHitCount()); - registry.register(prefix.resolve("on-disk-hits"), - (Gauge) () -> cache.getStatistics().localDiskHitCount()); + registry.registerGauge(prefix.resolve("on-disk-hits"), + () -> cache.getStatistics().localDiskHitCount()); - registry.register(prefix.resolve("misses"), - (Gauge) () -> cache.getStatistics().cacheMissCount()); + registry.registerGauge(prefix.resolve("misses"), + () -> cache.getStatistics().cacheMissCount()); - registry.register(prefix.resolve("in-memory-misses"), - (Gauge) () -> cache.getStatistics().localHeapMissCount()); + registry.registerGauge(prefix.resolve("in-memory-misses"), + () -> cache.getStatistics().localHeapMissCount()); - registry.register(prefix.resolve("off-heap-misses"), - (Gauge) () -> cache.getStatistics().localOffHeapMissCount()); + registry.registerGauge(prefix.resolve("off-heap-misses"), + () -> cache.getStatistics().localOffHeapMissCount()); - registry.register(prefix.resolve("on-disk-misses"), - (Gauge) () -> cache.getStatistics().localDiskMissCount()); + registry.registerGauge(prefix.resolve("on-disk-misses"), + () -> cache.getStatistics().localDiskMissCount()); - registry.register(prefix.resolve("objects"), - (Gauge) () -> cache.getStatistics().getSize()); + registry.registerGauge(prefix.resolve("objects"), + () -> cache.getStatistics().getSize()); - registry.register(prefix.resolve("in-memory-objects"), - (Gauge) () -> cache.getStatistics().getLocalHeapSize()); + registry.registerGauge(prefix.resolve("in-memory-objects"), + () -> cache.getStatistics().getLocalHeapSize()); - registry.register(prefix.resolve("off-heap-objects"), - (Gauge) () -> cache.getStatistics().getLocalOffHeapSize()); + registry.registerGauge(prefix.resolve("off-heap-objects"), + () -> cache.getStatistics().getLocalOffHeapSize()); - registry.register(prefix.resolve("on-disk-objects"), - (Gauge) () -> cache.getStatistics().getLocalDiskSize()); + registry.registerGauge(prefix.resolve("on-disk-objects"), + () -> cache.getStatistics().getLocalDiskSize()); - registry.register(prefix.resolve("mean-get-time"), - (Gauge) () -> cache.getStatistics().cacheGetOperation().latency().average().value()); + registry.registerGauge(prefix.resolve("mean-get-time"), + () -> cache.getStatistics().cacheGetOperation().latency().average().value()); - registry.register(prefix.resolve("mean-search-time"), - (Gauge) () -> cache.getStatistics().cacheSearchOperation().latency().average().value()); + registry.registerGauge(prefix.resolve("mean-search-time"), + () -> cache.getStatistics().cacheSearchOperation().latency().average().value()); - registry.register(prefix.resolve("eviction-count"), - (Gauge) () -> cache.getStatistics().cacheEvictionOperation().count().value()); + registry.registerGauge(prefix.resolve("eviction-count"), + () -> cache.getStatistics().cacheEvictionOperation().count().value()); - registry.register(prefix.resolve("searches-per-second"), - (Gauge) () -> cache.getStatistics().cacheSearchOperation().rate().value()); + registry.registerGauge(prefix.resolve("searches-per-second"), + () -> cache.getStatistics().cacheSearchOperation().rate().value()); - registry.register(prefix.resolve("writer-queue-size"), - (Gauge) () -> cache.getStatistics().getWriterQueueLength()); + registry.registerGauge(prefix.resolve("writer-queue-size"), + () -> cache.getStatistics().getWriterQueueLength()); return new InstrumentedEhcache(registry, cache); } diff --git a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java index d4303e36a3..92b5a9d09f 100644 --- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java +++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java @@ -11,6 +11,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; public class InstrumentedEhcacheTest { private static final CacheManager MANAGER = CacheManager.create(); @@ -23,6 +24,27 @@ public void setUp() { final Cache c = new Cache(new CacheConfiguration("test", 100)); MANAGER.addCache(c); this.cache = InstrumentedEhcache.instrument(registry, c); + assertThat(registry.getGauges().entrySet().stream() + .map(e -> entry(e.getKey().getKey(), (Number) e.getValue().getValue()))) + .containsOnly( + entry("net.sf.ehcache.Cache.test.eviction-count", 0L), + entry("net.sf.ehcache.Cache.test.hits", 0L), + entry("net.sf.ehcache.Cache.test.in-memory-hits", 0L), + entry("net.sf.ehcache.Cache.test.in-memory-misses", 0L), + entry("net.sf.ehcache.Cache.test.in-memory-objects", 0L), + entry("net.sf.ehcache.Cache.test.mean-get-time", Double.NaN), + entry("net.sf.ehcache.Cache.test.mean-search-time", Double.NaN), + entry("net.sf.ehcache.Cache.test.misses", 0L), + entry("net.sf.ehcache.Cache.test.objects", 0L), + entry("net.sf.ehcache.Cache.test.off-heap-hits", 0L), + entry("net.sf.ehcache.Cache.test.off-heap-misses", 0L), + entry("net.sf.ehcache.Cache.test.off-heap-objects", 0L), + entry("net.sf.ehcache.Cache.test.on-disk-hits", 0L), + entry("net.sf.ehcache.Cache.test.on-disk-misses", 0L), + entry("net.sf.ehcache.Cache.test.on-disk-objects", 0L), + entry("net.sf.ehcache.Cache.test.searches-per-second", 0.0), + entry("net.sf.ehcache.Cache.test.writer-queue-size", 0L) + ); } @Test diff --git a/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java b/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java index eb5a75415c..456f97c070 100644 --- a/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java +++ b/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java @@ -1,6 +1,5 @@ package io.dropwizard.metrics5.httpasyncclient; -import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricRegistry; import org.apache.http.config.Registry; import org.apache.http.conn.DnsResolver; @@ -20,26 +19,18 @@ public class InstrumentedNClientConnManager extends PoolingNHttpClientConnection public InstrumentedNClientConnManager(final ConnectingIOReactor ioreactor, final NHttpConnectionFactory connFactory, final SchemePortResolver schemePortResolver, final MetricRegistry metricRegistry, final Registry iosessionFactoryRegistry, final long timeToLive, final TimeUnit tunit, final DnsResolver dnsResolver, final String name) { super(ioreactor, connFactory, iosessionFactoryRegistry, schemePortResolver, dnsResolver, timeToLive, tunit); - metricRegistry.register(name(NHttpClientConnectionManager.class, name, "available-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getAvailable(); - }); - metricRegistry.register(name(NHttpClientConnectionManager.class, name, "leased-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getLeased(); - }); - metricRegistry.register(name(NHttpClientConnectionManager.class, name, "max-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getMax(); - }); - metricRegistry.register(name(NHttpClientConnectionManager.class, name, "pending-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getPending(); - }); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "available-connections"), + () -> getTotalStats().getAvailable()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "leased-connections"), + () -> getTotalStats().getLeased()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "max-connections"), + () -> getTotalStats().getMax()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "pending-connections"), + () -> getTotalStats().getPending()); } } diff --git a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java index 30eb185924..89cfcc86bc 100644 --- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java +++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java @@ -1,6 +1,5 @@ package io.dropwizard.metrics5.httpclient; -import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricRegistry; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; @@ -104,26 +103,18 @@ public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, this.metricsRegistry = metricsRegistry; this.name = name; - metricsRegistry.register(name(HttpClientConnectionManager.class, name, "available-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getAvailable(); - }); - metricsRegistry.register(name(HttpClientConnectionManager.class, name, "leased-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getLeased(); - }); - metricsRegistry.register(name(HttpClientConnectionManager.class, name, "max-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getMax(); - }); - metricsRegistry.register(name(HttpClientConnectionManager.class, name, "pending-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getPending(); - }); + // this acquires a lock on the connection pool; remove if contention sucks + metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "available-connections"), + () -> getTotalStats().getAvailable()); + // this acquires a lock on the connection pool; remove if contention sucks + metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "leased-connections"), + () -> getTotalStats().getLeased()); + // this acquires a lock on the connection pool; remove if contention sucks + metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "max-connections"), + () -> getTotalStats().getMax()); + // this acquires a lock on the connection pool; remove if contention sucks + metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "pending-connections"), + () -> getTotalStats().getPending()); } @Override diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java index bd53f78f49..40d6ec9502 100644 --- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java +++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java @@ -8,6 +8,8 @@ import org.mockito.Mockito; import static junit.framework.TestCase.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; @@ -17,7 +19,12 @@ public class InstrumentedHttpClientConnectionManagerTest { @Test public void shouldRemoveGauges() { final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); - Assert.assertEquals(4, metricRegistry.getGauges().size()); + assertThat(metricRegistry.getGauges().entrySet().stream() + .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) + .containsOnly(entry("org.apache.http.conn.HttpClientConnectionManager.available-connections", 0), + entry("org.apache.http.conn.HttpClientConnectionManager.leased-connections", 0), + entry("org.apache.http.conn.HttpClientConnectionManager.max-connections", 20), + entry("org.apache.http.conn.HttpClientConnectionManager.pending-connections", 0)); instrumentedHttpClientConnectionManager.close(); Assert.assertEquals(0, metricRegistry.getGauges().size()); @@ -37,7 +44,7 @@ public void configurableViaBuilder() { .close(); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); - Mockito.verify(registry, Mockito.atLeast(1)).register(argumentCaptor.capture(), any()); + Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); } } diff --git a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java index 26f57cc4e2..c3fc9d2787 100644 --- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java +++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java @@ -1,6 +1,5 @@ package io.dropwizard.metrics5.httpclient5; -import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricRegistry; import org.apache.hc.client5.http.DnsResolver; import org.apache.hc.client5.http.SchemePortResolver; @@ -49,26 +48,18 @@ protected static Registry getDefaultTlsStrategy() { this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); this.name = name; - metricRegistry.register(name(METRICS_PREFIX, name, "available-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getAvailable(); - }); - metricRegistry.register(name(METRICS_PREFIX, name, "leased-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getLeased(); - }); - metricRegistry.register(name(METRICS_PREFIX, name, "max-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getMax(); - }); - metricRegistry.register(name(METRICS_PREFIX, name, "pending-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getPending(); - }); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(METRICS_PREFIX, name, "available-connections"), + () -> getTotalStats().getAvailable()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(METRICS_PREFIX, name, "leased-connections"), + () -> getTotalStats().getLeased()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(METRICS_PREFIX, name, "max-connections"), + () -> getTotalStats().getMax()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(METRICS_PREFIX, name, "pending-connections"), + () -> getTotalStats().getPending()); } /** diff --git a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java index 250fc5f3e4..5728eccc34 100644 --- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java +++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java @@ -1,6 +1,5 @@ package io.dropwizard.metrics5.httpclient5; -import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricRegistry; import org.apache.hc.client5.http.DnsResolver; import org.apache.hc.client5.http.SchemePortResolver; @@ -52,26 +51,18 @@ protected static Registry getDefaultRegistry() { this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); this.name = name; - metricRegistry.register(name(METRICS_PREFIX, name, "available-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getAvailable(); - }); - metricRegistry.register(name(METRICS_PREFIX, name, "leased-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getLeased(); - }); - metricRegistry.register(name(METRICS_PREFIX, name, "max-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getMax(); - }); - metricRegistry.register(name(METRICS_PREFIX, name, "pending-connections"), - (Gauge) () -> { - // this acquires a lock on the connection pool; remove if contention sucks - return getTotalStats().getPending(); - }); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(METRICS_PREFIX, name, "available-connections"), + () -> getTotalStats().getAvailable()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(METRICS_PREFIX, name, "leased-connections"), + () -> getTotalStats().getLeased()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(METRICS_PREFIX, name, "max-connections"), + () -> getTotalStats().getMax()); + // this acquires a lock on the connection pool; remove if contention sucks + metricRegistry.registerGauge(name(METRICS_PREFIX, name, "pending-connections"), + () -> getTotalStats().getPending()); } /** diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java index 74a6eeedc9..5f1d79d924 100644 --- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java +++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java @@ -8,6 +8,8 @@ import org.mockito.Mockito; import static junit.framework.TestCase.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; public class InstrumentedAsyncClientConnectionManagerTest { @@ -16,7 +18,12 @@ public class InstrumentedAsyncClientConnectionManagerTest { @Test public void shouldRemoveGauges() { final InstrumentedAsyncClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build(); - Assert.assertEquals(4, metricRegistry.getGauges().size()); + assertThat(metricRegistry.getGauges().entrySet().stream() + .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) + .containsOnly(entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.available-connections", 0), + entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.leased-connections", 0), + entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.max-connections", 25), + entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.pending-connections", 0)); instrumentedHttpClientConnectionManager.close(); Assert.assertEquals(0, metricRegistry.getGauges().size()); @@ -36,7 +43,7 @@ public void configurableViaBuilder() { .close(); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); - Mockito.verify(registry, Mockito.atLeast(1)).register(argumentCaptor.capture(), any()); + Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); } } diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java index a0e0654775..613af8b015 100644 --- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java +++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java @@ -8,6 +8,8 @@ import org.mockito.Mockito; import static junit.framework.TestCase.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; public class InstrumentedHttpClientConnectionManagerTest { @@ -16,7 +18,12 @@ public class InstrumentedHttpClientConnectionManagerTest { @Test public void shouldRemoveGauges() { final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); - Assert.assertEquals(4, metricRegistry.getGauges().size()); + assertThat(metricRegistry.getGauges().entrySet().stream() + .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) + .containsOnly(entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.available-connections", 0), + entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.leased-connections", 0), + entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.max-connections", 25), + entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.pending-connections", 0)); instrumentedHttpClientConnectionManager.close(); Assert.assertEquals(0, metricRegistry.getGauges().size()); @@ -36,7 +43,7 @@ public void configurableViaBuilder() { .close(); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); - Mockito.verify(registry, Mockito.atLeast(1)).register(argumentCaptor.capture(), any()); + Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); } } diff --git a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPool.java b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPool.java index 3341f8a625..7b214b5be5 100644 --- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPool.java +++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPool.java @@ -1,6 +1,5 @@ package io.dropwizard.metrics5.jetty10; -import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.RatioGauge; @@ -88,13 +87,11 @@ protected Ratio getRatio() { return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); } }); - metricRegistry.register(prefix.resolve("size"), (Gauge) this::getThreads); - metricRegistry.register(prefix.resolve("jobs"), (Gauge) () -> { - // This assumes the QueuedThreadPool is using a BlockingArrayQueue or - // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. - return getQueue().size(); - }); - metricRegistry.register(prefix.resolve("jobs-queue-utilization"), new RatioGauge() { + // This assumes the QueuedThreadPool is using a BlockingArrayQueue or + // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. + metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); + metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); + metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { @Override protected Ratio getRatio() { BlockingQueue queue = getQueue(); diff --git a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPool.java b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPool.java index d8ce428d35..b186365330 100644 --- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPool.java +++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPool.java @@ -1,6 +1,5 @@ package io.dropwizard.metrics5.jetty11; -import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.RatioGauge; @@ -88,13 +87,11 @@ protected Ratio getRatio() { return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); } }); - metricRegistry.register(prefix.resolve("size"), (Gauge) this::getThreads); - metricRegistry.register(prefix.resolve("jobs"), (Gauge) () -> { - // This assumes the QueuedThreadPool is using a BlockingArrayQueue or - // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. - return getQueue().size(); - }); - metricRegistry.register(prefix.resolve("jobs-queue-utilization"), new RatioGauge() { + metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); + // This assumes the QueuedThreadPool is using a BlockingArrayQueue or + // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. + metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); + metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { @Override protected Ratio getRatio() { BlockingQueue queue = getQueue(); diff --git a/metrics-jetty9/src/main/java/io/dropwizard/metrics5/jetty9/InstrumentedQueuedThreadPool.java b/metrics-jetty9/src/main/java/io/dropwizard/metrics5/jetty9/InstrumentedQueuedThreadPool.java index d9d44135d6..f7eebb9b07 100644 --- a/metrics-jetty9/src/main/java/io/dropwizard/metrics5/jetty9/InstrumentedQueuedThreadPool.java +++ b/metrics-jetty9/src/main/java/io/dropwizard/metrics5/jetty9/InstrumentedQueuedThreadPool.java @@ -1,6 +1,5 @@ package io.dropwizard.metrics5.jetty9; -import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.RatioGauge; @@ -86,13 +85,11 @@ protected Ratio getRatio() { return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); } }); - metricRegistry.register(prefix.resolve("size"), (Gauge) this::getThreads); - metricRegistry.register(prefix.resolve("jobs"), (Gauge) () -> { - // This assumes the QueuedThreadPool is using a BlockingArrayQueue or - // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. - return getQueue().size(); - }); - metricRegistry.register(prefix.resolve("jobs-queue-utilization"), new RatioGauge() { + metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); + // This assumes the QueuedThreadPool is using a BlockingArrayQueue or + // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. + metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); + metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { @Override protected Ratio getRatio() { BlockingQueue queue = getQueue(); diff --git a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java index 5e9a4465b4..5d0cabd469 100644 --- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java +++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java @@ -130,15 +130,12 @@ public void registersMBeansForMetricObjectsUsingProvidedObjectNameFactory() thro try { String widgetName = "something"; when(mockObjectNameFactory.createName(any(String.class), any(String.class), any(MetricName.class))).thenReturn(n); - Gauge aGauge = mock(Gauge.class); - when(aGauge.getValue()).thenReturn(1); - JmxReporter reporter = JmxReporter.forRegistry(registry) .registerWith(mBeanServer) .inDomain(name) .createsObjectNamesWith(mockObjectNameFactory) .build(); - registry.register(widgetName, aGauge); + registry.registerGauge(widgetName, () -> 1); reporter.start(); verify(mockObjectNameFactory).createName(eq("gauges"), any(String.class), eq(MetricName.build("something"))); //verifyNoMoreInteractions(mockObjectNameFactory); diff --git a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java index 0d57660c1f..b27f068ee3 100644 --- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java +++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java @@ -35,6 +35,11 @@ public MetricRegistry(io.dropwizard.metrics5.MetricRegistry delegate) { this.delegate = requireNonNull(delegate); } + public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { + delegate.registerGauge(MetricName.build(name), metric.getDelegate()); + return metric; + } + public T register(String name, T metric) throws IllegalArgumentException { delegate.register(MetricName.build(name), metric.getDelegate()); return metric; diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java index a829983574..4ef53074ba 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java @@ -39,6 +39,12 @@ public void testRegisterAll() { assertThat(metrics.get("test-gauge")).isInstanceOf(Gauge.class); } + @Test + public void testRegisterGauge() { + metricRegistry.registerGauge("test-gauge", () -> 42); + assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); + } + @Test public void testCreateCustomGauge() { Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42);