Java Code Examples for io.prometheus.client.exporter.common.TextFormat#write004()

The following examples show how to use io.prometheus.client.exporter.common.TextFormat#write004() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: FunctionsMetricsResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Path("metrics")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getMetrics() throws IOException {

    WorkerService workerService = get();
    ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer();
    // if request, also attach the prometheus metrics
    if (workerService.getWorkerConfig().isIncludeStandardPrometheusMetrics()) {
        Writer writer = new BufWriter(buf);
        TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
    }

    try {
        SimpleTextOutputStream stream = new SimpleTextOutputStream(buf);
        FunctionsStatsGenerator.generate(workerService,"default", stream);
        byte[] payload = buf.array();
        int arrayOffset = buf.arrayOffset();
        int readableBytes = buf.readableBytes();
        StreamingOutput streamOut = out -> {
            out.write(payload, arrayOffset, readableBytes);
            out.flush();
        };
        return Response
            .ok(streamOut)
            .type(MediaType.TEXT_PLAIN_TYPE)
            .build();
    } finally {
        buf.release();
    }
}
 
Example 9
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 10
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 11
Source File: Exporter.java    From promagent with Apache License 2.0 5 votes vote down vote up
@Override
public String getTextFormat() {
    try {
        StringWriter result = new StringWriter();
        TextFormat.write004(result, registry.metricFamilySamples());
        return result.toString();
    } catch (IOException e) {
        throw new RuntimeException("Unexpected error when writing metrics to a String: " + e.getMessage(), e);
    }
}
 
Example 12
Source File: BuiltInServer.java    From promagent with Apache License 2.0 5 votes vote down vote up
private static void respondMetrics(CollectorRegistry registry, HttpExchange httpExchange) throws IOException {
    StringWriter respBodyWriter = new StringWriter();
    respBodyWriter.write("# Metrics will become visible when they are updated for the first time.\n");
    TextFormat.write004(respBodyWriter, registry.metricFamilySamples());
    byte[] respBody = respBodyWriter.toString().getBytes("UTF-8");
    httpExchange.getResponseHeaders().put("Context-Type", Collections.singletonList("text/plain; charset=UTF-8"));
    httpExchange.sendResponseHeaders(200, respBody.length);
    httpExchange.getResponseBody().write(respBody);
    httpExchange.getResponseBody().close();
}
 
Example 13
Source File: PrometheusEndpoint.java    From client_java with Apache License 2.0 5 votes vote down vote up
public String writeRegistry(Set<String> metricsToInclude) {
  try {
    Writer writer = new StringWriter();
    TextFormat.write004(writer, collectorRegistry.filteredMetricFamilySamples(metricsToInclude));
    return 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 14
Source File: MetricsHandler.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
  try {
    final BufferWriter writer = new BufferWriter();
    TextFormat.write004(writer, registry.filteredMetricFamilySamples(parse(ctx.request())));
    ctx.response()
            .setStatusCode(200)
            .putHeader("Content-Type", TextFormat.CONTENT_TYPE_004)
            .end(writer.getBuffer());
  } catch (IOException e) {
    ctx.fail(e);
  }
}
 
Example 15
Source File: MetricsServlet.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
  resp.setStatus(HttpServletResponse.SC_OK);
  resp.setContentType(TextFormat.CONTENT_TYPE_004);

  Writer writer = new BufferedWriter(resp.getWriter());
  try {
    TextFormat.write004(writer, registry.filteredMetricFamilySamples(parse(req)));
    writer.flush();
  } finally {
    writer.close();
  }
}
 
Example 16
Source File: PrometheusGetHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {

    Writer writer = new StringWriter();
    try {
        TextFormat.write004(writer, registry.metricFamilySamples());
    } catch (IOException e) {
        logger.error("error on put result:", e);
    }
    exchange.getResponseSender().send(writer.toString());

}
 
Example 17
Source File: HTTPServer.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    String query = t.getRequestURI().getRawQuery();

    String contextPath = t.getHttpContext().getPath();
    ByteArrayOutputStream response = this.response.get();
    response.reset();
    OutputStreamWriter osw = new OutputStreamWriter(response);
    if ("/-/healthy".equals(contextPath)) {
        osw.write(HEALTHY_RESPONSE);
    } else {
        TextFormat.write004(osw,
                registry.filteredMetricFamilySamples(parseQuery(query)));
    }

    osw.flush();
    osw.close();
    response.flush();
    response.close();
    t.getResponseHeaders().set("Content-Type",
            TextFormat.CONTENT_TYPE_004);
    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.close();
    } else {
        t.getResponseHeaders().set("Content-Length",
                String.valueOf(response.size()));
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
        response.writeTo(t.getResponseBody());
    }
    t.close();
}
 
Example 18
Source File: JmxCollectorRegistry.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
/**
 * @return Content that should be included in the response body for an endpoint designated for
 * Prometheus to scrape from.
 */
public String scrape() {
    Writer writer = new StringWriter();
    try {
        TextFormat.write004(writer, collectorRegistry.metricFamilySamples());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return writer.toString();
}
 
Example 19
Source File: PrometheusExporter.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
public StreamingOutput metrics() {

        return output -> {
            try (final Writer writer = new OutputStreamWriter(output)) {
                TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
            }
        };
    }
 
Example 20
Source File: PrometheusModel.java    From vespa with Apache License 2.0 5 votes vote down vote up
public String serialize() {
    var writer = new StringWriter();
    try {
        TextFormat.write004(writer, this);
    } catch (Exception e) {
        throw new PrometheusRenderingException("Could not render metrics. Check the log for details.", e);
    }
    return writer.toString();
}