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

The following examples show how to use com.linecorp.armeria.common.metric.MoreMeters. 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: 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 #2
Source File: CaffeineMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void sameCacheTwice() {
    final MockCache cache = new MockCache(1, 2, 3, 4, 5);
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final MeterIdPrefix idPrefix = new MeterIdPrefix("baz");

    // Register the same cache twice at the same meter ID.
    CaffeineMetricSupport.setup(registry, idPrefix, cache);
    CaffeineMetricSupport.setup(registry, idPrefix, cache);

    // .. and check if the stats are *not* doubled.
    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("baz.requests#count{result=hit}", 1.0)
            .containsEntry("baz.requests#count{result=miss}", 2.0)
            .containsEntry("baz.evictions#count", 3.0)
            .containsEntry("baz.eviction.weight#count", 4.0)
            .containsEntry("baz.estimated.size#value", 5.0);
}
 
Example #3
Source File: CaffeineMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void aggregation() {
    final MockLoadingCache cache1 = new MockLoadingCache(1, 2, 3, 4, 5, 6, 7, 8);
    final MockLoadingCache cache2 = new MockLoadingCache(9, 10, 11, 12, 13, 14, 15, 16);
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final MeterIdPrefix idPrefix = new MeterIdPrefix("baz");

    // Register two caches at the same meter ID.
    CaffeineMetricSupport.setup(registry, idPrefix, cache1);
    CaffeineMetricSupport.setup(registry, idPrefix, cache2);

    // .. and their stats are aggregated.
    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("baz.requests#count{result=hit}", 10.0)
            .containsEntry("baz.requests#count{result=miss}", 12.0)
            .containsEntry("baz.loads#count{result=success}", 14.0)
            .containsEntry("baz.loads#count{result=failure}", 16.0)
            .containsEntry("baz.load.duration#count", 18.0)
            .containsEntry("baz.evictions#count", 20.0)
            .containsEntry("baz.eviction.weight#count", 22.0)
            .containsEntry("baz.estimated.size#value", 24.0);
}
 
Example #4
Source File: CaffeineMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonLoadingCache() {
    final MockCache cache = new MockCache(1, 2, 3, 4, 5);
    final AtomicLong ticker = new AtomicLong();
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    CaffeineMetricSupport.setup(registry, new MeterIdPrefix("bar"), cache, ticker::get);

    assertThat(cache.statsCalls()).isOne();
    assertThat(cache.estimatedSizeCalls()).isOne();

    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("bar.requests#count{result=hit}", 1.0)
            .containsEntry("bar.requests#count{result=miss}", 2.0)
            .containsEntry("bar.evictions#count", 3.0)
            .containsEntry("bar.eviction.weight#count", 4.0)
            .containsEntry("bar.estimated.size#value", 5.0);

    // Make sure the meters related with loading are not registered.
    assertThat(MoreMeters.measureAll(registry)).doesNotContainKeys(
            "bar.loads#count{result=success}",
            "bar.loads#count{result=failure}",
            "bar.load.duration#count");
}
 
Example #5
Source File: HttpServerKeepAliveHandlerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@CsvSource({ "H1C, false", "H2C, false", "H2C, true" })
void closeByClientIdleTimeout(SessionProtocol protocol, boolean useHttp2Preface) {
    final long clientIdleTimeout = 2000;
    final WebClient client = newWebClient(clientIdleTimeout, useHttp2Preface, server.uri(protocol));
    final MeterRegistry meterRegistry = client.options().factory().meterRegistry();

    final Stopwatch stopwatch = Stopwatch.createStarted();
    client.get("/").aggregate().join();
    assertThat(counter).hasValue(1);

    // The HTTP/2 PING frames sent by the server should not prevent to close an idle connection.
    await().untilAtomic(counter, Matchers.is(0));
    final long elapsed = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
    assertThat(elapsed).isBetween(clientIdleTimeout, serverIdleTimeout - 1000);
    assertThat(MoreMeters.measureAll(meterRegistry))
            .hasEntrySatisfying(
                    "armeria.client.connections.lifespan#total{protocol=" + protocol.uriText() + '}',
                    value -> assertThat(value * 1000).isCloseTo(elapsed, withinPercentage(25)));
}
 
Example #6
Source File: RetryingClientWithMetricsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void metricCollectingThenRetrying() throws Exception {
    final WebClient client =
            WebClient.builder(server.httpUri())
                     .factory(clientFactory)
                     .decorator(RetryingClient.newDecorator(
                             RetryRule.builder().onServerErrorStatus().onException().thenBackoff()))
                     .decorator(MetricCollectingClient.newDecorator(meterIdPrefixFunction))
                     .build();
    assertThat(client.get("/hello").aggregate().join().contentUtf8()).isEqualTo("hello");

    // 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 #7
Source File: RetryingClientWithMetricsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void retryingThenMetricCollectingWithConnectionRefused() 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(MetricCollectingClient.newDecorator(meterIdPrefixFunction))
                     .decorator(RetryingClient.newDecorator(RetryRule.onUnprocessed()))
                     .build();
    assertThat(client.get("/ok").aggregate().join().status()).isEqualTo(HttpStatus.OK);

    // wait until 2 calls are 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)
                .containsEntry("foo.requests#count{http.status=0,method=GET,result=success}", 0.0)
                .containsEntry("foo.requests#count{http.status=0,method=GET,result=failure}", 1.0);
    });
}
 
Example #8
Source File: RetryingClientWithMetricsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void retryingThenMetricCollecting() throws Exception {
    final RetryRuleWithContent<HttpResponse> rule =
            (ctx, response, cause) -> response.aggregate().handle((msg, unused) -> {
                if ("hello".equals(msg.contentUtf8())) {
                    return RetryDecision.noRetry();
                }
                return RetryDecision.retry(Backoff.ofDefault());
            });
    final WebClient client = WebClient.builder(server.httpUri())
                                      .factory(clientFactory)
                                      .decorator(MetricCollectingClient.newDecorator(meterIdPrefixFunction))
                                      .decorator(RetryingClient.newDecorator(rule))
                                      .build();
    assertThat(client.get("/hello").aggregate().join().contentUtf8()).isEqualTo("hello");

    // wait until 3 calls are 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)
                .containsEntry("foo.requests#count{http.status=500,method=GET,result=success}", 0.0)
                .containsEntry("foo.requests#count{http.status=500,method=GET,result=failure}", 2.0);
    });
}
 
Example #9
Source File: HealthCheckedEndpointGroupIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@EnumSource(value = SessionProtocol.class, names = { "HTTP", "HTTPS" })
void endpoints_duplicateEntries(SessionProtocol protocol) throws Exception {
    serverOne.start();

    final int portOne = serverOne.port(protocol);
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(
                    EndpointGroup.of(Endpoint.of("127.0.0.1", portOne),
                                     Endpoint.of("127.0.0.1", portOne),
                                     Endpoint.of("127.0.0.1", portOne)),
                    HEALTH_CHECK_PATH),
            protocol)) {

        endpointGroup.newMeterBinder("baz").bindTo(registry);

        await().untilAsserted(() -> {
            assertThat(endpointGroup.endpoints())
                    .containsOnly(Endpoint.of("127.0.0.1", portOne));

            assertThat(MoreMeters.measureAll(registry))
                    .containsEntry("armeria.client.endpoint.group.count#value{name=baz,state=healthy}", 3.0)
                    .containsEntry("armeria.client.endpoint.group.count#value{name=baz,state=unhealthy}",
                                   0.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=127.0.0.1:" + portOne + ",ip=127.0.0.1,name=baz}", 1.0);
        });
        serverOne.stop();
        await().untilAsserted(() -> assertThat(endpointGroup.endpoints()).isEmpty());
    }
}
 
Example #10
Source File: CachingRepositoryTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void metrics() {
    final MeterRegistry meterRegistry = PrometheusMeterRegistries.newRegistry();
    final Repository repo = newCachingRepo(meterRegistry);
    final Map<String, Double> meters = MoreMeters.measureAll(meterRegistry);
    assertThat(meters).containsKeys("cache.load#count{cache=repository,result=success}");

    // Do something with 'repo' so that it is not garbage-collected even before the meters are measured.
    assertThat(repo.normalizeNow(HEAD)).isNotEqualTo("");
}
 
Example #11
Source File: PrematureClientFactoryCloseTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static void test(Function<CentralDogma, CompletableFuture<?>> watchAction) throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder().build();
    final CentralDogma client = new ArmeriaCentralDogmaBuilder()
            .clientFactory(clientFactory)
            .host("127.0.0.1", dogma.serverAddress().getPort())
            .build();

    final CompletableFuture<?> future = watchAction.apply(client);

    // Wait until the server receives the watch request.
    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(dogma.dogma().meterRegistry().get()))
                .containsEntry("watches.active#value", 1.0);
    });

    // Close the `ClientFactory` to trigger disconnection.
    clientFactory.close();

    // The watch request should finish without an exception.
    assertThat(future.join()).isNull();

    // Wait until the server detects the watch cancellation.
    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(dogma.dogma().meterRegistry().get()))
                .containsEntry("watches.active#value", 0.0);
    });
}
 
Example #12
Source File: Subscriber.java    From curiostack with MIT License 5 votes vote down vote up
public Subscriber(
    @Provided SubscriberStub stub,
    @Provided Optional<MeterRegistry> meterRegistry,
    @Provided Tracing tracing,
    SubscriberOptions options) {
  this.stub =
      options.getUnsafeWrapBuffers()
          ? Clients.newDerivedClient(
              stub, GrpcClientOptions.UNSAFE_WRAP_RESPONSE_BUFFERS.newValue(true))
          : stub;
  this.options = options;

  MeterRegistry registry = meterRegistry.orElse(NoopMeterRegistry.get());

  List<Tag> tags = ImmutableList.of(Tag.of("subscription", options.getSubscription()));

  receivedMessages = registry.counter("subscriber-received-messages", tags);
  ackedMessages = registry.counter("subscriber-acked-messages", tags);
  nackedMessages = registry.counter("subscriber-nacked-messages", tags);
  registry.gauge("reconnect-backoff-millis", tags, streamReconnectBackoff, Duration::toMillis);

  messageProcessingTime =
      MoreMeters.newTimer(registry, "subscriber-message-processing-time", tags);

  tracer = tracing.tracer();
  traceExtractor =
      tracing
          .propagation()
          .extractor((message, key) -> message.getAttributesOrDefault(key, null));
}
 
Example #13
Source File: KeepAliveHandlerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    channel = spy(new EmbeddedChannel());
    when(channel.eventLoop()).thenReturn(eventLoop.get());
    ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(channel);
    meterRegistry = new SimpleMeterRegistry();
    keepAliveTimer = MoreMeters.newTimer(meterRegistry, CONNECTION_LIFETIME, ImmutableList.of());
}
 
Example #14
Source File: MicrometerCommandLatencyCollector.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public void recordCommandLatency(
    SocketAddress local,
    SocketAddress remote,
    ProtocolKeyword commandType,
    long firstResponseLatency,
    long completionLatency) {
  MoreMeters.newTimer(
          registry,
          idPrefix.name(),
          idPrefix.tags("remote", remote.toString(), "command", commandType.name()))
      .record(Duration.ofNanos(completionLatency));
}
 
Example #15
Source File: HealthCheckedEndpointGroupIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * When an endpoint has an IP address already, the health checker must send a health check request using
 * an IP address, because otherwise the health checker can send the health check request to a wrong host
 * if there are more than one IP addresses assigned to the host name.
 */
@ParameterizedTest
@EnumSource(value = SessionProtocol.class, names = { "HTTP", "HTTPS" })
void endpoints_customAuthority(SessionProtocol protocol) throws Exception {
    serverOne.start();

    // This test case will fail if the health check does not use an IP address
    // because the host name 'foo' does not really exist.
    final int port = serverOne.port(protocol);
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(
                    Endpoint.of("foo", port).withIpAddr("127.0.0.1"),
                    HEALTH_CHECK_PATH),
            protocol)) {

        endpointGroup.newMeterBinder("qux").bindTo(registry);

        await().untilAsserted(() -> {
            assertThat(endpointGroup.endpoints())
                    .containsOnly(Endpoint.of("foo", port).withIpAddr("127.0.0.1"));

            assertThat(MoreMeters.measureAll(registry))
                    .containsEntry("armeria.client.endpoint.group.count#value{name=qux,state=healthy}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.count#value{name=qux,state=unhealthy}",
                                   0.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=foo:" + port + ",ip=127.0.0.1,name=qux}", 1.0);
        });
    }
}
 
Example #16
Source File: RetrofitMeterIdPrefixFunctionTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void metrics() {
    final RetrofitMeterIdPrefixFunction meterIdPrefixFunction = RetrofitMeterIdPrefixFunction.of("foo");
    final String serviceTag = "service=" + Example.class.getName();
    final Example example = ArmeriaRetrofit
            .of(WebClient.builder(server.httpUri())
                         .factory(clientFactory)
                         .decorator(MetricCollectingClient.newDecorator(meterIdPrefixFunction))
                         .build())
            .create(Example.class);

    example.getFoo().join();
    await().untilAsserted(() -> assertThat(MoreMeters.measureAll(meterRegistry))
            .containsKeys(
                    "foo.active.requests#value{http.method=GET,method=getFoo,path=/foo," + serviceTag + '}',
                    "foo.request.duration#count{" +
                    "http.method=GET,http.status=200,method=getFoo,path=/foo," + serviceTag + '}'));

    example.postFoo().join();
    await().untilAsserted(() -> assertThat(MoreMeters.measureAll(meterRegistry))
            .containsKeys(
                    "foo.active.requests#value{http.method=GET,method=getFoo,path=/foo," + serviceTag + '}',
                    "foo.request.duration#count{" +
                    "http.method=POST,http.status=200,method=postFoo,path=/foo," + serviceTag + '}'));

    example.traceFoo().join();
    await().untilAsserted(() -> assertThat(MoreMeters.measureAll(meterRegistry))
            .containsKeys(
                    "foo.active.requests#value{http.method=TRACE,method=traceFoo,path=/foo," +
                    serviceTag + '}',
                    "foo.request.duration#count{" +
                    "http.method=TRACE,http.status=200,method=traceFoo,path=/foo," + serviceTag + '}'));
}
 
Example #17
Source File: HealthCheckedEndpointGroupIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@EnumSource(value = SessionProtocol.class, names = { "HTTP", "HTTPS" })
void endpoints_containsUnhealthyServer(SessionProtocol protocol) throws Exception {
    serverOne.start();

    final int portOne = serverOne.port(protocol);
    final int portTwo = 1;
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(
                    EndpointGroup.of(Endpoint.of("127.0.0.1", portOne),
                                     Endpoint.of("127.0.0.1", portTwo)),
                    HEALTH_CHECK_PATH),
            protocol)) {

        endpointGroup.newMeterBinder("bar").bindTo(registry);

        await().untilAsserted(() -> {
            assertThat(endpointGroup.endpoints())
                    .containsOnly(Endpoint.of("127.0.0.1", portOne));

            assertThat(MoreMeters.measureAll(registry))
                    .containsEntry("armeria.client.endpoint.group.count#value{name=bar,state=healthy}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.count#value{name=bar,state=unhealthy}",
                                   1.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=127.0.0.1:" + portOne + ",ip=127.0.0.1,name=bar}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=127.0.0.1:" + portTwo + ",ip=127.0.0.1,name=bar}", 0.0);
        });
    }
}
 
Example #18
Source File: HealthCheckedEndpointGroupIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@EnumSource(value = SessionProtocol.class, names = { "HTTP", "HTTPS" })
void endpoints_withIpAndNoIp(SessionProtocol protocol) throws Exception {
    serverOne.start();
    serverTwo.start();

    final int portOne = serverOne.port(protocol);
    final int portTwo = serverTwo.port(protocol);

    try (HealthCheckedEndpointGroup groupFoo = build(
            HealthCheckedEndpointGroup.builder(Endpoint.of("127.0.0.1", portOne),
                    HEALTH_CHECK_PATH),
            protocol);
         HealthCheckedEndpointGroup groupBar = build(
                 HealthCheckedEndpointGroup.builder(Endpoint.of("localhost", portTwo),
                         HEALTH_CHECK_PATH),
                 protocol)) {

        groupFoo.newMeterBinder("foo").bindTo(registry);
        groupBar.newMeterBinder("bar").bindTo(registry);

        await().untilAsserted(() -> {
            assertThat(MoreMeters.measureAll(registry))
                    .containsEntry("armeria.client.endpoint.group.count#value{name=foo,state=healthy}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.count#value{name=bar,state=healthy}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=127.0.0.1:" + portOne + ",ip=127.0.0.1,name=foo}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=localhost:" + portTwo + ",ip=,name=bar}", 1.0);
        });
    }
}
 
Example #19
Source File: ZooKeeperCommandExecutorTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void metrics() throws Exception {
    final List<Replica> cluster = buildCluster(1, true /* start */,
                                               ZooKeeperCommandExecutorTest::newMockDelegate);
    try {
        final Map<String, Double> meters = MoreMeters.measureAll(cluster.get(0).meterRegistry);
        meters.forEach((k, v) -> logger.debug("{}={}", k, v));
        assertThat(meters).containsKeys("executor#total{name=zkCommandExecutor}",
                                        "executor#total{name=zkLeaderSelector}",
                                        "executor#total{name=zkLogWatcher}",
                                        "executor.pool.size#value{name=zkCommandExecutor}",
                                        "executor.pool.size#value{name=zkLeaderSelector}",
                                        "executor.pool.size#value{name=zkLogWatcher}",
                                        "replica.has.leadership#value",
                                        "replica.id#value",
                                        "replica.last.replayed.revision#value",
                                        "replica.read.only#value",
                                        "replica.replicating#value",
                                        "replica.zk.alive.client.connections#value",
                                        "replica.zk.approximate.data.size#value",
                                        "replica.zk.data.dir.size#value",
                                        "replica.zk.ephemerals#value",
                                        "replica.zk.state#value",
                                        "replica.zk.last.processed.zxid#value",
                                        "replica.zk.latency#value{type=avg}",
                                        "replica.zk.latency#value{type=max}",
                                        "replica.zk.latency#value{type=min}",
                                        "replica.zk.log.dir.size#value",
                                        "replica.zk.nodes#value",
                                        "replica.zk.outstanding.requests#value",
                                        "replica.zk.packets.received#count",
                                        "replica.zk.packets.sent#count",
                                        "replica.zk.watches#value");
    } finally {
        cluster.forEach(r -> r.rm.stop());
    }
}
 
Example #20
Source File: ArmeriaMeterBindersConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultMetrics() throws Exception {
    final Map<String, Double> measurements = MoreMeters.measureAll(registry);
    assertThat(measurements).containsKeys(
            "jvm.buffer.count#value{id=direct}",
            "jvm.classes.loaded#value",
            "jvm.threads.daemon#value",
            "logback.events#count{level=debug}",
            "process.uptime#value",
            "system.cpu.count#value");

    // Use prefix-matching for meter IDs because JVM memory meters differ between JVM versions.
    assertThat(measurements).hasKeySatisfying(new Condition<>(
            key -> key.startsWith("jvm.memory.max#value{area=nonheap,id="),
            "MeterRegistry must contain JVM memory meters"));

    final OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    boolean hasOpenFdCount = false;
    try {
        os.getClass().getDeclaredMethod("getOpenFileDescriptorCount");
        hasOpenFdCount = true;
    } catch (Exception ignored) {
        // Not supported
    }

    if (hasOpenFdCount) {
        assertThat(measurements).containsKeys("process.files.open#value");
    }
}
 
Example #21
Source File: GrpcMetricsIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Double findServerMeter(
        String method, String suffix, Statistic type, String... keyValues) {
    final MeterIdPrefix prefix = new MeterIdPrefix(
            "server." + suffix + '#' + type.getTagValueRepresentation(),
            "service", "armeria.grpc.testing.TestService",
            "method", method,
            "hostname.pattern", "*");
    final String meterIdStr = prefix.withTags(keyValues).toString();
    return MoreMeters.measureAll(registry).get(meterIdStr);
}
 
Example #22
Source File: GrpcMetricsIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static Double findClientMeter(
        String method, String suffix, Statistic type, String... keyValues) {
    final MeterIdPrefix prefix = new MeterIdPrefix(
            "client." + suffix + '#' + type.getTagValueRepresentation(),
            "service", "armeria.grpc.testing.TestService",
            "method", method,
            "http.status", "200");
    final String meterIdStr = prefix.withTags(keyValues).toString();
    return MoreMeters.measureAll(registry).get(meterIdStr);
}
 
Example #23
Source File: Http2ClientConnectionHandler.java    From armeria with Apache License 2.0 5 votes vote down vote up
Http2ClientConnectionHandler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder,
                             Http2Settings initialSettings, Channel channel,
                             HttpClientFactory clientFactory, SessionProtocol protocol) {

    super(decoder, encoder, initialSettings);
    this.clientFactory = clientFactory;

    if (clientFactory.idleTimeoutMillis() > 0 || clientFactory.pingIntervalMillis() > 0) {
        final Timer keepAliveTimer =
                MoreMeters.newTimer(clientFactory.meterRegistry(), "armeria.client.connections.lifespan",
                                    ImmutableList.of(Tag.of("protocol", protocol.uriText())));
        keepAliveHandler = new Http2ClientKeepAliveHandler(
                channel, encoder.frameWriter(), keepAliveTimer,
                clientFactory.idleTimeoutMillis(), clientFactory.pingIntervalMillis());
    } else {
        keepAliveHandler = null;
    }

    responseDecoder = new Http2ResponseDecoder(channel, encoder(), clientFactory, keepAliveHandler);
    connection().addListener(responseDecoder);
    decoder().frameListener(responseDecoder);

    // Setup post build options
    final long timeout = clientFactory.idleTimeoutMillis();
    if (timeout > 0) {
        gracefulShutdownTimeoutMillis(timeout);
    } else {
        // Timeout disabled
        gracefulShutdownTimeoutMillis(-1);
    }
}
 
Example #24
Source File: HealthCheckedEndpointGroupIntegrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@CsvSource({ "HTTP, false", "HTTP, true", "HTTPS, false", "HTTPS, true" })
void endpoints(SessionProtocol protocol, boolean useGet) throws Exception {
    serverOne.start();
    serverTwo.start();

    final int portOne = serverOne.port(protocol);
    final int portTwo = serverTwo.port(protocol);
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(
                    EndpointGroup.of(Endpoint.of("127.0.0.1", portOne),
                                     Endpoint.of("127.0.0.1", portTwo)),
                    HEALTH_CHECK_PATH).useGet(useGet),
            protocol)) {

        endpointGroup.newMeterBinder("foo").bindTo(registry);

        await().untilAsserted(() -> {
            assertThat(endpointGroup.endpoints()).containsExactlyInAnyOrder(
                    Endpoint.of("127.0.0.1", portOne),
                    Endpoint.of("127.0.0.1", portTwo));

            assertThat(MoreMeters.measureAll(registry))
                    .containsEntry("armeria.client.endpoint.group.count#value{name=foo,state=healthy}", 2.0)
                    .containsEntry("armeria.client.endpoint.group.count#value{name=foo,state=unhealthy}",
                                   0.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=127.0.0.1:" + portOne + ",ip=127.0.0.1,name=foo}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=127.0.0.1:" + portTwo + ",ip=127.0.0.1,name=foo}", 1.0);
        });

        serverTwo.stop().get();
        await().untilAsserted(() -> {
            assertThat(endpointGroup.endpoints()).containsExactly(
                    Endpoint.of("127.0.0.1", portOne));

            assertThat(MoreMeters.measureAll(registry))
                    .containsEntry("armeria.client.endpoint.group.count#value{name=foo,state=healthy}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.count#value{name=foo,state=unhealthy}",
                                   1.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=127.0.0.1:" + portOne + ",ip=127.0.0.1,name=foo}", 1.0)
                    .containsEntry("armeria.client.endpoint.group.healthy#value" +
                                   "{authority=127.0.0.1:" + portTwo + ",ip=127.0.0.1,name=foo}", 0.0);
        });
    }
}
 
Example #25
Source File: ServerMaxConnectionAgeTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@CsvSource({ "H2C", "H2" })
@ParameterizedTest
void http2MaxConnectionAge(SessionProtocol protocol) throws InterruptedException {
    final int concurrency = 200;
    final WebClient client = newWebClient(server.uri(protocol));

    // Make sure that a connection is opened.
    assertThat(client.get("/").aggregate().join().status()).isEqualTo(OK);
    assertThat(opened).hasValue(1);

    final Supplier<HttpResponse> execute = () -> client.get("/");

    await().untilAsserted(() -> {
        final List<HttpResponse> responses = IntStream.range(0, concurrency)
                                                      .mapToObj(unused -> execute.get())
                                                      .collect(toImmutableList());
        Throwable cause = null;
        for (HttpResponse response : responses) {
            try {
                response.aggregate().join();
            } catch (Exception e) {
                cause = e;
                break;
            }
        }

        assertThat(cause)
                .isInstanceOf(CompletionException.class)
                .hasCauseInstanceOf(UnprocessedRequestException.class)
                .hasRootCauseInstanceOf(GoAwayReceivedException.class);
    });

    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(meterRegistry))
                .hasEntrySatisfying(
                        "armeria.server.connections.lifespan.percentile#value{phi=0,protocol=" +
                        protocol.uriText() + '}',
                        value -> {
                            assertThat(value * 1000)
                                    .isBetween(MAX_CONNECTION_AGE - 200.0, MAX_CONNECTION_AGE + 3000.0);
                        })
                .hasEntrySatisfying(
                        "armeria.server.connections.lifespan.percentile#value{phi=1,protocol=" +
                        protocol.uriText() + '}',
                        value -> {
                            assertThat(value * 1000)
                                    .isBetween(MAX_CONNECTION_AGE - 200.0, MAX_CONNECTION_AGE + 3000.0);
                        }
                )
                .hasEntrySatisfying(
                        "armeria.server.connections.lifespan#count{protocol=" + protocol.uriText() + '}',
                        value -> assertThat(value).isEqualTo(closed.get()));
    });
}
 
Example #26
Source File: KeepAliveHandlerTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private void assertMeter(String name, double expected) {
    assertThat(MoreMeters.measureAll(meterRegistry)).anySatisfy((name0, value) -> {
        assertThat(name0).isEqualTo(name);
        assertThat(value).isEqualTo(expected);
    });
}
 
Example #27
Source File: KeepAliveHandlerTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private void assertMeter(String name, double expected, Percentage percentage) {
    assertThat(MoreMeters.measureAll(meterRegistry)).anySatisfy((name0, value) -> {
        assertThat(name0).isEqualTo(name);
        assertThat(value).isCloseTo(expected, percentage);
    });
}
 
Example #28
Source File: CaffeineMetricSupportTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
public void test() {
    final MockLoadingCache cache = new MockLoadingCache(1, 2, 3, 4, 5, 6, 7, 8);
    final AtomicLong ticker = new AtomicLong();
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    CaffeineMetricSupport.setup(registry, new MeterIdPrefix("foo"), cache, ticker::get);
    assertThat(registry.getMeters()).isNotEmpty();

    assertThat(cache.statsCalls()).isOne();
    assertThat(cache.estimatedSizeCalls()).isOne();

    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("foo.requests#count{result=hit}", 1.0)
            .containsEntry("foo.requests#count{result=miss}", 2.0)
            .containsEntry("foo.loads#count{result=success}", 3.0)
            .containsEntry("foo.loads#count{result=failure}", 4.0)
            .containsEntry("foo.load.duration#count", 5.0)
            .containsEntry("foo.evictions#count", 6.0)
            .containsEntry("foo.eviction.weight#count", 7.0)
            .containsEntry("foo.estimated.size#value", 8.0);

    // Make sure Cache.stats() and estimatedSize() are not called since the initial update.
    assertThat(cache.statsCalls()).isOne();
    assertThat(cache.estimatedSizeCalls()).isOne();

    // Advance the ticker so that the next collection triggers stats() and estimatedSize().
    ticker.addAndGet(CaffeineMetricSupport.UPDATE_INTERVAL_NANOS);
    cache.update(9, 10, 11, 12, 13, 14, 15, 16);

    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("foo.requests#count{result=hit}", 9.0)
            .containsEntry("foo.requests#count{result=miss}", 10.0)
            .containsEntry("foo.loads#count{result=success}", 11.0)
            .containsEntry("foo.loads#count{result=failure}", 12.0)
            .containsEntry("foo.load.duration#count", 13.0)
            .containsEntry("foo.evictions#count", 14.0)
            .containsEntry("foo.eviction.weight#count", 15.0)
            .containsEntry("foo.estimated.size#value", 16.0);

    // Make sure Cache.stats() and estimatedSize() were called once more since the initial update.
    assertThat(cache.statsCalls()).isEqualTo(2);
    assertThat(cache.estimatedSizeCalls()).isEqualTo(2);
}
 
Example #29
Source File: MetricCollectingCircuitBreakerListenerTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void test() throws Exception {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final CircuitBreakerListener l = new MetricCollectingCircuitBreakerListener(registry, "foo");

    // Note: We only use the name of the circuit breaker.
    final CircuitBreaker cb = CircuitBreaker.builder("bar").build();

    // Trigger the first event so that the metric group is registered.
    l.onEventCountUpdated(cb.name(), EventCount.of(1, 2));

    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("foo.state#value{name=bar}", 1.0)
            .containsEntry("foo.requests#value{name=bar,result=success}", 1.0)
            .containsEntry("foo.requests#value{name=bar,result=failure}", 2.0)
            .containsEntry("foo.transitions#count{name=bar,state=CLOSED}", 0.0)
            .containsEntry("foo.transitions#count{name=bar,state=OPEN}", 0.0)
            .containsEntry("foo.transitions#count{name=bar,state=HALF_OPEN}", 0.0)
            .containsEntry("foo.rejected.requests#count{name=bar}", 0.0);

    // Transit to CLOSED.
    l.onStateChanged(cb.name(), CircuitState.CLOSED);
    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("foo.state#value{name=bar}", 1.0)
            .containsEntry("foo.transitions#count{name=bar,state=CLOSED}", 1.0);

    // Transit to OPEN.
    l.onStateChanged(cb.name(), CircuitState.OPEN);
    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("foo.state#value{name=bar}", 0.0)
            .containsEntry("foo.transitions#count{name=bar,state=OPEN}", 1.0);

    // Transit to HALF_OPEN.
    l.onStateChanged(cb.name(), CircuitState.HALF_OPEN);
    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("foo.state#value{name=bar}", 0.5)
            .containsEntry("foo.transitions#count{name=bar,state=HALF_OPEN}", 1.0);

    // Reject a request.
    l.onRequestRejected(cb.name());
    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("foo.rejected.requests#count{name=bar}", 1.0);
}
 
Example #30
Source File: HttpServerPipelineConfigurator.java    From armeria with Apache License 2.0 4 votes vote down vote up
private Timer newKeepAliveTimer(SessionProtocol protocol) {
    return MoreMeters.newTimer(config.meterRegistry(), "armeria.server.connections.lifespan",
                               ImmutableList.of(Tag.of("protocol", protocol.uriText())));
}