Java源码示例:com.netflix.spectator.api.Timer

示例1
@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);
}
 
示例2
/**
 * 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;
}
 
示例3
@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"));
}
 
示例4
@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"));
}
 
示例5
@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"));
}
 
示例6
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"));
}
 
示例7
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);
    }
  }
}
 
示例8
@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());
}
 
示例9
@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());
}
 
示例10
@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);
}
 
示例11
@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());
    }
  }
}
 
示例12
@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);
}
 
示例13
@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);
}
 
示例14
@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);
}
 
示例15
@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);
}
 
示例16
@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);
}
 
示例17
@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());
}
 
示例18
@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());
}
 
示例19
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();
    }
}
 
示例20
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;
}
 
示例21
private static Timer getTimer(String name, String... additionalTags) {
    String key = className + "." + name + "." + Joiner.on(",").join(additionalTags);
    return monitors.computeIfAbsent(key, k -> {
        List<Tag> tagList = getTags(additionalTags);
        tagList.add(new BasicTag("unit", TimeUnit.MILLISECONDS.name()));
        return registry.timer(name, tagList);
    });
}
 
示例22
public static Timer getTimer(String className, String name, String... additionalTags) {
	Map<String, String> tags = toMap(className, additionalTags);
	return timers.computeIfAbsent(name, s -> new ConcurrentHashMap<>()).computeIfAbsent(tags, t -> {
		Id id = registry.createId(name, tags);
		return PercentileTimer.get(registry, id);
	});
}
 
示例23
private static Stopwatch start(Timer sm) {

		Stopwatch sw = new BasicStopwatch() {

			@Override
			public void stop() {
				super.stop();
				long duration = getDuration(TimeUnit.MILLISECONDS);
				sm.record(duration, TimeUnit.MILLISECONDS);
			}

		};
		sw.start();
		return sw;
	}
 
示例24
void recordTime(final SNSMessage<?> message, final String timeName) {
    final Timer timer = this.registry.timer(
        timeName,
        Metrics.TagEventsType.getMetricName(),
        message.getClass().getName()
    );
    timer.record(this.registry.clock().wallTime() - message.getTimestamp(), TimeUnit.MILLISECONDS);
}
 
示例25
@Test
public void metricsAreSentToAtlasPeriodically() throws InterruptedException {
	Timer t = registry.timer("t");

	for (int i = 0; i < 1000; i++)
		t.record(100, TimeUnit.MILLISECONDS);
	Thread.sleep(1500);

	Mockito.verify(exporter, Mockito.atLeastOnce()).export();
}
 
示例26
/** Determine if meter is a Timer or not. */
public boolean meterIsTimer(Registry registry, Meter meter) {
  return idToTimer.computeIfAbsent(
      meter.id(),
      k -> {
        try {
          return registry.timers().anyMatch(m -> m.id().equals(meter.id()));
        } catch (ArrayIndexOutOfBoundsException aoex) {
          // !!! 20160929
          // !!! I dont know if this is a bug or what
          // !!! but the tests all get an array out of bounds calling stream()
          return meter instanceof Timer;
        }
      });
}
 
示例27
@Test
public void writeRegistryWithTimer() throws IOException {
  DefaultRegistry testRegistry = new DefaultRegistry(clock);
  Timer timer = testRegistry.timer(idAXY);
  timer.record(123, TimeUnit.MILLISECONDS);

  // If we get the expected result then we matched the expected descriptors,
  // which means the transforms occurred as expected.
  List<TimeSeries> tsList = writer.registryToTimeSeries(testRegistry);
  Assert.assertEquals(2, tsList.size());
}
 
示例28
private Meter convert(io.micrometer.core.instrument.Meter meter) {
  Id id = convert(meter.getId());
  if (meter instanceof io.micrometer.core.instrument.Counter) {
    return counter(id);
  } else if (meter instanceof io.micrometer.core.instrument.Timer) {
    return timer(id);
  } else if (meter instanceof io.micrometer.core.instrument.DistributionSummary) {
    return distributionSummary(id);
  } else if (meter instanceof io.micrometer.core.instrument.Gauge) {
    return gauge(id);
  } else {
    return null;
  }
}
 
示例29
@Test
public void timerRecord() {
  Timer t = registry.timer("foo");
  Assertions.assertEquals(0, t.count());
  Assertions.assertEquals(0, t.totalTime());
  t.record(42, TimeUnit.SECONDS);
  Assertions.assertEquals(1, t.count());
  Assertions.assertEquals(TimeUnit.SECONDS.toNanos(42), t.totalTime());
}
 
示例30
@Test
public void timerRecordRunnable() {
  Timer t = registry.timer("foo");
  t.record((Runnable) () -> clock.add(42, TimeUnit.SECONDS));
  Assertions.assertEquals(1, t.count());
  Assertions.assertEquals(TimeUnit.SECONDS.toNanos(42), t.totalTime());
}