Skip to content

Commit 0327d2f

Browse files
authored
Various cleanups in prometheus-metrics-core (#1085)
Signed-off-by: Mickael Maison <[email protected]>
1 parent 2ca4dc8 commit 0327d2f

File tree

19 files changed

+452
-130
lines changed

19 files changed

+452
-130
lines changed

prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/exemplars/ExemplarSampler.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public class ExemplarSampler {
3434
private final Exemplar[] exemplars;
3535
private final Exemplar[]
3636
customExemplars; // Separate from exemplars, because we don't want custom exemplars
37-
// to be overwritten by automatic exemplar sampling. exemplars.lengt == customExemplars.length
37+
// to be overwritten by automatic exemplar sampling. exemplars.length == customExemplars.length
3838
private final AtomicBoolean acceptingNewExemplars = new AtomicBoolean(true);
3939
private final AtomicBoolean acceptingNewCustomExemplars = new AtomicBoolean(true);
4040
private final SpanContext

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ <T extends DataPointSnapshot> T run(
5454
int bufferSize;
5555
T result;
5656
synchronized (runLock) {
57-
Long count = observationCount.getAndAdd(signBit);
57+
long count = observationCount.getAndAdd(signBit);
5858
while (!complete.apply(count)) {
5959
Thread.yield();
6060
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ final class CKMSQuantiles {
3838
int n = 0;
3939

4040
/** List of sampled observations, ordered by Sample.value. */
41-
final LinkedList<Sample> samples = new LinkedList<Sample>();
41+
final LinkedList<Sample> samples = new LinkedList<>();
4242

4343
/**
4444
* Compress is called every compressInterval inserts. Note that the buffer is flushed whenever
@@ -127,7 +127,7 @@ private void insertBefore(ListIterator<Sample> iterator, double value, int r) {
127127
public double get(double q) {
128128
flush();
129129

130-
if (samples.size() == 0) {
130+
if (samples.isEmpty()) {
131131
return Double.NaN;
132132
}
133133

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

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -481,8 +481,8 @@ private boolean maybeReset() {
481481
nativeZeroCount.reset();
482482
count.reset();
483483
sum.reset();
484-
for (int i = 0; i < classicBuckets.length; i++) {
485-
classicBuckets[i].reset();
484+
for (LongAdder classicBucket : classicBuckets) {
485+
classicBucket.reset();
486486
}
487487
nativeZeroThreshold = nativeMinZeroThreshold;
488488
nativeSchema = Histogram.this.nativeInitialSchema;
@@ -592,11 +592,7 @@ private void doubleBucketWidth(Map<Integer, LongAdder> buckets) {
592592
buckets.clear();
593593
for (i = 0; i < keys.length; i++) {
594594
int index = (keys[i] + 1) / 2;
595-
LongAdder count = buckets.get(index);
596-
if (count == null) {
597-
count = new LongAdder();
598-
buckets.put(index, count);
599-
}
595+
LongAdder count = buckets.computeIfAbsent(index, k -> new LongAdder());
600596
count.add(values[i]);
601597
}
602598
}
@@ -789,9 +785,9 @@ public Builder classicLinearUpperBounds(double start, double width, int count) {
789785
}
790786

791787
/**
792-
* Create classic histogram bucxkets with exponential boundaries.
788+
* Create classic histogram buckets with exponential boundaries.
793789
*
794-
* <p>Example: {@code withClassicExponentialBuckets(1.0, 2.0, 10)} creates bucket bounaries
790+
* <p>Example: {@code withClassicExponentialBuckets(1.0, 2.0, 10)} creates bucket boundaries
795791
* {@code [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0]}
796792
*
797793
* @param start is the first bucket boundary

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ protected StatefulMetric(Builder<?, ?> builder) {
4848
protected abstract MetricSnapshot collect(List<Labels> labels, List<T> metricData);
4949

5050
public MetricSnapshot collect() {
51-
if (labelNames.length == 0 && data.size() == 0) {
51+
if (labelNames.length == 0 && data.isEmpty()) {
5252
// This is a metric without labels that has not been used yet. Initialize the data on the fly.
5353
labelValues();
5454
}
@@ -138,7 +138,7 @@ protected T getNoLabels() {
138138
}
139139

140140
protected MetricsProperties[] getMetricProperties(
141-
Builder builder, PrometheusProperties prometheusProperties) {
141+
Builder<?, ?> builder, PrometheusProperties prometheusProperties) {
142142
String metricName = getMetadata().getName();
143143
if (prometheusProperties.getMetricProperties(metricName) != null) {
144144
return new MetricsProperties[] {

prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/SpanContextSupplierTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public void markCurrentSpanAsExemplar() {}
4242
new ExemplarSamplerConfig(
4343
10, // min retention period in milliseconds
4444
20, // max retention period in milliseconds
45-
5, // sample interval in millisecnods
45+
5, // sample interval in milliseconds
4646
1, // number of exemplars
4747
null // histogram upper bounds
4848
);

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package io.prometheus.metrics.core.metrics;
22

3-
import static org.junit.Assert.*;
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertTrue;
5+
import static org.junit.Assert.fail;
46

57
import io.prometheus.metrics.core.metrics.CKMSQuantiles.Quantile;
68
import java.util.*;
@@ -233,7 +235,7 @@ public void testGetGaussian() {
233235
new NormalDistribution(
234236
rand, mean, stddev, NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
235237

236-
List<Quantile> quantiles = new ArrayList<Quantile>();
238+
List<Quantile> quantiles = new ArrayList<>();
237239
quantiles.add(new Quantile(0.10, 0.001));
238240
quantiles.add(new Quantile(0.50, 0.01));
239241
quantiles.add(new Quantile(0.90, 0.001));
@@ -297,7 +299,7 @@ public void testIllegalArgumentException() {
297299
}
298300

299301
private List<Double> shuffledValues(int n, Random random) {
300-
List<Double> result = new ArrayList<Double>(n);
302+
List<Double> result = new ArrayList<>(n);
301303
for (int i = 0; i < n; i++) {
302304
result.add(i + 1.0);
303305
}

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

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import static io.prometheus.metrics.core.metrics.TestUtil.assertExemplarEquals;
44
import static org.junit.Assert.assertEquals;
5+
import static org.junit.Assert.assertNull;
6+
import static org.junit.Assert.assertTrue;
57
import static org.junit.rules.ExpectedException.none;
68

79
import io.prometheus.metrics.core.exemplars.ExemplarSamplerConfigTestUtil;
@@ -14,21 +16,21 @@
1416
import io.prometheus.metrics.shaded.com_google_protobuf_3_25_3.TextFormat;
1517
import io.prometheus.metrics.tracer.common.SpanContext;
1618
import io.prometheus.metrics.tracer.initializer.SpanContextSupplier;
19+
import java.util.Arrays;
1720
import java.util.Iterator;
1821
import org.junit.After;
19-
import org.junit.Assert;
2022
import org.junit.Before;
2123
import org.junit.Rule;
2224
import org.junit.Test;
2325
import org.junit.rules.ExpectedException;
2426

2527
public class CounterTest {
2628

27-
Counter noLabels;
28-
Counter labels;
29+
private Counter noLabels;
30+
private Counter labels;
2931
private static final long exemplarSampleIntervalMillis = 10;
3032
private static final long exemplarMinAgeMillis = 100;
31-
SpanContext origSpanContext;
33+
private SpanContext origSpanContext;
3234

3335
@Rule public final ExpectedException thrown = none();
3436

@@ -53,15 +55,18 @@ private CounterSnapshot.CounterDataPointSnapshot getData(Counter counter, String
5355
return counter.collect().getDataPoints().stream()
5456
.filter(d -> d.getLabels().equals(Labels.of(labels)))
5557
.findAny()
56-
.orElseThrow(() -> new RuntimeException("counter with labels " + labels + " not found"));
58+
.orElseThrow(
59+
() ->
60+
new RuntimeException(
61+
"counter with labels " + Arrays.toString(labels) + " not found"));
5762
}
5863

5964
private double getValue(Counter counter, String... labels) {
6065
return getData(counter, labels).getValue();
6166
}
6267

6368
private int getNumberOfLabels(Counter counter) {
64-
return ((CounterSnapshot) counter.collect()).getDataPoints().size();
69+
return counter.collect().getDataPoints().size();
6570
}
6671

6772
@Test
@@ -131,30 +136,30 @@ public void testSnapshotComplete() {
131136
.build();
132137
counter.labelValues("/", "200").inc(2);
133138
counter.labelValues("/", "500").inc();
134-
CounterSnapshot snapshot = (CounterSnapshot) counter.collect();
135-
Assert.assertEquals("test_seconds", snapshot.getMetadata().getName());
136-
Assert.assertEquals("seconds", snapshot.getMetadata().getUnit().toString());
137-
Assert.assertEquals("help message", snapshot.getMetadata().getHelp());
138-
Assert.assertEquals(2, snapshot.getDataPoints().size());
139+
CounterSnapshot snapshot = counter.collect();
140+
assertEquals("test_seconds", snapshot.getMetadata().getName());
141+
assertEquals("seconds", snapshot.getMetadata().getUnit().toString());
142+
assertEquals("help message", snapshot.getMetadata().getHelp());
143+
assertEquals(2, snapshot.getDataPoints().size());
139144
Iterator<CounterSnapshot.CounterDataPointSnapshot> iter = snapshot.getDataPoints().iterator();
140145
// data is ordered by labels, so 200 comes before 500
141146
CounterSnapshot.CounterDataPointSnapshot data = iter.next();
142-
Assert.assertEquals(
147+
assertEquals(
143148
Labels.of(
144149
"const1name", "const1value", "const2name", "const2value", "path", "/", "status", "200"),
145150
data.getLabels());
146-
Assert.assertEquals(2, data.getValue(), 0.0001);
147-
Assert.assertTrue(data.getCreatedTimestampMillis() >= before);
148-
Assert.assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis());
151+
assertEquals(2, data.getValue(), 0.0001);
152+
assertTrue(data.getCreatedTimestampMillis() >= before);
153+
assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis());
149154
// 500
150155
data = iter.next();
151-
Assert.assertEquals(
156+
assertEquals(
152157
Labels.of(
153158
"const1name", "const1value", "const2name", "const2value", "path", "/", "status", "500"),
154159
data.getLabels());
155-
Assert.assertEquals(1, data.getValue(), 0.0001);
156-
Assert.assertTrue(data.getCreatedTimestampMillis() >= before);
157-
Assert.assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis());
160+
assertEquals(1, data.getValue(), 0.0001);
161+
assertTrue(data.getCreatedTimestampMillis() >= before);
162+
assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis());
158163
}
159164

160165
@Test
@@ -175,7 +180,7 @@ public void testIncWithExemplar() throws Exception {
175180

176181
private void assertExemplar(Counter counter, double value, String... labels) {
177182
Exemplar exemplar = getData(counter).getExemplar();
178-
Assert.assertEquals(value, exemplar.getValue(), 0.0001);
183+
assertEquals(value, exemplar.getValue(), 0.0001);
179184
assertEquals(Labels.of(labels), exemplar.getLabels());
180185
}
181186

@@ -230,10 +235,7 @@ public String getCurrentSpanId() {
230235
@Override
231236
public boolean isCurrentSpanSampled() {
232237
callNumber++;
233-
if (callNumber == 2) {
234-
return false;
235-
}
236-
return true;
238+
return callNumber != 2;
237239
}
238240

239241
@Override
@@ -289,9 +291,9 @@ public void testExemplarSamplerDisabled() {
289291
.withoutExemplars()
290292
.build();
291293
counter.incWithExemplar(3.0, Labels.of("a", "b"));
292-
Assert.assertNull(getData(counter).getExemplar());
294+
assertNull(getData(counter).getExemplar());
293295
counter.inc(2.0);
294-
Assert.assertNull(getData(counter).getExemplar());
296+
assertNull(getData(counter).getExemplar());
295297
}
296298

297299
@Test(expected = IllegalArgumentException.class)
Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,42 @@
11
package io.prometheus.metrics.core.metrics;
22

3+
import static org.junit.Assert.assertEquals;
4+
5+
import io.prometheus.metrics.model.snapshots.CounterSnapshot;
6+
import java.util.Arrays;
7+
import java.util.List;
8+
import java.util.concurrent.atomic.AtomicInteger;
9+
import org.junit.Test;
10+
311
public class CounterWithCallbackTest {
412

5-
// TODO :). Anyway, callbacks are implicitly covered by the JVM metrics tests as well.
13+
@Test
14+
public void testCounter() {
15+
final AtomicInteger value = new AtomicInteger(1);
16+
List<String> labelValues = Arrays.asList("v1", "v2");
17+
CounterWithCallback counter =
18+
CounterWithCallback.builder()
19+
.name("counter")
20+
.labelNames("l1", "l2")
21+
.callback(
22+
callback -> callback.call(value.doubleValue(), labelValues.toArray(new String[0])))
23+
.build();
24+
CounterSnapshot snapshot = counter.collect();
25+
26+
assertEquals(1, snapshot.getDataPoints().size());
27+
CounterSnapshot.CounterDataPointSnapshot datapoint = snapshot.getDataPoints().get(0);
28+
assertEquals(value.doubleValue(), datapoint.getValue(), 0.1);
29+
assertEquals(labelValues.size(), datapoint.getLabels().size());
30+
31+
value.incrementAndGet();
32+
snapshot = counter.collect();
33+
assertEquals(1, snapshot.getDataPoints().size());
34+
datapoint = snapshot.getDataPoints().get(0);
35+
assertEquals(value.doubleValue(), datapoint.getValue(), 0.1);
36+
}
37+
38+
@Test(expected = IllegalArgumentException.class)
39+
public void testCounterNoCallback() {
40+
CounterWithCallback.builder().name("counter").labelNames("l1", "l2").build();
41+
}
642
}

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

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import static io.prometheus.metrics.core.metrics.TestUtil.assertExemplarEquals;
44
import static org.junit.Assert.assertEquals;
5+
import static org.junit.Assert.assertNull;
56

67
import io.prometheus.metrics.core.datapoints.Timer;
78
import io.prometheus.metrics.core.exemplars.ExemplarSamplerConfigTestUtil;
@@ -11,7 +12,6 @@
1112
import io.prometheus.metrics.tracer.common.SpanContext;
1213
import io.prometheus.metrics.tracer.initializer.SpanContextSupplier;
1314
import org.junit.After;
14-
import org.junit.Assert;
1515
import org.junit.Before;
1616
import org.junit.Test;
1717

@@ -37,11 +37,10 @@ public void tearDown() {
3737
}
3838

3939
private GaugeSnapshot.GaugeDataPointSnapshot getData(Gauge gauge, String... labels) {
40-
return ((GaugeSnapshot) gauge.collect())
41-
.getDataPoints().stream()
42-
.filter(data -> data.getLabels().equals(Labels.of(labels)))
43-
.findAny()
44-
.orElseThrow(RuntimeException::new);
40+
return gauge.collect().getDataPoints().stream()
41+
.filter(data -> data.getLabels().equals(Labels.of(labels)))
42+
.findAny()
43+
.orElseThrow(RuntimeException::new);
4544
}
4645

4746
private double getValue(Gauge gauge, String... labels) {
@@ -153,10 +152,7 @@ public String getCurrentSpanId() {
153152
@Override
154153
public boolean isCurrentSpanSampled() {
155154
callNumber++;
156-
if (callNumber == 2) {
157-
return false;
158-
}
159-
return true;
155+
return callNumber != 2;
160156
}
161157

162158
@Override
@@ -206,8 +202,8 @@ public void markCurrentSpanAsExemplar() {}
206202
public void testExemplarSamplerDisabled() {
207203
Gauge gauge = Gauge.builder().name("test").withoutExemplars().build();
208204
gauge.setWithExemplar(3.0, Labels.of("a", "b"));
209-
Assert.assertNull(getData(gauge).getExemplar());
205+
assertNull(getData(gauge).getExemplar());
210206
gauge.inc(2.0);
211-
Assert.assertNull(getData(gauge).getExemplar());
207+
assertNull(getData(gauge).getExemplar());
212208
}
213209
}

0 commit comments

Comments
 (0)