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

The following examples show how to use com.linecorp.armeria.common.metric.PrometheusMeterRegistries. 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: 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 #2
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 #3
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 #4
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 #5
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void writeTimedOutInClientSide() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ClientRequestContext ctx = setupClientRequestCtx(registry);

    ctx.logBuilder().endRequest(WriteTimeoutException.get());
    ctx.logBuilder().endResponse(WriteTimeoutException.get());

    final Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements)
            .containsEntry("foo.active.requests#value{method=POST}", 0.0)
            .containsEntry("foo.requests#count{http.status=0,method=POST,result=success}", 0.0)
            .containsEntry("foo.requests#count{http.status=0,method=POST,result=failure}", 1.0)
            .containsEntry("foo.timeouts#count{cause=WriteTimeoutException,http.status=0,method=POST}", 1.0)
            .containsEntry("foo.timeouts#count{cause=ResponseTimeoutException," +
                           "http.status=0,method=POST}", 0.0)
            .containsEntry("foo.response.duration#count{http.status=0,method=POST}", 0.0)
            .containsEntry("foo.response.length#count{http.status=0,method=POST}", 0.0)
            .containsEntry("foo.total.duration#count{http.status=0,method=POST}", 0.0);
}
 
Example #6
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void responseTimedOutInClientSide() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ClientRequestContext ctx = setupClientRequestCtx(registry);

    ctx.logBuilder().requestFirstBytesTransferred();
    ctx.logBuilder().endRequest();
    ctx.logBuilder().endResponse(ResponseTimeoutException.get());

    final Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements)
            .containsEntry("foo.active.requests#value{method=POST}", 0.0)
            .containsEntry("foo.requests#count{http.status=0,method=POST,result=success}", 0.0)
            .containsEntry("foo.requests#count{http.status=0,method=POST,result=failure}", 1.0)
            .containsEntry("foo.timeouts#count{cause=WriteTimeoutException,http.status=0,method=POST}", 0.0)
            .containsEntry("foo.timeouts#count{cause=ResponseTimeoutException," +
                           "http.status=0,method=POST}", 1.0)
            .containsEntry("foo.response.duration#count{http.status=0,method=POST}", 1.0)
            .containsEntry("foo.response.length#count{http.status=0,method=POST}", 1.0)
            .containsEntry("foo.total.duration#count{http.status=0,method=POST}", 1.0);
}
 
Example #7
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void httpFailure() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ClientRequestContext ctx = setupClientRequestCtx(registry);

    ctx.logBuilder().requestFirstBytesTransferred();
    ctx.logBuilder().responseHeaders(ResponseHeaders.of(500));
    ctx.logBuilder().responseFirstBytesTransferred();
    ctx.logBuilder().responseLength(456);
    ctx.logBuilder().endRequest();
    ctx.logBuilder().endResponse();

    final Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements)
            .containsEntry("foo.active.requests#value{method=POST}", 0.0)
            .containsEntry("foo.requests#count{http.status=500,method=POST,result=success}", 0.0)
            .containsEntry("foo.requests#count{http.status=500,method=POST,result=failure}", 1.0)
            .containsEntry("foo.response.duration#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.response.length#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.total.duration#count{http.status=500,method=POST}", 1.0);
}
 
Example #8
Source File: CaffeineMetricSupportTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void notRecording() {
    when(policy.isRecordingStats()).thenReturn(false);
    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()).isEmpty();
}
 
Example #9
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 #10
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void actualRequestsIncreasedWhenRetrying() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ClientRequestContext ctx = setupClientRequestCtx(registry);

    addLogInfoInDerivedCtx(ctx);

    Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements).containsEntry("foo.active.requests#value{method=POST}", 1.0);

    addLogInfoInDerivedCtx(ctx);
    // Does not increase the active requests.
    assertThat(measurements).containsEntry("foo.active.requests#value{method=POST}", 1.0);

    ctx.logBuilder().endResponseWithLastChild();

    measurements = measureAll(registry);
    assertThat(measurements)
            .containsEntry("foo.active.requests#value{method=POST}", 0.0)
            .containsEntry("foo.requests#count{http.status=500,method=POST,result=success}", 0.0)
            .containsEntry("foo.requests#count{http.status=500,method=POST,result=failure}", 1.0)
            .containsEntry("foo.actual.requests#count{http.status=500,method=POST}", 2.0)
            .containsEntry("foo.connection.acquisition.duration#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.dns.resolution.duration#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.socket.connect.duration#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.pending.acquisition.duration#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.request.length#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.request.length#total{http.status=500,method=POST}", 123.0)
            .containsEntry("foo.response.duration#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.response.length#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.response.length#total{http.status=500,method=POST}", 456.0)
            .containsEntry("foo.total.duration#count{http.status=500,method=POST}", 1.0);
}
 
Example #11
Source File: CompositeServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.meterRegistry(PrometheusMeterRegistries.newRegistry());
    sb.serviceUnder("/qux/", composite);

    // Should not hit the following services
    sb.serviceUnder("/foo/", otherService);
    sb.serviceUnder("/bar/", otherService);
    sb.service(Route.builder().glob("/*").build(), otherService);
}
 
Example #12
Source File: ServerBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void monitorBlockingTaskExecutorAndSchedulersTogetherWithPrometheus() {
    final PrometheusMeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    Metrics.addRegistry(registry);
    Server.builder()
          .meterRegistry(registry)
          .service("/", (ctx, req) -> HttpResponse.of(200))
          .build();
    Schedulers.enableMetrics();
    Schedulers.decorateExecutorService(Schedulers.single(), Executors.newSingleThreadScheduledExecutor());
}
 
Example #13
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 #14
Source File: ZooKeeperCommandExecutorTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
Replica(InstanceSpec spec, Map<Integer, ZooKeeperAddress> servers,
        Function<Command<?>, CompletableFuture<?>> delegate, boolean start) throws Exception {
    this.delegate = delegate;

    dataDir = spec.getDataDirectory();
    meterRegistry = PrometheusMeterRegistries.newRegistry();

    final int id = spec.getServerId();
    final ZooKeeperReplicationConfig zkCfg = new ZooKeeperReplicationConfig(id, servers);

    rm = new ZooKeeperCommandExecutor(zkCfg, dataDir, new AbstractCommandExecutor(null, null) {
        @Override
        public int replicaId() {
            return id;
        }

        @Override
        protected void doStart(@Nullable Runnable onTakeLeadership,
                               @Nullable Runnable onReleaseLeadership) {}

        @Override
        protected void doStop(@Nullable Runnable onReleaseLeadership) {}

        @Override
        @SuppressWarnings("unchecked")
        protected <T> CompletableFuture<T> doExecute(Command<T> command) {
            return (CompletableFuture<T>) delegate.apply(command);
        }
    }, meterRegistry, null, null);

    startFuture = start ? rm.start() : null;
}
 
Example #15
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void httpSuccess() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ClientRequestContext ctx = setupClientRequestCtx(registry);

    // FIXME(trustin): In reality, most HTTP requests will not have any name.
    //                 As a result, `activeRequestPrefix()` will be invoked only after
    //                 a request is completed, i.e. active request count will be inaccurate,
    //                 especially for streaming requests.
    ctx.logBuilder().name("FooService", "POST");

    Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements).containsEntry("foo.active.requests#value{method=POST,service=FooService}",
                                           1.0);

    ctx.logBuilder().requestFirstBytesTransferred();
    ctx.logBuilder().requestLength(123);
    ctx.logBuilder().endRequest();

    ctx.logBuilder().responseHeaders(ResponseHeaders.of(200));
    ctx.logBuilder().responseLength(456);
    ctx.logBuilder().endResponse();

    measurements = measureAll(registry);
    assertThat(measurements)
            .containsEntry("foo.active.requests#value{method=POST,service=FooService}", 0.0)
            .containsEntry("foo.requests#count{http.status=200,method=POST,result=success," +
                           "service=FooService}", 1.0)
            .containsEntry("foo.requests#count{http.status=200,method=POST,result=failure," +
                           "service=FooService}", 0.0)
            .containsEntry("foo.connection.acquisition.duration#count{http.status=200,method=POST," +
                           "service=FooService}", 1.0)
            .containsEntry("foo.dns.resolution.duration#count{http.status=200,method=POST," +
                           "service=FooService}", 1.0)
            .containsEntry("foo.socket.connect.duration#count{http.status=200,method=POST," +
                           "service=FooService}", 1.0)
            .containsEntry("foo.pending.acquisition.duration#count{http.status=200,method=POST," +
                           "service=FooService}", 1.0)
            .containsEntry("foo.request.length#count{http.status=200,method=POST," +
                           "service=FooService}", 1.0)
            .containsEntry("foo.request.length#total{http.status=200,method=POST," +
                           "service=FooService}", 123.0)
            .containsEntry("foo.response.duration#count{http.status=200,method=POST," +
                           "service=FooService}", 1.0)
            .containsEntry("foo.response.length#count{http.status=200,method=POST," +
                           "service=FooService}", 1.0)
            .containsEntry("foo.response.length#total{http.status=200,method=POST," +
                           "service=FooService}", 456.0)
            .containsEntry("foo.total.duration#count{http.status=200,method=POST," +
                           "service=FooService}", 1.0)
            // This metric is inserted only when RetryingClient is Used.
            .doesNotContainKey("foo.actual.requests#count{http.status=200,method=POST," +
                               "service=FooService}");
}
 
Example #16
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 #17
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 #18
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 #19
Source File: MonitoringModule.java    From curiostack with MIT License 4 votes vote down vote up
@Provides
@Singleton
static MeterRegistry meterRegistry(CollectorRegistry collectorRegistry) {
  return PrometheusMeterRegistries.newRegistry(collectorRegistry);
}
 
Example #20
Source File: CaffeineMetricSupportTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
public void aggregationAfterGC() throws Exception {
    final MockCache cache1 = new MockCache(1, 2, 3, 4, 5);
    Object cache2 = new MockLoadingCache(6, 7, 8, 9, 10, 11, 12, 13);
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final AtomicLong ticker = new AtomicLong();
    final MeterIdPrefix idPrefix = new MeterIdPrefix("baz");

    // Register two caches at the same meter ID.
    CaffeineMetricSupport.setup(registry, idPrefix, cache1, ticker::get);
    CaffeineMetricSupport.setup(registry, idPrefix, (Cache<?, ?>) cache2, ticker::get);

    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("baz.requests#count{result=hit}", 7.0)
            .containsEntry("baz.requests#count{result=miss}", 9.0)
            .containsEntry("baz.loads#count{result=success}", 8.0)
            .containsEntry("baz.loads#count{result=failure}", 9.0)
            .containsEntry("baz.load.duration#count", 10.0)
            .containsEntry("baz.evictions#count", 14.0)
            .containsEntry("baz.eviction.weight#count", 16.0)
            .containsEntry("baz.estimated.size#value", 18.0);

    ticker.addAndGet(CaffeineMetricSupport.UPDATE_INTERVAL_NANOS);

    // Ensure the weak reference which held the cache is cleaned up.
    cache2 = new WeakReference<>(cache2);
    System.gc();
    Thread.sleep(1000);
    assertThat(((Reference<?>) cache2).get()).isNull();

    // Check if the counters are not decreased after the second cache is GC'd.
    assertThat(MoreMeters.measureAll(registry))
            .containsEntry("baz.requests#count{result=hit}", 7.0)
            .containsEntry("baz.requests#count{result=miss}", 9.0)
            .containsEntry("baz.loads#count{result=success}", 8.0)
            .containsEntry("baz.loads#count{result=failure}", 9.0)
            .containsEntry("baz.load.duration#count", 10.0)
            .containsEntry("baz.evictions#count", 14.0)
            .containsEntry("baz.eviction.weight#count", 16.0)
            .containsEntry("baz.estimated.size#value", 5.0); // .. except 'estimatedSize' which is a gauge
}
 
Example #21
Source File: CentralDogma.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
private void doStart() throws Exception {
    boolean success = false;
    ExecutorService repositoryWorker = null;
    ScheduledExecutorService purgeWorker = null;
    ProjectManager pm = null;
    CommandExecutor executor = null;
    PrometheusMeterRegistry meterRegistry = null;
    Server server = null;
    SessionManager sessionManager = null;
    try {
        meterRegistry = PrometheusMeterRegistries.newRegistry();

        logger.info("Starting the Central Dogma ..");
        final ThreadPoolExecutor repositoryWorkerImpl = new ThreadPoolExecutor(
                cfg.numRepositoryWorkers(), cfg.numRepositoryWorkers(),
                60, TimeUnit.SECONDS, new LinkedTransferQueue<>(),
                new DefaultThreadFactory("repository-worker", true));
        repositoryWorkerImpl.allowCoreThreadTimeOut(true);
        repositoryWorker = ExecutorServiceMetrics.monitor(meterRegistry, repositoryWorkerImpl,
                                                          "repositoryWorker");

        logger.info("Starting the project manager: {}", cfg.dataDir());

        purgeWorker = Executors.newSingleThreadScheduledExecutor(
                new DefaultThreadFactory("purge-worker", true));

        pm = new DefaultProjectManager(cfg.dataDir(), repositoryWorker, purgeWorker,
                                       meterRegistry, cfg.repositoryCacheSpec());

        logger.info("Started the project manager: {}", pm);

        logger.info("Current settings:\n{}", cfg);

        sessionManager = initializeSessionManager();

        logger.info("Starting the command executor ..");
        executor = startCommandExecutor(pm, repositoryWorker, purgeWorker,
                                        meterRegistry, sessionManager);
        if (executor.isWritable()) {
            logger.info("Started the command executor.");

            initializeInternalProject(executor);

            // Migrate tokens and create metadata files if it does not exist.
            MigrationUtil.migrate(pm, executor);
        }

        logger.info("Starting the RPC server.");
        server = startServer(pm, executor, meterRegistry, sessionManager);
        logger.info("Started the RPC server at: {}", server.activePorts());
        logger.info("Started the Central Dogma successfully.");
        success = true;
    } finally {
        if (success) {
            this.repositoryWorker = repositoryWorker;
            this.purgeWorker = purgeWorker;
            this.pm = pm;
            this.executor = executor;
            this.meterRegistry = meterRegistry;
            this.server = server;
            this.sessionManager = sessionManager;
        } else {
            doStop(server, executor, pm, repositoryWorker, purgeWorker, sessionManager);
        }
    }
}