001package io.prometheus.metrics.exporter.httpserver;
002
003import com.sun.net.httpserver.HttpExchange;
004import com.sun.net.httpserver.HttpHandler;
005import io.prometheus.metrics.annotations.StableApi;
006import io.prometheus.metrics.config.PrometheusProperties;
007import io.prometheus.metrics.exporter.common.PrometheusScrapeHandler;
008import io.prometheus.metrics.model.registry.PrometheusRegistry;
009import java.io.IOException;
010
011/** Handler for the /metrics endpoint */
012@StableApi
013public class MetricsHandler implements HttpHandler {
014
015  private final PrometheusScrapeHandler prometheusScrapeHandler;
016  private final HttpErrorHandlingPolicy errorHandlingPolicy;
017
018  public MetricsHandler() {
019    this(new PrometheusScrapeHandler(), HttpErrorHandlingPolicy.builder().build());
020  }
021
022  public MetricsHandler(PrometheusRegistry registry) {
023    this(new PrometheusScrapeHandler(registry), HttpErrorHandlingPolicy.builder().build());
024  }
025
026  public MetricsHandler(PrometheusProperties config) {
027    this(new PrometheusScrapeHandler(config), HttpErrorHandlingPolicy.builder().build());
028  }
029
030  public MetricsHandler(PrometheusProperties config, PrometheusRegistry registry) {
031    this(new PrometheusScrapeHandler(config, registry), HttpErrorHandlingPolicy.builder().build());
032  }
033
034  public MetricsHandler(
035      PrometheusProperties config,
036      PrometheusRegistry registry,
037      HttpErrorHandlingPolicy errorHandlingPolicy) {
038    this(new PrometheusScrapeHandler(config, registry), errorHandlingPolicy);
039  }
040
041  private MetricsHandler(
042      PrometheusScrapeHandler prometheusScrapeHandler,
043      HttpErrorHandlingPolicy errorHandlingPolicy) {
044    this.prometheusScrapeHandler = prometheusScrapeHandler;
045    this.errorHandlingPolicy = errorHandlingPolicy;
046  }
047
048  @Override
049  public void handle(HttpExchange t) throws IOException {
050    prometheusScrapeHandler.handleRequest(new HttpExchangeAdapter(t, errorHandlingPolicy));
051  }
052}