Skip to content

Commit

Permalink
Revise cache metrics implementations + tests (micrometer-metrics#1107)
Browse files Browse the repository at this point in the history
  • Loading branch information
OleksiiBondar authored and jkschneider committed Jan 2, 2019
1 parent a99d397 commit bb65f8a
Show file tree
Hide file tree
Showing 12 changed files with 898 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,6 @@ public static Tags of(@Nullable Iterable<? extends Tag> tags) {
} else if (tags instanceof Tags) {
return (Tags) tags;
} else if (tags instanceof Collection) {
@SuppressWarnings("unchecked")
Collection<? extends Tag> tagsCollection = (Collection<? extends Tag>) tags;
return new Tags(tagsCollection.toArray(new Tag[0]));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

import java.lang.ref.WeakReference;


/**
* A common base class for cache metrics that ensures that all caches are instrumented
* with the same basic set of metrics while allowing for additional detail that is specific
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public CaffeineCacheMetrics(Cache<?, ?> cache, String cacheName, Iterable<Tag> t
* @param <C> The cache type.
* @return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
*/
public static <C extends Cache> C monitor(MeterRegistry registry, C cache, String cacheName, String... tags) {
public static <C extends Cache<?, ?>> C monitor(MeterRegistry registry, C cache, String cacheName, String... tags) {
return monitor(registry, cache, cacheName, Tags.of(tags));
}

Expand All @@ -83,7 +83,7 @@ public static <C extends Cache> C monitor(MeterRegistry registry, C cache, Strin
* @return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
* @see CacheStats
*/
public static <C extends Cache> C monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags) {
public static <C extends Cache<?, ?>> C monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags) {
new CaffeineCacheMetrics(cache, cacheName, tags).bindTo(registry);
return cache;
}
Expand All @@ -99,7 +99,7 @@ public static <C extends Cache> C monitor(MeterRegistry registry, C cache, Strin
* @param <C> The cache type.
* @return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
*/
public static <C extends AsyncLoadingCache> C monitor(MeterRegistry registry, C cache, String cacheName, String... tags) {
public static <C extends AsyncLoadingCache<?, ?>> C monitor(MeterRegistry registry, C cache, String cacheName, String... tags) {
return monitor(registry, cache, cacheName, Tags.of(tags));
}

Expand All @@ -115,7 +115,7 @@ public static <C extends AsyncLoadingCache> C monitor(MeterRegistry registry, C
* @return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
* @see CacheStats
*/
public static <C extends AsyncLoadingCache> C monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags) {
public static <C extends AsyncLoadingCache<?, ?>> C monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags) {
monitor(registry, cache.synchronous(), cacheName, tags);
return cache;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ protected long putCount() {
@Override
protected void bindImplementationSpecificMetrics(MeterRegistry registry) {
Gauge.builder("cache.remoteSize", stats, StatisticsGateway::getRemoteSize)
.tags(getTagsWithCacheName())
.description("The number of entries held remotely in this cache")
.register(registry);

Expand All @@ -102,7 +103,7 @@ protected void bindImplementationSpecificMetrics(MeterRegistry registry) {
.description("Cache puts resulting in a new key/value pair")
.register(registry);

FunctionCounter.builder("cache.puts.added", stats, StatisticsGateway::cachePutAddedCount)
FunctionCounter.builder("cache.puts.added", stats, StatisticsGateway::cachePutUpdatedCount)
.tags(getTagsWithCacheName()).tags("result", "updated")
.description("Cache puts resulting in an updated value")
.register(registry);
Expand All @@ -112,7 +113,7 @@ protected void bindImplementationSpecificMetrics(MeterRegistry registry) {
rollbackTransactionMetrics(registry);
recoveryTransactionMetrics(registry);

Gauge.builder("cache.local.offheap.size", stats, StatisticsGateway::getLocalOffHeapSize)
Gauge.builder("cache.local.offheap.size", stats, StatisticsGateway::getLocalOffHeapSizeInBytes)
.tags(getTagsWithCacheName())
.description("Local off-heap size")
.baseUnit("bytes")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class GuavaCacheMetrics extends CacheMeterBinder {
* @return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
* @see com.google.common.cache.CacheStats
*/
public static <C extends Cache> C monitor(MeterRegistry registry, C cache, String cacheName, String... tags) {
public static <C extends Cache<?, ?>> C monitor(MeterRegistry registry, C cache, String cacheName, String... tags) {
return monitor(registry, cache, cacheName, Tags.of(tags));
}

Expand All @@ -60,7 +60,7 @@ public static <C extends Cache> C monitor(MeterRegistry registry, C cache, Strin
* @return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
* @see com.google.common.cache.CacheStats
*/
public static <C extends Cache> C monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags) {
public static <C extends Cache<?, ?>> C monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags) {
new GuavaCacheMetrics(cache, cacheName, tags).bindTo(registry);
return cache;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,17 +129,19 @@ protected void bindImplementationSpecificMetrics(MeterRegistry registry) {
}

private Long lookupStatistic(String name) {
try {
List<MBeanServer> mBeanServers = MBeanServerFactory.findMBeanServer(null);
for (MBeanServer mBeanServer : mBeanServers) {
try {
return (Long) mBeanServer.getAttribute(objectName, name);
} catch (AttributeNotFoundException | InstanceNotFoundException ex) {
// did not find MBean, try the next server
if (objectName != null) {
try {
List<MBeanServer> mBeanServers = MBeanServerFactory.findMBeanServer(null);
for (MBeanServer mBeanServer : mBeanServers) {
try {
return (Long) mBeanServer.getAttribute(objectName, name);
} catch (AttributeNotFoundException | InstanceNotFoundException ex) {
// did not find MBean, try the next server
}
}
} catch (MBeanException | ReflectionException ex) {
throw new IllegalStateException(ex);
}
} catch (MBeanException | ReflectionException ex) {
throw new IllegalStateException(ex);
}

// didn't find the MBean in any servers
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Copyright 2018 Pivotal Software, Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micrometer.core.instrument.binder.cache;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.search.RequiredSearch;

/**
* @author Oleksii Bondar
*/
abstract class AbstractCacheMetricsTest {

protected Tags expectedTag = Tags.of("app", "test");

/**
* Verifies base metrics presence
*/
protected void verifyCommonCacheMetrics(MeterRegistry meterRegistry, CacheMeterBinder meterBinder) {
meterRegistry.get("cache.puts").tags(expectedTag).functionCounter();
meterRegistry.get("cache.gets").tags(expectedTag).tag("result", "hit").functionCounter();

if (meterBinder.size() != null) {
meterRegistry.get("cache.size").tags(expectedTag).gauge();
}
if (meterBinder.missCount() != null) {
meterRegistry.get("cache.gets").tags(expectedTag).tag("result", "miss").functionCounter();
}
if (meterBinder.evictionCount() != null) {
meterRegistry.get("cache.evictions").tags(expectedTag).functionCounter();
}
}

protected RequiredSearch fetch(MeterRegistry meterRegistry, String name) {
return meterRegistry.get(name).tags(expectedTag);
}

protected RequiredSearch fetch(MeterRegistry meterRegistry, String name, Iterable<Tag> tags) {
return fetch(meterRegistry, name).tags(tags);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* Copyright 2018 Pivotal Software, Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micrometer.core.instrument.binder.cache;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.stats.CacheStats;

import io.micrometer.core.instrument.FunctionCounter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.TimeGauge;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Tests for {@link CaffeineCacheMetrics}.
*
* @author Oleksii Bondar
*/
class CaffeineCacheMetricsTest extends AbstractCacheMetricsTest {

private LoadingCache<String, String> cache = Caffeine.newBuilder().build(new CacheLoader<String, String>() {
public String load(String key) throws Exception {
return "";
};
});
private CaffeineCacheMetrics metrics = new CaffeineCacheMetrics(cache, "testCache", expectedTag);

@Test
void reportExpectedGeneralMetrics() {
MeterRegistry registry = new SimpleMeterRegistry();
metrics.bindTo(registry);

verifyCommonCacheMetrics(registry, metrics);

Gauge evictionWeight = fetch(registry, "cache.eviction.weight").gauge();
CacheStats stats = cache.stats();
assertThat(evictionWeight.value()).isEqualTo(stats.evictionCount());

// specific to LoadingCache instance
TimeGauge loadDuration = fetch(registry, "cache.load.duration").timeGauge();
assertThat(loadDuration.value()).isEqualTo(stats.totalLoadTime());

FunctionCounter successfulLoad = fetch(registry, "cache.load", Tags.of("result", "success")).functionCounter();
assertThat(successfulLoad.count()).isEqualTo(stats.loadSuccessCount());

FunctionCounter failedLoad = fetch(registry, "cache.load", Tags.of("result", "failure")).functionCounter();
assertThat(failedLoad.count()).isEqualTo(stats.loadFailureCount());
}

@Test
void constructInstanceViaStaticMethodMonitor() {
MeterRegistry meterRegistry = new SimpleMeterRegistry();
CaffeineCacheMetrics.monitor(meterRegistry, cache, "testCache", expectedTag);

meterRegistry.get("cache.eviction.weight").tags(expectedTag).gauge();
}

@Test
void doNotReportMetricsForNonLoadingCache() {
MeterRegistry meterRegistry = new SimpleMeterRegistry();
Cache<Object, Object> cache = Caffeine.newBuilder().build();
CaffeineCacheMetrics metrics = new CaffeineCacheMetrics(cache, "testCache", expectedTag);
metrics.bindTo(meterRegistry);

assertThat(meterRegistry.find("cache.load.duration").timeGauge()).isNull();
}

@Test
void returnCacheSize() {
assertThat(metrics.size()).isEqualTo(cache.estimatedSize());
}

@Test
void returnHitCount() {
assertThat(metrics.hitCount()).isEqualTo(cache.stats().hitCount());
}

@Test
void returnMissCount() {
assertThat(metrics.missCount()).isEqualTo(cache.stats().missCount());
}

@Test
void returnEvictionCount() {
assertThat(metrics.evictionCount()).isEqualTo(cache.stats().evictionCount());
}

@Test
void returnPutCount() {
assertThat(metrics.putCount()).isEqualTo(cache.stats().loadCount());
}

}
Loading

0 comments on commit bb65f8a

Please sign in to comment.