com.netflix.spectator.api.Counter Java Examples

The following examples show how to use com.netflix.spectator.api.Counter. 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: MonotonicCounterTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void usingAtomicLong() {
  AtomicLong count = new AtomicLong();
  AtomicLong c = PolledMeter.using(registry).withId(id).monitorMonotonicCounter(count);
  Assertions.assertSame(count, c);

  Counter counter = registry.counter(id);
  update();
  Assertions.assertEquals(0L, counter.count());

  c.incrementAndGet();
  update();
  Assertions.assertEquals(1L, counter.count());

  c.addAndGet(42);
  update();
  Assertions.assertEquals(43L, counter.count());
}
 
Example #2
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 #3
Source File: ConsolidatorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void avgRandom() {
  Id id = Id.create("test");
  Id measurementId = id.withTag("atlas.dstype", "rate").withTag(Statistic.count);
  ManualClock clock = new ManualClock();

  Counter primary = registry(clock, PRIMARY_STEP).counter(id);
  Counter consolidated = registry(clock, CONSOLIDATED_STEP).counter(id);

  Consolidator consolidator = new Consolidator.Avg(CONSOLIDATED_STEP, MULTIPLE);

  consolidateRandomData(
      measurementId,
      clock,
      consolidator,
      primary::add,
      consolidated::add,
      primary::measure,
      consolidated::measure);
}
 
Example #4
Source File: ConsolidatorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void noneRandom() {
  Id id = Id.create("test");
  Id measurementId = id.withTag("atlas.dstype", "rate").withTag(Statistic.count);
  ManualClock clock = new ManualClock();

  Counter primary = registry(clock, CONSOLIDATED_STEP).counter(id);
  Counter consolidated = registry(clock, CONSOLIDATED_STEP).counter(id);

  Consolidator consolidator = new Consolidator.None();

  consolidateRandomData(
      measurementId,
      clock,
      consolidator,
      primary::add,
      consolidated::add,
      primary::measure,
      consolidated::measure);
}
 
Example #5
Source File: SchedulerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void updateNextFixedDelay() {
  ManualClock clock = new ManualClock();
  Registry registry = new DefaultRegistry(clock);
  Counter skipped = registry.counter("skipped");

  Scheduler.Options options = new Scheduler.Options()
      .withFrequency(Scheduler.Policy.FIXED_DELAY, Duration.ofSeconds(10));

  clock.setWallTime(5437L);
  Scheduler.DelayedTask task = new Scheduler.DelayedTask(clock, options, () -> {});
  Assertions.assertEquals(5437L, task.getNextExecutionTime());
  Assertions.assertEquals(0L, skipped.count());

  clock.setWallTime(12123L);
  task.updateNextExecutionTime(skipped);
  Assertions.assertEquals(22123L, task.getNextExecutionTime());
  Assertions.assertEquals(0L, skipped.count());

  clock.setWallTime(27000L);
  task.updateNextExecutionTime(skipped);
  Assertions.assertEquals(37000L, task.getNextExecutionTime());
  Assertions.assertEquals(0L, skipped.count());
}
 
Example #6
Source File: DefaultPlaceholderCounterTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncrement() {
  String[] tagValue = new String[] { "default" };
  Counter c = factory.counter(factory.createId("testIncrement",
          Collections.singleton(new TestTagFactory(tagValue))));
  Assertions.assertEquals(0L, c.count());
  Assertions.assertEquals("testIncrement:tag=default", c.id().toString());
  c.increment();
  Assertions.assertEquals(1L, c.count());
  c.increment();
  c.increment();
  Assertions.assertEquals(3L, c.count());

  tagValue[0] = "value2";
  Assertions.assertEquals("testIncrement:tag=value2", c.id().toString());
  c.increment();
  Assertions.assertEquals(1L, c.count());

  tagValue[0] = "default";
  Assertions.assertEquals("testIncrement:tag=default", c.id().toString());
  c.increment();
  Assertions.assertEquals(4L, c.count());
}
 
Example #7
Source File: ThreadPoolMonitorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void taskCountUpdates() throws InterruptedException {
  final Counter counter = getCounter(ThreadPoolMonitor.TASK_COUNT);
  Assertions.assertEquals(0, counter.count());

  final CountDownLatch synchronizer = new CountDownLatch(1);
  final CountDownLatch terminator = new CountDownLatch(1);
  final TestRunnable command = new TestRunnable(synchronizer, terminator);

  latchedExecutor.execute(command);

  synchronizer.await(6, TimeUnit.SECONDS);
  PolledMeter.update(registry);
  Assertions.assertEquals(1, counter.count(), 1e-12);
  terminator.countDown();
}
 
Example #8
Source File: StackdriverWriterTest.java    From kork with Apache License 2.0 6 votes vote down vote up
@Test
public void writeRegistryWithSmallRegistry() throws IOException {
  TestableStackdriverWriter spy = spy(new TestableStackdriverWriter(writerConfig.build()));
  Monitoring.Projects.TimeSeries.Create mockCreateMethod =
      Mockito.mock(Monitoring.Projects.TimeSeries.Create.class);

  DefaultRegistry registry = new DefaultRegistry(clock);
  Counter counterA = registry.counter(idAXY);
  Counter counterB = registry.counter(idBXY);
  counterA.increment(4);
  counterB.increment(10);

  when(timeseriesApi.create(eq("projects/test-project"), any(CreateTimeSeriesRequest.class)))
      .thenReturn(mockCreateMethod);
  when(mockCreateMethod.execute()).thenReturn(null);

  spy.writeRegistry(registry);
  verify(mockCreateMethod, times(1)).execute();

  ArgumentCaptor<CreateTimeSeriesRequest> captor =
      ArgumentCaptor.forClass(CreateTimeSeriesRequest.class);
  verify(timeseriesApi, times(1)).create(eq("projects/test-project"), captor.capture());
  // A, B, timer count and totalTime.
  Assert.assertEquals(4, captor.getValue().getTimeSeries().size());
}
 
Example #9
Source File: MetricDescriptorCache.java    From kork with Apache License 2.0 6 votes vote down vote up
/** Convert a Spectator Meter type into a Stackdriver Metric kind. */
public String meterToKind(Registry registry, Meter meter) {
  if (meter instanceof Counter) {
    return "CUMULATIVE";
  }

  if (registry.counters().anyMatch(m -> m.id().equals(meter.id()))) {
    return "CUMULATIVE";
  }

  if (meterIsTimer(registry, meter)) {
    return "CUMULATIVE";
  }

  return "GAUGE";
}
 
Example #10
Source File: SpectatorAppenderTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void properties() {
  Spectator.globalRegistry().add(registry);

  Properties props = new Properties();
  props.setProperty("log4j.rootLogger", "ALL, A1");
  props.setProperty("log4j.appender.A1", "com.netflix.spectator.log4j.SpectatorAppender");
  PropertyConfigurator.configure(props);

  Counter c = registry.counter("log4j.numStackTraces",
      "loglevel", "5_DEBUG",
      "exception", "IllegalArgumentException",
      "file", "SpectatorAppenderTest.java");
  Assertions.assertEquals(0, c.count());
  Exception e = new IllegalArgumentException("foo");
  e.fillInStackTrace();
  Logger.getLogger(getClass()).debug("foo", e);

  Assertions.assertEquals(1, c.count());
}
 
Example #11
Source File: ServoCounterTest.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);
  Counter c = newCounter("foo");
  Assertions.assertFalse(c.hasExpired());
  c.increment(42);
  Assertions.assertFalse(c.hasExpired());

  // Expires with inactivity, total count in memory is maintained
  clock.setWallTime(initTime + fifteenMinutes);
  Assertions.assertFalse(c.hasExpired());

  // Expires with inactivity, total count in memory is maintained
  clock.setWallTime(initTime + fifteenMinutes + 1);
  Assertions.assertEquals(c.count(), 42);
  Assertions.assertTrue(c.hasExpired());

  // Activity brings it back
  c.increment();
  Assertions.assertEquals(c.count(), 43);
  Assertions.assertFalse(c.hasExpired());
}
 
Example #12
Source File: MonotonicCounterTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void nonMonotonicUpdates() {
  AtomicLong count = new AtomicLong();
  AtomicLong c = PolledMeter.using(registry).withId(id).monitorMonotonicCounter(count);

  Counter counter = registry.counter(id);
  update();
  Assertions.assertEquals(0L, counter.count());

  c.set(42L);
  update();
  Assertions.assertEquals(42L, counter.count());

  // Should not update the counter because it is lower, but must update
  // the previous recorded value
  c.set(21L);
  update();
  Assertions.assertEquals(42L, counter.count());

  // Make sure a subsequent increase is detected
  c.set(23L);
  update();
  Assertions.assertEquals(44L, counter.count());
}
 
Example #13
Source File: ServoRegistryTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void resurrectExpiredAndIncrement() {
  ManualClock clock = new ManualClock();
  ServoRegistry registry = Servo.newRegistry(clock);
  Counter c = registry.counter("test");

  clock.setWallTime(60000 * 30);
  registry.getMonitors();

  Assertions.assertTrue(c.hasExpired());

  c.increment();
  Assertions.assertEquals(1, c.count());
  Assertions.assertEquals(1, registry.counter("test").count());

  clock.setWallTime(60000 * 60);
  registry.getMonitors();

  Assertions.assertTrue(c.hasExpired());

  c.increment();
  Assertions.assertEquals(1, c.count());
  Assertions.assertEquals(1, registry.counter("test").count());
}
 
Example #14
Source File: MonotonicCounterTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void usingLongAdder() {
  LongAdder count = new LongAdder();
  LongAdder c = PolledMeter.using(registry).withId(id).monitorMonotonicCounter(count);
  Assertions.assertSame(count, c);

  Counter counter = registry.counter(id);
  update();
  Assertions.assertEquals(0L, counter.count());

  c.increment();
  update();
  Assertions.assertEquals(1L, counter.count());

  c.add(42);
  update();
  Assertions.assertEquals(43L, counter.count());
}
 
Example #15
Source File: Scheduler.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Update the next execution time based on the options for this task.
 *
 * @param skipped
 *     Counter that will be incremented each time an expected execution is
 *     skipped when using {@link Policy#FIXED_RATE_SKIP_IF_LONG}.
 */
void updateNextExecutionTime(Counter skipped) {
  switch (options.schedulingPolicy) {
    case FIXED_DELAY:
      nextExecutionTime = clock.wallTime() + options.frequencyMillis;
      break;
    case FIXED_RATE_SKIP_IF_LONG:
      final long now = clock.wallTime();
      nextExecutionTime += options.frequencyMillis;
      while (nextExecutionTime < now) {
        nextExecutionTime += options.frequencyMillis;
        skipped.increment();
      }
      break;
    default:
      break;
  }
}
 
Example #16
Source File: ActionMetrics.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public void failure(long startTime, Throwable error) {
    lastCompletionRef.set(registry.clock().wallTime());
    if (startTime >= 0) {
        latencyTimerOnError.record(registry.clock().wallTime() - startTime, TimeUnit.MILLISECONDS);
    }

    Counter exceptionCounter = exceptionCounters.get(error.getClass());
    if (exceptionCounter == null) {
        Id errorId = registry.createId(root, commonTags)
                .withTag("status", "failure")
                .withTag("exception", error.getClass().getSimpleName());
        exceptionCounter = registry.counter(errorId);
        exceptionCounters.put(error.getClass(), exceptionCounter);
    }
    exceptionCounter.increment();
}
 
Example #17
Source File: SpectatorAppenderTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void numStackTraces() {
  Counter c = registry.counter("log4j.numStackTraces",
      "loglevel", "5_DEBUG",
      "exception", "IllegalArgumentException",
      "file", "?"); // Location is unknown because it is not called via logger
  Assertions.assertEquals(0, c.count());
  Exception e = new IllegalArgumentException("foo");
  e.fillInStackTrace();
  appender.append(newEvent(Level.DEBUG, e));
  Assertions.assertEquals(1, c.count());
}
 
Example #18
Source File: IntervalCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReusesInstance() {
  Registry r = new DefaultRegistry(clock);
  Id id = r.createId("test");
  Counter c1 = IntervalCounter.get(r, id);
  Counter c2 = IntervalCounter.get(r, id);
  Assertions.assertSame(c1, c2);
}
 
Example #19
Source File: SpectatorAppenderTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void numMessagesDEBUG() {
  Counter c = registry.counter("log4j.numMessages", "loglevel", "5_DEBUG");
  Assertions.assertEquals(0, c.count());
  appender.append(newEvent(Level.DEBUG, null));
  Assertions.assertEquals(1, c.count());
}
 
Example #20
Source File: ServoCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void hasStatistic() {
  List<Monitor<?>> ms = new ArrayList<>();
  Counter c = newCounter("foo");
  ((ServoCounter) c).addMonitors(ms);
  Assertions.assertEquals(1, ms.size());
  Assertions.assertEquals("count", ms.get(0).getConfig().getTags().getValue("statistic"));
}
 
Example #21
Source File: ServoCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testInit() {
  Counter c = newCounter("foo");
  Assertions.assertEquals(c.count(), 0L);
  c.increment();
  Assertions.assertEquals(c.count(), 1L);
}
 
Example #22
Source File: DefaultPlaceholderCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testHasExpired() {
  String[] tagValue = new String[] { "default" };
  Counter c = factory.counter(factory.createId("testHasExpired",
          Collections.singleton(new TestTagFactory(tagValue))));

  Assertions.assertFalse(c.hasExpired());
}
 
Example #23
Source File: ServoRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void iteratorDoesNotContainNullMeters() {
  Registry dflt = Servo.newRegistry();

  boolean found = false;
  Counter counter = dflt.counter("servo.testCounter");
  for (Meter m : dflt) {
    found = m.id().equals(counter.id());
  }
  Assertions.assertTrue(found, "id could not be found in iterator");
}
 
Example #24
Source File: MetricsControllerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeSimpleRegistry() {
  DefaultRegistry registry = new DefaultRegistry(clock);
  Counter counterA = registry.counter(idAXY);
  Counter counterB = registry.counter(idBXY);
  counterA.increment(4);
  counterB.increment(10);

  List<TaggedDataPoints> expectedTaggedDataPointsA
    = Arrays.asList(
        new TaggedDataPoints(
            Arrays.asList(new BasicTag("tagA", "X"),
                          new BasicTag("tagB", "Y")),
            Arrays.asList(new DataPoint(clock.wallTime(), 4))));

  List<TaggedDataPoints> expectedTaggedDataPointsB
    = Arrays.asList(
        new TaggedDataPoints(
            Arrays.asList(new BasicTag("tagA", "X"),
                          new BasicTag("tagB", "Y")),
            Arrays.asList(new DataPoint(clock.wallTime(), 10))));

  HashMap<String, MetricValues> expect = new HashMap<>();
  expect.put("idA", new MetricValues("Counter", expectedTaggedDataPointsA));
  expect.put("idB", new MetricValues("Counter", expectedTaggedDataPointsB));
  Assertions.assertEquals(expect, controller.encodeRegistry(registry, allowAll));
}
 
Example #25
Source File: SpectatorAppenderTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void numStackTraces() {
  Counter c = registry.counter("log4j.numStackTraces",
      "appender", "foo",
      "loglevel", "5_DEBUG",
      "exception", "IllegalArgumentException",
      "file", "SpectatorAppenderTest.java");
  Assertions.assertEquals(0, c.count());
  appender.append(newEvent(Level.DEBUG, new IllegalArgumentException("foo")));
  Assertions.assertEquals(1, c.count());
}
 
Example #26
Source File: SchedulerTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void updateNextFixedRateSkip() {
  ManualClock clock = new ManualClock();
  Registry registry = new DefaultRegistry(clock);
  Counter skipped = registry.counter("skipped");

  Scheduler.Options options = new Scheduler.Options()
      .withFrequency(Scheduler.Policy.FIXED_RATE_SKIP_IF_LONG, Duration.ofSeconds(10));

  clock.setWallTime(5437L);
  Scheduler.DelayedTask task = new Scheduler.DelayedTask(clock, options, () -> {});
  Assertions.assertEquals(5437L, task.getNextExecutionTime());
  Assertions.assertEquals(0L, skipped.count());

  clock.setWallTime(12123L);
  task.updateNextExecutionTime(skipped);
  Assertions.assertEquals(15437L, task.getNextExecutionTime());
  Assertions.assertEquals(0L, skipped.count());

  clock.setWallTime(27000L);
  task.updateNextExecutionTime(skipped);
  Assertions.assertEquals(35437L, task.getNextExecutionTime());
  Assertions.assertEquals(1L, skipped.count());

  clock.setWallTime(57000L);
  task.updateNextExecutionTime(skipped);
  Assertions.assertEquals(65437L, task.getNextExecutionTime());
  Assertions.assertEquals(3L, skipped.count());
}
 
Example #27
Source File: ThreadPoolMonitorTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void completedTaskCountUpdates() throws InterruptedException {
  final Counter counter = getCounter(ThreadPoolMonitor.COMPLETED_TASK_COUNT);
  Assertions.assertEquals(0, counter.count());

  final CountDownLatch synchronizer = new CountDownLatch(2);
  final CountDownLatch terminator1 = new CountDownLatch(1);
  final CountDownLatch terminator2 = new CountDownLatch(1);
  final TestRunnable command1 = new TestRunnable(synchronizer, terminator1);
  final TestRunnable command2 = new TestRunnable(synchronizer, terminator2);

  latchedExecutor.execute(command1);
  latchedExecutor.execute(command2);

  synchronizer.await(6, TimeUnit.SECONDS);
  PolledMeter.update(registry);
  Assertions.assertEquals(0, counter.count());

  terminator1.countDown();
  latchedExecutor.getCompletedLatch().await(6, TimeUnit.SECONDS);
  PolledMeter.update(registry);
  Assertions.assertEquals(1, counter.count(), 1e-12);

  latchedExecutor.setCompletedLatch(new CountDownLatch(1));
  terminator2.countDown();
  latchedExecutor.getCompletedLatch().await(6, TimeUnit.SECONDS);
  PolledMeter.update(registry);
  Assertions.assertEquals(2, counter.count());
}
 
Example #28
Source File: IntervalCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncrement() {
  Registry r = new DefaultRegistry(clock);
  Id id = r.createId("test");
  Counter c = IntervalCounter.get(r, id);
  Assertions.assertEquals(0, c.count());
  c.increment();
  Assertions.assertEquals(1, c.count());
  c.increment(41);
  Assertions.assertEquals(42, c.count());
}
 
Example #29
Source File: IntervalCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testMeasure() {
  Registry r = new DefaultRegistry(clock);
  clock.setWallTime(61000L);
  Id id = r.createId("test");
  Counter c = IntervalCounter.get(r, id);

  // all meters should have the correct timestamp
  r.stream().forEach(meter -> {
    for (Measurement m : meter.measure()) {
      Assertions.assertEquals(m.timestamp(), 61000L);
    }
  });

  final List<Measurement> measurements = getAllMeasurements(r);
  final double initAge = Utils.first(measurements, Statistic.duration).value();
  final double initCount = Utils.first(measurements, Statistic.count).value();
  Assertions.assertEquals(61.0, initAge, EPSILON);
  Assertions.assertEquals(0.0, initCount, EPSILON);

  clock.setWallTime(120000L);
  c.increment();
  final List<Measurement> afterMeasurements = getAllMeasurements(r);
  final double afterAge = Utils.first(afterMeasurements, Statistic.duration).value();
  final double afterCount = Utils.first(afterMeasurements, Statistic.count).value();
  Assertions.assertEquals(0.0, afterAge, EPSILON);
  Assertions.assertEquals(1.0, afterCount, EPSILON);
}
 
Example #30
Source File: ThreadPoolMonitorTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void threadPoolMonitorHasRejectedExecutionsCounter() {
  ThreadPoolMonitor.attach(registry, latchedExecutor, THREAD_POOL_NAME);
  latchedExecutor.shutdown();
  int rejected = 0;
  try {
    latchedExecutor.submit(() -> {});
  } catch (RejectedExecutionException e) {
    e.printStackTrace();
    ++rejected;
  }
  Counter c = registry.counter(ThreadPoolMonitor.REJECTED_TASK_COUNT, "id", THREAD_POOL_NAME);
  Assertions.assertNotNull(c);
  Assertions.assertEquals(rejected, c.count());
}