com.netflix.spectator.api.Gauge Java Examples

The following examples show how to use com.netflix.spectator.api.Gauge. 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: EVCacheClientPool.java    From EVCache with Apache License 2.0 6 votes vote down vote up
private Gauge getStatsGauge(String metric, EVCacheClient client) {
    final String name = metric + client.getServerGroupName();
    Gauge gauge = gaugeMap.get(name );
    if(gauge != null) return gauge;

    final List<Tag> tags = new ArrayList<Tag>(4);
    EVCacheMetricsFactory.getInstance().addAppNameTags(tags, _appName);
    tags.add(new BasicTag(EVCacheMetricsFactory.STAT_NAME, metric));
    tags.add(new BasicTag(EVCacheMetricsFactory.CONNECTION_ID, String.valueOf(client.getId())));
    tags.add(new BasicTag(EVCacheMetricsFactory.SERVERGROUP, client.getServerGroupName()));

    final Id id = EVCacheMetricsFactory.getInstance().getId(EVCacheMetricsFactory.INTERNAL_STATS, tags);
    gauge = EVCacheMetricsFactory.getInstance().getRegistry().gauge(id);
    gaugeMap.put(name, gauge);
    return gauge;
}
 
Example #2
Source File: EVCacheClientPool.java    From EVCache with Apache License 2.0 6 votes vote down vote up
private Gauge getConfigGauge(String metric, ServerGroup serverGroup) {
    final String name = (serverGroup == null ? metric : metric + serverGroup.getName() + isInWriteOnly(serverGroup));
    Gauge gauge = gaugeMap.get(name );
    if(gauge != null) return gauge;

    final List<Tag> tags = new ArrayList<Tag>(5);
    EVCacheMetricsFactory.getInstance().addAppNameTags(tags, _appName);
    tags.add(new BasicTag(EVCacheMetricsFactory.CONFIG_NAME, metric));
    if(serverGroup != null) {
        tags.add(new BasicTag(EVCacheMetricsFactory.SERVERGROUP, serverGroup.getName()));
    }

    final Id id = EVCacheMetricsFactory.getInstance().getId(EVCacheMetricsFactory.INTERNAL_POOL_SG_CONFIG, tags);
    gauge = EVCacheMetricsFactory.getInstance().getRegistry().gauge(id);
    gaugeMap.put(name, gauge);
    return gauge;
}
 
Example #3
Source File: ConsolidatorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void maxRandom() {
  Id id = Id.create("test");
  Id measurementId = id.withTag("atlas.dstype", "gauge").withTag(Statistic.max);
  ManualClock clock = new ManualClock();

  Gauge primary = registry(clock, PRIMARY_STEP).maxGauge(id);
  Gauge consolidated = registry(clock, CONSOLIDATED_STEP).maxGauge(id);

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

  consolidateRandomData(
      measurementId,
      clock,
      consolidator,
      primary::set,
      consolidated::set,
      primary::measure,
      consolidated::measure);
}
 
Example #4
Source File: PolledMeter.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Poll by executing {@code f(obj)} and reporting the returned value. The provided
 * function must be thread safe and cheap to execute. Expensive operations, including
 * any IO or network calls, should not be performed inline unless using a custom
 * executor by calling {@link #scheduleOn(ScheduledExecutorService)}. Assume that the
 * function will be called frequently and may be called concurrently.
 *
 * <p>A weak reference will be kept to {@code obj} so that monitoring the object will
 * not prevent garbage collection. The meter will go away when {@code obj} is collected.
 * If {@code obj} is null, then it will be treated as an already collected object and a
 * warning will be logged.</p>
 *
 * <p>To explicitly disable polling call {@link #remove(Registry, Id)} with the same id used
 * with this builder.</p>
 *
 * @param obj
 *     Object used to compute a value.
 * @param f
 *     Function that is applied on the value for the number.
 * @return
 *     The object that was passed in so the registration can be done as part of an assignment
 *     statement.
 */
@SuppressWarnings("unchecked")
public <T> T monitorValue(T obj, ToDoubleFunction<T> f) {
  final Id id = baseId.withTags(extraTags);
  if (obj == null) {
    registry.propagate(new IllegalArgumentException(
        "obj is null for PolledMeter (id = " + id + "), no data will be reported. "
            + "See the API docs for monitorValue for guidance on how to fix the code."));
    return null;
  }
  final Gauge gauge = registry.gauge(id);
  final ValueState<T> tuple = new ValueState<>(gauge);

  ConcurrentMap<Id, Object> state = registry.state();
  Object c = Utils.computeIfAbsent(state, id, i -> tuple);
  if (!(c instanceof ValueState)) {
    Utils.propagateTypeError(registry, id, PolledMeter.class, c.getClass());
  } else {
    ValueState<T> t = (ValueState<T>) c;
    t.add(obj, f);
    t.schedule(registry, executor, delay);
  }

  return obj;
}
 
Example #5
Source File: JobAndTaskMetrics.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private void updateCapacityGroupCounters(Map<String, Map<String, Histogram.Builder>> capacityGroupsHistograms, Map<String, Tier> tierMap) {
    capacityGroupsHistograms.forEach((capacityGroup, histograms) -> {
        Id baseId = registry.createId(
                TASK_IN_STATE_METRIC_NAME,
                "tier", tierMap.get(capacityGroup).name(),
                "capacityGroup", capacityGroup
        );
        Map<String, List<Gauge>> capacityMetricsByState = capacityGroupsMetrics.computeIfAbsent(capacityGroup, k -> new HashMap<>());
        for (String state : TRACKED_STATES) {
            List<Gauge> updatedGauges = updateStateCounters(baseId, state, histograms.get(state), capacityMetricsByState.get(state));
            if (updatedGauges.isEmpty()) {
                capacityMetricsByState.remove(capacityGroup);
            } else {
                capacityMetricsByState.put(state, updatedGauges);
            }
        }
    });
}
 
Example #6
Source File: ThreadPoolMonitorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void currentThreadsBusyCountUpdates() throws InterruptedException {
  final Gauge gauge = getGauge(ThreadPoolMonitor.CURRENT_THREADS_BUSY);
  Assertions.assertEquals(0.0, gauge.value(), 1e-12);

  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.0, gauge.value(), 1e-12);

  terminator.countDown();
  latchedExecutor.getCompletedLatch().await(6, TimeUnit.SECONDS);
  PolledMeter.update(registry);
  Assertions.assertEquals(0.0, gauge.value(), 1e-12);
}
 
Example #7
Source File: ThreadPoolMonitorTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void poolSizeUpdates() throws InterruptedException {
  final Gauge gauge = getGauge(ThreadPoolMonitor.POOL_SIZE);
  Assertions.assertEquals(0.0, gauge.value(), 1e-12);

  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(2.0, gauge.value(), 1e-12);

  terminator1.countDown();
  terminator2.countDown();
}
 
Example #8
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 #9
Source File: DefaultPlaceholderGaugeTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncrement() {
  String[] tagValue = new String[] { "default" };
  Gauge g = factory.gauge(factory.createId("testIncrement",
      Collections.singleton(new TestTagFactory(tagValue))));
  Assertions.assertEquals(Double.NaN, g.value(), 1e-12);
  Assertions.assertEquals("testIncrement:tag=default", g.id().toString());
  g.set(1);
  Assertions.assertEquals(1.0, g.value(), 1e-12);
  g.set(3);
  Assertions.assertEquals(3.0, g.value(), 1e-12);

  tagValue[0] = "value2";
  Assertions.assertEquals("testIncrement:tag=value2", g.id().toString());
  g.set(1);
  Assertions.assertEquals(1.0, g.value(), 1e-12);

  tagValue[0] = "default";
  Assertions.assertEquals("testIncrement:tag=default", g.id().toString());
  g.set(4);
  Assertions.assertEquals(4.0, g.value(), 1e-12);
}
 
Example #10
Source File: MicrometerRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void maxGaugeSet() {
  Gauge g = registry.maxGauge("foo");
  Assertions.assertTrue(Double.isNaN(g.value()));
  g.set(42.0);
  g.set(20.0);
  clock.addSeconds(60);
  Assertions.assertEquals(42.0, g.value(), 1e-12);
}
 
Example #11
Source File: EVCacheInMemoryCache.java    From EVCache with Apache License 2.0 5 votes vote down vote up
private Gauge getGauge(String name) {
    Gauge gauge = gaugeMap.get(name);
    if(gauge != null) return gauge;

    final List<Tag> tags = new ArrayList<Tag>(3);
    tags.addAll(impl.getTags());
    tags.add(new BasicTag(EVCacheMetricsFactory.METRIC, name));

    final Id id = EVCacheMetricsFactory.getInstance().getId(EVCacheMetricsFactory.IN_MEMORY, tags);
    gauge = EVCacheMetricsFactory.getInstance().getRegistry().gauge(id);
    gaugeMap.put(name, gauge);
    return gauge;
}
 
Example #12
Source File: MicrometerRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void patternUsingState() {
  LongTaskTimer t = LongTaskTimer.get(registry, registry.createId("foo"));
  long tid = t.start();
  clock.addSeconds(60);
  PolledMeter.update(registry);

  Gauge g = registry.gauge(registry.createId("foo").withTag(Statistic.duration));
  Assertions.assertEquals(60.0, g.value(), 1e-12);

  t.stop(tid);
  PolledMeter.update(registry);
  Assertions.assertEquals(0.0, g.value(), 1e-12);
}
 
Example #13
Source File: ThreadPoolMonitorTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void maxThreadsUpdatesWhenRegistryIsUpdated() {
  final Gauge gauge = getGauge(ThreadPoolMonitor.MAX_THREADS);
  Assertions.assertEquals(10.0, gauge.value(), 1e-12);

  latchedExecutor.setMaximumPoolSize(42);
  PolledMeter.update(registry);
  Assertions.assertEquals(42.0, gauge.value(), 1e-12);
}
 
Example #14
Source File: ThreadPoolMonitorTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void corePoolSizeUpdatesWhenRegistryIsUpdated() {
  final Gauge gauge = getGauge(ThreadPoolMonitor.CORE_POOL_SIZE);
  Assertions.assertEquals(3.0, gauge.value(), 1e-12);

  // Must be <= 10 because that is the max pool size used in the test. Starting with
  // jdk9 the it will validate and fail if trying to set the pool size larger than
  // the max
  latchedExecutor.setCorePoolSize(7);

  PolledMeter.update(registry);
  Assertions.assertEquals(7.0, gauge.value(), 1e-12);
}
 
Example #15
Source File: DefaultPlaceholderGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncrementAmount() {
  String[] tagValue = new String[] { "default" };
  Gauge g = factory.gauge(factory.createId("testIncrementAmount",
      Collections.singleton(new TestTagFactory(tagValue))));

  g.set(42);
  Assertions.assertEquals(42.0, g.value(), 1e-12);

  tagValue[0] = "value2";
  g.set(54);
  Assertions.assertEquals(54.0, g.value(), 1e-12);
}
 
Example #16
Source File: DefaultPlaceholderGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testMeasure() {
  String[] tagValue = new String[] { "default" };
  Gauge g = factory.gauge(factory.createId("testMeasure",
      Collections.singleton(new TestTagFactory(tagValue))));

  doMeasurementTest(g, 42, 3712345L);
  tagValue[0] = "value2";
  doMeasurementTest(g, 54, 3712346L);
}
 
Example #17
Source File: DefaultPlaceholderGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
private void doMeasurementTest(Gauge g, int expectedValue, long expectedTime) {
  g.set(expectedValue);
  clock.setWallTime(expectedTime);
  List<Measurement> measurements = Utils.toList(g.measure());

  Assertions.assertEquals(1, measurements.size());

  Measurement m = measurements.get(0);
  Assertions.assertEquals(g.id(), m.id());
  Assertions.assertEquals(expectedTime, m.timestamp());
  Assertions.assertEquals(expectedValue, m.value(), 0.1e-12);
}
 
Example #18
Source File: DefaultPlaceholderGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testHasExpired() {
  String[] tagValue = new String[] { "default" };
  Gauge g = factory.gauge(factory.createId("testHasExpired",
      Collections.singleton(new TestTagFactory(tagValue))));

  Assertions.assertFalse(g.hasExpired());
}
 
Example #19
Source File: ServoGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testInit() {
  Gauge g = newGauge("foo");
  Assertions.assertEquals(g.value(), Double.NaN, 1e-12);
  g.set(1.0);
  Assertions.assertEquals(g.value(), 1.0, 1e-12);
}
 
Example #20
Source File: ServoGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testGet() {
  final ServoRegistry r = Servo.newRegistry(clock);
  Gauge g = r.gauge(r.createId("foo"));
  g.set(1.0);

  Assertions.assertEquals(1, r.getMonitors().size());
  Assertions.assertEquals(1.0, (Double) r.getMonitors().get(0).getValue(0), 1e-12);
}
 
Example #21
Source File: ServoGaugeTest.java    From spectator with Apache License 2.0 5 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);
  Gauge g = newGauge("foo");
  Assertions.assertFalse(g.hasExpired());
  g.set(42.0);
  Assertions.assertFalse(g.hasExpired());
  Assertions.assertEquals(g.value(), 42.0, 1e-12);

  // Expires with inactivity
  clock.setWallTime(initTime + fifteenMinutes);
  Assertions.assertFalse(g.hasExpired());

  // Expires with inactivity
  clock.setWallTime(initTime + fifteenMinutes + 1);
  Assertions.assertEquals(g.value(), Double.NaN, 1e-12);
  Assertions.assertTrue(g.hasExpired());

  // Activity brings it back
  g.set(1.0);
  Assertions.assertEquals(g.value(), 1.0, 1e-12);
  Assertions.assertFalse(g.hasExpired());
}
 
Example #22
Source File: ServoGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void hasGaugeType() {
  final ServoRegistry r = Servo.newRegistry(clock);
  Gauge g = r.gauge(r.createId("foo"));
  g.set(1.0);

  Map<String, String> tags = r.getMonitors().get(0).getConfig().getTags().asMap();
  Assertions.assertEquals("GAUGE", tags.get("type"));
}
 
Example #23
Source File: ServoGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void measure() {
  final ServoRegistry r = Servo.newRegistry(clock);
  Gauge g = r.gauge(r.createId("foo"));
  g.set(1.0);

  Iterator<Measurement> ms = g.measure().iterator();
  Assertions.assertTrue(ms.hasNext());
  Measurement m = ms.next();
  Assertions.assertFalse(ms.hasNext());
  Assertions.assertEquals("foo", m.id().name());
  Assertions.assertEquals(1.0, 1.0, 1e-12);
}
 
Example #24
Source File: ServoGaugeTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void hasStatistic() {
  List<Monitor<?>> ms = new ArrayList<>();
  Gauge g = newGauge("foo");
  ((ServoGauge) g).addMonitors(ms);
  Assertions.assertEquals(1, ms.size());
  Assertions.assertEquals("gauge", ms.get(0).getConfig().getTags().getValue("statistic"));
}
 
Example #25
Source File: MicrometerRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void gaugeMeasure() {
  Gauge g = registry.gauge("foo");
  g.set(42.0);
  int i = 0;
  for (Measurement m : g.measure()) {
    ++i;
    Assertions.assertEquals("foo", m.id().name());
    Assertions.assertEquals(42.0, m.value(), 1e-12);
  }
  Assertions.assertEquals(1, i);
}
 
Example #26
Source File: MultiDimensionalGauge.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private Gauge newGauge(List<String> tagValues) {
    List<Tag> tags = new ArrayList<>(dimension);
    for (int i = 0; i < dimension; i++) {
        tags.add(new BasicTag(discerningTagNames.get(i), tagValues.get(i)));
    }
    return registry.gauge(rootId.withTags(tags));
}
 
Example #27
Source File: JobAndTaskMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private List<Gauge> updateStateCounters(Id baseId, String state, Histogram.Builder histogramBuilder, List<Gauge> gauges) {
    if (histogramBuilder == null) {
        // Nothing running for this state, reset gauges
        if (gauges != null) {
            gauges.forEach(g -> g.set(0));
        }
        return Collections.emptyList();
    }

    List<Long> counters = histogramBuilder.build().getCounters();

    // First time we have data for this capacity group.
    if (gauges == null) {
        Id id = baseId.withTag("state", state);
        List<Long> valueBounds = HISTOGRAM_DESCRIPTOR.getValueBounds();
        List<Gauge> newGauges = new ArrayList<>();
        for (int i = 0; i <= valueBounds.size(); i++) {
            Gauge newGauge;
            if (i < valueBounds.size()) {
                long delayMs = valueBounds.get(i);
                newGauge = registry.gauge(id.withTag("delay", DateTimeExt.toTimeUnitString(delayMs)));
            } else {
                newGauge = registry.gauge(id.withTag("delay", "Unlimited"));
            }
            newGauge.set(counters.get(i));
            newGauges.add(newGauge);
        }
        return newGauges;
    }

    // Update gauges
    for (int i = 0; i < counters.size(); i++) {
        gauges.get(i).set(counters.get(i));
    }

    return gauges;
}
 
Example #28
Source File: MetricsRegistry.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Override protected Gauge newGauge(Id id) {
  final String name = toMetricName(id);
  DoubleGauge gauge = registeredGauges.computeIfAbsent(name, n -> {
    DoubleGauge g = new DoubleGauge();
    impl.register(name, g);
    return g;
  });
  return new MetricsGauge(clock(), id, gauge);
}
 
Example #29
Source File: MetricsRegistry.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Override protected Gauge newMaxGauge(Id id) {
  final String name = toMetricName(id);
  DoubleGauge gauge = registeredGauges.computeIfAbsent(name, n -> {
    DoubleMaxGauge g = new DoubleMaxGauge();
    impl.register(name, g);
    return g;
  });
  return new MetricsGauge(clock(), id, gauge);
}
 
Example #30
Source File: MicrometerRegistry.java    From spectator with Apache License 2.0 5 votes vote down vote up
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;
  }
}