package io.vertx.micrometer.backends;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.micrometer.VertxPrometheusOptions;
public final class PrometheusBackendRegistry implements BackendRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(PrometheusBackendRegistry.class);
private final PrometheusMeterRegistry registry;
private final VertxPrometheusOptions options;
private Vertx vertx;
public PrometheusBackendRegistry(VertxPrometheusOptions options) {
this(options, new PrometheusMeterRegistry(PrometheusConfig.DEFAULT));
}
public PrometheusBackendRegistry(VertxPrometheusOptions options, PrometheusMeterRegistry registry) {
this.options = options;
this.registry = registry;
if (options.isPublishQuantiles()) {
registry.config().meterFilter(
new MeterFilter() {
@Override
public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) {
return DistributionStatisticConfig.builder()
.percentilesHistogram(true)
.build()
.merge(config);
}
});
}
}
@Override
public MeterRegistry getMeterRegistry() {
return registry;
}
@Override
public void init() {
if (options.isStartEmbeddedServer()) {
this.vertx = Vertx.vertx();
HttpServerOptions serverOptions = options.getEmbeddedServerOptions();
if (serverOptions == null) {
serverOptions = new HttpServerOptions();
}
vertx.createHttpServer(serverOptions)
.requestHandler(this::handleRequest)
.exceptionHandler(t -> LOGGER.error("Error in Prometheus registry embedded server", t))
.listen(serverOptions.getPort(), serverOptions.getHost());
}
}
private void handleRequest(HttpServerRequest request) {
if (options.getEmbeddedServerEndpoint().equals(request.path())) {
request.response()
.putHeader(HttpHeaders.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
.end(registry.scrape());
} else {
request.response().setStatusCode(404).end();
}
}
@Override
public void close() {
if (this.vertx != null) {
vertx.close();
}
}
}