com.linecorp.armeria.common.metric.MeterIdPrefixFunction Java Examples

The following examples show how to use com.linecorp.armeria.common.metric.MeterIdPrefixFunction. 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: CentralDogma.java    From centraldogma with Apache License 2.0 7 votes vote down vote up
private void configureMetrics(ServerBuilder sb, PrometheusMeterRegistry registry) {
    sb.meterRegistry(registry);
    sb.service(METRICS_PATH, new PrometheusExpositionService(registry.getPrometheusRegistry()));
    sb.decorator(MetricCollectingService.newDecorator(MeterIdPrefixFunction.ofDefault("api")));

    // Bind system metrics.
    new FileDescriptorMetrics().bindTo(registry);
    new ProcessorMetrics().bindTo(registry);
    new ClassLoaderMetrics().bindTo(registry);
    new UptimeMetrics().bindTo(registry);
    new DiskSpaceMetrics(cfg.dataDir()).bindTo(registry);
    new JvmGcMetrics().bindTo(registry);
    new JvmMemoryMetrics().bindTo(registry);
    new JvmThreadMetrics().bindTo(registry);

    // Bind global thread pool metrics.
    ExecutorServiceMetrics.monitor(registry, ForkJoinPool.commonPool(), "commonPool");
}
 
Example #2
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void rpc() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ClientRequestContext ctx =
            ClientRequestContext.builder(HttpRequest.of(HttpMethod.POST, "/bar"))
                                .meterRegistry(registry)
                                .endpoint(Endpoint.of("example.com", 8080))
                                .build();

    final MeterIdPrefixFunction meterIdPrefixFunction = MeterIdPrefixFunction.ofDefault("bar");
    RequestMetricSupport.setup(ctx, REQUEST_METRICS_SET, meterIdPrefixFunction, false);

    ctx.logBuilder().name("BarService", "baz");

    assertThat(measureAll(registry))
            .containsEntry("bar.active.requests#value{method=baz,service=BarService}", 1.0);
}
 
Example #3
Source File: GrpcMetricsIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void makeRequest(String name) throws Exception {
    final TestServiceBlockingStub client =
            Clients.builder(server.httpUri(GrpcSerializationFormats.PROTO))
                   .factory(clientFactory)
                   .decorator(MetricCollectingClient.newDecorator(
                           MeterIdPrefixFunction.ofDefault("client")))
                   .build(TestServiceBlockingStub.class);

    final SimpleRequest request =
            SimpleRequest.newBuilder()
                         .setPayload(Payload.newBuilder()
                                            .setBody(ByteString.copyFromUtf8(name)))
                         .build();
    try {
        client.unaryCall(request);
    } catch (Throwable t) {
        // Ignore, we will count these up
    }
}
 
Example #4
Source File: RetryingClientWithMetricsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void metricCollectingThenRetryingWithConnectionRefused() throws Exception {
    // The first request will fail with an UnprocessedException and
    // the second request will succeed with 200.
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("127.0.0.1", 1),
                                                 server.httpEndpoint());
    final WebClient client =
            WebClient.builder(SessionProtocol.HTTP, group)
                     .factory(clientFactory)
                     .decorator(RetryingClient.newDecorator(RetryRule.onUnprocessed()))
                     .decorator(MetricCollectingClient.newDecorator(MeterIdPrefixFunction.ofDefault("foo")))
                     .build();

    assertThat(client.get("/ok").aggregate().join().status()).isEqualTo(HttpStatus.OK);

    // wait until 1 call is recorded.
    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(meterRegistry))
                .containsEntry("foo.requests#count{http.status=200,method=GET,result=success}", 1.0)
                .containsEntry("foo.requests#count{http.status=200,method=GET,result=failure}", 0.0);
    });
}
 
Example #5
Source File: RequestMetricSupport.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void onRequest(RequestLog log, MeterIdPrefixFunction meterIdPrefixFunction, boolean server) {
    final RequestContext ctx = log.context();
    final MeterRegistry registry = ctx.meterRegistry();
    final MeterIdPrefix activeRequestsId =
            meterIdPrefixFunction.activeRequestPrefix(registry, log)
                                 .append(Flags.useLegacyMeterNames() ? "activeRequests"
                                                                     : "active.requests");

    final ActiveRequestMetrics activeRequestMetrics = MicrometerUtil.register(
            registry, activeRequestsId, ActiveRequestMetrics.class,
            (reg, prefix) ->
                    reg.gauge(prefix.name(), prefix.tags(),
                              new ActiveRequestMetrics(), ActiveRequestMetrics::doubleValue));
    activeRequestMetrics.increment();
    ctx.log().whenComplete().thenAccept(requestLog -> {
        onResponse(requestLog, meterIdPrefixFunction, server);
        activeRequestMetrics.decrement();
    });
}
 
Example #6
Source File: RequestMetricSupport.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Sets up request metrics.
 */
public static void setup(RequestContext ctx, AttributeKey<Boolean> requestMetricsSetKey,
                         MeterIdPrefixFunction meterIdPrefixFunction, boolean server) {
    final Boolean isRequestMetricsSet = ctx.attr(requestMetricsSetKey);

    if (Boolean.TRUE.equals(isRequestMetricsSet)) {
        return;
    }
    ctx.setAttr(requestMetricsSetKey, true);

    ctx.log()
       .whenAvailable(RequestLogProperty.REQUEST_START_TIME,
                      RequestLogProperty.REQUEST_HEADERS,
                      RequestLogProperty.NAME,
                      RequestLogProperty.SESSION)
       .thenAccept(log -> onRequest(log, meterIdPrefixFunction, server));
}
 
Example #7
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void requestTimedOutInServerSide() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ServiceRequestContext ctx =
            ServiceRequestContext.builder(HttpRequest.of(HttpMethod.POST, "/foo"))
                                 .meterRegistry(registry)
                                 .build();
    final String serviceTag = "service=" + ctx.config().service().getClass().getName();

    final MeterIdPrefixFunction meterIdPrefixFunction = MeterIdPrefixFunction.ofDefault("foo");
    RequestMetricSupport.setup(ctx, REQUEST_METRICS_SET, meterIdPrefixFunction, true);

    ctx.logBuilder().requestFirstBytesTransferred();
    ctx.logBuilder().responseHeaders(ResponseHeaders.of(503)); // 503 when request timed out
    ctx.logBuilder().responseFirstBytesTransferred();
    ctx.logBuilder().responseLength(456);
    ctx.logBuilder().endRequest();
    ctx.logBuilder().endResponse(RequestTimeoutException.get());

    final Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements)
            .containsEntry("foo.active.requests#value{hostname.pattern=*,method=POST," + serviceTag + '}',
                           0.0)
            .containsEntry("foo.requests#count{hostname.pattern=*,http.status=503,method=POST," +
                           "result=success," + serviceTag + '}', 0.0)
            .containsEntry("foo.requests#count{hostname.pattern=*,http.status=503,method=POST," +
                           "result=failure," + serviceTag + '}', 1.0)
            .containsEntry("foo.timeouts#count{cause=RequestTimeoutException,hostname.pattern=*," +
                           "http.status=503,method=POST," + serviceTag + '}', 1.0)
            .containsEntry("foo.response.duration#count{hostname.pattern=*,http.status=503,method=POST," +
                           serviceTag + '}', 1.0)
            .containsEntry("foo.response.length#count{hostname.pattern=*,http.status=503,method=POST," +
                           serviceTag + '}', 1.0)
            .containsEntry("foo.total.duration#count{hostname.pattern=*,http.status=503,method=POST," +
                           serviceTag + '}', 1.0);
}
 
Example #8
Source File: GrpcMetricsIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.meterRegistry(registry);
    sb.service(GrpcService.builder()
                          .addService(new TestServiceImpl())
                          .enableUnframedRequests(true)
                          .build(),
               MetricCollectingService.newDecorator(MeterIdPrefixFunction.ofDefault("server")),
               LoggingService.newDecorator());
}
 
Example #9
Source File: DropwizardMetricsIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.meterRegistry(registry);
    sb.service("/helloservice", THttpService.of((Iface) name -> {
        if ("world".equals(name)) {
            return "success";
        }
        throw new IllegalArgumentException("bad argument");
    }).decorate(MetricCollectingService.newDecorator(
            MeterIdPrefixFunction.ofDefault("armeria.server.hello.service"))));
}
 
Example #10
Source File: DropwizardMetricsIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void makeRequest(String name) {
    final Iface client = Clients.builder(server.httpUri(BINARY) + "/helloservice")
                                .factory(clientFactory)
                                .rpcDecorator(MetricCollectingRpcClient.newDecorator(
                                        MeterIdPrefixFunction.ofDefault("armeria.client.hello.service")))
                                .build(Iface.class);
    try {
        client.hello(name);
    } catch (Throwable t) {
        // Ignore, we will count these up
    }
}
 
Example #11
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static ClientRequestContext setupClientRequestCtx(MeterRegistry registry) {
    final ClientRequestContext ctx =
            ClientRequestContext.builder(HttpRequest.of(HttpMethod.POST, "/foo"))
                                .meterRegistry(registry)
                                .endpoint(Endpoint.of("example.com", 8080))
                                .connectionTimings(newConnectionTimings())
                                .build();

    final MeterIdPrefixFunction meterIdPrefixFunction = MeterIdPrefixFunction.ofDefault("foo");
    RequestMetricSupport.setup(ctx, REQUEST_METRICS_SET, meterIdPrefixFunction, false);
    return ctx;
}
 
Example #12
Source File: MetricCollectingService.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link HttpService} decorator that tracks request stats using {@link MeterRegistry}.
 */
public static Function<? super HttpService, MetricCollectingService> newDecorator(
        MeterIdPrefixFunction meterIdPrefixFunction) {

    requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
    return delegate -> new MetricCollectingService(delegate, meterIdPrefixFunction);
}
 
Example #13
Source File: MetricCollectingRpcClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
MetricCollectingRpcClient(RpcClient delegate, MeterIdPrefixFunction meterIdPrefixFunction) {
    super(delegate, meterIdPrefixFunction);
}
 
Example #14
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void serviceAndClientContext() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ServiceRequestContext sctx =
            ServiceRequestContext.builder(HttpRequest.of(HttpMethod.POST, "/foo"))
                                 .meterRegistry(registry)
                                 .build();
    final String serviceTag = "service=" + sctx.config().service().getClass().getName();

    RequestMetricSupport.setup(sctx, REQUEST_METRICS_SET, MeterIdPrefixFunction.ofDefault("foo"), true);
    sctx.logBuilder().endRequest();
    try (SafeCloseable ignored = sctx.push()) {
        final ClientRequestContext cctx =
                ClientRequestContext.builder(HttpRequest.of(HttpMethod.POST, "/foo"))
                                    .meterRegistry(registry)
                                    .endpoint(Endpoint.of("example.com", 8080))
                                    .build();
        RequestMetricSupport.setup(cctx, AttributeKey.valueOf("differentKey"),
                                   MeterIdPrefixFunction.ofDefault("bar"), false);
        cctx.logBuilder().endRequest();
        cctx.logBuilder().responseHeaders(ResponseHeaders.of(200));
        cctx.logBuilder().endResponse();
    }
    sctx.logBuilder().responseHeaders(ResponseHeaders.of(200));
    sctx.logBuilder().endResponse();

    final Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements)
            // clientRequestContext
            .containsEntry("bar.active.requests#value{method=POST}", 0.0)
            .containsEntry("bar.requests#count{http.status=200,method=POST,result=success}", 1.0)
            .containsEntry("bar.requests#count{http.status=200,method=POST,result=failure}", 0.0)
            .containsEntry("bar.response.duration#count{http.status=200,method=POST}", 1.0)
            .containsEntry("bar.response.length#count{http.status=200,method=POST}", 1.0)
            .containsEntry("bar.total.duration#count{http.status=200,method=POST}", 1.0)
            // serviceRequestContext
            .containsEntry("foo.active.requests#value{hostname.pattern=*,method=POST," +
                           serviceTag + '}', 0.0)
            .containsEntry("foo.requests#count{hostname.pattern=*,http.status=200,method=POST," +
                           "result=success," + serviceTag + '}', 1.0)
            .containsEntry("foo.requests#count{hostname.pattern=*,http.status=200,method=POST," +
                           "result=failure," + serviceTag + '}', 0.0)
            .containsEntry("foo.response.duration#count{hostname.pattern=*,http.status=200,method=POST," +
                           serviceTag + '}', 1.0)
            .containsEntry("foo.response.length#count{hostname.pattern=*,http.status=200,method=POST," +
                           serviceTag + '}', 1.0)
            .containsEntry("foo.total.duration#count{hostname.pattern=*,http.status=200,method=POST," +
                           serviceTag + '}', 1.0);
}
 
Example #15
Source File: Http1ClientKeepAliveHandlerTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@CsvSource({ "20000", "0" })
@ParameterizedTest
void shouldCloseConnectionWhenNoPingAck(long idleTimeoutMillis) throws Exception {
    try (ServerSocket ss = new ServerSocket(0)) {
        final int port = ss.getLocalPort();

        final ClientFactory factory = ClientFactory.builder()
                                                   .idleTimeoutMillis(idleTimeoutMillis)
                                                   .pingIntervalMillis(10000)
                                                   .useHttp1Pipelining(true)
                                                   .build();
        final WebClient client = WebClient.builder("h1c://127.0.0.1:" + port)
                                          .factory(factory)
                                          .decorator(MetricCollectingClient.newDecorator(
                                                  MeterIdPrefixFunction.ofDefault("client")))
                                          .build();
        client.get("/").aggregate();

        try (Socket s = ss.accept()) {
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(s.getInputStream(), StandardCharsets.US_ASCII));
            final OutputStream out = s.getOutputStream();

            assertThat(in.readLine()).isEqualTo("GET / HTTP/1.1");
            assertThat(in.readLine()).startsWith("host: 127.0.0.1:");
            assertThat(in.readLine()).startsWith("user-agent: armeria/");
            assertThat(in.readLine()).isEmpty();
            out.write(("HTTP/1.1 200 OK\r\n" +
                       "Content-Length: 0\r\n" +
                       "\r\n").getBytes(StandardCharsets.US_ASCII));

            // No response for OPTIONS *
            assertThat(in.readLine()).isEqualTo("OPTIONS * HTTP/1.1");
            assertThat(in.readLine()).startsWith("user-agent: armeria/");
            assertThat(in.readLine()).startsWith("host: 127.0.0.1:");
            assertThat(in.readLine()).isEmpty();

            // Send another request before the PING timeout
            Thread.sleep(5000);
            client.get("/").aggregate();

            String line;
            while ((line = in.readLine()) != null) {
                assertThat(line).doesNotContain("OPTIONS * HTTP/1.1");
            }
        }
    }
}
 
Example #16
Source File: MetricCollectingService.java    From armeria with Apache License 2.0 4 votes vote down vote up
MetricCollectingService(HttpService delegate, MeterIdPrefixFunction meterIdPrefixFunction) {
    super(delegate);
    this.meterIdPrefixFunction = requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
}
 
Example #17
Source File: MetricCollectingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
MetricCollectingClient(HttpClient delegate, MeterIdPrefixFunction meterIdPrefixFunction) {
    super(delegate, meterIdPrefixFunction);
}
 
Example #18
Source File: MetricCollectingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an {@link HttpClient} decorator that tracks request stats using {@link MeterRegistry}.
 */
public static Function<? super HttpClient, MetricCollectingClient> newDecorator(
        MeterIdPrefixFunction meterIdPrefixFunction) {
    requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
    return delegate -> new MetricCollectingClient(delegate, meterIdPrefixFunction);
}
 
Example #19
Source File: MetricCollectingRpcClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an {@link RpcClient} decorator that tracks request stats using {@link MeterRegistry}.
 */
public static Function<? super RpcClient, MetricCollectingRpcClient> newDecorator(
        MeterIdPrefixFunction meterIdPrefixFunction) {
    requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
    return delegate -> new MetricCollectingRpcClient(delegate, meterIdPrefixFunction);
}
 
Example #20
Source File: AbstractMetricCollectingClient.java    From armeria with Apache License 2.0 4 votes vote down vote up
AbstractMetricCollectingClient(Client<I, O> delegate, MeterIdPrefixFunction meterIdPrefixFunction) {
    super(delegate);
    this.meterIdPrefixFunction = requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
}
 
Example #21
Source File: PrometheusMetricsIntegrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public MeterIdPrefix activeRequestPrefix(MeterRegistry registry, RequestOnlyLog log) {
    return MeterIdPrefixFunction.ofDefault(name)
                                .withTags("handler", serviceName)
                                .activeRequestPrefix(registry, log);
}
 
Example #22
Source File: PrometheusMetricsIntegrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public MeterIdPrefix completeRequestPrefix(MeterRegistry registry, RequestLog log) {
    return MeterIdPrefixFunction.ofDefault(name)
                                .withTags("handler", serviceName)
                                .completeRequestPrefix(registry, log);
}
 
Example #23
Source File: MetricLabels.java    From curiostack with MIT License 4 votes vote down vote up
public static MeterIdPrefixFunction grpcRequestLabeler() {
  return GrpcRequestLabeler.INSTANCE;
}
 
Example #24
Source File: MetricLabels.java    From curiostack with MIT License 4 votes vote down vote up
static MeterIdPrefixFunction storageRequestLabeler() {
  return StorageRequestLabeler.INSTANCE;
}
 
Example #25
Source File: MeterIdPrefixFunctionFactory.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the {@link MeterIdPrefixFunction} for the specified service name.
 */
MeterIdPrefixFunction get(String type, String serviceName);