001package io.prometheus.metrics.expositionformats;
002
003import io.prometheus.metrics.annotations.StableApi;
004import io.prometheus.metrics.config.EscapingScheme;
005import io.prometheus.metrics.config.ExporterProperties;
006import io.prometheus.metrics.config.OpenMetrics2Properties;
007import io.prometheus.metrics.config.PrometheusProperties;
008import javax.annotation.Nullable;
009
010@StableApi
011public class ExpositionFormats {
012
013  private final PrometheusProtobufWriter prometheusProtobufWriter;
014  private final PrometheusTextFormatWriter prometheusTextFormatWriter;
015  private final OpenMetricsTextFormatWriter openMetricsTextFormatWriter;
016  private final OpenMetrics2TextFormatWriter openMetrics2TextFormatWriter;
017
018  private ExpositionFormats(
019      PrometheusProtobufWriter prometheusProtobufWriter,
020      PrometheusTextFormatWriter prometheusTextFormatWriter,
021      OpenMetricsTextFormatWriter openMetricsTextFormatWriter,
022      OpenMetrics2TextFormatWriter openMetrics2TextFormatWriter) {
023    this.prometheusProtobufWriter = prometheusProtobufWriter;
024    this.prometheusTextFormatWriter = prometheusTextFormatWriter;
025    this.openMetricsTextFormatWriter = openMetricsTextFormatWriter;
026    this.openMetrics2TextFormatWriter = openMetrics2TextFormatWriter;
027  }
028
029  public static ExpositionFormats init() {
030    return init(PrometheusProperties.get());
031  }
032
033  @SuppressWarnings("deprecation")
034  public static ExpositionFormats init(PrometheusProperties properties) {
035    ExporterProperties exporterProps = properties.getExporterProperties();
036    OpenMetrics2Properties om2Props = properties.getOpenMetrics2Properties();
037
038    return new ExpositionFormats(
039        new PrometheusProtobufWriter(),
040        PrometheusTextFormatWriter.builder()
041            .setIncludeCreatedTimestamps(exporterProps.getIncludeCreatedTimestamps())
042            .setTimestampsInMs(exporterProps.getPrometheusTimestampsInMs())
043            .build(),
044        OpenMetricsTextFormatWriter.builder()
045            .setCreatedTimestampsEnabled(exporterProps.getIncludeCreatedTimestamps())
046            .setExemplarsOnAllMetricTypesEnabled(exporterProps.getExemplarsOnAllMetricTypes())
047            .build(),
048        OpenMetrics2TextFormatWriter.builder()
049            .setOpenMetrics2Properties(om2Props)
050            .setCreatedTimestampsEnabled(exporterProps.getIncludeCreatedTimestamps())
051            .setExemplarsOnAllMetricTypesEnabled(exporterProps.getExemplarsOnAllMetricTypes())
052            .build());
053  }
054
055  /**
056   * @deprecated Use {@link #init(PrometheusProperties)} instead.
057   */
058  @Deprecated
059  @SuppressWarnings({"InlineMeSuggester"})
060  public static ExpositionFormats init(ExporterProperties properties) {
061    return init(PrometheusProperties.builder().exporterProperties(properties).build());
062  }
063
064  /**
065   * Finds the exposition format writer for the given Accept header.
066   *
067   * @see #findWriterWithEscaping(String) to select a format and bind its escaping scheme together
068   */
069  public ExpositionFormatWriter findWriter(@Nullable String acceptHeader) {
070    if (prometheusProtobufWriter.accepts(acceptHeader)) {
071      return prometheusProtobufWriter;
072    }
073
074    if (isOpenMetrics2Enabled() && openMetrics2TextFormatWriter.accepts(acceptHeader)) {
075      if (openMetrics2TextFormatWriter.getOpenMetrics2Properties().getContentNegotiation()) {
076        String version = parseOpenMetricsVersion(findOpenMetricsMediaType(acceptHeader));
077        if ("2.0.0".equals(version)) {
078          return openMetrics2TextFormatWriter;
079        }
080        // version=1.0.0 or no version: fall through to OM1.
081      } else {
082        // contentNegotiation=false: OM2 handles all OpenMetrics requests.
083        return openMetrics2TextFormatWriter;
084      }
085    }
086
087    if (openMetricsTextFormatWriter.accepts(acceptHeader)) {
088      return openMetricsTextFormatWriter;
089    }
090
091    return prometheusTextFormatWriter;
092  }
093
094  /**
095   * Finds the exposition format writer and escaping scheme negotiated by the given Accept header.
096   *
097   * <p>Use this method when writing a scrape response to select the format and its escaping scheme
098   * from the same {@code Accept} header. Only parameters on the media range accepted by the
099   * selected format affect the escaping scheme. The returned writer's content type is the format's
100   * standard content type; as with {@link #findWriter(String)}, it does not include an escaping
101   * parameter.
102   *
103   * <pre>{@code
104   * ExpositionFormats.init().findWriterWithEscaping(acceptHeader).write(out, registry.scrape());
105   * }</pre>
106   *
107   * @see #findWriter(String) to select only the format writer
108   */
109  public ExpositionFormatWriterWithEscaping findWriterWithEscaping(@Nullable String acceptHeader) {
110    ExpositionFormatWriter writer = findWriter(acceptHeader);
111    String mediaType = findMatchingMediaType(writer, acceptHeader);
112    EscapingScheme fallback = EscapingScheme.DEFAULT;
113    // OpenMetrics 2.0 has no escaping parameter and permits UTF-8 names. Only an explicit request
114    // for version 2.0.0 selects unescaped names; the OM2 writer may also serve OM1/unversioned
115    // requests when content negotiation is disabled.
116    if (writer instanceof OpenMetrics2TextFormatWriter
117        && "2.0.0".equals(parseOpenMetricsVersion(mediaType))) {
118      fallback = EscapingScheme.ALLOW_UTF8;
119    }
120    return new ExpositionFormatWriterWithEscaping(
121        writer, EscapingScheme.fromAcceptHeader(mediaType, fallback));
122  }
123
124  @Nullable
125  private static String findMatchingMediaType(
126      ExpositionFormatWriter writer, @Nullable String acceptHeader) {
127    if (acceptHeader == null) {
128      return null;
129    }
130    for (String mediaType : acceptHeader.split(",")) {
131      if (writer.accepts(mediaType)) {
132        return mediaType;
133      }
134    }
135    return null;
136  }
137
138  @Nullable
139  private static String findOpenMetricsMediaType(@Nullable String acceptHeader) {
140    if (acceptHeader == null) {
141      return null;
142    }
143    for (String mediaType : acceptHeader.split(",")) {
144      if (mediaType.contains("application/openmetrics-text")) {
145        return mediaType;
146      }
147    }
148    return null;
149  }
150
151  private boolean isOpenMetrics2Enabled() {
152    return openMetrics2TextFormatWriter.getOpenMetrics2Properties().getEnabled();
153  }
154
155  public PrometheusProtobufWriter getPrometheusProtobufWriter() {
156    return prometheusProtobufWriter;
157  }
158
159  public PrometheusTextFormatWriter getPrometheusTextFormatWriter() {
160    return prometheusTextFormatWriter;
161  }
162
163  public OpenMetricsTextFormatWriter getOpenMetricsTextFormatWriter() {
164    return openMetricsTextFormatWriter;
165  }
166
167  public OpenMetrics2TextFormatWriter getOpenMetrics2TextFormatWriter() {
168    return openMetrics2TextFormatWriter;
169  }
170
171  @Nullable
172  private static String parseOpenMetricsVersion(@Nullable String mediaType) {
173    if (mediaType == null) {
174      return null;
175    }
176    for (String param : mediaType.split(";")) {
177      String[] tokens = param.split("=");
178      if (tokens.length == 2) {
179        String key = tokens[0].trim();
180        String value = tokens[1].trim();
181        if (key.equals("version")) {
182          return value;
183        }
184      }
185    }
186    return null;
187  }
188}