com.netflix.spectator.api.Tag Java Examples

The following examples show how to use com.netflix.spectator.api.Tag. 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: EVCacheMetricsFactory.java    From EVCache with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #2
Source File: ClusterAgentAutoScaler.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
TierAutoScalerExecution(Tier tier, Registry registry) {
    List<Tag> commonTags = singletonList(new BasicTag("tier", tier.name()));
    totalIdleInstancesGauge = registry.gauge(METRIC_ROOT + "totalIdleInstances", commonTags);
    totalFailedTasksGauge = registry.gauge(METRIC_ROOT + "totalFailedTasks", commonTags);
    totalTasksPastSloGauge = registry.gauge(METRIC_ROOT + "totalTasksPastSlo", commonTags);
    totalTasksForScaleUpGauge = registry.gauge(METRIC_ROOT + "totalTasksForScaleUp", commonTags);
    totalAgentsToScaleUpGauge = registry.gauge(METRIC_ROOT + "totalAgentsToScaleUp", commonTags);
    totalAgentsBeingScaledUpGauge = registry.gauge(METRIC_ROOT + "totalAgentsBeingScaledUp", commonTags);
    totalAgentsToScaleDownGauge = registry.gauge(METRIC_ROOT + "totalAgentsToScaleDown", commonTags);
    totalAgentsBeingScaledDownGauge = registry.gauge(METRIC_ROOT + "totalAgentsBeingScaledDown", commonTags);

    ImmutableRefillStrategy scaleUpRefillStrategy = ImmutableLimiters.refillAtFixedInterval(SCALE_UP_TOKEN_BUCKET_REFILL_AMOUNT,
            SCALE_UP_TOKEN_BUCKET_REFILL_INTERVAL_MS, TimeUnit.MILLISECONDS);
    lastScaleUpTokenBucket = ImmutableLimiters.tokenBucket(SCALE_UP_TOKEN_BUCKET_CAPACITY, scaleUpRefillStrategy);

    ImmutableRefillStrategy scaleDownRefillStrategy = ImmutableLimiters.refillAtFixedInterval(SCALE_DOWN_TOKEN_BUCKET_REFILL_AMOUNT,
            SCALE_DOWN_TOKEN_BUCKET_REFILL_INTERVAL_MS, TimeUnit.MILLISECONDS);
    lastScaleDownTokenBucket = ImmutableLimiters.tokenBucket(SCALE_DOWN_TOKEN_BUCKET_CAPACITY, scaleDownRefillStrategy);
}
 
Example #3
Source File: DefaultPlaceholderIdTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithNoopTagFactory() {
  DefaultPlaceholderId id = new DefaultPlaceholderId("foo", REGISTRY).withTagFactory(new TagFactory() {
    @Override
    public String name() {
      return "noopTagFactory";
    }

    @Override
    /* Implementation that always returns null, which should result in the tag being omitted. */
    public Tag createTag() {
      return null;
    }
  });
  Iterator<Tag> tags = id.resolveToId().tags().iterator();

  Assertions.assertFalse(tags.hasNext(), "tags not empty");
}
 
Example #4
Source File: TagMeasurementFilter.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Implements MeasurementFilter interface.
 */
@SuppressWarnings("PMD.JUnit4TestShouldUseTestAnnotation")
@Override public boolean test(Measurement measurement) {
  Id id = measurement.id();
  if (!stringMatches(id.name(), meterNamePattern)) {
      return false;
  }

  if (tagNamePattern != null || tagValuePattern != null) {
    for (Tag tag : id.tags()) {
      boolean nameOk = stringMatches(tag.key(), tagNamePattern);
      boolean valueOk = stringMatches(tag.value(), tagValuePattern);
      if (nameOk && valueOk) {
        return true;
      }
    }
    return false;
  }

  return true;
}
 
Example #5
Source File: MeasurementTree.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public void from(Iterable<Measurement> measurements, MeasurementGroupConfig groupConfig) {
  for (Measurement measurement : measurements) {
    Id id = measurement.id();
    MeasurementNode node = addChild(id.name(), measurement);

    List<TagFinder> tagFinders = groupConfig.findTagFinders(id.name());
    if (tagFinders == null) {
      continue;
    }

    for (TagFinder tagFinder : tagFinders) {
      Tag tag = tagFinder.find(id.tags());
      if (tag == null) {
        if (tagFinder.skipOnNull()) {
          break;
        }
        throw new IllegalStateException(
            String.format("tag key \"%s\" not exist in %s",
                tagFinder.getTagKey(),
                measurement));
      }

      node = node.addChild(tag.value(), measurement);
    }
  }
}
 
Example #6
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 #7
Source File: SpringSpectatorInterceptor.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    super.postHandle(request, response, handler, modelAndView);

    String callerId = getCallerId();
    String path = request.getServletPath() == null ? "unknown" : trimPath(request.getServletPath());

    List<Tag> tags = Arrays.asList(
            new BasicTag("port", "" + request.getServerPort()),
            new BasicTag("method", request.getMethod()),
            new BasicTag("path", path),
            new BasicTag("status", "" + response.getStatus()),
            new BasicTag("caller", callerId)
    );

    registry.counter(METRICS_REQUEST, tags).increment();

    Long timestamp = (Long) request.getAttribute(REQUEST_TIMESTAMP);
    if (timestamp != null) {
        registry.timer(METRICS_REQUEST_LATENCY, tags).record(clock.wallTime() - timestamp, TimeUnit.MILLISECONDS);
    }
}
 
Example #8
Source File: MetricsRegistry.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance. */
public MetricsRegistry(Clock clock, com.codahale.metrics.MetricRegistry impl) {
  this(clock, impl, id -> {
    Id normalized = Utils.normalize(id);
    StringBuilder buf = new StringBuilder();
    buf.append(normalized.name());
    for (Tag t : normalized.tags()) {
      buf.append('.').append(t.key()).append('-').append(t.value());
    }
    return buf.toString();
  });
}
 
Example #9
Source File: DatabaseMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public void registerDeleteLatency(long startTimeMs, int numRecordsDeleted, String tableName, List<Tag> additionalTags) {
    List<Tag> tags = new ArrayList<>();
    tags.add(new BasicTag(RECORD_COUNT_TAG, Integer.toString(numRecordsDeleted)));

    registerLatency(Operations.DELETE, tableName, Stream.concat(tags.stream(),
            additionalTags.stream()).collect(Collectors.toList()),
            System.currentTimeMillis() - startTimeMs);
}
 
Example #10
Source File: EVCacheClientPool.java    From EVCache with Apache License 2.0 5 votes vote down vote up
private void incrementFailure(String metric, ServerGroup serverGroup) {

        final List<Tag> tags = new ArrayList<Tag>(4);
        EVCacheMetricsFactory.getInstance().addAppNameTags(tags, _appName);
        tags.add(new BasicTag(EVCacheMetricsFactory.CONFIG_NAME, metric));
        tags.add(new BasicTag(EVCacheMetricsFactory.SERVERGROUP, serverGroup.getName()));

        EVCacheMetricsFactory.getInstance().increment(EVCacheMetricsFactory.INTERNAL_POOL_INIT_ERROR, tags);
    }
 
Example #11
Source File: MetricsContainer.java    From conductor with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private static List<Tag> getTags(String[] additionalTags) {
    List<Tag> tagList = new ArrayList();
    tagList.add(new BasicTag("class", className));
    for (int j = 0; j < additionalTags.length - 1; j++) {
        tagList.add(new BasicTag(additionalTags[j], additionalTags[j + 1]));
        j++;
    }
    return tagList;
}
 
Example #12
Source File: MetricsContainer.java    From conductor with Apache License 2.0 5 votes vote down vote up
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);
    });
}
 
Example #13
Source File: EVCacheMemcachedClient.java    From EVCache with Apache License 2.0 5 votes vote down vote up
private DistributionSummary getDataSizeDistributionSummary(String operation, String type, String metric) {
    DistributionSummary distributionSummary = distributionSummaryMap.get(operation);
    if(distributionSummary != null) return distributionSummary;

    final List<Tag> tagList = new ArrayList<Tag>(6);
    tagList.addAll(client.getTagList());
    tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, operation));
    tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TYPE_TAG, type));
    distributionSummary = EVCacheMetricsFactory.getInstance().getDistributionSummary(metric, tagList);
    distributionSummaryMap.put(operation, distributionSummary);
    return distributionSummary;
}
 
Example #14
Source File: EVCacheInMemoryCache.java    From EVCache with Apache License 2.0 5 votes vote down vote up
private Counter getCounter(String name) {
    Counter counter = counterMap.get(name);
    if(counter != null) return counter;

    final List<Tag> tags = new ArrayList<Tag>(3);
    tags.addAll(impl.getTags());
    tags.add(new BasicTag(EVCacheMetricsFactory.METRIC, name));
    counter = EVCacheMetricsFactory.getInstance().getCounter(EVCacheMetricsFactory.IN_MEMORY, tags);
    counterMap.put(name, counter);
    return counter;
}
 
Example #15
Source File: EVCacheMetricsFactory.java    From EVCache with Apache License 2.0 5 votes vote down vote up
private void addCommonTags(List<Tag> tagList) {
    tagList.add(new BasicTag(OWNER, "evcache"));
    final String additionalTags = EVCacheConfig.getInstance().getPropertyRepository().get("evcache.additional.tags", String.class).orElse(null).get();
    if(additionalTags != null && additionalTags.length() > 0) {
        final StringTokenizer st = new StringTokenizer(additionalTags, ","); 
        while(st.hasMoreTokens()) {
            final String token = st.nextToken().trim();
            String val = System.getProperty(token);
            if(val == null) val = System.getenv(token);
            if(val != null) tagList.add(new BasicTag(token, val));
        }
    }        
}
 
Example #16
Source File: PrototypeMeasurementFilterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void keepTagOk() {
    PrototypeMeasurementFilter.TagFilterPattern pattern
        = new PrototypeMeasurementFilter.TagFilterPattern(
                  Pattern.compile(".+_name_.+"), Pattern.compile(".+_value_.+"));
    Tag tagA = new BasicTag("some_name_value", "some_value_string");
    Assertions.assertTrue(pattern.test(tagA));
}
 
Example #17
Source File: TagsBuilder.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Add additional tag values. */
public T withTags(Iterable<Tag> tags) {
  for (Tag t : tags) {
    extraTags.add(t);
  }
  return (T) this;
}
 
Example #18
Source File: IdTraversal.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void iterator(Blackhole bh) {
  for (Tag t : baseId) {
    bh.consume(t.key());
    bh.consume(t.value());
  }
}
 
Example #19
Source File: EVCacheImpl.java    From EVCache with Apache License 2.0 5 votes vote down vote up
private Timer getTimer(String operation, String operationType, String hit, String status, int tries, long duration, ServerGroup serverGroup) {
        String name = ((hit != null) ? operation + hit : operation);
        if(status != null) name += status;
        if(tries >= 0) name += tries;
        if(serverGroup != null) name += serverGroup.getName();
        //if(_cacheName != null) name += _cacheName;

        Timer timer = timerMap.get(name);
        if(timer != null) return timer;

        final List<Tag> tagList = new ArrayList<Tag>(7);
        tagList.addAll(tags);
        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) tagList.add(new BasicTag(EVCacheMetricsFactory.IPC_RESULT, status));
        if(hit != null) tagList.add(new BasicTag(EVCacheMetricsFactory.CACHE_HIT, hit));
        switch(tries) {
            case 0 :
            case 1 :
                tagList.add(new BasicTag(EVCacheMetricsFactory.ATTEMPT, EVCacheMetricsFactory.INITIAL));
                break;
            case 2 :
                tagList.add(new BasicTag(EVCacheMetricsFactory.ATTEMPT, EVCacheMetricsFactory.SECOND));
                break;
            default:
                tagList.add(new BasicTag(EVCacheMetricsFactory.ATTEMPT, EVCacheMetricsFactory.THIRD_UP));
                break;
        }

//        if(tries == 0) tagList.add(new BasicTag(EVCacheMetricsFactory.ATTEMPT, String.valueOf(tries)));
        if(serverGroup != null) {
            tagList.add(new BasicTag(EVCacheMetricsFactory.SERVERGROUP, serverGroup.getName()));
            tagList.add(new BasicTag(EVCacheMetricsFactory.ZONE, serverGroup.getZone()));
        }

        timer = EVCacheMetricsFactory.getInstance().getPercentileTimer(EVCacheMetricsFactory.OVERALL_CALL, tagList, Duration.ofMillis(duration));
        timerMap.put(name, timer);
        return timer;
    }
 
Example #20
Source File: DoubleDistributionSummaryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
private String get(Id id, String key) {
  for (Tag t : id.tags()) {
    if (key.equals(t.key())) {
      return t.value();
    }
  }
  return null;
}
 
Example #21
Source File: DatabaseMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public DatabaseMetrics(Registry registry, String metricsNamespace, String databaseName) {
    List<Tag> commonTags = Collections.emptyList();

    this.registry = registry;

    String metricsRoot = metricsNamespace + ROOT_NAME;
    this.operationLatency = registry.createId(metricsRoot + databaseName + "." + OPERATION_LATENCY, commonTags);
    this.errorCounter = registry.createId(metricsRoot + databaseName + "." + OPERATION_ERROR, commonTags);
}
 
Example #22
Source File: IamConnectorMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private ExecutionMetrics getOrCreateMetrics(IamMethods methodName) {
    String methodNameStr = methodName.name();
    if (methodMetricsMap.containsKey(methodNameStr)) {
        return methodMetricsMap.get(methodNameStr);
    }

    List<Tag> tags = new ArrayList<>();
    tags.add(new BasicTag("methodName", methodNameStr));
    ExecutionMetrics metric = new ExecutionMetrics(METRICS_ROOT, iamConnectorClass, registry, tags);

    methodMetricsMap.put(methodNameStr, metric);
    return metric;
}
 
Example #23
Source File: DefaultPlaceholderIdTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithFactoriesNullIterable() {
  DefaultPlaceholderId id = DefaultPlaceholderId.createWithFactories("foo", null, REGISTRY);
  Iterator<Tag> tags = id.resolveToId().tags().iterator();

  Assertions.assertEquals("foo", id.name());
  Assertions.assertFalse(tags.hasNext(), "tags not empty");
}
 
Example #24
Source File: EVCacheClient.java    From EVCache with Apache License 2.0 5 votes vote down vote up
private void incrementFailure(String metric, EVCache.Call call, String host) {
    Counter counter = counterMap.get(metric);
    if(counter == null) {
        final List<Tag> tagList = new ArrayList<Tag>(6);
        tagList.addAll(tags);
        if(call != null) {
            tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, call.name()));
            switch(call) {
            case GET:
            case GETL:
            case GET_AND_TOUCH:
            case ASYNC_GET:
            case  BULK:
            case  GET_ALL:
                tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TYPE_TAG, EVCacheMetricsFactory.READ));
                break;
            default :
                tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TYPE_TAG, EVCacheMetricsFactory.WRITE));
                break;
            }
        }
        tagList.add(new BasicTag(EVCacheMetricsFactory.FAILURE_REASON, metric));
        if(host != null) tagList.add(new BasicTag(EVCacheMetricsFactory.FAILED_HOST, host));
        counter = EVCacheMetricsFactory.getInstance().getCounter(EVCacheMetricsFactory.INTERNAL_FAIL, tagList);
        counterMap.put(metric, counter);
    }
    counter.increment();
}
 
Example #25
Source File: AwsLoadBalancerConnectorMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private ExecutionMetrics getOrCreateMetrics(AwsLoadBalancerMethods methodName) {
    String methodNameStr = methodName.name();
    if (methodMetricsMap.containsKey(methodNameStr)) {
        return methodMetricsMap.get(methodNameStr);
    }

    List<Tag> tags = new ArrayList<>();
    tags.add(new BasicTag("methodName", methodNameStr));
    ExecutionMetrics metric = new ExecutionMetrics(METRICS_ROOT, AwsLoadBalancerConnector.class, registry, tags);

    methodMetricsMap.put(methodNameStr, metric);
    return metric;
}
 
Example #26
Source File: GaugeCallback.java    From mantis with Apache License 2.0 5 votes vote down vote up
public GaugeCallback(final String metricGroup,
                     final String metricName,
                     final Func0<Double> valueCallback,
                     final Registry registry,
                     final Iterable<Tag> tags) {
    this(new MetricId(metricGroup, metricName, tags), valueCallback, registry);
}
 
Example #27
Source File: InstrumentedRequestDispatcher.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public InstrumentedRequestDispatcher(RequestDispatcher underlying,
                                     RestServerConfiguration config,
                                     ClientInvocationMetrics clientInvocationMetrics,
                                     List<Tag> tags,
                                     Registry registry) {
    this.underlying = underlying;
    this.config = config;
    this.clientInvocationMetrics = clientInvocationMetrics;
    this.tags = tags;
    this.registry = registry;
}
 
Example #28
Source File: JobReconciliationFrameworkFactory.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private List<Tag> extraChangeActionTags(ChangeAction changeAction) {
    if (changeAction instanceof TitusChangeAction) {
        TitusChangeAction titusChangeAction = (TitusChangeAction) changeAction;
        return Collections.singletonList(new BasicTag("action", titusChangeAction.getName()));
    }
    return Collections.emptyList();
}
 
Example #29
Source File: MetricDescriptorCache.java    From kork with Apache License 2.0 5 votes vote down vote up
/**
 * Get the labels to use for a given metric instance.
 *
 * @param descriptorType The Stackdriver custom descriptor ype name for the labels.
 * @param tags The Spectator Measurement tags for the data.
 * @return A map of label key, value bindings may include fewer or more tags than those provided
 *     depending on the extra tags and configured custom descriptor hints.
 */
public Map<String, String> tagsToTimeSeriesLabels(String descriptorType, Iterable<Tag> tags) {
  HashMap<String, String> labels = new HashMap<String, String>(extraTimeSeriesLabels);

  for (Tag tag : tags) {
    labels.put(tag.key(), tag.value());
  }
  return labels;
}
 
Example #30
Source File: AwsLoadBalancerConnectorMetrics.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public AwsLoadBalancerConnectorMetrics(Registry registry) {
    this.registry = registry;
    methodMetricsMap = new ConcurrentHashMap<>();

    for (AwsLoadBalancerMethods methodName : AwsLoadBalancerMethods.values()) {
        // Create ExecutionMetrics that are preconfigured with the appropriate tags. This
        // allows latency metrics to be collected per method.
        List<Tag> tags = new ArrayList<>();
        String methodNameStr = methodName.name();
        tags.add(new BasicTag("method", methodNameStr));
        methodMetricsMap.put(methodNameStr,
                new ExecutionMetrics(METRICS_ROOT, AwsLoadBalancerConnector.class, registry, tags));
    }
}