Java Code Examples for com.netflix.spectator.api.Registry#counter()

The following examples show how to use com.netflix.spectator.api.Registry#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: 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 2
Source File: RateLimitedBatcher.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private RateLimitedBatcher(TokenBucket tokenBucket,
                           long initialDelay,
                           long maxDelay,
                           IndexExtractor<T, I> indexExtractor,
                           EmissionStrategy emissionStrategy,
                           String metricsRoot,
                           Registry registry,
                           Scheduler scheduler) {
    Preconditions.checkArgument(initialDelay > 0, "initialDelayMs must be > 0");
    Preconditions.checkArgument(maxDelay >= initialDelay, "maxDelayMs must be >= initialDelayMs");
    Preconditions.checkArgument(!metricsRoot.endsWith("."), "metricsRoot must not end with a '.' (dot)");
    this.tokenBucket = tokenBucket;
    this.initialDelayMs = initialDelay;
    this.maxDelayMs = maxDelay;
    this.indexExtractor = indexExtractor;
    this.emissionStrategy = emissionStrategy;
    this.metricsRoot = metricsRoot;
    this.registry = registry;
    this.rateLimitCounter = registry.counter(metricsRoot + ".rateLimit");
    this.clock = Clocks.scheduler(scheduler);
    this.worker = new InstrumentedEventLoop(metricsRoot, registry, scheduler);
}
 
Example 3
Source File: ExecutionMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public ExecutionMetrics(String root, Class<?> aClass, Registry registry, List<Tag> additionalTags) {
    this.root = root;
    this.registry = registry;
    this.commonTags = CollectionsExt.copyAndAdd(additionalTags, new BasicTag("class", aClass.getSimpleName()));

    this.successCounter = registry.counter(registry.createId(root, commonTags).withTag("status", "success"));
    this.errorCounter = registry.counter(registry.createId(root, commonTags).withTag("status", "failure"));

    Id successLatencyId = registry.createId(root + ".latency", commonTags).withTag("status", "success");
    PolledMeter.using(registry).withId(successLatencyId).monitorValue(successLatency);
    Id failureLatencyId = registry.createId(root + ".latency", commonTags).withTag("status", "failure");
    PolledMeter.using(registry).withId(failureLatencyId).monitorValue(failureLatency);
}
 
Example 4
Source File: CaffeineStatsCounter.java    From kork with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance for use by a single cache.
 *
 * @param registry the registry of metric instances
 * @param metricsPrefix the prefix name for the metrics
 */
public CaffeineStatsCounter(Registry registry, String metricsPrefix) {
  hitCount = registry.counter(metricsPrefix + ".hits");
  missCount = registry.counter(metricsPrefix + ".misses");
  totalLoadTime = registry.timer(metricsPrefix + ".loads");
  loadSuccessCount = registry.counter(metricsPrefix + ".loads-success");
  loadFailureCount = registry.counter(metricsPrefix + ".loads-failure");
  evictionCount = registry.counter(metricsPrefix + ".evictions");
  evictionWeight = registry.counter(metricsPrefix + ".evictions-weight");
}
 
Example 5
Source File: EmbeddedHiveClient.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * Embedded hive client implementation.
 *
 * @param catalogName catalogName
 * @param handler     handler
 * @param registry    registry
 */
public EmbeddedHiveClient(final String catalogName,
                          @Nullable final IMetacatHMSHandler handler,
                          final Registry registry) {
    this.handler = handler;
    this.registry = registry;
    this.requestTimerId = registry.createId(HiveMetrics.TimerHiveRequest.getMetricName());
    this.hiveSqlErrorCounter =
        registry.counter(HiveMetrics.CounterHiveSqlLockError.getMetricName() + "." + catalogName);
}
 
Example 6
Source File: MetacatEventBus.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param applicationEventMulticaster The event multicaster to use
 * @param registry         The registry to spectator
 */
public MetacatEventBus(
    @Nonnull @NonNull final MetacatApplicationEventMulticaster applicationEventMulticaster,
    @Nonnull @NonNull final Registry registry
) {
    this.applicationEventMulticaster = applicationEventMulticaster;
    this.eventPublishCounter = registry.counter(Metrics.CounterEventPublish.getMetricName());
}
 
Example 7
Source File: ScheduleMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
ScheduleMetrics(Schedule schedule, Clock clock, Registry registry) {
    this.lastSchedule = schedule;
    this.clock = clock;
    this.registry = registry;

    this.currentState = SpectatorExt.fsmMetrics(
            registry.createId(ROOT_NAME + "scheduleState", "scheduleName", schedule.getDescriptor().getName()),
            SchedulingState::isFinal,
            SchedulingState.Waiting,
            registry
    );
    this.successes = registry.counter(ROOT_NAME + "executions",
            "scheduleName", schedule.getDescriptor().getName(),
            "status", "succeeded"
    );
    this.failures = registry.counter(ROOT_NAME + "executions",
            "scheduleName", schedule.getDescriptor().getName(),
            "status", "failed"
    );

    this.waitingId = registry.createId(ROOT_NAME + "waitingTimeMs", "scheduleName", schedule.getDescriptor().getName());
    PolledMeter.using(registry)
            .withId(waitingId)
            .monitorValue(this, self -> howLongInState(SchedulingState.Waiting));
    this.runningId = registry.createId(ROOT_NAME + "runningTimeMs", "scheduleName", schedule.getDescriptor().getName());
    PolledMeter.using(registry)
            .withId(runningId)
            .monitorValue(this, self -> howLongInState(SchedulingState.Running));
    this.cancellingId = registry.createId(ROOT_NAME + "cancellingTimeMs", "scheduleName", schedule.getDescriptor().getName());
    PolledMeter.using(registry)
            .withId(cancellingId)
            .monitorValue(this, self -> howLongInState(SchedulingState.Cancelling));
}
 
Example 8
Source File: SpectatorTokenBucketDecorator.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public SpectatorTokenBucketDecorator(TokenBucket delegate, TitusRuntime titusRuntime) {
    super(delegate);

    Registry registry = titusRuntime.getRegistry();

    this.takeSuccessCounter = registry.counter(
            NAME_PREFIX + "tokenRequest",
            "bucketName", delegate.getName(),
            "success", "true"
    );
    this.takeFailureCounter = registry.counter(
            NAME_PREFIX + "tokenRequest",
            "bucketName", delegate.getName(),
            "success", "false"
    );

    PolledMeter.using(registry).withId(registry.createId(
            NAME_PREFIX + "capacity",
            "bucketName", delegate.getName(),
            "available", "false"
    )).monitorValue(this, self -> self.getCapacity() - self.getNumberOfTokens());
    PolledMeter.using(registry).withId(registry.createId(
            NAME_PREFIX + "capacity",
            "bucketName", delegate.getName(),
            "available", "true"
    )).monitorValue(this, TokenBucketDelegate::getNumberOfTokens);
}
 
Example 9
Source File: ReactorSerializedInvokerMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
ReactorSerializedInvokerMetrics(String name, Registry registry) {
    this.name = name;
    this.registry = registry;

    this.submitCounter = registry.counter(ROOT_NAME + "submit", "name", name);
    this.queueFullCounter = registry.counter(ROOT_NAME + "queueFull", "name", name);
    this.queueSize = registry.gauge(ROOT_NAME + "queueSize", "name", name);

    this.queueingTimer = registry.timer(ROOT_NAME + "queueingTime", "name", name);
    this.executionTimer = registry.timer(ROOT_NAME + "executionTime", "name", name, "status", "success");
    this.executionErrorTimer = registry.timer(ROOT_NAME + "executionTime", "name", name, "status", "error");
    this.executionDisposedTimer = registry.timer(ROOT_NAME + "executionTime", "name", name, "status", "disposed");
}
 
Example 10
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 11
Source File: LfuCache.java    From spectator with Apache License 2.0 5 votes vote down vote up
LfuCache(Registry registry, String id, int baseSize, int compactionSize) {
  this.hits = registry.counter("spectator.cache.requests", "id", id, "result", "hit");
  this.misses = registry.counter("spectator.cache.requests", "id", id, "result", "miss");
  this.compactions = registry.counter("spectator.cache.compactions", "id", id);
  data = new ConcurrentHashMap<>();
  this.baseSize = baseSize;
  this.compactionSize = compactionSize;
  this.size = new AtomicInteger();
  this.lock = new ReentrantLock();
}
 
Example 12
Source File: SubscriptionMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
SubscriptionMetrics(String root, List<Tag> commonTags, Registry registry) {
    this.rootId = registry.createId(root, commonTags);
    this.registry = registry;
    this.onNextCounter = registry.counter(root + ".onNext", commonTags);
    this.unsubscribed = registry.gauge(rootId.withTag("status", "unsubscribed"), new AtomicInteger());
    this.lastEmitTimestamp = new AtomicLong(registry.clock().wallTime());
    registry.gauge(
            registry.createId(root + ".lastEmit", commonTags),
            0L,
            this::getTimeSinceLastEmit
    );
}
 
Example 13
Source File: CloudWatchClient.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Inject
public CloudWatchClient(AWSCredentialsProvider awsCredentialsProvider,
                        AwsConfiguration awsConfiguration,
                        Registry registry) {

    awsCloudWatch = AmazonCloudWatchAsyncClientBuilder.standard().withCredentials(awsCredentialsProvider)
            .withRegion(awsConfiguration.getRegion()).build();

    createAlarmCounter = registry.counter(METRIC_CLOUD_WATCH_CREATE_ALARM);
    deleteAlarmCounter = registry.counter(METRIC_CLOUD_WATCH_DELETE_ALARM);
    deleteErrorCounter = registry.counter(METRIC_CLOUD_WATCH_DELETE_ERROR);
    createErrorCounter = registry.counter(METRIC_CLOUD_WATCH_CREATE_ERROR);
}
 
Example 14
Source File: AppScaleManagerMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public AppScaleManagerMetrics(Registry registry) {
    errorMetricId = registry.createId(METRIC_APPSCALE_ERRORS);
    fsmMetricsMap = new ConcurrentHashMap<>();
    numTargets = registry.gauge(METRIC_TITUS_APPSCALE_NUM_TARGETS, new AtomicInteger(0));
    this.registry = registry;
    droppedRequestsCount = registry.counter(METRIC_BACK_PRESSURE_DROP_COUNT);
}
 
Example 15
Source File: DefaultLoadBalancerReconciler.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
DefaultLoadBalancerReconciler(LoadBalancerConfiguration configuration,
                              LoadBalancerStore store,
                              LoadBalancerConnector connector,
                              LoadBalancerJobOperations loadBalancerJobOperations,
                              Runnable afterReconciliation,
                              Registry registry,
                              Scheduler scheduler) {
    this.store = store;
    this.connector = connector;
    this.jobOperations = loadBalancerJobOperations;
    this.delayMs = configuration.getReconciliationDelayMs();
    this.timeoutMs = configuration::getReconciliationTimeoutMs;
    this.afterReconciliation = afterReconciliation;
    this.registry = registry;
    this.scheduler = scheduler;

    List<Tag> tags = Collections.singletonList(new BasicTag("class", DefaultLoadBalancerReconciler.class.getSimpleName()));
    final Id updatesCounterId = registry.createId(METRIC_RECONCILER + ".updates", tags);
    this.registerCounter = registry.counter(updatesCounterId.withTag("operation", "register"));
    this.deregisterCounter = registry.counter(updatesCounterId.withTag("operation", "deregister"));
    this.removeCounter = registry.counter(updatesCounterId.withTag("operation", "remove"));
    this.fullReconciliationMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".full", tags, registry);
    this.orphanUpdateMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".orphanUpdates", tags, registry);
    this.removeMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".remove", tags, registry);
    this.removeTargetsMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".removeTargets", tags, registry);
    this.registeredIpsMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".getRegisteredIps", tags, registry);
    this.ignoredMetricsId = registry.createId(METRIC_RECONCILER + ".ignored", tags);
    this.orphanMetricsId = registry.createId(METRIC_RECONCILER + ".orphan", tags);
    PolledMeter.using(registry).withId(ignoredMetricsId).monitorSize(ignored);
    PolledMeter.using(registry).withId(orphanMetricsId).monitorSize(markedAsOrphan);
}
 
Example 16
Source File: StepMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
StepMetrics(String stepName, TitusRuntime titusRuntime) {
    Registry registry = titusRuntime.getRegistry();

    Id baseCounterId = registry.createId(RelocationMetrics.METRIC_ROOT + "steps", "step", stepName);
    this.successCounter = registry.counter(baseCounterId.withTag("status", "success"));
    this.failureCounter = registry.counter(baseCounterId.withTag("status", "failure"));

    Id baseTimerId = registry.createId(RelocationMetrics.METRIC_ROOT + "steps", "stepExecutionTime", stepName);
    this.successExecutionTime = registry.timer(baseTimerId.withTag("status", "success"));
    this.failureExecutionTime = registry.timer(baseTimerId.withTag("status", "failure"));
}
 
Example 17
Source File: SpectatorCodeInvariants.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
public SpectatorCodeInvariants(Id rootId, Registry registry) {
    this.violations = registry.counter(rootId);
}
 
Example 18
Source File: PassportLoggingHandler.java    From zuul with Apache License 2.0 4 votes vote down vote up
public PassportLoggingHandler(Registry spectatorRegistry)
{
    incompleteProxySessionCounter = spectatorRegistry.counter("server.http.session.incomplete");
}
 
Example 19
Source File: KubeApiServerIntegrator.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Inject
public KubeApiServerIntegrator(TitusRuntime titusRuntime,
                               MesosConfiguration mesosConfiguration,
                               DirectKubeConfiguration directKubeConfiguration,
                               @Named(GC_UNKNOWN_PODS) FixedIntervalTokenBucketConfiguration gcUnknownPodsTokenBucketConfiguration,
                               LocalScheduler scheduler,
                               Injector injector,
                               KubeApiFacade kubeApiFacade,
                               ContainerResultCodeResolver containerResultCodeResolver) {
    this.titusRuntime = titusRuntime;
    this.mesosConfiguration = mesosConfiguration;
    this.directKubeConfiguration = directKubeConfiguration;
    this.gcUnknownPodsTokenBucketConfiguration = gcUnknownPodsTokenBucketConfiguration;
    this.scheduler = scheduler;
    this.clock = titusRuntime.getClock();
    this.injector = injector;
    this.kubeApiFacade = kubeApiFacade;
    this.containerResultCodeResolver = containerResultCodeResolver;

    this.vmTaskStatusObserver = PublishSubject.create();

    Registry registry = titusRuntime.getRegistry();
    launchTaskCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "launchTask");
    launchTasksTimer = registry.timer(MetricConstants.METRIC_KUBERNETES + "launchTasksLatency");
    this.podSizeMetrics = BucketCounter.get(
            registry,
            registry.createId(MetricConstants.METRIC_KUBERNETES + "podSize"),
            BucketFunctions.bytes(32768)
    );
    rejectLeaseCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "rejectLease");
    killTaskCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "killTask");
    nodeAddCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "nodeAdd");
    nodeUpdateCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "nodeUpdate");
    nodeDeleteCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "nodeDelete");
    podAddCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "podAdd");
    podUpdateCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "podUpdate");
    podDeleteCounter = registry.counter(MetricConstants.METRIC_KUBERNETES + "podDelete");
    timedOutNodesToGcGauge = registry.gauge(MetricConstants.METRIC_KUBERNETES + "timedOutNodesToGc");
    orphanedPodsWithoutValidNodesToGcGauge = registry.gauge(MetricConstants.METRIC_KUBERNETES + "orphanedPodsWithoutValidNodesToGc");
    terminalPodsToGcGauge = registry.gauge(MetricConstants.METRIC_KUBERNETES + "terminalPodsToGc");
    potentialUnknownPodsToGcGauge = registry.gauge(MetricConstants.METRIC_KUBERNETES + "potentialUnknownPodsToGc");
    unknownPodsToGcGauge = registry.gauge(MetricConstants.METRIC_KUBERNETES + "unknownPodsToGc");
    podsPastDeletionTimestampToGcGauge = registry.gauge(MetricConstants.METRIC_KUBERNETES + "podsPastDeletionTimestampToGc");
    pendingPodsWithDeletionTimestampToGcGauge = registry.gauge(MetricConstants.METRIC_KUBERNETES + "pendingPodsWithDeletionTimestampToGc");
}
 
Example 20
Source File: StorageServiceSupport.java    From front50 with Apache License 2.0 4 votes vote down vote up
public StorageServiceSupport(
    ObjectType objectType,
    StorageService service,
    Scheduler scheduler,
    ObjectKeyLoader objectKeyLoader,
    long refreshIntervalMs,
    boolean shouldWarmCache,
    Registry registry,
    CircuitBreakerRegistry circuitBreakerRegistry) {
  this.objectType = objectType;
  this.service = service;
  this.scheduler = scheduler;
  this.objectKeyLoader = objectKeyLoader;
  this.refreshIntervalMs = refreshIntervalMs;
  if (refreshIntervalMs >= getHealthMillis()) {
    throw new IllegalArgumentException(
        "Cache refresh time must be more frequent than cache health timeout");
  }
  this.shouldWarmCache = shouldWarmCache;
  this.registry = registry;
  this.circuitBreakerRegistry = circuitBreakerRegistry;

  String typeName = objectType.name();
  this.autoRefreshTimer =
      registry.timer(
          registry.createId("storageServiceSupport.autoRefreshTime", "objectType", typeName));
  this.scheduledRefreshTimer =
      registry.timer(
          registry.createId(
              "storageServiceSupport.scheduledRefreshTime", "objectType", typeName));
  this.addCounter =
      registry.counter(
          registry.createId("storageServiceSupport.numAdded", "objectType", typeName));
  this.removeCounter =
      registry.counter(
          registry.createId("storageServiceSupport.numRemoved", "objectType", typeName));
  this.updateCounter =
      registry.counter(
          registry.createId("storageServiceSupport.numUpdated", "objectType", typeName));
  this.mismatchedIdCounter =
      registry.counter(
          registry.createId("storageServiceSupport.mismatchedIds", "objectType", typeName));

  registry.gauge(
      registry.createId("storageServiceSupport.cacheSize", "objectType", typeName),
      this,
      new ToDoubleFunction() {
        @Override
        public double applyAsDouble(Object ignore) {
          Set itemCache = allItemsCache.get();
          return itemCache != null ? itemCache.size() : 0;
        }
      });
  registry.gauge(
      registry.createId("storageServiceSupport.cacheAge", "objectType", typeName),
      lastRefreshedTime,
      (lrt) -> Long.valueOf(System.currentTimeMillis() - lrt.get()).doubleValue());
}