001package io.prometheus.metrics.exporter.common; 002 003import io.prometheus.metrics.annotations.StableApi; 004import io.prometheus.metrics.config.EscapingScheme; 005import io.prometheus.metrics.config.ExporterFilterProperties; 006import io.prometheus.metrics.config.PrometheusProperties; 007import io.prometheus.metrics.expositionformats.ExpositionFormatWriterWithEscaping; 008import io.prometheus.metrics.expositionformats.ExpositionFormats; 009import io.prometheus.metrics.model.registry.MetricNameFilter; 010import io.prometheus.metrics.model.registry.PrometheusRegistry; 011import io.prometheus.metrics.model.snapshots.MetricSnapshots; 012import java.io.ByteArrayOutputStream; 013import java.io.IOException; 014import java.io.OutputStream; 015import java.nio.charset.StandardCharsets; 016import java.util.ArrayList; 017import java.util.Arrays; 018import java.util.Enumeration; 019import java.util.List; 020import java.util.concurrent.atomic.AtomicInteger; 021import java.util.function.Predicate; 022import java.util.zip.GZIPOutputStream; 023import javax.annotation.Nullable; 024 025/** Prometheus scrape endpoint. */ 026@StableApi 027public class PrometheusScrapeHandler { 028 029 private final PrometheusRegistry registry; 030 private final ExpositionFormats expositionFormats; 031 @Nullable private final Predicate<String> nameFilter; 032 private final AtomicInteger lastResponseSize = new AtomicInteger(2 << 9); // 0.5 MB 033 private final List<String> supportedFormats; 034 private final boolean preferUncompressedResponse; 035 036 public PrometheusScrapeHandler() { 037 this(PrometheusProperties.get(), PrometheusRegistry.defaultRegistry); 038 } 039 040 public PrometheusScrapeHandler(PrometheusRegistry registry) { 041 this(PrometheusProperties.get(), registry); 042 } 043 044 public PrometheusScrapeHandler(PrometheusProperties config) { 045 this(config, PrometheusRegistry.defaultRegistry); 046 } 047 048 public PrometheusScrapeHandler(PrometheusProperties config, PrometheusRegistry registry) { 049 this.expositionFormats = ExpositionFormats.init(config); 050 this.preferUncompressedResponse = 051 config.getExporterHttpServerProperties().isPreferUncompressedResponse(); 052 this.registry = registry; 053 this.nameFilter = makeNameFilter(config.getExporterFilterProperties()); 054 supportedFormats = new ArrayList<>(Arrays.asList("openmetrics", "text")); 055 if (expositionFormats.getPrometheusProtobufWriter().isAvailable()) { 056 supportedFormats.add("prometheus-protobuf"); 057 } 058 } 059 060 public void handleRequest(PrometheusHttpExchange exchange) throws IOException { 061 try { 062 PrometheusHttpRequest request = exchange.getRequest(); 063 String[] includedNames = null; 064 String debugParam = null; 065 try { 066 includedNames = request.getParameterValues("name[]"); 067 debugParam = request.getParameter("debug"); 068 } catch (InvalidQueryParameterException e) { 069 writeInvalidQueryParametersResponse(exchange); 070 return; 071 } 072 MetricSnapshots snapshots = scrape(request, includedNames); 073 String acceptHeader = request.getHeader("Accept"); 074 if (writeDebugResponse( 075 snapshots, EscapingScheme.fromAcceptHeader(acceptHeader), debugParam, exchange)) { 076 return; 077 } 078 ExpositionFormatWriterWithEscaping writer = 079 expositionFormats.findWriterWithEscaping(acceptHeader); 080 PrometheusHttpResponse response = exchange.getResponse(); 081 response.setHeader("Content-Type", writer.getContentType()); 082 083 if (shouldUseCompression(request)) { 084 response.setHeader("Content-Encoding", "gzip"); 085 try (GZIPOutputStream gzipOutputStream = 086 new GZIPOutputStream(response.sendHeadersAndGetBody(200, 0))) { 087 writer.write(gzipOutputStream, snapshots); 088 } 089 } else { 090 ByteArrayOutputStream responseBuffer = 091 new ByteArrayOutputStream(lastResponseSize.get() + 1024); 092 writer.write(responseBuffer, snapshots); 093 lastResponseSize.set(responseBuffer.size()); 094 int contentLength = responseBuffer.size(); 095 if (contentLength > 0) { 096 response.setHeader("Content-Length", String.valueOf(contentLength)); 097 } 098 if (request.getMethod().equals("HEAD")) { 099 // The HTTPServer implementation will throw an Exception if we close the output stream 100 // without sending a response body, so let's not close the output stream in case of a HEAD 101 // response. 102 response.sendHeadersAndGetBody(200, -1); 103 } else { 104 try (OutputStream outputStream = response.sendHeadersAndGetBody(200, contentLength)) { 105 responseBuffer.writeTo(outputStream); 106 } 107 } 108 } 109 } catch (IOException e) { 110 exchange.handleException(e); 111 } catch (RuntimeException e) { 112 exchange.handleException(e); 113 } finally { 114 exchange.close(); 115 } 116 } 117 118 @Nullable 119 private Predicate<String> makeNameFilter(ExporterFilterProperties props) { 120 if (props.getAllowedMetricNames() == null 121 && props.getExcludedMetricNames() == null 122 && props.getAllowedMetricNamePrefixes() == null 123 && props.getExcludedMetricNamePrefixes() == null) { 124 return null; 125 } else { 126 return MetricNameFilter.builder() 127 .nameMustBeEqualTo(props.getAllowedMetricNames()) 128 .nameMustNotBeEqualTo(props.getExcludedMetricNames()) 129 .nameMustStartWith(props.getAllowedMetricNamePrefixes()) 130 .nameMustNotStartWith(props.getExcludedMetricNamePrefixes()) 131 .build(); 132 } 133 } 134 135 @Nullable 136 private Predicate<String> makeNameFilter(@Nullable String[] includedNames) { 137 Predicate<String> result = null; 138 if (includedNames != null && includedNames.length > 0) { 139 result = MetricNameFilter.builder().nameMustBeEqualTo(includedNames).build(); 140 } 141 if (result != null && nameFilter != null) { 142 result = result.and(nameFilter); 143 } else if (nameFilter != null) { 144 result = nameFilter; 145 } 146 return result; 147 } 148 149 private MetricSnapshots scrape(PrometheusHttpRequest request, @Nullable String[] includedNames) { 150 151 Predicate<String> filter = makeNameFilter(includedNames); 152 if (filter != null) { 153 return registry.scrape(filter, request); 154 } else { 155 return registry.scrape(request); 156 } 157 } 158 159 private boolean writeDebugResponse( 160 MetricSnapshots snapshots, 161 EscapingScheme escapingScheme, 162 @Nullable String debugParam, 163 PrometheusHttpExchange exchange) 164 throws IOException { 165 PrometheusHttpResponse response = exchange.getResponse(); 166 if (debugParam == null) { 167 return false; 168 } else { 169 response.setHeader("Content-Type", "text/plain; charset=utf-8"); 170 int responseStatus = supportedFormats.contains(debugParam) ? 200 : 500; 171 OutputStream body = response.sendHeadersAndGetBody(responseStatus, 0); 172 switch (debugParam) { 173 case "openmetrics": 174 expositionFormats.getOpenMetricsTextFormatWriter().write(body, snapshots, escapingScheme); 175 break; 176 case "text": 177 expositionFormats.getPrometheusTextFormatWriter().write(body, snapshots, escapingScheme); 178 break; 179 case "prometheus-protobuf": 180 String debugString = 181 expositionFormats 182 .getPrometheusProtobufWriter() 183 .toDebugString(snapshots, escapingScheme); 184 body.write(debugString.getBytes(StandardCharsets.UTF_8)); 185 break; 186 default: 187 body.write( 188 ("debug=" 189 + debugParam 190 + ": Unsupported query parameter. Valid values are 'openmetrics', " 191 + "'text', and 'prometheus-protobuf'.") 192 .getBytes(StandardCharsets.UTF_8)); 193 break; 194 } 195 return true; 196 } 197 } 198 199 private void writeInvalidQueryParametersResponse(PrometheusHttpExchange exchange) 200 throws IOException { 201 PrometheusHttpResponse response = exchange.getResponse(); 202 response.setHeader("Content-Type", "text/plain; charset=utf-8"); 203 byte[] message = "Invalid query parameters".getBytes(StandardCharsets.UTF_8); 204 try (OutputStream outputStream = response.sendHeadersAndGetBody(400, message.length)) { 205 outputStream.write(message); 206 } 207 } 208 209 private boolean shouldUseCompression(PrometheusHttpRequest request) { 210 if (preferUncompressedResponse) { 211 return false; 212 } 213 214 Enumeration<String> encodingHeaders = request.getHeaders("Accept-Encoding"); 215 if (encodingHeaders == null) { 216 return false; 217 } 218 while (encodingHeaders.hasMoreElements()) { 219 String encodingHeader = encodingHeaders.nextElement(); 220 String[] encodings = encodingHeader.split(","); 221 for (String encoding : encodings) { 222 if (encoding.trim().equalsIgnoreCase("gzip")) { 223 return true; 224 } 225 } 226 } 227 return false; 228 } 229}