Skip to content

Commit 627d6d9

Browse files
committed
Fix MAL histogram() failing on Prometheus le=+Inf buckets.
Double.parseDouble rejected Prometheus/OpenMetrics +Inf/-Inf spellings, so percentile rules failed for scraped histograms. Accept those forms (and Java Infinity), reject NaN bounds, and map Inf to Long.MAX/MIN_VALUE. Percentile calculation sorts the -Inf dataset key without throwing and reports the highest finite upper bound when a rank lands in the overflow bucket.
1 parent 28d097d commit 627d6d9

13 files changed

Lines changed: 509 additions & 19 deletions

File tree

‎docs/en/changes/changes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
* Bump Armeria `1.34.2` → `1.43.1`, and the managed versions of the libraries it is built against to its versions: gRPC `1.80.0` → `1.85.1`, Jackson `2.18.12` → `2.22.4` (jackson-annotations `2.22`, which has no patch versions since `2.20`) and Micrometer `1.16.8` → `1.17.2`. graphql-java stays at `25.2`, though armeria-graphql `1.43.1` is built against `26.1`: graphql-java `26` removed `graphql.schema.idl.DirectiveInfo`, which graphql-java-tools `14.0.1`, its latest release, still uses to build the schema, so the OAP failed to boot on it. Armeria `1.43.1` builds a gRPC stub on the client factory named in the stub's options instead of the one `newClient` is called on, so the Cilium fetcher's stubs fell back to Armeria's default factory and connected without the fetcher's TLS settings, and the fetcher read nothing from a TLS Hubble endpoint; it now names its factory in the options. Armeria `1.43.1` also applies a `tlsCustomizer` after `tlsNoVerify()`, so the Cilium fetcher's CA replaced the trust-all setting and Hubble's certificates failed the host name check. The fetcher now verifies Hubble's certificates against `SW_CILIUM_FETCHER_CA_FILE_PATH`, without checking host names; before, `tlsNoVerify()` won and the CA file was ignored, so a CA file that does not sign Hubble's server certificates no longer connects. jackson-datatype-jsr310, which Armeria pulls, is pinned to the managed Jackson version; it was `2.20.1` beside Jackson `2.18.12`. Transitively, brotli4j moves `1.20.0` → `1.24.0`, micrometer context-propagation `1.2.0` → `1.2.1`, proto-google-common-protos `2.63.2` → `2.64.1` and animal-sniffer-annotations `1.26` → `1.27`, and LatencyUtils is no longer shipped.
1616

1717
#### OAP Server
18+
* Fix MAL `histogram()` / percentile rules failing on Prometheus histogram buckets labeled `le="+Inf"` (or `-Inf`): `Double.parseDouble` rejected those spellings, so the whole expression failed. Accept Prometheus and Java Inf forms and map them to `Long.MAX_VALUE` / `Long.MIN_VALUE`; reject `NaN` bounds. Histogram percentile calculation now sorts the `-Inf` dataset key without throwing, and when a rank lands in the overflow (`+Inf`) bucket it reports the highest finite upper bound instead of `Long.MAX_VALUE`.
1819
* Fix the Cilium fetcher dropping or double-reading Cilium nodes. The Peer notify stream, the cluster watcher and the 10-second refresh timer rebuilt the shared node list without a lock, which could open two flow streams for one node or keep a closed node as in use. A node closed when this OAP's share of nodes moved away was reused, still closed, when the share moved back (e.g. after scaling the OAP cluster out and back in), so that node went unread while the assignment lasted. A `Receiver`-role OAP on a ZooKeeper, Consul, Nacos or etcd coordinator never finds itself in the cluster list and, when Cilium nodes and other OAPs were listed, threw on every refresh; it now skips Cilium fetching quietly, as the `Mixed` and `Aggregator` OAPs share all Cilium nodes among themselves.
1920
* Fix the gRPC alarm hook throwing a `NullPointerException` on every alarm until OAP restart: once an alarm fired while no gRPC hook was configured (at boot, or after the hooks were removed through dynamic configuration), adding a gRPC hook later broke it. Also shut down the client of a gRPC hook removed from the configuration.
2021
* Fix the Cilium fetcher silently stopping a Cilium node's flow stream. When a stream failed and was retried (e.g. a Cilium agent restart), the ended stream's thread interrupt stayed registered on its node, so closing that node later (e.g. when the OAP cluster scaled) interrupted whichever stream the pooled thread then ran for another node, and an interrupted stream is treated as closed and never retried. A stream that started just as its node closed was also never interrupted. Each stream now registers before it opens and deregisters when it ends, and a closed node refuses new registrations.

‎oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/Analyzer.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,9 +357,11 @@ public void analyse(final ImmutableMap<String, SampleFamily> sampleFamilies) {
357357
long[] vv = new long[bb.length];
358358
for (int i = 0; i < subSs.size(); i++) {
359359
Sample s = subSs.get(i);
360-
final double leVal = Double.parseDouble(s.getLabels().get("le"));
360+
final double leVal = SampleFamily.parseBucketBound(s.getLabels().get("le"));
361361
if (leVal == Double.NEGATIVE_INFINITY) {
362362
bb[i] = Long.MIN_VALUE;
363+
} else if (leVal == Double.POSITIVE_INFINITY) {
364+
bb[i] = Long.MAX_VALUE;
363365
} else {
364366
bb[i] = (long) leVal;
365367
}

‎oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/dsl/SampleFamily.java‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -548,17 +548,20 @@ public SampleFamily histogram(String le, TimeUnit unit) {
548548
Arrays.stream(samples).filter(s -> !s.labels.containsKey(le)),
549549
Arrays.stream(samples)
550550
.filter(s -> s.labels.containsKey(le))
551-
.sorted(Comparator.comparingDouble(s -> Double.parseDouble(s.labels.get(le))))
551+
.sorted(Comparator.comparingDouble(s -> parseBucketBound(s.labels.get(le))))
552552
.map(s -> {
553553
double r = s.value;
554+
final double bound = parseBucketBound(s.labels.get(le));
555+
// OTel/Prometheus +Inf becomes Long.MAX_VALUE after unit scale (HeatMap / Analyzer).
556+
final long scaled = Double.isInfinite(bound)
557+
? (bound > 0 ? Long.MAX_VALUE : Long.MIN_VALUE)
558+
: (long) (bound * scale);
554559
ImmutableMap<String, String> ll = ImmutableMap.<String, String>builder()
555560
.putAll(Maps.filterKeys(s.labels,
556561
key -> !Objects.equals(
557562
key, le)
558563
))
559-
.put(
560-
"le",
561-
String.valueOf((long) ((Double.parseDouble(s.labels.get(le))) * scale)))
564+
.put("le", String.valueOf(scaled))
562565
.build();
563566
return InternalOps.newSample(s.name, ll, s.timestamp, r);
564567
})
@@ -799,6 +802,32 @@ static RunningContext instance() {
799802
private TimeUnit defaultHistogramBucketUnit;
800803
}
801804

805+
/**
806+
* Parse a histogram bucket upper bound. Accepts Prometheus text ({@code +Inf}/{@code -Inf})
807+
* and Java {@link Double#toString()} forms ({@code Infinity}/{@code -Infinity}).
808+
* Rejects {@code NaN}: OpenMetrics forbids it as a bucket bound, and casting NaN to {@code long}
809+
* would silently become {@code 0}.
810+
*/
811+
public static double parseBucketBound(final String raw) {
812+
if (raw == null) {
813+
throw new NumberFormatException("null histogram bucket bound");
814+
}
815+
if ("+Inf".equalsIgnoreCase(raw) || "Inf".equalsIgnoreCase(raw) || "Infinity".equalsIgnoreCase(raw)) {
816+
return Double.POSITIVE_INFINITY;
817+
}
818+
if ("-Inf".equalsIgnoreCase(raw) || "-Infinity".equalsIgnoreCase(raw)) {
819+
return Double.NEGATIVE_INFINITY;
820+
}
821+
if ("NaN".equalsIgnoreCase(raw)) {
822+
throw new NumberFormatException("NaN histogram bucket bound");
823+
}
824+
final double value = Double.parseDouble(raw);
825+
if (Double.isNaN(value)) {
826+
throw new NumberFormatException("NaN histogram bucket bound");
827+
}
828+
return value;
829+
}
830+
802831
private static class InternalOps {
803832

804833
private static Sample[] left(List<Sample> samples, List<String> labelKeys) {
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*
17+
*/
18+
19+
package org.apache.skywalking.oap.meter.analyzer.v2;
20+
21+
import com.google.common.collect.ImmutableMap;
22+
import org.apache.skywalking.oap.meter.analyzer.v2.dsl.Sample;
23+
import org.apache.skywalking.oap.meter.analyzer.v2.dsl.SampleFamily;
24+
import org.apache.skywalking.oap.meter.analyzer.v2.dsl.SampleFamilyBuilder;
25+
import org.apache.skywalking.oap.server.core.analysis.meter.MeterEntity;
26+
import org.apache.skywalking.oap.server.core.analysis.meter.MeterSystem;
27+
import org.apache.skywalking.oap.server.core.analysis.meter.function.AcceptableValue;
28+
import org.apache.skywalking.oap.server.core.analysis.meter.function.BucketedValues;
29+
import org.apache.skywalking.oap.server.core.analysis.meter.function.PercentileArgument;
30+
import org.apache.skywalking.oap.server.core.analysis.worker.MetricsStreamProcessor;
31+
import org.apache.skywalking.oap.server.core.config.NamingControl;
32+
import org.apache.skywalking.oap.server.core.config.group.EndpointNameGrouping;
33+
import org.junit.jupiter.api.AfterAll;
34+
import org.junit.jupiter.api.BeforeAll;
35+
import org.junit.jupiter.api.Test;
36+
import org.junit.jupiter.api.extension.ExtendWith;
37+
import org.mockito.ArgumentCaptor;
38+
import org.mockito.Mock;
39+
import org.mockito.MockedStatic;
40+
import org.mockito.junit.jupiter.MockitoExtension;
41+
42+
import static com.google.common.collect.ImmutableMap.of;
43+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
44+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
45+
import static org.junit.jupiter.api.Assertions.assertEquals;
46+
import static org.mockito.ArgumentMatchers.any;
47+
import static org.mockito.ArgumentMatchers.anyString;
48+
import static org.mockito.ArgumentMatchers.eq;
49+
import static org.mockito.Mockito.doNothing;
50+
import static org.mockito.Mockito.mock;
51+
import static org.mockito.Mockito.mockStatic;
52+
import static org.mockito.Mockito.verify;
53+
import static org.mockito.Mockito.when;
54+
55+
/**
56+
* End-to-end coverage for Analyzer building histogram / percentile meters when a bucket
57+
* is labeled {@code le="+Inf"} (Prometheus) or {@code Infinity} (Java). FunctionTest only
58+
* asserts the MAL expression result; this hits {@link Analyzer#analyse} which parses {@code le}
59+
* again while assembling {@link BucketedValues}.
60+
*/
61+
@ExtendWith(MockitoExtension.class)
62+
public class AnalyzerHistogramInfTest {
63+
64+
@Mock
65+
private MeterSystem meterSystem;
66+
67+
@BeforeAll
68+
public static void setUp() {
69+
MeterEntity.setNamingControl(new NamingControl(512, 512, 512, new EndpointNameGrouping()));
70+
}
71+
72+
@AfterAll
73+
public static void tearDown() {
74+
MeterEntity.setNamingControl(null);
75+
}
76+
77+
@Test
78+
void analysePercentileAcceptsPrometheusPlusInfBucket() {
79+
final AcceptableValue<PercentileArgument> sink = mock(AcceptableValue.class);
80+
when(meterSystem.buildMetrics(anyString(), eq(PercentileArgument.class))).thenReturn(sink);
81+
doNothing().when(meterSystem).create(anyString(), anyString(), any());
82+
doNothing().when(meterSystem).doStreamingCalculation(any());
83+
84+
final Analyzer analyzer = Analyzer.build(
85+
"http_latency_percentile",
86+
null,
87+
"http_request_duration_bucket.histogram().histogram_percentile([75, 99])"
88+
+ ".service(['service'], Layer.GENERAL)",
89+
meterSystem
90+
);
91+
92+
final ImmutableMap<String, SampleFamily> input = of(
93+
"http_request_duration_bucket",
94+
SampleFamilyBuilder.newBuilder(
95+
sample("0.025", 100),
96+
sample("0.75", 22),
97+
sample("1.25", 30),
98+
sample("+Inf", 40)
99+
).build()
100+
);
101+
102+
try (MockedStatic<MetricsStreamProcessor> ignored = mockStatic(MetricsStreamProcessor.class)) {
103+
final MetricsStreamProcessor processor = mock(MetricsStreamProcessor.class);
104+
ignored.when(MetricsStreamProcessor::getInstance).thenReturn(processor);
105+
assertDoesNotThrow(() -> analyzer.analyse(input));
106+
}
107+
108+
final ArgumentCaptor<PercentileArgument> captor = ArgumentCaptor.forClass(PercentileArgument.class);
109+
verify(sink).accept(any(MeterEntity.class), captor.capture());
110+
final BucketedValues buckets = captor.getValue().getBucketedValues();
111+
assertArrayEquals(
112+
new long[] {25L, 750L, 1250L, Long.MAX_VALUE},
113+
buckets.getBuckets()
114+
);
115+
assertArrayEquals(new long[] {100L, 22L, 30L, 40L}, buckets.getValues());
116+
assertArrayEquals(new int[] {75, 99}, captor.getValue().getRanks());
117+
}
118+
119+
@Test
120+
void analyseHistogramAcceptsJavaInfinityAndNegInfBuckets() {
121+
final AcceptableValue<BucketedValues> sink = mock(AcceptableValue.class);
122+
when(meterSystem.buildMetrics(anyString(), eq(BucketedValues.class))).thenReturn(sink);
123+
doNothing().when(meterSystem).create(anyString(), anyString(), any());
124+
doNothing().when(meterSystem).doStreamingCalculation(any());
125+
126+
final Analyzer analyzer = Analyzer.build(
127+
"http_latency_histogram",
128+
null,
129+
"http_request_duration_bucket.histogram().service(['service'], Layer.GENERAL)",
130+
meterSystem
131+
);
132+
133+
final ImmutableMap<String, SampleFamily> input = of(
134+
"http_request_duration_bucket",
135+
SampleFamilyBuilder.newBuilder(
136+
sample("-Inf", 1),
137+
sample("0.025", 100),
138+
sample("Infinity", 120)
139+
).build()
140+
);
141+
142+
try (MockedStatic<MetricsStreamProcessor> ignored = mockStatic(MetricsStreamProcessor.class)) {
143+
final MetricsStreamProcessor processor = mock(MetricsStreamProcessor.class);
144+
ignored.when(MetricsStreamProcessor::getInstance).thenReturn(processor);
145+
assertDoesNotThrow(() -> analyzer.analyse(input));
146+
}
147+
148+
final ArgumentCaptor<BucketedValues> captor = ArgumentCaptor.forClass(BucketedValues.class);
149+
verify(sink).accept(any(MeterEntity.class), captor.capture());
150+
assertArrayEquals(
151+
new long[] {Long.MIN_VALUE, 25L, Long.MAX_VALUE},
152+
captor.getValue().getBuckets()
153+
);
154+
assertEquals(3, captor.getValue().getValues().length);
155+
}
156+
157+
private static Sample sample(final String le, final double value) {
158+
return Sample.builder()
159+
.name("http_request_duration_bucket")
160+
.labels(of("service", "ds-api", "le", le))
161+
.value(value)
162+
.timestamp(1_700_000_000_000L)
163+
.build();
164+
}
165+
}

0 commit comments

Comments
 (0)