com.netflix.spectator.api.Clock Java Examples

The following examples show how to use com.netflix.spectator.api.Clock. 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: GcsStorageService.java    From front50 with Apache License 2.0 6 votes vote down vote up
private <T> T timeExecute(Id timerId, AbstractGoogleClientRequest<T> request) throws IOException {
  T result;
  Clock clock = registry.clock();
  long startTime = clock.monotonicTime();
  int statusCode = -1;

  try {
    result = request.execute();
    statusCode = request.getLastStatusCode();
  } catch (HttpResponseException e) {
    statusCode = e.getStatusCode();
    throw e;
  } catch (IOException ioex) {
    throw ioex;
  } catch (Exception ex) {
    throw new IllegalStateException(ex);
  } finally {
    long nanos = clock.monotonicTime() - startTime;
    String status = Integer.toString(statusCode).charAt(0) + "xx";

    Id id = timerId.withTags("status", status, "statusCode", Integer.toString(statusCode));
    registry.timer(id).record(nanos, TimeUnit.NANOSECONDS);
  }
  return result;
}
 
Example #2
Source File: SpectatorModuleTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void injectedRegistryAddedToGlobal() {
  final ManualClock clock = new ManualClock();
  Injector injector = Guice.createInjector(
      new AbstractModule() {
        @Override protected void configure() {
          OptionalBinder.newOptionalBinder(binder(), Clock.class)
              .setBinding()
              .toInstance(clock);
        }
      },
      new SpectatorModule());
  Registry registry = injector.getInstance(Registry.class);
  Spectator.globalRegistry().counter("test").increment();
  clock.setWallTime(5000);
  Assertions.assertEquals(1, registry.counter("test").count());
}
 
Example #3
Source File: SpectatorModule.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Override protected void configure() {
  // Servo is all based on static classes. The context for servo needs to be set as early
  // as possible to avoid missing metrics because the context has not yet been set.
  SpectatorContext.setRegistry(Spectator.globalRegistry());
  bind(Plugin.class).asEagerSingleton();
  bind(StaticManager.class).asEagerSingleton();
  bind(Config.class)
      .annotatedWith(Names.named("spectator"))
      .toProvider(ConfigProvider.class);
  bind(AtlasConfig.class).to(AtlasConfiguration.class);
  OptionalBinder.newOptionalBinder(binder(), ExtendedRegistry.class)
      .setDefault()
      .toInstance(Spectator.registry());
  OptionalBinder.newOptionalBinder(binder(), Clock.class)
      .setDefault()
      .toInstance(Clock.SYSTEM);
  OptionalBinder.newOptionalBinder(binder(), Registry.class)
      .setDefault()
      .to(AtlasRegistry.class)
      .in(Scopes.SINGLETON);
}
 
Example #4
Source File: SparkSink.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance. Spark looks for a constructor with all three parameters, so the
 * {@code SecurityManager} needs to be in the signature even though it isn't used.
 */
@SuppressWarnings("PMD.UnusedFormalParameter")
public SparkSink(
    Properties properties,
    MetricRegistry registry,
    org.apache.spark.SecurityManager manager) throws MalformedURLException {
  final Config config = loadConfig();
  statelessRegistry = new StatelessRegistry(
      Clock.SYSTEM, new SpectatorConfig(config.getConfig("spectator.spark.stateless")));
  reporter = SpectatorReporter.forRegistry(registry)
      .withSpectatorRegistry(statelessRegistry)
      .withNameFunction(SparkNameFunction.fromConfig(config, statelessRegistry))
      .withValueFunction(SparkValueFunction.fromConfig(config))
      .withGaugeCounters(Pattern.compile(config.getString("spectator.spark.gauge-counters")))
      .build();
  pollPeriod = getPeriod(properties);
  pollUnit = getUnit(properties);

  // If there is a need to collect application metrics from jobs running on Spark, then
  // this should be enabled. The apps can report to the global registry and it will get
  // picked up by the Spark integration.
  if (shouldAddToGlobal(properties)) {
    Spectator.globalRegistry().add(statelessRegistry);
  }
}
 
Example #5
Source File: DoubleDistributionSummary.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance.
 */
DoubleDistributionSummary(Clock clock, Id id, long resetFreq) {
  this.clock = clock;
  this.id = id;
  this.resetFreq = resetFreq;
  lastResetTime = new AtomicLong(clock.wallTime());
  lastUpdateTime = new AtomicLong(clock.wallTime());
  count = new AtomicLong(0L);
  totalAmount = new AtomicLong(ZERO);
  totalOfSquares = new AtomicLong(ZERO);
  max = new AtomicLong(ZERO);
  countId = id.withTag(Statistic.count);
  totalAmountId = id.withTag(Statistic.totalAmount);
  totalOfSquaresId = id.withTag(Statistic.totalOfSquares);
  maxId = id.withTag(Statistic.max);
}
 
Example #6
Source File: TestMetricsRestPublisher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void measure_normal() {
  Clock clock = new ManualClock();
  GlobalRegistry globalRegistry = new GlobalRegistry();
  Registry registry = new DefaultRegistry(clock);
  registry.timer(registry.createId("name", "t1", "v1", "t2", "v2"));
  globalRegistry.add(registry);

  EventBus eventBus = new EventBus();

  publisher.init(globalRegistry, eventBus, new MetricsBootstrapConfig());
  Map<String, Double> result = publisher.measure();

  Assert.assertEquals(2, result.size());
  Assert.assertEquals(0, result.get("name(statistic=count,t1=v1,t2=v2)"), 0);
  Assert.assertEquals(0, result.get("name(statistic=totalTime,t1=v1,t2=v2)"), 0);
}
 
Example #7
Source File: CardinalityLimiters.java    From spectator with Apache License 2.0 5 votes vote down vote up
MostFrequentLimiter(int n, Clock clock) {
  this.n = n;
  this.clock = clock;
  this.limiter = first(n);
  this.limiterTimestamp = clock.wallTime();
  this.cutoff = 0L;
  this.updatesWithHighChurn = 0;
}
 
Example #8
Source File: MicrometerMeter.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Helper for converting Micrometer measurements to Spectator measurements. */
Iterable<Measurement> convert(Iterable<io.micrometer.core.instrument.Measurement> ms) {
  long now = Clock.SYSTEM.wallTime();
  List<Measurement> measurements = new ArrayList<>();
  for (io.micrometer.core.instrument.Measurement m : ms) {
    Id measurementId = id.withTag("statistic", m.getStatistic().getTagValueRepresentation());
    measurements.add(new Measurement(measurementId, now, m.getValue()));
  }
  return measurements;
}
 
Example #9
Source File: IpcLogger.java    From spectator with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance. Allows the clock to be explicitly set for unit tests.
 */
IpcLogger(Registry registry, Clock clock, Logger logger) {
  this.registry = registry;
  this.clock = clock;
  this.logger = logger;
  this.inflightRequests = new ConcurrentHashMap<>();
  this.limiters = new ConcurrentHashMap<>();
  this.entries = new LinkedBlockingQueue<>(1000);
}
 
Example #10
Source File: ConsolidatorTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
private AtlasRegistry registry(Clock clock, long step) {
  Map<String, String> config = new HashMap<>();
  config.put("atlas.meterTTL", Duration.ofMillis(TTL).toString());
  config.put("atlas.step", Duration.ofMillis(step).toString());
  config.put("atlas.lwc.step", Duration.ofMillis(step).toString());
  return new AtlasRegistry(clock, config::get);
}
 
Example #11
Source File: AtlasRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void shutdownWithoutStarting() {
  AtlasRegistry r = new AtlasRegistry(
      Clock.SYSTEM,
      k -> k.equals("atlas.enabled") ? "true" : null);
  r.close();
}
 
Example #12
Source File: AtlasConfig.java    From spectator with Apache License 2.0 5 votes vote down vote up
/**
 * Avoid collecting right on boundaries to minimize transitions on step longs
 * during a collection. By default it will randomly distribute across the middle
 * of the step interval.
 */
default long initialPollingDelay(Clock clock, long stepSize) {
  long now = clock.wallTime();
  long stepBoundary = now / stepSize * stepSize;

  // Buffer by 10% of the step interval on either side
  long offset = stepSize / 10;

  // For larger intervals spread it out, otherwise bias towards the start
  // to ensure there is plenty of time to send without needing to cross over
  // to the next interval. The threshold of 1s was chosen because it is typically
  // big enough to avoid GC troubles where it is common to see pause times in the
  // low 100s of milliseconds.
  if (offset >= 1000L) {
    // Check if the current delay is within the acceptable range
    long delay = now - stepBoundary;
    if (delay < offset) {
      return delay + offset;
    } else {
      return Math.min(delay, stepSize - offset);
    }
  } else {
    long firstTime = stepBoundary + stepSize / 10;
    return firstTime > now
        ? firstTime - now
        : firstTime + stepSize - now;
  }
}
 
Example #13
Source File: AtlasCounter.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
AtlasCounter(Registry registry, Id id, Clock clock, long ttl, long step) {
  super(id, clock, ttl);
  this.value = new StepDouble(0.0, clock, step);
  // Add the statistic for typing. Re-adding the tags from the id is to retain
  // the statistic from the id if it was already set
  this.stat = registry.createId(id.name())
      .withTag(Statistic.count)
      .withTag(DsType.rate)
      .withTags(id.tags());
}
 
Example #14
Source File: AtlasGauge.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
AtlasGauge(Registry registry, Id id, Clock clock, long ttl) {
  super(id, clock, ttl);
  this.value = new AtomicDouble(0.0);
  // Add the statistic for typing. Re-adding the tags from the id is to retain
  // the statistic from the id if it was already set
  this.stat = registry.createId(id.name())
      .withTag(Statistic.gauge)
      .withTag(DsType.gauge)
      .withTags(id.tags());
}
 
Example #15
Source File: MetricsTimer.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
MetricsTimer(Clock clock, Id id, com.codahale.metrics.Timer impl) {
  super(clock);
  this.id = id;
  this.impl = impl;
  this.totalTime = new AtomicLong(0L);
}
 
Example #16
Source File: StatelessRegistry.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
public StatelessRegistry(Clock clock, StatelessConfig config) {
  super(clock, config);
  this.enabled = config.enabled();
  this.frequency = config.frequency();
  this.meterTTL = config.meterTTL().toMillis();
  this.connectTimeout = (int) config.connectTimeout().toMillis();
  this.readTimeout = (int) config.readTimeout().toMillis();
  this.uri = URI.create(config.uri());
  this.batchSize = config.batchSize();
  this.commonTags = config.commonTags();
  this.client = HttpClient.create(this);
}
 
Example #17
Source File: AtlasTimer.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
AtlasTimer(Id id, Clock clock, long ttl, long step) {
  super(id, clock, ttl);
  this.count = new StepLong(0L, clock, step);
  this.total = new StepDouble(0.0, clock, step);
  this.totalOfSquares = new StepDouble(0.0, clock, step);
  this.max = new StepLong(0L, clock, step);
  this.stats = new Id[] {
      id.withTags(DsType.rate,  Statistic.count),
      id.withTags(DsType.rate,  Statistic.totalTime),
      id.withTags(DsType.rate,  Statistic.totalOfSquares),
      id.withTags(DsType.gauge, Statistic.max)
  };
}
 
Example #18
Source File: PercentileTimer.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Override public <T> T record(Callable<T> rf) throws Exception {
  final Clock clock = registry.clock();
  final long s = clock.monotonicTime();
  try {
    return rf.call();
  } finally {
    final long e = clock.monotonicTime();
    record(e - s, TimeUnit.NANOSECONDS);
  }
}
 
Example #19
Source File: PercentileTimer.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Override public void record(Runnable rf) {
  final Clock clock = registry.clock();
  final long s = clock.monotonicTime();
  try {
    rf.run();
  } finally {
    final long e = clock.monotonicTime();
    record(e - s, TimeUnit.NANOSECONDS);
  }
}
 
Example #20
Source File: BucketTimer.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Override public <T> T record(Callable<T> rf) throws Exception {
  final Clock clock = registry.clock();
  final long s = clock.monotonicTime();
  try {
    return rf.call();
  } finally {
    final long e = clock.monotonicTime();
    record(e - s, TimeUnit.NANOSECONDS);
  }
}
 
Example #21
Source File: BucketTimer.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Override public void record(Runnable rf) {
  final Clock clock = registry.clock();
  final long s = clock.monotonicTime();
  try {
    rf.run();
  } finally {
    final long e = clock.monotonicTime();
    record(e - s, TimeUnit.NANOSECONDS);
  }
}
 
Example #22
Source File: StepDouble.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
public StepDouble(double init, Clock clock, long step) {
  this.init = init;
  this.clock = clock;
  this.step = step;
  previous = init;
  current = new AtomicDouble(init);
  lastInitPos = new AtomicLong(clock.wallTime() / step);
}
 
Example #23
Source File: StepLong.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
public StepLong(long init, Clock clock, long step) {
  this.init = init;
  this.clock = clock;
  this.step = step;
  previous = init;
  current = new AtomicLong(init);
  lastInitPos = new AtomicLong(clock.wallTime() / step);
}
 
Example #24
Source File: PolledMeterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void monitorValueNull() {
  Registry r = new DefaultRegistry(Clock.SYSTEM, p -> null);
  Id id = r.createId("test");

  PolledMeter.using(r).withId(id).<Collection<?>>monitorValue(null, Collection::size);
  PolledMeter.update(r);

  Assertions.assertEquals(Double.NaN, r.gauge(id).value());
}
 
Example #25
Source File: PolledMeterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void monitorValueNullPropagate() {
  RegistryConfig config = s -> s.equals("propagateWarnings") ? "true" : null;
  Registry r = new DefaultRegistry(Clock.SYSTEM, config);
  Id id = r.createId("test");

  IllegalArgumentException e = Assertions.assertThrows(
      IllegalArgumentException.class,
      () -> PolledMeter.using(r)
          .withId(id)
          .<Collection<?>>monitorValue(null, Collection::size)
  );
  Assertions.assertTrue(e.getMessage().startsWith("obj is null"));
}
 
Example #26
Source File: PolledMeterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void monitorMonotonicCounterNull() {
  Registry r = new DefaultRegistry(Clock.SYSTEM, p -> null);
  Id id = r.createId("test");

  AtomicLong v = new AtomicLong(42);
  PolledMeter.using(r).withId(id).<AtomicLong>monitorMonotonicCounter(null, n -> v.get());
  PolledMeter.update(r);

  Assertions.assertEquals(0, r.counter(id).count());
}
 
Example #27
Source File: PolledMeterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void monitorMonotonicCounterNullPropagate() {
  RegistryConfig config = s -> s.equals("propagateWarnings") ? "true" : null;
  Registry r = new DefaultRegistry(Clock.SYSTEM, config);
  Id id = r.createId("test");

  AtomicLong v = new AtomicLong(42);
  IllegalArgumentException e = Assertions.assertThrows(
      IllegalArgumentException.class,
      () -> PolledMeter.using(r)
          .withId(id)
          .<AtomicLong>monitorValue(null, n -> v.get())
  );
  Assertions.assertTrue(e.getMessage().startsWith("obj is null"));
}
 
Example #28
Source File: ServoCounter.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
ServoCounter(Id id, Clock clock, DoubleCounter impl) {
  this.id = id;
  this.clock = clock;
  this.impl = impl;
  this.count = new AtomicDouble(0.0);
  this.lastUpdated = new AtomicLong(clock.wallTime());
}
 
Example #29
Source File: ServoGauge.java    From spectator with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new monitor that returns {@code value}.
 */
ServoGauge(Id id, Clock clock, MonitorConfig config) {
  super(config.withAdditionalTag(DataSourceType.GAUGE));
  this.id = id;
  this.clock = clock;
  this.value = new AtomicDouble(Double.NaN);
  this.lastUpdated = new AtomicLong(clock.wallTime());
}
 
Example #30
Source File: ServoMaxGauge.java    From spectator with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new monitor that returns {@code value}.
 */
ServoMaxGauge(Id id, Clock clock, MonitorConfig config) {
  super(config.withAdditionalTag(DataSourceType.GAUGE));
  this.id = id;
  this.clock = clock;
  this.impl = new MaxGauge(config);
  this.lastUpdated = new AtomicLong(clock.wallTime());
}