Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redesign of Collector architecture. #905

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class Main {

public static void main(String[] args) throws IOException, InterruptedException {

SampleMultiCollector xmc = new SampleMultiCollector();
SampleCollector xmc = new SampleCollector();
PrometheusRegistry.defaultRegistry.register(xmc);
HTTPServer server = HTTPServer.builder()
.port(9401)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,37 +1,23 @@
package io.prometheus.metrics.examples.multitarget;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

import io.prometheus.metrics.model.registry.MultiCollector;
import io.prometheus.metrics.model.registry.Collector;
import io.prometheus.metrics.model.registry.PrometheusScrapeRequest;
import io.prometheus.metrics.model.snapshots.CounterSnapshot;
import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot.Builder;
import io.prometheus.metrics.model.snapshots.GaugeSnapshot;
import io.prometheus.metrics.model.snapshots.Labels;
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
import io.prometheus.metrics.model.snapshots.PrometheusNaming;

public class SampleMultiCollector implements MultiCollector {

public SampleMultiCollector() {
super();
}

@Override
public MetricSnapshots collect() {
return new MetricSnapshots();
}

public class SampleCollector implements Collector {
@Override
public MetricSnapshots collect(PrometheusScrapeRequest scrapeRequest) {
return collectMetricSnapshots(scrapeRequest);
public MetricSnapshots collect(Predicate<String> nameFilter, PrometheusScrapeRequest scrapeRequest) {
return collectMetricSnapshots(scrapeRequest).filter(nameFilter);
}

protected MetricSnapshots collectMetricSnapshots(PrometheusScrapeRequest scrapeRequest) {

GaugeSnapshot.Builder gaugeBuilder = GaugeSnapshot.builder();
gaugeBuilder.name("x_load").help("process load");

Expand Down Expand Up @@ -71,18 +57,7 @@ protected MetricSnapshots collectMetricSnapshots(PrometheusScrapeRequest scrapeR
gaugeBuilder.dataPoint(gaugeDataPointBuilder.build());
}
}
Collection<MetricSnapshot> snaps = new ArrayList<MetricSnapshot>();
snaps.add(counterBuilder.build());
snaps.add(gaugeBuilder.build());
MetricSnapshots msnaps = new MetricSnapshots(snaps);
MetricSnapshots msnaps = new MetricSnapshots(counterBuilder.build(), gaugeBuilder.build());
return msnaps;
}

public List<String> getPrometheusNames() {
List<String> names = new ArrayList<String>();
names.add("x_calls_total");
names.add("x_load");
return names;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import io.prometheus.metrics.core.metrics.Gauge;
import io.prometheus.metrics.core.metrics.Info;
import io.prometheus.metrics.exporter.httpserver.HTTPServer;
import io.prometheus.metrics.model.registry.CollectorBuilder;
import io.prometheus.metrics.model.registry.Collector;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
import io.prometheus.metrics.model.snapshots.Unit;

import java.io.IOException;
Expand Down Expand Up @@ -53,9 +53,9 @@ public static void main(String[] args) throws IOException, InterruptedException
gauge.labelValues("outside").set(27.0);

if (mode == Mode.error) {
Collector failingCollector = () -> {
Collector failingCollector = CollectorBuilder.fromMetric(() -> {
throw new RuntimeException("Simulating an error.");
};
});

PrometheusRegistry.defaultRegistry.register(failingCollector);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import io.prometheus.metrics.core.metrics.Gauge;
import io.prometheus.metrics.core.metrics.Info;
import io.prometheus.metrics.exporter.servlet.jakarta.PrometheusMetricsServlet;
import io.prometheus.metrics.model.registry.CollectorBuilder;
import io.prometheus.metrics.model.registry.Collector;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
import io.prometheus.metrics.model.snapshots.Unit;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
Expand Down Expand Up @@ -57,9 +57,9 @@ public static void main(String[] args) throws Exception {
gauge.labelValues("outside").set(27.0);

if (mode == Mode.error) {
Collector failingCollector = () -> {
Collector failingCollector = CollectorBuilder.fromMetrics(() -> {
throw new RuntimeException("Simulating an error.");
};
});

PrometheusRegistry.defaultRegistry.register(failingCollector);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import io.prometheus.metrics.core.metrics.Gauge;
import io.prometheus.metrics.core.metrics.Info;
import io.prometheus.metrics.exporter.servlet.jakarta.PrometheusMetricsServlet;
import io.prometheus.metrics.model.registry.CollectorBuilder;
import io.prometheus.metrics.model.registry.Collector;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
import io.prometheus.metrics.model.snapshots.Unit;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
Expand Down Expand Up @@ -61,9 +61,9 @@ public static void main(String[] args) throws LifecycleException, IOException {
gauge.labelValues("outside").set(27.0);

if (mode == Mode.error) {
Collector failingCollector = () -> {
Collector failingCollector = CollectorBuilder.fromMetrics(() -> {
throw new RuntimeException("Simulating an error.");
};
});

PrometheusRegistry.defaultRegistry.register(failingCollector);
}
Expand Down
12 changes: 12 additions & 0 deletions prometheus-metrics-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@
<properties>
<automatic.module.name>io.prometheus.metrics.core</automatic.module.name>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
</plugins>
</build>

<licenses>
<license>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.prometheus.metrics.config.PrometheusProperties;
import io.prometheus.metrics.model.registry.Collector;
import io.prometheus.metrics.model.registry.CollectorBuilder;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.Label;
import io.prometheus.metrics.model.snapshots.Labels;
Expand All @@ -21,9 +22,6 @@ protected Metric(Builder<?, ?> builder) {
this.constLabels = builder.constLabels;
}

@Override
public abstract MetricSnapshot collect();

protected static abstract class Builder<B extends Builder<B, M>, M extends Metric> {

protected final List<String> illegalLabelNames;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package io.prometheus.metrics.core.metrics;

import io.prometheus.metrics.config.PrometheusProperties;
import io.prometheus.metrics.model.snapshots.Labels;
import io.prometheus.metrics.model.snapshots.MetricMetadata;
import io.prometheus.metrics.model.snapshots.PrometheusNaming;
import io.prometheus.metrics.model.snapshots.Unit;
import io.prometheus.metrics.model.registry.Collector;
import io.prometheus.metrics.model.registry.CollectorBuilder;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.registry.PrometheusScrapeRequest;
import io.prometheus.metrics.model.snapshots.*;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
* Almost all metrics have fixed metadata, i.e. the metric name is known when the metric is created.
Expand All @@ -30,6 +32,15 @@ protected MetricMetadata getMetadata() {
return metadata;
}

protected abstract MetricSnapshot collect();

public MetricSnapshots collect(Predicate<String> includedNames, PrometheusScrapeRequest scrapeRequest) {
if(includedNames.test(this.metadata.getPrometheusName()))
return MetricSnapshots.of(collect());
else
return MetricSnapshots.empty();
}

private String makeName(String name, Unit unit) {
if (unit != null) {
if (!name.endsWith(unit.toString())) {
Expand All @@ -39,11 +50,6 @@ private String makeName(String name, Unit unit) {
return name;
}

@Override
public String getPrometheusName() {
return metadata.getPrometheusName();
}

public static abstract class Builder<B extends Builder<B, M>, M extends MetricWithFixedMetadata> extends Metric.Builder<B, M> {

protected String name;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package io.prometheus.metrics.core.metrics;

import io.prometheus.metrics.model.registry.MetricNameFilter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;

public class NameFilterTest {
@Test
public void testCounterWithCallback() {
AtomicInteger accessCount = new AtomicInteger();
CounterWithCallback metrics = CounterWithCallback.builder()
.name("my_counter")
.callback(cb -> {
accessCount.incrementAndGet();
cb.call(1.0);
})
.build();


PrometheusRegistry registry = new PrometheusRegistry();
registry.register(metrics);

var result1 = registry.scrape(MetricNameFilter.builder().nameMustBeEqualTo("XXX").build());
Assert.assertEquals(accessCount.get(), 0);
Assert.assertTrue(result1.stream().toList().isEmpty());

var result2 = registry.scrape(MetricNameFilter.builder().nameMustBeEqualTo("my_counter").build());
Assert.assertEquals(accessCount.get(), 1);
Assert.assertEquals(result2.stream().toList().size(), 1);
Assert.assertEquals(result2.get(0).getMetadata().getPrometheusName(), "my_counter");
}

@Test
public void testGaugeWithCallback() {
AtomicInteger accessCount = new AtomicInteger();
GaugeWithCallback metrics = GaugeWithCallback.builder()
.name("my_gauge")
.callback(cb -> {
accessCount.incrementAndGet();
cb.call(1.0);
})
.build();


PrometheusRegistry registry = new PrometheusRegistry();
registry.register(metrics);

var result1 = registry.scrape(MetricNameFilter.builder().nameMustBeEqualTo("XXX").build());
Assert.assertEquals(accessCount.get(), 0);
Assert.assertTrue(result1.stream().toList().isEmpty());

var result2 = registry.scrape(MetricNameFilter.builder().nameMustBeEqualTo("my_gauge").build());
Assert.assertEquals(accessCount.get(), 1);
Assert.assertEquals(result2.stream().toList().size(), 1);
Assert.assertEquals(result2.get(0).getMetadata().getPrometheusName(), "my_gauge");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import io.prometheus.metrics.config.PrometheusProperties;
import io.prometheus.metrics.expositionformats.ExpositionFormatWriter;
import io.prometheus.metrics.expositionformats.ExpositionFormats;
import io.prometheus.metrics.model.registry.Collector;
import io.prometheus.metrics.model.registry.MetricNameFilter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
Expand All @@ -23,7 +24,7 @@
*/
public class PrometheusScrapeHandler {

private final PrometheusRegistry registry;
private final Collector registry;
private final ExpositionFormats expositionFormats;
private final Predicate<String> nameFilter;
private AtomicInteger lastResponseSize = new AtomicInteger(2 << 9); // 0.5 MB
Expand All @@ -32,15 +33,15 @@ public PrometheusScrapeHandler() {
this(PrometheusProperties.get(), PrometheusRegistry.defaultRegistry);
}

public PrometheusScrapeHandler(PrometheusRegistry registry) {
public PrometheusScrapeHandler(Collector registry) {
this(PrometheusProperties.get(), registry);
}

public PrometheusScrapeHandler(PrometheusProperties config) {
this(config, PrometheusRegistry.defaultRegistry);
}

public PrometheusScrapeHandler(PrometheusProperties config, PrometheusRegistry registry) {
public PrometheusScrapeHandler(PrometheusProperties config, Collector registry) {
this.expositionFormats = ExpositionFormats.init(config.getExporterProperties());
this.registry = registry;
this.nameFilter = makeNameFilter(config.getExporterFilterProperties());
Expand Down Expand Up @@ -92,7 +93,7 @@ public void handleRequest(PrometheusHttpExchange exchange) throws IOException {

private Predicate<String> makeNameFilter(ExporterFilterProperties props) {
if (props.getAllowedMetricNames() == null && props.getExcludedMetricNames() == null && props.getAllowedMetricNamePrefixes() == null && props.getExcludedMetricNamePrefixes() == null) {
return null;
return MetricNameFilter.ALLOW_ALL;
} else {
return MetricNameFilter.builder()
.nameMustBeEqualTo(props.getAllowedMetricNames())
Expand All @@ -104,26 +105,16 @@ private Predicate<String> makeNameFilter(ExporterFilterProperties props) {
}

private MetricSnapshots scrape(PrometheusHttpRequest request) {

Predicate<String> filter = makeNameFilter(request.getParameterValues("name[]"));
if (filter != null) {
return registry.scrape(filter, request);
} else {
return registry.scrape(request);
}
return registry.collect(filter, request);
}

private Predicate<String> makeNameFilter(String[] includedNames) {
Predicate<String> result = null;
if (includedNames != null && includedNames.length > 0) {
result = MetricNameFilter.builder().nameMustBeEqualTo(includedNames).build();
}
if (result != null && nameFilter != null) {
result = result.and(nameFilter);
} else if (nameFilter != null) {
result = nameFilter;
return nameFilter.and(MetricNameFilter.builder().nameMustBeEqualTo(includedNames).build());
} else {
return nameFilter;
}
return result;
}

private boolean writeDebugResponse(MetricSnapshots snapshots, PrometheusHttpExchange exchange) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import io.prometheus.metrics.config.ExporterHttpServerProperties;
import io.prometheus.metrics.config.PrometheusProperties;
import io.prometheus.metrics.model.registry.Collector;
import io.prometheus.metrics.model.registry.PrometheusRegistry;

import java.io.Closeable;
Expand Down Expand Up @@ -46,7 +46,7 @@ public class HTTPServer implements Closeable {
protected final HttpServer server;
protected final ExecutorService executorService;

private HTTPServer(PrometheusProperties config, ExecutorService executorService, HttpServer httpServer, PrometheusRegistry registry, Authenticator authenticator, HttpHandler defaultHandler) {
private HTTPServer(PrometheusProperties config, ExecutorService executorService, HttpServer httpServer, Collector registry, Authenticator authenticator, HttpHandler defaultHandler) {
if (httpServer.getAddress() == null) {
throw new IllegalArgumentException("HttpServer hasn't been bound to an address");
}
Expand Down Expand Up @@ -104,7 +104,7 @@ public static class Builder {
private String hostname = null;
private InetAddress inetAddress = null;
private ExecutorService executorService = null;
private PrometheusRegistry registry = null;
private Collector registry = null;
private Authenticator authenticator = null;
private HttpsConfigurator httpsConfigurator = null;
private HttpHandler defaultHandler = null;
Expand Down Expand Up @@ -153,7 +153,7 @@ public Builder executorService(ExecutorService executorService) {
/**
* Optional: Default is {@link PrometheusRegistry#defaultRegistry}.
*/
public Builder registry(PrometheusRegistry registry) {
public Builder registry(Collector registry) {
this.registry = registry;
return this;
}
Expand Down
Loading