Skip to content

Commit 2625cb1

Browse files
authored
Eagerly reject null label values (#1335)
Scraping generally doesn't support null label values and can throw NPEs at various points. It's easiest to debug such problems at the point null is introduced. Signed-off-by: Benjamin Peterson <[email protected]> Signed-off-by: Benjamin Peterson <[email protected]>
1 parent 365d205 commit 2625cb1

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StatefulMetric.java

+14-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,20 @@ public D labelValues(String... labelValues) {
112112
"Expected " + labelNames.length + " label values, but got " + labelValues.length + ".");
113113
}
114114
}
115-
return data.computeIfAbsent(Arrays.asList(labelValues), l -> newDataPoint());
115+
return data.computeIfAbsent(
116+
Arrays.asList(labelValues),
117+
l -> {
118+
for (int i = 0; i < l.size(); i++) {
119+
if (l.get(i) == null) {
120+
throw new IllegalArgumentException(
121+
"null label value for metric "
122+
+ getMetadata().getName()
123+
+ " and label "
124+
+ labelNames[i]);
125+
}
126+
}
127+
return newDataPoint();
128+
});
116129
}
117130

118131
/**

prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StatefulMetricTest.java

+9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.prometheus.metrics.core.metrics;
22

33
import static org.assertj.core.api.Assertions.assertThat;
4+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
45

56
import java.lang.reflect.Field;
67
import java.util.Map;
@@ -67,4 +68,12 @@ public void testClearNoLabels() {
6768
assertThat(counter.collect().getDataPoints()).hasSize(1);
6869
assertThat(counter.collect().getDataPoints().get(0).getValue()).isEqualTo(1.0);
6970
}
71+
72+
@Test
73+
public void testNullLabel() {
74+
Counter counter = Counter.builder().name("test").labelNames("l1", "l2").build();
75+
assertThatExceptionOfType(IllegalArgumentException.class)
76+
.isThrownBy(() -> counter.labelValues("l1", null))
77+
.withMessage("null label value for metric test and label l2");
78+
}
7079
}

0 commit comments

Comments
 (0)