io.prometheus.client.exporter.common.TextFormat Java Examples

The following examples show how to use io.prometheus.client.exporter.common.TextFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MetricsServlet.java    From Patterdale with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType(TextFormat.CONTENT_TYPE_004);

    List<ProbeResult> probeResults = metricsCache.get();

    formatProbeResults(probeResults)
            .forEach(formattedProbeResult -> {
                try {
                    resp.getWriter().print(formattedProbeResult + "\n");
                } catch (IOException e) {
                    logger.error("IO error occurred writing to /metrics page.", e);
                }
            });

    try (Writer writer = resp.getWriter()) {
        TextFormat.write004(writer, registry.filteredMetricFamilySamples(parse(req)));
        writer.flush();
    }
}
 
Example #2
Source File: PrometheusServlet.java    From foremast with Apache License 2.0 6 votes vote down vote up
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter("action");
    if (getCommonMetricsFilter() != null && getCommonMetricsFilter().isActionEnabled() && action != null) {
        String metricName = req.getParameter("metric");
        if ("enable".equalsIgnoreCase(action)) {
            getCommonMetricsFilter().enableMetric(metricName);
        }
        else if ("disable".equalsIgnoreCase(action)) {
            getCommonMetricsFilter().disableMetric(metricName);
        }
        resp.getWriter().write("OK");
        return;
    }

    try {
        StringWriter writer = new StringWriter();
        TextFormat.write004(writer, getCollectorRegistry().metricFamilySamples());
        resp.setContentType(TextFormat.CONTENT_TYPE_004);
        resp.getWriter().write(writer.toString());
    } catch (IOException e) {
        // This actually never happens since StringWriter::write() doesn't throw any IOException
        throw new RuntimeException("Writing metrics failed", e);
    }
}
 
Example #3
Source File: PrometheusScrapingHandlerImpl.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext rc) {
  MeterRegistry registry;
  if (registryName == null) {
    registry = BackendRegistries.getDefaultNow();
  } else {
    registry = BackendRegistries.getNow(registryName);
  }
  if (registry instanceof PrometheusMeterRegistry) {
    PrometheusMeterRegistry prometheusMeterRegistry = (PrometheusMeterRegistry) registry;
    rc.response()
      .putHeader(HttpHeaders.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
      .end(prometheusMeterRegistry.scrape());
  } else {
    String statusMessage = "Invalid registry: " + (registry != null ? registry.getClass().getName() : null);
    rc.response()
      .setStatusCode(500).setStatusMessage(statusMessage)
      .end();
  }
}
 
Example #4
Source File: MetricsHttpServer.java    From dts with Apache License 2.0 6 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    String query = t.getRequestURI().getRawQuery();
    ByteArrayOutputStream response = this.response.get();
    response.reset();
    OutputStreamWriter osw = new OutputStreamWriter(response);
    TextFormat.write004(osw, registry.filteredMetricFamilySamples(parseQuery(query)));
    osw.flush();
    osw.close();
    response.flush();
    response.close();
    t.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
    t.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
    if (shouldUseCompression(t)) {
        t.getResponseHeaders().set("Content-Encoding", "gzip");
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
        final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
        response.writeTo(os);
        os.finish();
    } else {
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
        response.writeTo(t.getResponseBody());
    }
    t.close();
}
 
Example #5
Source File: PrometheusServlet.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String securityToken =
      (String) getServletContext().getAttribute(SECURITY_TOKEN);
  if (securityToken != null) {
    String authorizationHeader = req.getHeader("Authorization");
    if (authorizationHeader == null
        || !authorizationHeader.startsWith(BEARER)
        || !securityToken.equals(
            authorizationHeader.substring(BEARER.length() + 1))) {
      resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
      return;
    }
  }
  DefaultMetricsSystem.instance().publishMetricsNow();
  PrintWriter writer = resp.getWriter();
  getPrometheusSink().writeMetrics(writer);
  writer.write("\n\n#Dropwizard metrics\n\n");
  //print out dropwizard metrics used by ratis.
  TextFormat.write004(writer,
      CollectorRegistry.defaultRegistry.metricFamilySamples());
  writer.flush();
}
 
Example #6
Source File: TestRatisDropwizardExports.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void export() throws IOException {
  //create Ratis metrics
  RaftLogMetrics instance = new RaftLogMetrics("instance");
  instance.getRaftLogSyncTimer().update(10, TimeUnit.MILLISECONDS);
  MetricRegistry dropWizardMetricRegistry =
      instance.getRegistry().getDropWizardMetricRegistry();

  //create and register prometheus collector
  RatisDropwizardExports exports =
      new RatisDropwizardExports(dropWizardMetricRegistry);

  CollectorRegistry collector = new CollectorRegistry();
  collector.register(new RatisDropwizardExports(dropWizardMetricRegistry));

  //export metrics to the string
  StringWriter writer = new StringWriter();
  TextFormat.write004(writer, collector.metricFamilySamples());

  System.out.println(writer.toString());

  Assert.assertFalse("Instance name is not moved to be a tag",
      writer.toString()
          .contains("ratis_core_ratis_log_worker_instance_syncTime"));

}
 
Example #7
Source File: PrometheusExporter.java    From jira-prometheus-exporter with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected void doGet(
        HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException {
    String paramToken = httpServletRequest.getParameter("token");
    String storedToken = secureTokenManager.getToken();

    if (StringUtils.isNotBlank(storedToken) && !storedToken.equals(paramToken)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    httpServletResponse.setContentType(TextFormat.CONTENT_TYPE_004);

    try (Writer writer = httpServletResponse.getWriter()) {
        TextFormat.write004(writer, metricCollector.getRegistry().filteredMetricFamilySamples(parse(httpServletRequest)));
        writer.flush();
    }
}
 
Example #8
Source File: PrometheusExporter.java    From prom-bitbucket-exporter with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected void doGet(
        final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) throws IOException {
    String paramToken = httpServletRequest.getParameter("token");
    String storedToken = secureTokenManager.getToken();

    if (StringUtils.isNotBlank(storedToken) && !storedToken.equals(paramToken)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    httpServletResponse.setContentType(TextFormat.CONTENT_TYPE_004);

    try (Writer writer = httpServletResponse.getWriter()) {
        TextFormat.write004(writer, metricCollector.getRegistry().filteredMetricFamilySamples(parse(httpServletRequest)));
        writer.flush();
    }
}
 
Example #9
Source File: PrometheusExporter.java    From prom-confluence-exporter with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected void doGet(
        final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) throws IOException {
    String paramToken = httpServletRequest.getParameter("token");
    String storedToken = secureTokenManager.getToken();

    if (StringUtils.isNotBlank(storedToken) && !storedToken.equals(paramToken)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    httpServletResponse.setContentType(TextFormat.CONTENT_TYPE_004);

    try (Writer writer = httpServletResponse.getWriter()) {
        TextFormat.write004(writer, metricCollector.getRegistry().filteredMetricFamilySamples(parse(httpServletRequest)));
        writer.flush();
    }
}
 
Example #10
Source File: PrometheusMetricsController.java    From Lavalink with MIT License 6 votes vote down vote up
private ResponseEntity<String> buildAnswer(@Nullable String[] includedParam) throws IOException {
    Set<String> params;
    if (includedParam == null) {
        params = Collections.emptySet();
    } else {
        params = new HashSet<>(Arrays.asList(includedParam));
    }

    Writer writer = new StringWriter();
    try {
        TextFormat.write004(writer, this.registry.filteredMetricFamilySamples(params));
        writer.flush();
    } finally {
        writer.close();
    }

    return new ResponseEntity<>(writer.toString(), HttpStatus.OK);
}
 
Example #11
Source File: PrometheusScrapeEndpointController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping( value = "/metrics", method = RequestMethod.GET, produces = TextFormat.CONTENT_TYPE_004 )
@ResponseBody
public String scrape()
{
    try
    {
        Writer writer = new StringWriter();
        TextFormat.write004( writer, this.collectorRegistry.metricFamilySamples() );
        return writer.toString();
    }
    catch ( IOException ex )
    {
        // This never happens since StringWriter::write() doesn't throw IOException

        throw new UncheckedIOException( "Writing metrics failed", ex );
    }
}
 
Example #12
Source File: MetricsListTest.java    From prometheus-hystrix with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteNiceMetricsOutput() throws IOException {
    // given
    HystrixPrometheusMetricsPublisher.builder().shouldExportDeprecatedMetrics(false).buildAndRegister();
    TestHystrixCommand command = new TestHystrixCommand("any");

    // when
    command.execute();

    // then
    Writer writer = new FileWriter("target/sample.txt");
    try {
        TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
        writer.flush();
    } finally {
        writer.close();
    }
}
 
Example #13
Source File: MetricsListTest.java    From prometheus-hystrix with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHaveExponentialBuckets() throws IOException {
    // given
    HystrixPrometheusMetricsPublisher.builder().withExponentialBuckets().buildAndRegister();
    TestHystrixCommand command = new TestHystrixCommand("any");

    // when
    command.execute();

    // then
    StringWriter writer = new StringWriter();
    try {
        TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
        writer.flush();
    } finally {
        writer.close();
    }
    String result = writer.toString();
    Assertions.assertThat(result).contains("le=\"0.001\"");
    Assertions.assertThat(result).contains("le=\"2.5169093494697568\"");
}
 
Example #14
Source File: MetricsListTest.java    From prometheus-hystrix with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHaveLinearBuckets() throws IOException {
    // given
    HystrixPrometheusMetricsPublisher.builder().withLinearBuckets(0.1, 0.2, 3).buildAndRegister();
    TestHystrixCommand command = new TestHystrixCommand("any");

    // when
    command.execute();

    // then
    StringWriter writer = new StringWriter();
    try {
        TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
        writer.flush();
    } finally {
        writer.close();
    }
    String result = writer.toString();
    Assertions.assertThat(result).contains("le=\"0.1\"");
    Assertions.assertThat(result).contains("le=\"0.5\"");
}
 
Example #15
Source File: MetricsListTest.java    From prometheus-hystrix with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHaveDistinctBuckets() throws IOException {
    // given
    HystrixPrometheusMetricsPublisher.builder().withBuckets(0.1, 1.0).buildAndRegister();
    TestHystrixCommand command = new TestHystrixCommand("any");

    // when
    command.execute();

    // then
    StringWriter writer = new StringWriter();
    try {
        TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
        writer.flush();
    } finally {
        writer.close();
    }
    String result = writer.toString();
    Assertions.assertThat(result).contains("le=\"0.1\"");
    Assertions.assertThat(result).contains("le=\"1.0\"");
}
 
Example #16
Source File: OMetricsResource.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
	protected ResourceResponse newResourceResponse(Attributes attributes) {
		ResourceResponse response = new ResourceResponse();
        response.setLastModified(Time.now());
//        response.setStatusCode(HttpServlet);
        response.setContentType(TextFormat.CONTENT_TYPE_004);
        response.disableCaching();
        if (response.dataNeedsToBeWritten(attributes)) {
        	
        	PageParameters params = attributes.getParameters();
        	Set<String> includedMetrics = new HashSet<>();
        	params.getValues("name").forEach((sv) -> {if(!sv.isEmpty()) includedMetrics.add(sv.toString()); });
        	
            response.setWriteCallback(createWriteCallback(CollectorRegistry.defaultRegistry, includedMetrics));
        }
        return response;
	}
 
Example #17
Source File: PrometheusServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("PrometheusServer Do get called");
    }

    ServletOutputStream response = resp.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(response);

    for(Function<ReportingContext, CollectorRegistry> mc : metricsCollectors) {
        CollectorRegistry collectorRegistry = mc.apply(getReportingContext());
        TextFormat.write004(osw, collectorRegistry.metricFamilySamples());
    }

    osw.flush();
    osw.close();
    response.flush();
    response.close();
    resp.setHeader("Content-Type", TextFormat.CONTENT_TYPE_004);
    resp.setStatus(HttpURLConnection.HTTP_OK);
    resp.flushBuffer();
}
 
Example #18
Source File: PrometheusMvcEndpoint.java    From client_java with Apache License 2.0 6 votes vote down vote up
@RequestMapping(
        method = {RequestMethod.GET},
        produces = { "*/*" }
)
@ResponseBody
public ResponseEntity value(
        @RequestParam(value = "name[]", required = false, defaultValue = "") Set<String> name) {
  if (!getDelegate().isEnabled()) {
    // Shouldn't happen - MVC endpoint shouldn't be registered when delegate's
    // disabled
    return getDisabledResponse();
  }

  String result = delgate.writeRegistry(name);
  return ResponseEntity.ok()
          .header(CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
          .body(result);
}
 
Example #19
Source File: PrometheusScrapeMetrics.java    From apiman with Apache License 2.0 6 votes vote down vote up
private HttpServer setupWebserver(Handler<AsyncResult<HttpServer>> listenHandler) {
    String port = componentConfig.get("port");
    Objects.requireNonNull(port, "Must specify port for scrape server to listen on");
    return vertx.createHttpServer().requestHandler(request -> {
        HttpServerResponse response = request.response();
        StringWriter sw = new StringWriter();
        try {
            TextFormat.write004(sw, collectorRegistry.metricFamilySamples());
            response.setStatusCode(200)
                .putHeader("Content-Type", TextFormat.CONTENT_TYPE_004)
                .setChunked(true)
                .write(sw.toString());
        } catch (Exception e) {
            response.setStatusCode(500)
                .write(Json.encode(e));
        }
        response.end();
    }).listen(Integer.parseInt(port), listenHandler);
}
 
Example #20
Source File: PrometheusEndpointTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetricsExportedThroughPrometheusEndpoint() {
  // given:
  final Counter promCounter = Counter.build("foo_bar", "test counter")
          .labelNames("label1", "label2")
          .register();
  final Counter filteredCounter = Counter.build("filtered_foo_bar", "test counter")
          .labelNames("label1", "label2")
          .register();

  // when:
  promCounter.labels("val1", "val2").inc(3);
  filteredCounter.labels("val1", "val2").inc(6);

  HttpHeaders headers = new HttpHeaders();
  headers.set("Accept", "text/plain");

  ResponseEntity<String> metricsResponse = template.exchange(getBaseUrl() + "/prometheus?name[]=foo_bar", HttpMethod.GET, new HttpEntity(headers), String.class);

  // then:
  assertEquals(HttpStatus.OK, metricsResponse.getStatusCode());
  assertEquals(StringUtils.deleteWhitespace(TextFormat.CONTENT_TYPE_004), metricsResponse.getHeaders().getContentType().toString().toLowerCase());

  List<String> responseLines = Arrays.asList(metricsResponse.getBody().split("\n"));
  assertThat(responseLines, CustomMatchers.<String>exactlyNItems(1,
          matchesPattern("foo_bar\\{label1=\"val1\",label2=\"val2\",?\\} 3.0")));
}
 
Example #21
Source File: PrometheusCollectorTest.java    From opentelemetry-java with Apache License 2.0 5 votes vote down vote up
@Test
public void registerToDefault() throws IOException {
  when(metricProducer.getAllMetrics()).thenReturn(generateTestData());
  StringWriter stringWriter = new StringWriter();
  TextFormat.write004(stringWriter, CollectorRegistry.defaultRegistry.metricFamilySamples());
  assertThat(stringWriter.toString())
      .isEqualTo(
          "# HELP grpc_name long_description\n"
              + "# TYPE grpc_name counter\n"
              + "grpc_name{kc=\"vc\",kp=\"vp\",} 5.0\n"
              + "# HELP http_name double_description\n"
              + "# TYPE http_name counter\n"
              + "http_name{kc=\"vc\",kp=\"vp\",} 3.5\n");
}
 
Example #22
Source File: MetricsResource.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@GET
@Produces({MediaType.TEXT_PLAIN})
public Response getMetrics() {
    Enumeration<Collector.MetricFamilySamples> mfs = prometheusRegistry.metricFamilySamples();

    StreamingOutput stream = os -> {
        Writer writer = new BufferedWriter(new OutputStreamWriter(os));
        TextFormat.write004(writer, mfs);
        writer.flush();
    };

    return Response.ok(stream).build();

}
 
Example #23
Source File: PrometheusScrapeEndpoint.java    From foremast with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<String> invoke() {
    try {
        Writer writer = new StringWriter();
        TextFormat.write004(writer, collectorRegistry.metricFamilySamples());
        return ResponseEntity.ok()
            .header(CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
            .body(writer.toString());
    } catch (IOException e) {
        // This actually never happens since StringWriter::write() doesn't throw any IOException
        throw new RuntimeException("Writing metrics failed", e);
    }
}
 
Example #24
Source File: PrometheusExpositionService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try (OutputStreamWriter writer = new OutputStreamWriter(stream)) {
        TextFormat.write004(writer, collectorRegistry.metricFamilySamples());
    }
    return HttpResponse.of(HttpStatus.OK, CONTENT_TYPE_004, stream.toByteArray());
}
 
Example #25
Source File: ArmeriaSpringActuatorAutoConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testPrometheus() throws Exception {
    final AggregatedHttpResponse res = client.get("/internal/actuator/prometheus").aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.contentType()).isEqualTo(MediaType.parse(TextFormat.CONTENT_TYPE_004));
    assertThat(res.contentAscii()).startsWith("# HELP ");
}
 
Example #26
Source File: PrometheusApiMetrics.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see IEditingMetrics#getCurrentMetricsInfo()
 */
@Override
public String getCurrentMetricsInfo() throws IOException {
    StringWriter writer = new StringWriter();
    TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());

    String content = writer.getBuffer().toString();
    return content;
}
 
Example #27
Source File: MetricsServlet.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType(TextFormat.CONTENT_TYPE_004);
    
    Writer writer = resp.getWriter();
    try {
        writer.write(metrics.getCurrentMetricsInfo());
        writer.flush();
    } finally {
        writer.close();
    }
}
 
Example #28
Source File: SystemResource.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apicurio.hub.api.rest.ISystemResource#getMetrics()
 */
@Override
public Response getMetrics() throws ServerError {
    try {
        String metricsInfo = metrics.getCurrentMetricsInfo();
        ResponseBuilder builder = Response.ok().entity(metricsInfo)
                .header("Content-Type", TextFormat.CONTENT_TYPE_004)
                .header("Content-Length", metricsInfo.length());
        return builder.build();
    } catch (IOException e) {
        throw new ServerError(e);
    }
}
 
Example #29
Source File: PrometheusApiMetrics.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apicurio.hub.api.metrics.IApiMetrics#getCurrentMetricsInfo()
 */
@Override
public String getCurrentMetricsInfo() throws IOException {
    StringWriter writer = new StringWriter();
    TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());

    String content = writer.getBuffer().toString();
    return content;
}
 
Example #30
Source File: PromregatorMetricsEndpoint.java    From promregator with Apache License 2.0 5 votes vote down vote up
@GetMapping(produces=TextFormat.CONTENT_TYPE_004)
public String getMetrics() {
	HashMap<String, MetricFamilySamples> mfsMap = this.gmfspr.determineEnumerationOfMetricFamilySamples(this.collectorRegistry);
	
	MergableMetricFamilySamples mmfs = new MergableMetricFamilySamples();
	mmfs.merge(mfsMap);
	
	return mmfs.toType004String();
}