com.netflix.spectator.api.Timer Java Examples

The following examples show how to use com.netflix.spectator.api.Timer. 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: SpectatorExecutionInterceptorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void awsThrottling() {
  SdkHttpRequest request = SdkHttpRequest.builder()
      .method(SdkHttpMethod.POST)
      .uri(URI.create("https://ec2.us-east-1.amazonaws.com"))
      .build();
  SdkHttpResponse response = SdkHttpResponse.builder()
      .statusCode(400)
      .build();
  Throwable error = AwsServiceException.builder()
      .awsErrorDetails(AwsErrorDetails.builder()
          .errorCode("Throttling")
          .errorMessage("too many requests")
          .build())
      .build();
  TestContext context = new TestContext(request, response, error);
  execute(context, createAttributes("EC2", "DescribeInstances"), millis(30));
  Assertions.assertEquals(1, registry.timers().count());

  Timer t = registry.timers().findFirst().orElse(null);
  Assertions.assertNotNull(t);
  Assertions.assertEquals(1, t.count());
  Assertions.assertEquals(millis(30), t.totalTime());
  Assertions.assertEquals("400", get(t.id(), "http.status"));
  Assertions.assertEquals("throttled", get(t.id(), "ipc.status"));
}
 
Example #2
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void totalOfSquaresOverflow() {
  final long seconds = 10;
  final long nanos = TimeUnit.SECONDS.toNanos(seconds);
  final BigInteger s = new BigInteger("" + nanos);
  final BigInteger s2 = s.multiply(s);

  Timer t = newTimer("foo");
  t.record(seconds, TimeUnit.SECONDS);
  clock.setWallTime(61000L);

  final double v = Utils.first(t.measure(), Statistic.totalOfSquares).value();

  final double factor = 1e9 * 1e9;
  final BigInteger perSec = s2.divide(BigInteger.valueOf(60));
  Assertions.assertEquals(perSec.doubleValue() / factor, v, 1e-12);
}
 
Example #3
Source File: MicrometerRegistryTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void timerMeasure() {
  Timer t = registry.timer("foo");
  t.record(42, TimeUnit.SECONDS);
  int i = 0;
  for (Measurement m : t.measure()) {
    ++i;
    Assertions.assertEquals("foo", m.id().name());
    switch (Utils.getTagValue(m.id(), "statistic")) {
      case "count":
        Assertions.assertEquals(1.0, m.value(), 1e-12);
        break;
      case "total":
        Assertions.assertEquals(42.0, m.value(), 1e-12);
        break;
      case "max":
        Assertions.assertEquals(42.0, m.value(), 1e-12);
        break;
      default:
        Assertions.fail("invalid statistic for measurment: " + m);
    }
  }
  Assertions.assertEquals(3, i);
}
 
Example #4
Source File: GcLogger.java    From spectator with Apache License 2.0 6 votes vote down vote up
private void processGcEvent(GarbageCollectionNotificationInfo info) {
  GcEvent event = new GcEvent(info, jvmStartTime + info.getGcInfo().getStartTime());
  gcLogs.get(info.getGcName()).add(event);
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug(event.toString());
  }

  // Update pause timer for the action and cause...
  Id eventId = (isConcurrentPhase(info) ? CONCURRENT_PHASE_TIME : PAUSE_TIME)
    .withTag("action", info.getGcAction())
    .withTag("cause", info.getGcCause());
  Timer timer = Spectator.globalRegistry().timer(eventId);
  timer.record(info.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);

  // Update promotion and allocation counters
  updateMetrics(info.getGcName(), info.getGcInfo());

  // Notify an event listener if registered
  if (eventListener != null) {
    try {
      eventListener.onComplete(event);
    } catch (Exception e) {
      LOGGER.warn("exception thrown by event listener", e);
    }
  }
}
 
Example #5
Source File: SpectatorRequestMetricCollectorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricCollection() {
  execRequest("http://foo", 200);

  //then
  List<Meter> allMetrics = new ArrayList<>();
  registry.iterator().forEachRemaining(allMetrics::add);

  assertEquals(2, allMetrics.size());
  Optional<Timer> expectedTimer = registry.timers().findFirst();
  assertTrue(expectedTimer.isPresent());
  Timer timer = expectedTimer.get();
  assertEquals(1, timer.count());
  assertEquals(100000, timer.totalTime());

  Optional<Counter> expectedCounter = registry.counters().findFirst();
  assertTrue(expectedCounter.isPresent());
  assertEquals(12345L, expectedCounter.get().count());
}
 
Example #6
Source File: DefaultPlaceholderTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecord() {
  String[] tagValue = new String[] { "default" };
  Timer timer = factory.timer(factory.createId("testRecord",
          Collections.singleton(new TestTagFactory(tagValue))));

  timer.record(42, TimeUnit.MILLISECONDS);
  Assertions.assertEquals("testRecord:tag=default", timer.id().toString());
  Assertions.assertEquals(timer.count(), 1L);
  Assertions.assertEquals(42000000L, timer.totalTime());

  tagValue[0] = "value2";
  Assertions.assertEquals("testRecord:tag=value2", timer.id().toString());
  Assertions.assertEquals(0L, timer.count());
  Assertions.assertEquals(0L, timer.totalTime());
}
 
Example #7
Source File: SpectatorExecutionInterceptorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
private void parseRetryHeaderTest(String expected, String header) {
  SdkHttpRequest request = SdkHttpRequest.builder()
      .method(SdkHttpMethod.POST)
      .uri(URI.create("https://ec2.us-east-1.amazonaws.com"))
      .appendHeader("amz-sdk-retry", header)
      .build();
  SdkHttpResponse response = SdkHttpResponse.builder()
      .statusCode(200)
      .build();
  TestContext context = new TestContext(request, response);
  execute(context, createAttributes("EC2", "DescribeInstances"), millis(30));
  Assertions.assertEquals(1, registry.timers().count());

  Timer t = registry.timers().findFirst().orElse(null);
  Assertions.assertNotNull(t);
  Assertions.assertEquals(1, t.count());
  Assertions.assertEquals(millis(30), t.totalTime());
  Assertions.assertEquals(expected, get(t.id(), "ipc.attempt"));
}
 
Example #8
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void expiration() {
  final long initTime = TimeUnit.MINUTES.toMillis(30);
  final long fifteenMinutes = TimeUnit.MINUTES.toMillis(15);

  // Not expired on init, wait for activity to mark as active
  clock.setWallTime(initTime);
  Timer t = newTimer("foo");
  Assertions.assertFalse(t.hasExpired());
  t.record(1, TimeUnit.SECONDS);
  Assertions.assertFalse(t.hasExpired());

  // Expires with inactivity
  clock.setWallTime(initTime + fifteenMinutes + 1);
  Assertions.assertTrue(t.hasExpired());

  // Activity brings it back
  t.record(42, TimeUnit.SECONDS);
  Assertions.assertFalse(t.hasExpired());
}
 
Example #9
Source File: EVCacheMetricsFactory.java    From EVCache with Apache License 2.0 6 votes vote down vote up
public Timer getPercentileTimer(String metric, Collection<Tag> tags, Duration max) {
    final String name = tags != null ? metric + tags.toString() : metric;
    final Timer duration = timerMap.get(name);
    if (duration != null) return duration;

    writeLock.lock();
    try {
        if (timerMap.containsKey(name))
            return timerMap.get(name);
        else {
            Id id = getId(metric, tags);
            final Timer _duration = PercentileTimer.builder(getRegistry()).withId(id).withRange(Duration.ofNanos(100000), max).build();
            timerMap.put(name, _duration);
            return _duration;
        }
    } finally {
        writeLock.unlock();
    }
}
 
Example #10
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void totalOfSquaresManyBigValues() {
  Timer t = newTimer("foo");
  BigInteger sumOfSq = new BigInteger("0");
  for (int i = 0; i < 100000; ++i) {
    final long nanos = TimeUnit.SECONDS.toNanos(i);
    final BigInteger s = new BigInteger("" + nanos);
    final BigInteger s2 = s.multiply(s);
    sumOfSq = sumOfSq.add(s2);
    t.record(i, TimeUnit.SECONDS);
  }
  clock.setWallTime(61000L);

  final double v = Utils.first(t.measure(), Statistic.totalOfSquares).value();

  // Expected :3.3332833335E14
  // Actual   :3.3332833334999825E14
  final double factor = 1e9 * 1e9;
  sumOfSq = sumOfSq.divide(BigInteger.valueOf(60));
  Assertions.assertEquals(sumOfSq.doubleValue() / factor, v, 2.0);
}
 
Example #11
Source File: EVCacheMemcachedClient.java    From EVCache with Apache License 2.0 6 votes vote down vote up
private Timer getTimer(String operation, String operationType, OperationStatus status, String hit, String host, long maxDuration) {
    String name = ((status != null) ? operation + status.getMessage() : operation );
    if(hit != null) name = name + hit;

    Timer timer = timerMap.get(name);
    if(timer != null) return timer;

    final List<Tag> tagList = new ArrayList<Tag>(client.getTagList().size() + 4 + (host == null ? 0 : 1));
    tagList.addAll(client.getTagList());
    if(operation != null) tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, operation));
    if(operationType != null) tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TYPE_TAG, operationType));
    if(status != null) {
        if(status.getStatusCode() == StatusCode.SUCCESS || status.getStatusCode() == StatusCode.ERR_NOT_FOUND || status.getStatusCode() == StatusCode.ERR_EXISTS) {
            tagList.add(new BasicTag(EVCacheMetricsFactory.IPC_RESULT, EVCacheMetricsFactory.SUCCESS));
        } else {
            tagList.add(new BasicTag(EVCacheMetricsFactory.IPC_RESULT, EVCacheMetricsFactory.FAIL));
        }
        tagList.add(new BasicTag(EVCacheMetricsFactory.IPC_STATUS, getStatusCode(status.getStatusCode())));
    }
    if(hit != null) tagList.add(new BasicTag(EVCacheMetricsFactory.CACHE_HIT, hit));
    if(host != null) tagList.add(new BasicTag(EVCacheMetricsFactory.FAILED_HOST, host));

    timer = EVCacheMetricsFactory.getInstance().getPercentileTimer(EVCacheMetricsFactory.IPC_CALL, tagList, Duration.ofMillis(maxDuration));
    timerMap.put(name, timer);
    return timer;
}
 
Example #12
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void totalOfSquaresManySmallValues() {
  Timer t = newTimer("foo");
  BigInteger sumOfSq = new BigInteger("0");
  for (int i = 0; i < 100000; ++i) {
    final long nanos = i;
    final BigInteger s = new BigInteger("" + nanos);
    final BigInteger s2 = s.multiply(s);
    sumOfSq = sumOfSq.add(s2);
    t.record(i, TimeUnit.NANOSECONDS);
  }
  clock.setWallTime(61000L);

  final double v = Utils.first(t.measure(), Statistic.totalOfSquares).value();

  final double factor = 1e9 * 1e9;
  sumOfSq = sumOfSq.divide(BigInteger.valueOf(60));
  Assertions.assertEquals(sumOfSq.doubleValue() / factor, v, 1e-12);
}
 
Example #13
Source File: DefaultPlaceholderTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecordRunnableException() throws Exception {
  Timer timer = factory.timer(factory.createId("testRecordRunnableException"));
  clock.setMonotonicTime(100L);
  Exception expectedExc = new RuntimeException("foo");
  Exception actualExc = null;
  try {
    timer.record(() -> {
      clock.setMonotonicTime(500L);
      throw expectedExc;
    });
  } catch (Exception e) {
    actualExc = e;
  }
  Assertions.assertSame(expectedExc, actualExc);
  Assertions.assertEquals(1L, timer.count());
  Assertions.assertEquals(timer.totalTime(), 400L);
}
 
Example #14
Source File: DefaultPlaceholderTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMeasure() {
  Timer timer = factory.timer(factory.createId("testMeasure"));
  timer.record(42, TimeUnit.MILLISECONDS);
  clock.setWallTime(3712345L);
  for (Measurement m : timer.measure()) {
    Assertions.assertEquals(m.timestamp(), 3712345L);
    if (m.id().equals(timer.id().withTag(Statistic.count))) {
      Assertions.assertEquals(1.0, m.value(), 0.1e-12);
    } else if (m.id().equals(timer.id().withTag(Statistic.totalTime))) {
      Assertions.assertEquals(42e6, m.value(), 0.1e-12);
    } else {
      Assertions.fail("unexpected id: " + m.id());
    }
  }
}
 
Example #15
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecordRunnableException() throws Exception {
  Timer t = newTimer("foo");
  clock.setMonotonicTime(100L);
  boolean seen = false;
  try {
    t.record((Runnable) () -> {
      clock.setMonotonicTime(500L);
      throw new RuntimeException("foo");
    });
  } catch (Exception e) {
    seen = true;
  }
  Assertions.assertTrue(seen);
  Assertions.assertEquals(t.count(), 1L);
  Assertions.assertEquals(t.totalTime(), 400L);
}
 
Example #16
Source File: MetricsController.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Determine the type of a meter for reporting purposes.
 *
 * @param registry
 *    Used to provide supplemental information (e.g. to search for the meter).
 *
 * @param meter
 *    The meters whose kind we want to know.
 *
 * @return
 *    A string such as "Counter". If the type cannot be identified as one of
 *    the standard Spectator api interface variants, then the simple class name
 *    is returned.
 */
public static String meterToKind(Registry registry, Meter meter) {
  String kind;
  if (meter instanceof Timer) {
    kind = "Timer";
  } else if (meter instanceof Counter) {
    kind = "Counter";
  } else if (meter instanceof Gauge) {
    kind = "Gauge";
  } else if (meter instanceof DistributionSummary) {
    kind = "DistributionSummary";
  } else {
    kind = meter.getClass().getSimpleName();
  }
  return kind;
}
 
Example #17
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecordCallableException() throws Exception {
  Timer t = newTimer("foo");
  clock.setMonotonicTime(100L);
  boolean seen = false;
  try {
    t.record((Callable<Integer>) () -> {
      clock.setMonotonicTime(500L);
      throw new RuntimeException("foo");
    });
  } catch (Exception e) {
    seen = true;
  }
  Assertions.assertTrue(seen);
  Assertions.assertEquals(t.count(), 1L);
  Assertions.assertEquals(t.totalTime(), 400L);
}
 
Example #18
Source File: SpectatorExecutionInterceptorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void successfulRequest() {
  SdkHttpRequest request = SdkHttpRequest.builder()
      .method(SdkHttpMethod.POST)
      .uri(URI.create("https://ec2.us-east-1.amazonaws.com"))
      .build();
  SdkHttpResponse response = SdkHttpResponse.builder()
      .statusCode(200)
      .build();
  TestContext context = new TestContext(request, response);
  execute(context, createAttributes("EC2", "DescribeInstances"), millis(42));
  Assertions.assertEquals(1, registry.timers().count());

  Timer t = registry.timers().findFirst().orElse(null);
  Assertions.assertNotNull(t);
  Assertions.assertEquals(1, t.count());
  Assertions.assertEquals(millis(42), t.totalTime());
  Assertions.assertEquals("EC2.DescribeInstances", get(t.id(), "ipc.endpoint"));
  Assertions.assertEquals("200", get(t.id(), "http.status"));
  Assertions.assertEquals("POST", get(t.id(), "http.method"));
}
 
Example #19
Source File: SpectatorExecutionInterceptorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void awsFailure() {
  SdkHttpRequest request = SdkHttpRequest.builder()
      .method(SdkHttpMethod.POST)
      .uri(URI.create("https://ec2.us-east-1.amazonaws.com"))
      .build();
  SdkHttpResponse response = SdkHttpResponse.builder()
      .statusCode(403)
      .build();
  Throwable error = AwsServiceException.builder()
      .awsErrorDetails(AwsErrorDetails.builder()
          .errorCode("AccessDenied")
          .errorMessage("credentials have expired")
          .build())
      .build();
  TestContext context = new TestContext(request, response, error);
  execute(context, createAttributes("EC2", "DescribeInstances"), millis(30));
  Assertions.assertEquals(1, registry.timers().count());

  Timer t = registry.timers().findFirst().orElse(null);
  Assertions.assertNotNull(t);
  Assertions.assertEquals(1, t.count());
  Assertions.assertEquals(millis(30), t.totalTime());
  Assertions.assertEquals("403", get(t.id(), "http.status"));
  Assertions.assertEquals("AccessDenied", get(t.id(), "ipc.status.detail"));
}
 
Example #20
Source File: DefaultPlaceholderTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecordCallableException() throws Exception {
  Timer timer = factory.timer(factory.createId("testRecordCallableException"));
  clock.setMonotonicTime(100L);
  boolean seen = false;
  try {
    timer.record(() -> {
      clock.setMonotonicTime(500L);
      throw new Exception("foo");
    });
  } catch (Exception e) {
    seen = true;
  }
  Assertions.assertTrue(seen);
  Assertions.assertEquals(1L, timer.count());
  Assertions.assertEquals(400L, timer.totalTime());
}
 
Example #21
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testMeasure() {
  Timer t = newTimer("foo");
  t.record(42, TimeUnit.MILLISECONDS);
  clock.setWallTime(61000L);
  for (Measurement m : t.measure()) {
    Assertions.assertEquals(m.timestamp(), 61000L);
    final double count = Utils.first(t.measure(), Statistic.count).value();
    final double totalTime = Utils.first(t.measure(), Statistic.totalTime).value();
    Assertions.assertEquals(count, 1.0 / 60.0, 0.1e-12);
    Assertions.assertEquals(totalTime, 42e-3 / 60.0, 0.1e-12);
  }
}
 
Example #22
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordCallable() throws Exception {
  Timer t = newTimer("foo");
  clock.setMonotonicTime(100L);
  int v = t.record(() -> {
    clock.setMonotonicTime(500L);
    return 42;
  });
  Assertions.assertEquals(v, 42);
  Assertions.assertEquals(t.count(), 1L);
  Assertions.assertEquals(t.totalTime(), 400L);
}
 
Example #23
Source File: DefaultPlaceholderTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testInit() {
  Timer timer = new DefaultPlaceholderTimer(new DefaultPlaceholderId("testInit", registry), registry);

  Assertions.assertEquals(0L, timer.count());
  Assertions.assertEquals(0L, timer.totalTime());
}
 
Example #24
Source File: DefaultPlaceholderTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordZero() {
  Timer timer = factory.timer(factory.createId("testRecordZero"));
  timer.record(0, TimeUnit.MILLISECONDS);
  Assertions.assertEquals(1L, timer.count(), 1L);
  Assertions.assertEquals(0L, timer.totalTime());
}
 
Example #25
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordRunnable() throws Exception {
  Timer t = newTimer("foo");
  clock.setMonotonicTime(100L);
  t.record(() -> clock.setMonotonicTime(500L));
  Assertions.assertEquals(t.count(), 1L);
  Assertions.assertEquals(t.totalTime(), 400L);
}
 
Example #26
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecord() {
  Timer t = newTimer("foo");
  t.record(42, TimeUnit.MILLISECONDS);
  Assertions.assertEquals(t.count(), 1L);
  Assertions.assertEquals(t.totalTime(), 42000000L);
}
 
Example #27
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordNegative() {
  Timer t = newTimer("foo");
  t.record(-42, TimeUnit.MILLISECONDS);
  Assertions.assertEquals(t.count(), 0L);
  Assertions.assertEquals(t.totalTime(), 0L);
}
 
Example #28
Source File: ServoTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordZero() {
  Timer t = newTimer("foo");
  t.record(0, TimeUnit.MILLISECONDS);
  Assertions.assertEquals(t.count(), 1L);
  Assertions.assertEquals(t.totalTime(), 0L);
}
 
Example #29
Source File: DefaultPlaceholderTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordRunnable() throws Exception {
  Timer timer = factory.timer(factory.createId("testRecordRunnable"));
  clock.setMonotonicTime(100L);
  timer.record(() -> clock.setMonotonicTime(500L));
  Assertions.assertEquals(1L, timer.count());
  Assertions.assertEquals(timer.totalTime(), 400L);
}
 
Example #30
Source File: DefaultPlaceholderTimerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordNegative() {
  Timer timer = factory.timer(factory.createId("testRecordNegative"));
  timer.record(-42, TimeUnit.MILLISECONDS);
  Assertions.assertEquals(timer.count(), 0L);
  Assertions.assertEquals(0L, timer.totalTime());
}