Skip to content

Commit

Permalink
Prevent name conflicts and rename jvm_classes_loaded (#681)
Browse files Browse the repository at this point in the history
Signed-off-by: Fabian Stäber <fabian@fstab.de>
  • Loading branch information
fstab committed Aug 6, 2021
1 parent 9701230 commit 17c98eb
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
Expand Up @@ -48,10 +48,13 @@ public CollectorRegistry(boolean autoDescribe) {
*/
public void register(Collector m) {
List<String> names = collectorNames(m);
assertNoDuplicateNames(m, names);
synchronized (namesCollectorsLock) {
for (String name : names) {
if (namesToCollectors.containsKey(name)) {
throw new IllegalArgumentException("Collector already registered that provides name: " + name);
throw new IllegalArgumentException("Failed to register Collector of type " + m.getClass().getSimpleName()
+ ": " + name + " is already in use by another Collector of type "
+ namesToCollectors.get(name).getClass().getSimpleName());
}
}
for (String name : names) {
Expand All @@ -61,6 +64,16 @@ public void register(Collector m) {
}
}

private void assertNoDuplicateNames(Collector m, List<String> names) {
Set<String> uniqueNames = new HashSet<String>();
for (String name : names) {
if (!uniqueNames.add(name)) {
throw new IllegalArgumentException("Failed to register Collector of type " + m.getClass().getSimpleName()
+ ": The Collector exposes the same name multiple times: " + name);
}
}
}

/**
* Unregister a Collector.
*/
Expand Down
Expand Up @@ -20,7 +20,7 @@
* </pre>
* Example metrics being exported:
* <pre>
* jvm_classes_loaded{} 1000
* jvm_classes_currently_loaded{} 1000
* jvm_classes_loaded_total{} 2000
* jvm_classes_unloaded_total{} 500
* </pre>
Expand All @@ -38,7 +38,7 @@ public ClassLoadingExports(ClassLoadingMXBean clBean) {

void addClassLoadingMetrics(List<MetricFamilySamples> sampleFamilies) {
sampleFamilies.add(new GaugeMetricFamily(
"jvm_classes_loaded",
"jvm_classes_currently_loaded",
"The number of classes that are currently loaded in the JVM",
clBean.getLoadedClassCount()));
sampleFamilies.add(new CounterMetricFamily(
Expand Down
Expand Up @@ -13,7 +13,7 @@
public class ClassLoadingExportsTest {

private ClassLoadingMXBean mockClassLoadingsBean = Mockito.mock(ClassLoadingMXBean.class);
private CollectorRegistry registry = new CollectorRegistry();
private CollectorRegistry registry = new CollectorRegistry(true);
private ClassLoadingExports collectorUnderTest;

private static final String[] EMPTY_LABEL = new String[0];
Expand All @@ -31,7 +31,7 @@ public void testClassLoading() {
assertEquals(
1000,
registry.getSampleValue(
"jvm_classes_loaded", EMPTY_LABEL, EMPTY_LABEL),
"jvm_classes_currently_loaded", EMPTY_LABEL, EMPTY_LABEL),
.0000001);
assertEquals(
2000L,
Expand Down

0 comments on commit 17c98eb

Please sign in to comment.