GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [improve][monitor] Port the Netty direct memory gauges and pulsar_ver… · apache/pulsar@e618631

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pulsar-broker/src
    • main/java/org/apache/pulsar/broker/stats/prometheus
      • MetricsExports.java
    • test/java/org/apache/pulsar/broker/stats
      • JvmMetricsExportTest.java
  • pulsar-functions/worker/src
    • main/java/org/apache/pulsar/functions/worker
      • WorkerStatsManager.java
    • test/java/org/apache/pulsar/functions/worker/rest/api
      • FunctionsMetricsResourceTest.java
  • pulsar-proxy/src
    • main/java/org/apache/pulsar/proxy/server
      • ProxyServiceStarter.java
    • test/java/org/apache/pulsar/proxy/server
      • ProxyServiceStarterTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/stats/prometheus/MetricsExports.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/stats/prometheus/MetricsExports.java
+25-26Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919
package org.apache.pulsar.broker.stats.prometheus;
2020

2121
import static org.apache.pulsar.common.stats.JvmMetrics.getJvmDirectMemoryUsed;
22-
import io.prometheus.client.CollectorRegistry;
23-
import io.prometheus.client.Gauge;
22+
import io.prometheus.metrics.core.metrics.Gauge;
23+
import io.prometheus.metrics.core.metrics.GaugeWithCallback;
2424
import io.prometheus.metrics.instrumentation.jvm.JvmMetrics;
25+
import io.prometheus.metrics.model.registry.PrometheusRegistry;
2526
import org.apache.pulsar.PulsarVersion;
2627
import org.apache.pulsar.common.util.DirectMemoryUtils;
2728

@@ -34,35 +35,33 @@ private MetricsExports() {
3435
public static synchronized void initialize() {
3536
if (!initialized) {
3637
JvmMetrics.builder().register();
37-
register(CollectorRegistry.defaultRegistry);
38+
register(PrometheusRegistry.defaultRegistry);
3839
initialized = true;
3940
}
4041
}
4142

42-
public static void register(CollectorRegistry registry) {
43-
Gauge.build("jvm_memory_direct_bytes_used", "-").create().setChild(new Gauge.Child() {
44-
@Override
45-
public double get() {
46-
return getJvmDirectMemoryUsed();
47-
}
48-
}).register(registry);
49-
50-
Gauge.build("jvm_memory_direct_bytes_max", "-").create().setChild(new Gauge.Child() {
51-
@Override
52-
public double get() {
53-
return DirectMemoryUtils.jvmMaxDirectMemory();
54-
}
55-
}).register(registry);
43+
public static void register(PrometheusRegistry registry) {
44+
GaugeWithCallback.builder()
45+
.name("jvm_memory_direct_bytes_used")
46+
.help("-")
47+
.callback(callback -> callback.call(getJvmDirectMemoryUsed()))
48+
.register(registry);
5649

57-
// metric to export pulsar version info
58-
Gauge.build("pulsar_version_info", "-")
59-
.labelNames("version", "commit").create()
60-
.setChild(new Gauge.Child() {
61-
@Override
62-
public double get() {
63-
return 1.0;
64-
}
65-
}, PulsarVersion.getVersion(), PulsarVersion.getGitSha())
50+
GaugeWithCallback.builder()
51+
.name("jvm_memory_direct_bytes_max")
52+
.help("-")
53+
.callback(callback -> callback.call(DirectMemoryUtils.jvmMaxDirectMemory()))
6654
.register(registry);
55+
56+
// metric to export pulsar version info. Nothing exports exemplars, so the gauge skips the sampling that
57+
// 1.x gauges do by default.
58+
Gauge.builder()
59+
.name("pulsar_version_info")
60+
.help("-")
61+
.labelNames("version", "commit")
62+
.withoutExemplars()
63+
.register(registry)
64+
.labelValues(PulsarVersion.getVersion(), PulsarVersion.getGitSha())
65+
.set(1);
6766
}
6867
}
Collapse file

‎pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/JvmMetricsExportTest.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/JvmMetricsExportTest.java
+52-3Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,20 @@
1818
*/
1919
package org.apache.pulsar.broker.stats;
2020

21+
import static org.apache.pulsar.broker.stats.prometheus.PrometheusMetricsClient.Metric;
22+
import static org.apache.pulsar.broker.stats.prometheus.PrometheusMetricsClient.parseMetrics;
2123
import static org.assertj.core.api.Assertions.assertThat;
24+
import com.google.common.collect.Multimap;
25+
import io.prometheus.client.CollectorRegistry;
26+
import io.prometheus.metrics.model.registry.PrometheusRegistry;
2227
import java.io.ByteArrayOutputStream;
2328
import java.nio.charset.StandardCharsets;
29+
import java.util.Collections;
2430
import java.util.Map;
2531
import org.apache.pulsar.PrometheusMetricsTestUtil;
32+
import org.apache.pulsar.PulsarVersion;
2633
import org.apache.pulsar.broker.service.SharedPulsarBaseTest;
34+
import org.apache.pulsar.common.util.DirectMemoryUtils;
2735
import org.testng.annotations.Test;
2836

2937
@Test(groups = "broker")
@@ -43,9 +51,7 @@ public class JvmMetricsExportTest extends SharedPulsarBaseTest {
4351

4452
@Test
4553
public void testBrokerExportsTheJvmMetricsUnderThe1xNames() throws Exception {
46-
ByteArrayOutputStream out = new ByteArrayOutputStream();
47-
PrometheusMetricsTestUtil.generate(getPulsar(), false, false, false, out);
48-
String metrics = out.toString(StandardCharsets.UTF_8);
54+
String metrics = scrape();
4955

5056
RENAMED.forEach((oldName, newName) -> assertThat(metrics)
5157
.as("broker /metrics declares %s and not %s", newName, oldName)
@@ -56,4 +62,47 @@ public void testBrokerExportsTheJvmMetricsUnderThe1xNames() throws Exception {
5662
.contains("# TYPE jvm_memory_direct_bytes_used gauge\n")
5763
.contains("# TYPE jvm_memory_direct_bytes_max gauge\n");
5864
}
65+
66+
@Test
67+
public void testBrokerExportsTheNettyDirectMemoryGauges() throws Exception {
68+
Multimap<String, Metric> metrics = parseMetrics(scrape());
69+
assertThat(metrics.get("jvm_memory_direct_bytes_max")).singleElement()
70+
.satisfies(max -> assertThat(max.value).isEqualTo(DirectMemoryUtils.jvmMaxDirectMemory()));
71+
assertThat(metrics.get("jvm_memory_direct_bytes_used")).singleElement()
72+
.satisfies(used -> assertThat(used.value).as("-1 means the JVM cannot estimate it")
73+
.isGreaterThanOrEqualTo(-1));
74+
assertRegisteredInThe1xRegistryOnly("jvm_memory_direct_bytes_max");
75+
assertRegisteredInThe1xRegistryOnly("jvm_memory_direct_bytes_used");
76+
}
77+
78+
@Test
79+
public void testBrokerExportsItsVersionAndCommit() throws Exception {
80+
assertThat(parseMetrics(scrape()).get("pulsar_version_info")).singleElement().satisfies(versionInfo -> {
81+
assertThat(versionInfo.tags)
82+
.containsEntry("version", PulsarVersion.getVersion())
83+
.containsEntry("commit", PulsarVersion.getGitSha());
84+
assertThat(versionInfo.value).isEqualTo(1.0);
85+
});
86+
assertRegisteredInThe1xRegistryOnly("pulsar_version_info");
87+
}
88+
89+
/**
90+
* The broker /metrics writes the simpleclient registry and the 1.x registry, so the scrape alone does not tell
91+
* in which of them a family is registered.
92+
*/
93+
private static void assertRegisteredInThe1xRegistryOnly(String family) {
94+
assertThat(PrometheusRegistry.defaultRegistry.scrape(family::equals))
95+
.as("%s in the 1.x registry", family)
96+
.hasSize(1);
97+
assertThat(Collections.list(CollectorRegistry.defaultRegistry.metricFamilySamples()))
98+
.as("families in the simpleclient registry")
99+
.extracting(legacyFamily -> legacyFamily.name)
100+
.doesNotContain(family);
101+
}
102+
103+
private String scrape() throws Exception {
104+
ByteArrayOutputStream out = new ByteArrayOutputStream();
105+
PrometheusMetricsTestUtil.generate(getPulsar(), false, false, false, out);
106+
return out.toString(StandardCharsets.UTF_8);
107+
}
59108
}
Collapse file

‎pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/WorkerStatsManager.java‎

Copy file name to clipboardExpand all lines: pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/WorkerStatsManager.java
+12-17Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@
2121
import static org.apache.pulsar.common.stats.JvmMetrics.getJvmDirectMemoryUsed;
2222
import io.opentelemetry.api.OpenTelemetry;
2323
import io.opentelemetry.api.metrics.Meter;
24-
import io.prometheus.client.CollectorRegistry;
2524
import io.prometheus.metrics.core.datapoints.DistributionDataPoint;
2625
import io.prometheus.metrics.core.datapoints.GaugeDataPoint;
2726
import io.prometheus.metrics.core.metrics.Gauge;
27+
import io.prometheus.metrics.core.metrics.GaugeWithCallback;
2828
import io.prometheus.metrics.core.metrics.Summary;
2929
import io.prometheus.metrics.expositionformats.PrometheusTextFormatWriter;
3030
import io.prometheus.metrics.instrumentation.jvm.JvmMetrics;
@@ -170,22 +170,17 @@ public WorkerStatsManager(WorkerConfig workerConfig, boolean runAsStandalone, Me
170170
drainTotalExecutionTimeChild = drainTotalExecutionTime.labelValues(metricsLabels);
171171

172172
if (runAsStandalone) {
173-
// 1.x JvmMetrics does not export these two names, so they stay on the simpleclient default registry.
174-
io.prometheus.client.Gauge.build("jvm_memory_direct_bytes_used", "-").create()
175-
.setChild(new io.prometheus.client.Gauge.Child() {
176-
@Override
177-
public double get() {
178-
return getJvmDirectMemoryUsed();
179-
}
180-
}).register(CollectorRegistry.defaultRegistry);
181-
182-
io.prometheus.client.Gauge.build("jvm_memory_direct_bytes_max", "-").create()
183-
.setChild(new io.prometheus.client.Gauge.Child() {
184-
@Override
185-
public double get() {
186-
return DirectMemoryUtils.jvmMaxDirectMemory();
187-
}
188-
}).register(CollectorRegistry.defaultRegistry);
173+
GaugeWithCallback.builder()
174+
.name("jvm_memory_direct_bytes_used")
175+
.help("-")
176+
.callback(callback -> callback.call(getJvmDirectMemoryUsed()))
177+
.register();
178+
179+
GaugeWithCallback.builder()
180+
.name("jvm_memory_direct_bytes_max")
181+
.help("-")
182+
.callback(callback -> callback.call(DirectMemoryUtils.jvmMaxDirectMemory()))
183+
.register();
189184
}
190185
}
191186

Collapse file

‎pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/FunctionsMetricsResourceTest.java‎

Copy file name to clipboardExpand all lines: pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/FunctionsMetricsResourceTest.java
+66Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
*/
1919
package org.apache.pulsar.functions.worker.rest.api;
2020

21+
import static org.assertj.core.api.Assertions.assertThat;
2122
import static org.mockito.ArgumentMatchers.any;
2223
import static org.mockito.Mockito.doAnswer;
2324
import static org.mockito.Mockito.mock;
@@ -34,10 +35,19 @@
3435
import jakarta.ws.rs.core.StreamingOutput;
3536
import java.io.ByteArrayOutputStream;
3637
import java.nio.charset.StandardCharsets;
38+
import java.util.ArrayList;
39+
import java.util.Collections;
40+
import java.util.List;
41+
import java.util.regex.Matcher;
42+
import java.util.regex.Pattern;
43+
import org.apache.pulsar.common.util.DirectMemoryUtils;
3744
import org.apache.pulsar.common.util.SimpleTextOutputStream;
3845
import org.apache.pulsar.functions.worker.WorkerConfig;
3946
import org.apache.pulsar.functions.worker.WorkerService;
47+
import org.apache.pulsar.functions.worker.WorkerStatsManager;
48+
import org.testng.annotations.AfterClass;
4049
import org.testng.annotations.AfterMethod;
50+
import org.testng.annotations.BeforeClass;
4151
import org.testng.annotations.BeforeMethod;
4252
import org.testng.annotations.Test;
4353

@@ -53,6 +63,25 @@ public class FunctionsMetricsResourceTest {
5363

5464
private Gauge legacyGauge;
5565
private Collector modernCollector;
66+
private WorkerStatsManager standaloneWorkerStats;
67+
68+
@BeforeClass
69+
public void startStandaloneWorkerStats() {
70+
// A standalone worker registers the Netty direct memory gauges for the life of the JVM, and registering
71+
// them a second time fails. A later run of this class in the same JVM therefore reuses the first run's.
72+
if (!isInTheDefaultRegistry("jvm_memory_direct_bytes_max")
73+
&& !isInTheDefaultRegistry("jvm_memory_direct_bytes_used")) {
74+
standaloneWorkerStats = new WorkerStatsManager(
75+
new WorkerConfig().setPulsarFunctionsCluster("test-cluster"), true);
76+
}
77+
}
78+
79+
@AfterClass(alwaysRun = true)
80+
public void closeStandaloneWorkerStats() {
81+
if (standaloneWorkerStats != null) {
82+
standaloneWorkerStats.close();
83+
}
84+
}
5685

5786
@BeforeMethod
5887
public void setup() {
@@ -95,6 +124,30 @@ public void testStandardMetricsDisabledExportsOnlyFunctionsStats() throws Except
95124
assertTrue(body.contains(FUNCTIONS_MARKER), body);
96125
}
97126

127+
@Test
128+
public void testStandaloneWorkerExportsTheNettyDirectMemoryGauges() throws Exception {
129+
String body = scrape(true);
130+
assertThat(sampleValues(body, "jvm_memory_direct_bytes_max"))
131+
.as("jvm_memory_direct_bytes_max samples in the worker /metrics")
132+
.containsExactly((double) DirectMemoryUtils.jvmMaxDirectMemory());
133+
assertThat(sampleValues(body, "jvm_memory_direct_bytes_used"))
134+
.as("jvm_memory_direct_bytes_used samples in the worker /metrics")
135+
.singleElement()
136+
.satisfies(used -> assertThat(used).as("-1 means the JVM cannot estimate it")
137+
.isGreaterThanOrEqualTo(-1.0));
138+
// The worker /metrics writes the simpleclient registry and the 1.x registry, so the scrape alone does not
139+
// tell in which of them the gauges are registered
140+
for (String gauge : List.of("jvm_memory_direct_bytes_max", "jvm_memory_direct_bytes_used")) {
141+
assertThat(PrometheusRegistry.defaultRegistry.scrape(gauge::equals))
142+
.as("%s in the 1.x registry", gauge)
143+
.hasSize(1);
144+
assertThat(Collections.list(CollectorRegistry.defaultRegistry.metricFamilySamples()))
145+
.as("families in the simpleclient registry")
146+
.extracting(family -> family.name)
147+
.doesNotContain(gauge);
148+
}
149+
}
150+
98151
private static String scrape(boolean includeStandardPrometheusMetrics) throws Exception {
99152
WorkerConfig workerConfig = new WorkerConfig();
100153
workerConfig.setIncludeStandardPrometheusMetrics(includeStandardPrometheusMetrics);
@@ -117,4 +170,17 @@ public WorkerService get() {
117170
((StreamingOutput) response.getEntity()).write(out);
118171
return out.toString(StandardCharsets.UTF_8);
119172
}
173+
174+
private static List<Double> sampleValues(String body, String name) {
175+
Matcher sample = Pattern.compile("^" + Pattern.quote(name) + " (\\S+)$", Pattern.MULTILINE).matcher(body);
176+
List<Double> values = new ArrayList<>();
177+
while (sample.find()) {
178+
values.add(Double.parseDouble(sample.group(1)));
179+
}
180+
return values;
181+
}
182+
183+
private static boolean isInTheDefaultRegistry(String name) {
184+
return PrometheusRegistry.defaultRegistry.scrape(name::equals).size() > 0;
185+
}
120186
}
Collapse file

‎pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyServiceStarter.java‎

Copy file name to clipboardExpand all lines: pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyServiceStarter.java
+18-36Lines changed: 18 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,9 @@
2424
import static org.apache.commons.lang3.StringUtils.isNotBlank;
2525
import static org.apache.pulsar.common.stats.JvmMetrics.getJvmDirectMemoryUsed;
2626
import com.google.common.annotations.VisibleForTesting;
27-
import io.prometheus.client.Collector;
28-
import io.prometheus.client.CollectorRegistry;
29-
import io.prometheus.client.Gauge;
30-
import io.prometheus.client.Gauge.Child;
27+
import io.prometheus.metrics.core.metrics.GaugeWithCallback;
3128
import io.prometheus.metrics.instrumentation.jvm.JvmMetrics;
29+
import io.prometheus.metrics.model.registry.PrometheusRegistry;
3230
import jakarta.servlet.Servlet;
3331
import java.io.IOException;
3432
import java.text.DateFormat;
@@ -39,6 +37,7 @@
3937
import java.util.Objects;
4038
import java.util.concurrent.atomic.AtomicReference;
4139
import java.util.function.Consumer;
40+
import java.util.function.LongSupplier;
4241
import lombok.CustomLog;
4342
import lombok.Getter;
4443
import org.apache.logging.log4j.LogManager;
@@ -291,40 +290,10 @@ public void start() throws Exception {
291290
if (!metricsInitialized) {
292291
// Setup metrics
293292
JvmMetrics.builder().register();
294-
CollectorRegistry registry = CollectorRegistry.defaultRegistry;
295293

296294
// Report direct memory from Netty counters
297-
Collector jvmMemoryDirectBytesUsed =
298-
Gauge.build("jvm_memory_direct_bytes_used", "-").create().setChild(new Child() {
299-
@Override
300-
public double get() {
301-
return getJvmDirectMemoryUsed();
302-
}
303-
});
304-
try {
305-
registry.register(jvmMemoryDirectBytesUsed);
306-
} catch (IllegalArgumentException e) {
307-
// workaround issue in tests where the metric is already registered
308-
log.debug()
309-
.exceptionMessage(e)
310-
.log("Failed to register jvm_memory_direct_bytes_used");
311-
}
312-
313-
Collector jvmMemoryDirectBytesMax =
314-
Gauge.build("jvm_memory_direct_bytes_max", "-").create().setChild(new Child() {
315-
@Override
316-
public double get() {
317-
return DirectMemoryUtils.jvmMaxDirectMemory();
318-
}
319-
});
320-
try {
321-
registry.register(jvmMemoryDirectBytesMax);
322-
} catch (IllegalArgumentException e) {
323-
// workaround issue in tests where the metric is already registered
324-
log.debug()
325-
.exceptionMessage(e)
326-
.log("Failed to register jvm_memory_direct_bytes_max");
327-
}
295+
registerGaugeUnlessNameIsTaken("jvm_memory_direct_bytes_used", () -> getJvmDirectMemoryUsed());
296+
registerGaugeUnlessNameIsTaken("jvm_memory_direct_bytes_max", DirectMemoryUtils::jvmMaxDirectMemory);
328297

329298
metricsInitialized = true;
330299
}
@@ -338,6 +307,19 @@ public double get() {
338307
server.start();
339308
}
340309

310+
private static void registerGaugeUnlessNameIsTaken(String name, LongSupplier currentValue) {
311+
try {
312+
GaugeWithCallback.builder()
313+
.name(name)
314+
.help("-")
315+
.callback(callback -> callback.call(currentValue.getAsLong()))
316+
.register(PrometheusRegistry.defaultRegistry);
317+
} catch (IllegalArgumentException nameIsTakenByABrokerInThisJvm) {
318+
log.debug().attr("gauge", name).exceptionMessage(nameIsTakenByABrokerInThisJvm)
319+
.log("Prometheus gauge is already registered");
320+
}
321+
}
322+
341323
public void close() {
342324
try {
343325
if (proxyService != null) {

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.