com.alibaba.metrics.MetricName

Here are the examples of the java api com.alibaba.metrics.MetricName taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

94 Examples 7

19 Source : MetricsResourceTest.java
with Apache License 2.0
from alibaba

@Test
public void testCompreplacedAddonMatch() {
    Set<String> names = new HashSet<String>();
    names.add("shared.carts.my_cart.hit.count");
    MetricName mn = MetricName.build("shared.carts.my_cart");
    Compreplaced compreplaced = new CompreplacedImpl();
    Compreplaced.Context context = compreplaced.time();
    context.markAddon("hit");
    context.stop();
    MetricNameSetFilter filter = new MetricNameSetFilter(names);
    replacedert.replacedertTrue(filter.matches(mn, compreplaced));
}

19 Source : Slf4jReporter.java
with Apache License 2.0
from alibaba

/**
 * A reporter clreplaced for logging metrics values to a SLF4J {@link Logger} periodically, similar to
 * {@link ConsoleReporter} or {@link CsvReporter}, but using the SLF4J framework instead. It also
 * supports specifying a {@link Marker} instance that can be used by custom appenders and filters
 * for the bound logging toolkit to further process metrics reports.
 */
public clreplaced Slf4jReporter extends ScheduledReporter {

    /**
     * Returns a new {@link Builder} for {@link Slf4jReporter}.
     *
     * @param registry the registry to report
     * @return a {@link Builder} instance for a {@link Slf4jReporter}
     */
    public static Builder forRegistry(MetricRegistry registry) {
        return new Builder(registry);
    }

    public enum LoggingLevel {

        TRACE, DEBUG, INFO, WARN, ERROR
    }

    /**
     * A builder for {@link Slf4jReporter} instances. Defaults to logging to {@code metrics}, not
     * using a marker, converting rates to events/second, converting durations to milliseconds, and
     * not filtering metrics.
     */
    public static clreplaced Builder {

        private final MetricRegistry registry;

        private Logger logger;

        private LoggingLevel loggingLevel;

        private Marker marker;

        private String prefix;

        private TimeUnit rateUnit;

        private TimeUnit durationUnit;

        private MetricFilter filter;

        private Builder(MetricRegistry registry) {
            this.registry = registry;
            this.logger = LoggerFactory.getLogger("metrics");
            this.marker = null;
            this.prefix = "";
            this.rateUnit = TimeUnit.SECONDS;
            this.durationUnit = TimeUnit.MILLISECONDS;
            this.filter = MetricFilter.ALL;
            this.loggingLevel = LoggingLevel.INFO;
        }

        /**
         * Log metrics to the given logger.
         *
         * @param logger an SLF4J {@link Logger}
         * @return {@code this}
         */
        public Builder outputTo(Logger logger) {
            this.logger = logger;
            return this;
        }

        /**
         * Mark all logged metrics with the given marker.
         *
         * @param marker an SLF4J {@link Marker}
         * @return {@code this}
         */
        public Builder markWith(Marker marker) {
            this.marker = marker;
            return this;
        }

        /**
         * Prefix all metric names with the given string.
         *
         * @param prefix the prefix for all metric names
         * @return {@code this}
         */
        public Builder prefixedWith(String prefix) {
            this.prefix = prefix;
            return this;
        }

        /**
         * Convert rates to the given time unit.
         *
         * @param rateUnit a unit of time
         * @return {@code this}
         */
        public Builder convertRatesTo(TimeUnit rateUnit) {
            this.rateUnit = rateUnit;
            return this;
        }

        /**
         * Convert durations to the given time unit.
         *
         * @param durationUnit a unit of time
         * @return {@code this}
         */
        public Builder convertDurationsTo(TimeUnit durationUnit) {
            this.durationUnit = durationUnit;
            return this;
        }

        /**
         * Only report metrics which match the given filter.
         *
         * @param filter a {@link MetricFilter}
         * @return {@code this}
         */
        public Builder filter(MetricFilter filter) {
            this.filter = filter;
            return this;
        }

        /**
         * Use Logging Level when reporting.
         *
         * @param loggingLevel a (@link Slf4jReporter.LoggingLevel}
         * @return {@code this}
         */
        public Builder withLoggingLevel(LoggingLevel loggingLevel) {
            this.loggingLevel = loggingLevel;
            return this;
        }

        /**
         * Builds a {@link Slf4jReporter} with the given properties.
         *
         * @return a {@link Slf4jReporter}
         */
        public Slf4jReporter build() {
            LoggerProxy loggerProxy;
            switch(loggingLevel) {
                case TRACE:
                    loggerProxy = new TraceLoggerProxy(logger);
                    break;
                case INFO:
                    loggerProxy = new InfoLoggerProxy(logger);
                    break;
                case WARN:
                    loggerProxy = new WarnLoggerProxy(logger);
                    break;
                case ERROR:
                    loggerProxy = new ErrorLoggerProxy(logger);
                    break;
                default:
                case DEBUG:
                    loggerProxy = new DebugLoggerProxy(logger);
                    break;
            }
            return new Slf4jReporter(registry, loggerProxy, marker, prefix, rateUnit, durationUnit, filter);
        }
    }

    private final LoggerProxy loggerProxy;

    private final Marker marker;

    private final MetricName prefix;

    private Slf4jReporter(MetricRegistry registry, LoggerProxy loggerProxy, Marker marker, String prefix, TimeUnit rateUnit, TimeUnit durationUnit, MetricFilter filter) {
        super(registry, "logger-reporter", filter, rateUnit, durationUnit);
        this.loggerProxy = loggerProxy;
        this.marker = marker;
        this.prefix = MetricName.build(prefix);
    }

    @Override
    public void report(SortedMap<MetricName, Gauge> gauges, SortedMap<MetricName, Counter> counters, SortedMap<MetricName, Histogram> histograms, SortedMap<MetricName, Meter> meters, SortedMap<MetricName, Timer> timers) {
        if (loggerProxy.isEnabled(marker)) {
            for (Entry<MetricName, Gauge> entry : gauges.entrySet()) {
                logGauge(entry.getKey(), entry.getValue());
            }
            for (Entry<MetricName, Counter> entry : counters.entrySet()) {
                logCounter(entry.getKey(), entry.getValue());
            }
            for (Entry<MetricName, Histogram> entry : histograms.entrySet()) {
                logHistogram(entry.getKey(), entry.getValue());
            }
            for (Entry<MetricName, Meter> entry : meters.entrySet()) {
                logMeter(entry.getKey(), entry.getValue());
            }
            for (Entry<MetricName, Timer> entry : timers.entrySet()) {
                logTimer(entry.getKey(), entry.getValue());
            }
        }
    }

    private void logTimer(MetricName name, Timer timer) {
        final Snapshot snapshot = timer.getSnapshot();
        loggerProxy.log(marker, "type={}, name={}, count={}, min={}, max={}, mean={}, stddev={}, median={}, " + "p75={}, p95={}, p98={}, p99={}, p999={}, mean_rate={}, m1={}, m5={}, " + "m15={}, rate_unit={}, duration_unit={}", "TIMER", prefix(name), timer.getCount(), convertDuration(snapshot.getMin()), convertDuration(snapshot.getMax()), convertDuration(snapshot.getMean()), convertDuration(snapshot.getStdDev()), convertDuration(snapshot.getMedian()), convertDuration(snapshot.get75thPercentile()), convertDuration(snapshot.get95thPercentile()), convertDuration(snapshot.get98thPercentile()), convertDuration(snapshot.get99thPercentile()), convertDuration(snapshot.get999thPercentile()), convertRate(timer.getMeanRate()), convertRate(timer.getOneMinuteRate()), convertRate(timer.getFiveMinuteRate()), convertRate(timer.getFifteenMinuteRate()), getRateUnit(), getDurationUnit());
    }

    private void logMeter(MetricName name, Meter meter) {
        loggerProxy.log(marker, "type={}, name={}, count={}, mean_rate={}, m1={}, m5={}, m15={}, rate_unit={}", "METER", prefix(name), meter.getCount(), convertRate(meter.getMeanRate()), convertRate(meter.getOneMinuteRate()), convertRate(meter.getFiveMinuteRate()), convertRate(meter.getFifteenMinuteRate()), getRateUnit());
    }

    private void logHistogram(MetricName name, Histogram histogram) {
        final Snapshot snapshot = histogram.getSnapshot();
        loggerProxy.log(marker, "type={}, name={}, count={}, min={}, max={}, mean={}, stddev={}, " + "median={}, p75={}, p95={}, p98={}, p99={}, p999={}", "HISTOGRAM", prefix(name), histogram.getCount(), snapshot.getMin(), snapshot.getMax(), snapshot.getMean(), snapshot.getStdDev(), snapshot.getMedian(), snapshot.get75thPercentile(), snapshot.get95thPercentile(), snapshot.get98thPercentile(), snapshot.get99thPercentile(), snapshot.get999thPercentile());
    }

    private void logCounter(MetricName name, Counter counter) {
        loggerProxy.log(marker, "type={}, name={}, count={}", "COUNTER", prefix(name), counter.getCount());
    }

    private void logGauge(MetricName name, Gauge gauge) {
        loggerProxy.log(marker, "type={}, name={}, value={}", "GAUGE", prefix(name), gauge.getValue());
    }

    @Override
    protected String getRateUnit() {
        return "events/" + super.getRateUnit();
    }

    private String prefix(MetricName name, String... components) {
        return MetricName.join(MetricName.join(prefix, name), MetricName.build(components)).getKey();
    }

    /* private clreplaced to allow logger configuration */
    static abstract clreplaced LoggerProxy {

        protected final Logger logger;

        public LoggerProxy(Logger logger) {
            this.logger = logger;
        }

        abstract void log(Marker marker, String format, Object... arguments);

        abstract boolean isEnabled(Marker marker);
    }

    /* private clreplaced to allow logger configuration */
    private static clreplaced DebugLoggerProxy extends LoggerProxy {

        public DebugLoggerProxy(Logger logger) {
            super(logger);
        }

        @Override
        public void log(Marker marker, String format, Object... arguments) {
            logger.debug(marker, format, arguments);
        }

        @Override
        public boolean isEnabled(Marker marker) {
            return logger.isDebugEnabled(marker);
        }
    }

    /* private clreplaced to allow logger configuration */
    private static clreplaced TraceLoggerProxy extends LoggerProxy {

        public TraceLoggerProxy(Logger logger) {
            super(logger);
        }

        @Override
        public void log(Marker marker, String format, Object... arguments) {
            logger.trace(marker, format, arguments);
        }

        @Override
        public boolean isEnabled(Marker marker) {
            return logger.isTraceEnabled(marker);
        }
    }

    /* private clreplaced to allow logger configuration */
    private static clreplaced InfoLoggerProxy extends LoggerProxy {

        public InfoLoggerProxy(Logger logger) {
            super(logger);
        }

        @Override
        public void log(Marker marker, String format, Object... arguments) {
            logger.info(marker, format, arguments);
        }

        @Override
        public boolean isEnabled(Marker marker) {
            return logger.isInfoEnabled(marker);
        }
    }

    /* private clreplaced to allow logger configuration */
    private static clreplaced WarnLoggerProxy extends LoggerProxy {

        public WarnLoggerProxy(Logger logger) {
            super(logger);
        }

        @Override
        public void log(Marker marker, String format, Object... arguments) {
            logger.warn(marker, format, arguments);
        }

        @Override
        public boolean isEnabled(Marker marker) {
            return logger.isWarnEnabled(marker);
        }
    }

    /* private clreplaced to allow logger configuration */
    private static clreplaced ErrorLoggerProxy extends LoggerProxy {

        public ErrorLoggerProxy(Logger logger) {
            super(logger);
        }

        @Override
        public void log(Marker marker, String format, Object... arguments) {
            logger.error(marker, format, arguments);
        }

        @Override
        public boolean isEnabled(Marker marker) {
            return logger.isErrorEnabled(marker);
        }
    }
}

19 Source : Slf4jReporter.java
with Apache License 2.0
from alibaba

private String prefix(MetricName name, String... components) {
    return MetricName.join(MetricName.join(prefix, name), MetricName.build(components)).getKey();
}

19 Source : Slf4jReporter.java
with Apache License 2.0
from alibaba

private void logCounter(MetricName name, Counter counter) {
    loggerProxy.log(marker, "type={}, name={}, count={}", "COUNTER", prefix(name), counter.getCount());
}

19 Source : OpenTsdbReporter.java
with Apache License 2.0
from alibaba

private OpenTsdbMetric buildCounter(MetricName name, Counter counter, long timestamp) {
    return OpenTsdbMetric.named(prefix(name.getKey(), "count")).withTimestamp(timestamp).withValue(counter.getCount()).withTags(merge(globalTags, name.getTags())).build();
}

19 Source : OpenTsdbMetricManagerReporter.java
with Apache License 2.0
from alibaba

private Set<OpenTsdbMetric> buildCompreplaced(MetricName name, Compreplaced compreplaced, long timestamp) {
    final MetricsCollector collector = MetricsCollector.createNew(prefix(name.getKey()), merge(globalTags, name.getTags()), timestamp);
    // TODO add build compreplaced logic
    return collector.build();
}

19 Source : FixedNameCsvFileProvider.java
with Apache License 2.0
from alibaba

@Override
public File getFile(File directory, MetricName metricName) {
    return new File(directory, sanitize(metricName) + ".csv");
}

19 Source : CsvReporter.java
with Apache License 2.0
from alibaba

private void reportCounter(long timestamp, MetricName name, Counter counter) {
    report(timestamp, name, "count", "%d", counter.getCount());
}

19 Source : AlibabaMetricsExports.java
with Apache License 2.0
from alibaba

public void fromClusterHistogram(List<MetricFamilySamples> samples, MetricName metricName, ClusterHistogram clusterHistogram, long timestamp) {
    List<MetricFamilySamples.Sample> bucketSamples = new ArrayList<MetricFamilySamples.Sample>();
    long start = getNormalizedStartTime(timestamp, metricsCollectPeriodConfig.period(metricName.getMetricLevel()));
    Map<Long, Map<Long, Long>> bucketValues = clusterHistogram.getBucketValues(start);
    long[] buckets = clusterHistogram.getBuckets();
    if (bucketValues.containsKey(start)) {
        Map<Long, Long> bucketAndValues = bucketValues.get(start);
        for (long bucket : buckets) {
            bucketSamples.add(sampleBuilder.createSample(metricName, "_cluster_percentile", Arrays.asList("bucket"), Arrays.asList(bucket == Long.MAX_VALUE ? "+Inf" : Long.toString(bucket)), bucketAndValues.containsKey(bucket) ? bucketAndValues.get(bucket) : 0L));
        }
    } else {
        bucketSamples.add(sampleBuilder.createSample(metricName, "_cluster_percentile", EMPTY_LIST, EMPTY_LIST, 0L));
    }
    samples.add(new MetricFamilySamples(bucketSamples.get(0).name, Type.HISTOGRAM, getHelpMessage(metricName.getKey(), clusterHistogram), bucketSamples));
}

19 Source : AlibabaMetricsExports.java
with Apache License 2.0
from alibaba

public void fromCounter(List<MetricFamilySamples> samples, MetricName metricName, Counter counter, long timestamp) {
    samples.add(new CounterMetricFamily(normalizeName(metricName.getKey()) + "_count", getHelpMessage(metricName.getKey(), counter), counter.getCount()));
    if (counter instanceof BucketCounter) {
        long start = getNormalizedStartTime(timestamp, ((BucketCounter) counter).getBucketInterval());
        if (((BucketCounter) counter).getBucketCounts().containsKey(start)) {
            samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_bucket_count", getHelpMessage(metricName.getKey(), counter), ((BucketCounter) counter).getBucketCounts().get(start)));
        } else {
            samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_bucket_count", getHelpMessage(metricName.getKey(), counter), 0));
        }
    }
}

19 Source : AlibabaMetricsExports.java
with Apache License 2.0
from alibaba

public void fromCompreplaced(List<MetricFamilySamples> samples, MetricName metricName, Compreplaced compreplaced, long timestamp) {
    String helpMessage = getHelpMessage(metricName.getKey(), compreplaced);
    fromSnapshot(samples, metricName, compreplaced.getSnapshot(), 1.0d / TimeUnit.MILLISECONDS.toNanos(1L), helpMessage);
    fromMeter(samples, metricName, compreplaced, timestamp, false);
    List<MetricFamilySamples.Sample> bucketSamples = new ArrayList<MetricFamilySamples.Sample>();
    int bucketInterval = compreplaced.getInstantCountInterval();
    long start = getNormalizedStartTime(timestamp, bucketInterval);
    // success count
    BucketCounter successCounter = compreplaced.getBucketSuccessCount();
    if (successCounter.getBucketCounts().containsKey(start)) {
        bucketSamples.add(sampleBuilder.createSample(metricName, "_bucket_count", Arrays.asList("category"), Arrays.asList("success"), successCounter.getBucketCounts().get(start)));
    } else {
        bucketSamples.add(sampleBuilder.createSample(metricName, "_bucket_count", Arrays.asList("category"), Arrays.asList("success"), 0));
    }
    // error count
    for (Map.Entry<String, BucketCounter> entry : compreplaced.getErrorCodeCounts().entrySet()) {
        String tag = entry.getKey();
        // error bucket count
        if (entry.getValue().getBucketCounts().containsKey(start)) {
            bucketSamples.add(sampleBuilder.createSample(metricName, "_bucket_count", Arrays.asList("category"), Arrays.asList(tag), entry.getValue().getBucketCounts().get(start)));
        } else {
            bucketSamples.add(sampleBuilder.createSample(metricName, "_bucket_count", Arrays.asList("category"), Arrays.asList(tag), 0));
        }
    }
    samples.add(new MetricFamilySamples(bucketSamples.get(0).name, Type.GAUGE, helpMessage, bucketSamples));
    List<MetricFamilySamples.Sample> addonSamples = new ArrayList<MetricFamilySamples.Sample>();
    // addon count
    for (Map.Entry<String, BucketCounter> entry : compreplaced.getAddonCounts().entrySet()) {
        String tag = entry.getKey();
        if (entry.getValue().getBucketCounts().containsKey(start)) {
            addonSamples.add(sampleBuilder.createSample(metricName, "_addon_bucket_count", Arrays.asList("addon"), Arrays.asList(tag), entry.getValue().getBucketCounts().get(start)));
        } else {
            addonSamples.add(sampleBuilder.createSample(metricName, "_addon_bucket_count", Arrays.asList("addon"), Arrays.asList(tag), 0));
        }
    }
    samples.add(new MetricFamilySamples(addonSamples.get(0).name, Type.GAUGE, helpMessage, addonSamples));
}

19 Source : AlibabaMetricsExports.java
with Apache License 2.0
from alibaba

public void fromFastCompreplaced(List<MetricFamilySamples> samples, MetricName metricName, FastCompreplaced fastCompreplaced, long timestamp) {
    int bucketInterval = fastCompreplaced.getBucketInterval();
    long start = getNormalizedStartTime(timestamp, bucketInterval);
    List<MetricFamilySamples.Sample> bucketSamples = new ArrayList<MetricFamilySamples.Sample>();
    Map<String, Map<Long, Long>> countPerCategory = fastCompreplaced.getMethodCountPerCategory(start);
    for (Map.Entry<String, Map<Long, Long>> entry : countPerCategory.entrySet()) {
        String tag = entry.getKey();
        if (entry.getValue().containsKey(start)) {
            long count = entry.getValue().get(start);
            bucketSamples.add(sampleBuilder.createSample(metricName, "_bucket_count", Arrays.asList("category"), Arrays.asList(tag), count));
        } else {
            bucketSamples.add(sampleBuilder.createSample(metricName, "_bucket_count", Arrays.asList("category"), Arrays.asList(tag), 0));
        }
    }
    for (Map.Entry<String, Map<Long, Long>> entry : fastCompreplaced.getMethodRtPerCategory(start).entrySet()) {
        String tag = entry.getKey();
        if (entry.getValue().containsKey(start)) {
            long rt = entry.getValue().get(start);
            bucketSamples.add(sampleBuilder.createSample(metricName, "_bucket_sum", Arrays.asList("category"), Arrays.asList(tag), rt));
        } else {
            bucketSamples.add(sampleBuilder.createSample(metricName, "_bucket_sum", Arrays.asList("category"), Arrays.asList(tag), 0));
        }
    }
    samples.add(new MetricFamilySamples(bucketSamples.get(0).name, Type.GAUGE, getHelpMessage(metricName.getKey(), fastCompreplaced), bucketSamples));
}

19 Source : AlibabaMetricsExports.java
with Apache License 2.0
from alibaba

private void fromSnapshot(List<MetricFamilySamples> samples, MetricName metricName, Snapshot snapshot, double factor, String helpMessage) {
    List<MetricFamilySamples.Sample> snapshotSamples = Arrays.asList(sampleBuilder.createSample(metricName, "_summary", Arrays.asList("quantile"), Arrays.asList("0.5"), snapshot.getMedian() * factor), sampleBuilder.createSample(metricName, "_summary", Arrays.asList("quantile"), Arrays.asList("0.75"), snapshot.get75thPercentile() * factor), sampleBuilder.createSample(metricName, "_summary", Arrays.asList("quantile"), Arrays.asList("0.95"), snapshot.get95thPercentile() * factor), sampleBuilder.createSample(metricName, "_summary", Arrays.asList("quantile"), Arrays.asList("0.99"), snapshot.get99thPercentile() * factor));
    samples.add(new MetricFamilySamples(snapshotSamples.get(0).name, Type.SUMMARY, helpMessage, snapshotSamples));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey() + "_min"), helpMessage, snapshot.getMin() * factor));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey() + "_max"), helpMessage, snapshot.getMax() * factor));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey() + "_mean"), helpMessage, snapshot.getMean() * factor));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey() + "_stddev"), helpMessage, snapshot.getStdDev() * factor));
}

19 Source : AlibabaMetricsExports.java
with Apache License 2.0
from alibaba

public void fromHistogram(List<MetricFamilySamples> samples, MetricName metricName, Histogram histogram) {
    String helpMessage = getHelpMessage(metricName.getKey(), histogram);
    fromSnapshot(samples, metricName, histogram.getSnapshot(), 1.0d, helpMessage);
    samples.add(new CounterMetricFamily(normalizeName(metricName.getKey()) + "_count", helpMessage, histogram.getCount()));
}

19 Source : AlibabaMetricsExports.java
with Apache License 2.0
from alibaba

public void fromMeter(List<MetricFamilySamples> samples, MetricName metricName, Metered meter, long timestamp, boolean collectBucketCount) {
    samples.add(new CounterMetricFamily(normalizeName(metricName.getKey()) + "_count", getHelpMessage(metricName.getKey(), meter), meter.getCount()));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_m1", getHelpMessage(metricName.getKey(), meter), meter.getOneMinuteRate()));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_m5", getHelpMessage(metricName.getKey(), meter), meter.getFiveMinuteRate()));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_m15", getHelpMessage(metricName.getKey(), meter), meter.getFifteenMinuteRate()));
    if (!collectBucketCount) {
        return;
    }
    long start = getNormalizedStartTime(timestamp, meter.getInstantCountInterval());
    if (meter.getInstantCount().containsKey(start)) {
        samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_bucket_count", getHelpMessage(metricName.getKey(), meter), meter.getInstantCount().get(start)));
    } else {
        samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_bucket_count", getHelpMessage(metricName.getKey(), meter), 0));
    }
}

19 Source : AlibabaMetricsExports.java
with Apache License 2.0
from alibaba

public void fromTimer(List<MetricFamilySamples> samples, MetricName metricName, Timer timer, long timestamp) {
    String helpMessage = getHelpMessage(metricName.getKey(), timer);
    fromSnapshot(samples, metricName, timer.getSnapshot(), 1.0d / TimeUnit.MILLISECONDS.toNanos(1L), helpMessage);
    fromMeter(samples, metricName, timer, timestamp, true);
}

19 Source : BufferPoolMetricSetTest.java
with Apache License 2.0
from alibaba

public clreplaced BufferPoolMetricSetTest {

    private final MBeanServer mBeanServer = mock(MBeanServer.clreplaced);

    private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer);

    private ObjectName mapped;

    private ObjectName direct;

    private final MetricName DIRECT = MetricName.build("direct");

    private final MetricName MAPPED = MetricName.build("mapped");

    private final MetricName DIRECT_COUNT = DIRECT.resolve("count");

    private final MetricName DIRECT_CAPACITY = DIRECT.resolve("capacity");

    private final MetricName DIRECT_USED = DIRECT.resolve("used");

    private final MetricName MAPPED_COUNT = MAPPED.resolve("count");

    private final MetricName MAPPED_CAPACITY = MAPPED.resolve("capacity");

    private final MetricName MAPPED_USED = MAPPED.resolve("used");

    @Before
    public void setUp() throws Exception {
        this.mapped = new ObjectName("java.nio:type=BufferPool,name=mapped");
        this.direct = new ObjectName("java.nio:type=BufferPool,name=direct");
    }

    @Test
    public void includesGaugesForDirectAndMappedPools() throws Exception {
        replacedertThat(buffers.getMetrics().keySet()).containsOnly(DIRECT_COUNT, DIRECT_USED, DIRECT_CAPACITY, MAPPED_COUNT, MAPPED_USED, MAPPED_CAPACITY);
    }

    @Test
    public void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception {
        when(mBeanServer.getMBeanInfo(mapped)).thenThrow(new InstanceNotFoundException());
        replacedertThat(buffers.getMetrics().keySet()).containsOnly(DIRECT_COUNT, DIRECT_USED, DIRECT_CAPACITY);
    }

    @Test
    public void includesAGaugeForDirectCount() throws Exception {
        final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_COUNT);
        when(mBeanServer.getAttribute(direct, "Count")).thenReturn(100);
        replacedertThat(gauge.getValue()).isEqualTo(100);
    }

    @Test
    public void includesAGaugeForDirectMemoryUsed() throws Exception {
        final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_USED);
        when(mBeanServer.getAttribute(direct, "MemoryUsed")).thenReturn(100);
        replacedertThat(gauge.getValue()).isEqualTo(100);
    }

    @Test
    public void includesAGaugeForDirectCapacity() throws Exception {
        final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_CAPACITY);
        when(mBeanServer.getAttribute(direct, "TotalCapacity")).thenReturn(100);
        replacedertThat(gauge.getValue()).isEqualTo(100);
    }

    @Test
    public void includesAGaugeForMappedCount() throws Exception {
        final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_COUNT);
        when(mBeanServer.getAttribute(mapped, "Count")).thenReturn(100);
        replacedertThat(gauge.getValue()).isEqualTo(100);
    }

    @Test
    public void includesAGaugeForMappedMemoryUsed() throws Exception {
        final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_USED);
        when(mBeanServer.getAttribute(mapped, "MemoryUsed")).thenReturn(100);
        replacedertThat(gauge.getValue()).isEqualTo(100);
    }

    @Test
    public void includesAGaugeForMappedCapacity() throws Exception {
        final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_CAPACITY);
        when(mBeanServer.getAttribute(mapped, "TotalCapacity")).thenReturn(100);
        replacedertThat(gauge.getValue()).isEqualTo(100);
    }
}

19 Source : TimeMetricLevelFilterTest.java
with Apache License 2.0
from alibaba

private void testTimeLevelFilterPerformance(TimeMetricLevelFilter filter, int iterations) {
    MetricName name = new MetricName("test", MetricLevel.CRITICAL);
    long start = System.currentTimeMillis();
    for (int i = 0; i < iterations; i++) {
        filter.matches(name, counter);
    }
    System.out.println("TimeMetricLevelFilter#matches costs: " + (System.currentTimeMillis() - start) + " ms for " + iterations + " calls.");
}

19 Source : TimeMetricLevelFilterTest.java
with Apache License 2.0
from alibaba

@Test
public void testNull() throws InterruptedException {
    TimeMetricLevelFilter filter = new TimeMetricLevelFilter(null);
    MetricName name = new MetricName("test", MetricLevel.NORMAL);
    replacedert.replacedertTrue(filter.matches(name, null));
    TimeUnit.SECONDS.sleep(2);
    replacedert.replacedertTrue(filter.matches(name, null));
}

19 Source : NormalMetricsCollector.java
with Apache License 2.0
from alibaba

@Override
public void collect(MetricName name, Counter counter, long timestamp) {
    MetricName normalizedName = name.getKey().endsWith("count") ? name : name.resolve("count");
    this.addMetric(normalizedName, counter.getCount(), timestamp, MetricObject.MetricType.COUNTER, metricsCollectPeriodConfig.period(name.getMetricLevel()));
    if (counter instanceof BucketCounter) {
        int countInterval = ((BucketCounter) counter).getBucketInterval();
        // bucket count
        addInstantCountMetric(((BucketCounter) counter).getBucketCounts(), name, countInterval, timestamp);
    }
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

public MetricsCollector addMetric(MetricName name, MetricName suffix, Object value, long timestamp, MetricObject.MetricType type, int interval) {
    MetricName fullName = MetricName.join(name, suffix);
    return addMetric(fullName, value, timestamp, type, interval);
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

protected void addCompreplacedErrorCode(MetricName name, Compreplaced compreplaced, long timestamp) {
    int countInterval = compreplaced.getInstantCountInterval();
    long start = getNormalizedStartTime(timestamp, countInterval);
    for (Map.Entry<String, BucketCounter> entry : compreplaced.getErrorCodeCounts().entrySet()) {
        this.addMetric(name, MetricName.build("error.count").tagged("error", entry.getKey()), entry.getValue().getCount(), timestamp, MetricObject.MetricType.COUNTER, metricsCollectPeriodConfig.period(name.getMetricLevel()));
        MetricName errorName = MetricName.build("error_bucket_count").tagged("error", entry.getKey());
        Map<Long, Long> errorCodeBucket = entry.getValue().getBucketCounts();
        if (errorCodeBucket.containsKey(start)) {
            this.addMetric(name, errorName, errorCodeBucket.get(start), start, MetricObject.MetricType.DELTA, countInterval);
        } else {
            this.addMetric(name, errorName, 0L, start, MetricObject.MetricType.DELTA, countInterval);
        }
    }
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

protected void addInstantCountMetric(Map<Long, Long> instantCount, MetricName name, int countInterval, long timestamp) {
    long start = getNormalizedStartTime(timestamp, countInterval);
    // only the latest instant rate, for compatibility
    if (instantCount.containsKey(start)) {
        this.addMetric(name, "bucket_count", instantCount.get(start), start, MetricObject.MetricType.DELTA, countInterval);
        this.addMetric(name, "qps", rate(instantCount.get(start), countInterval), start, MetricObject.MetricType.GAUGE, countInterval);
    } else {
        this.addMetric(name, "bucket_count", 0L, start, MetricObject.MetricType.DELTA, countInterval);
        this.addMetric(name, "qps", 0.0d, start, MetricObject.MetricType.GAUGE, countInterval);
    }
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

@Override
public void collect(MetricName name, FastCompreplaced fastCompreplaced, long timestamp) {
    int bucketInterval = fastCompreplaced.getBucketInterval();
    long start = getNormalizedStartTime(timestamp, bucketInterval);
    long totalCount = 0;
    long totalRt = 0;
    long successCount = 0;
    long hitCount = -1;
    Map<String, Map<Long, Long>> countPerCategory = fastCompreplaced.getMethodCountPerCategory(start);
    for (Map.Entry<String, Map<Long, Long>> entry : countPerCategory.entrySet()) {
        if (entry.getValue().containsKey(start)) {
            this.addMetric(name, entry.getKey() + "_bucket_count", entry.getValue().get(start), start, MetricObject.MetricType.DELTA, bucketInterval);
            totalCount += entry.getValue().get(start);
            if ("success".equals(entry.getKey())) {
                successCount += entry.getValue().get(start);
            }
            if ("hit".equals(entry.getKey())) {
                hitCount = entry.getValue().get(start);
                successCount += entry.getValue().get(start);
            }
        } else {
            this.addMetric(name, entry.getKey() + "_bucket_count", 0L, start, MetricObject.MetricType.DELTA, bucketInterval);
        }
    }
    for (Map.Entry<String, Map<Long, Long>> entry : fastCompreplaced.getMethodRtPerCategory(start).entrySet()) {
        if (entry.getValue().containsKey(start)) {
            totalRt += entry.getValue().get(start);
        }
    }
    this.addMetric(name, "bucket_count", totalCount, start, MetricObject.MetricType.DELTA, bucketInterval);
    this.addMetric(name, "bucket_sum", totalRt, start, MetricObject.MetricType.DELTA, bucketInterval);
    this.addMetric(name, "qps", rate(totalCount, bucketInterval), start, MetricObject.MetricType.GAUGE, bucketInterval);
    this.addMetric(name, "rt", rate(totalRt, totalCount), start, MetricObject.MetricType.GAUGE, bucketInterval);
    this.addMetric(name, "success_rate", ratio(successCount, totalCount), start, MetricObject.MetricType.GAUGE, bucketInterval);
    if (hitCount >= 0) {
        // TODO special case for tair
        this.addMetric(name, "hit_rate", ratio(hitCount, successCount), start, MetricObject.MetricType.GAUGE, bucketInterval);
    }
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

public MetricsCollector addMetric(MetricName fullName, Object value, long timestamp, MetricObject.MetricType type, int interval) {
    MetricObject obj = MetricObject.named(fullName.getKey()).withType(type).withTimestamp(timestamp).withValue(value).withTags(merge(globalTags, fullName.getTags())).withLevel(fullName.getMetricLevel()).withInterval(interval).build();
    return addMetric(obj);
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

public MetricsCollector addMetric(MetricName name, String suffix, Object value, long timestamp, MetricObject.MetricType type, int interval) {
    MetricName fullName = name.resolve(suffix);
    return addMetric(fullName, value, timestamp, type, interval);
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

protected void addAddonMetric(MetricName name, Compreplaced compreplaced, long timestamp) {
    int countInterval = compreplaced.getInstantCountInterval();
    long start = getNormalizedStartTime(timestamp, countInterval);
    for (Map.Entry<String, BucketCounter> entry : compreplaced.getAddonCounts().entrySet()) {
        MetricName addonName = MetricName.build(entry.getKey(), "count");
        this.addMetric(name, addonName, entry.getValue().getCount(), timestamp, MetricObject.MetricType.COUNTER, metricsCollectPeriodConfig.period(name.getMetricLevel()));
        MetricName addonBucketName = MetricName.build(entry.getKey() + "_bucket_count");
        Map<Long, Long> addOnBucket = entry.getValue().getBucketCounts();
        if (addOnBucket.containsKey(start)) {
            this.addMetric(name, addonBucketName, addOnBucket.get(start), start, MetricObject.MetricType.DELTA, countInterval);
            Long successTotal = compreplaced.getBucketSuccessCount().getBucketCounts().get(start);
            if (successTotal == null) {
                // 当addon的统计桶被更新,然而总次数的更新被延迟到了下一个桶时会出现这种情况,
                // 这种情况下认为addon == successTotal
                successTotal = addOnBucket.get(start);
            }
            this.addMetric(name, entry.getKey() + "_rate", ratio(addOnBucket.get(start), successTotal), start, MetricObject.MetricType.GAUGE, compreplaced.getInstantCountInterval());
        } else {
            this.addMetric(name, addonBucketName, 0L, start, MetricObject.MetricType.DELTA, countInterval);
            this.addMetric(name, entry.getKey() + "_rate", 0.0d, start, MetricObject.MetricType.GAUGE, compreplaced.getInstantCountInterval());
        }
    }
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

public MetricsCollector addMetric(MetricName name, String suffix, Object value, long timestamp, MetricObject.MetricType type) {
    MetricName fullName = name.resolve(suffix);
    return addMetric(fullName, value, timestamp, type, metricsCollectPeriodConfig.period(fullName.getMetricLevel()));
}

19 Source : MetricsCollector.java
with Apache License 2.0
from alibaba

public MetricsCollector addMetric(MetricName name, String suffix, Object value, long timestamp) {
    return addMetric(name, suffix, value, timestamp, MetricObject.MetricType.GAUGE);
}

19 Source : MetricNameSetFilter.java
with Apache License 2.0
from alibaba

private boolean matchCompreplacedAddon(String nameToMatch, MetricName name, Compreplaced compreplaced) {
    if (nameToMatch == null) {
        return false;
    }
    for (String addon : compreplaced.getAddonCounts().keySet()) {
        String nameWithAddon = name.getKey() + "." + addon + ".count";
        if (nameToMatch.equals(nameWithAddon)) {
            return true;
        }
        String nameWithAddonBucket = name.getKey() + "." + addon + "_bucket_count";
        if (nameToMatch.equals(nameWithAddonBucket)) {
            return true;
        }
        String nameWithAddonRate = name.getKey() + "." + addon + "_rate";
        if (nameToMatch.equals(nameWithAddonRate)) {
            return true;
        }
    }
    return false;
}

19 Source : CompactMetricsCollector.java
with Apache License 2.0
from alibaba

@Override
public void collect(MetricName name, Histogram histogram, long timestamp) {
    final Snapshot snapshot = histogram.getSnapshot();
    this.addMetric(name, "mean", snapshot.getMean(), timestamp);
}

19 Source : CompactMetricsCollector.java
with Apache License 2.0
from alibaba

@Override
public void collect(MetricName name, Timer timer, long timestamp) {
    final Snapshot snapshot = timer.getSnapshot();
    this.addMetric(name, "count", timer.getCount(), timestamp, MetricObject.MetricType.COUNTER).addMetric(name, "m1", convertRate(timer.getOneMinuteRate()), timestamp).addMetric(name, "rt", convertDuration(snapshot.getMean()), timestamp).addMetric(name, "mean", convertDuration(snapshot.getMean()), timestamp);
    // instant count
    addInstantCountMetric(timer.getInstantCount(), name, timer.getInstantCountInterval(), timestamp);
}

19 Source : ClassifiedMetricsCollector.java
with Apache License 2.0
from alibaba

private MetricsCollector addMetric(MetricName fullName, Object value, long timestamp, MetricObject.MetricType type, String meterName) {
    MetricObject obj = MetricObject.named(fullName.getKey()).withType(type).withTimestamp(timestamp).withValue(value).withTags(merge(globalTags, fullName.getTags())).withLevel(fullName.getMetricLevel()).withMeterName(meterName).build();
    return addMetric(obj);
}

19 Source : ClassifiedMetricsCollector.java
with Apache License 2.0
from alibaba

public MetricsCollector addMetric(MetricName name, String suffix, Object value, long timestamp, MetricObject.MetricType type, String meterName) {
    MetricName fullName = name.resolve(suffix);
    return addMetric(fullName, value, timestamp, type, meterName);
}

19 Source : ClassifiedMetricsCollector.java
with Apache License 2.0
from alibaba

@Override
public void collect(MetricName name, Counter counter, long timestamp) {
    int interval = metricsCollectPeriodConfig.period(name.getMetricLevel()) * 1000;
    long startTime = lastTimestamp.get(name.getMetricLevel()) + interval;
    long endTime = (timestamp / interval - 1) * interval;
    startTime = adjustStartTime(startTime, endTime, interval, name.getMetricLevel());
    long guageTimestamp = startTime;
    if (counter instanceof BucketCounter) {
        Map<Long, Long> totalCounts = ((BucketCounter) counter).getBucketCounts(startTime);
        // String suffix = "s" + ((BucketCounter) counter).getBucketInterval() + "_count";
        for (long time = startTime; time <= endTime; time = time + interval) {
            long metricValue = 0;
            if (totalCounts.containsKey(time)) {
                metricValue = totalCounts.get(time);
            }
            this.addMetric(name, "bucket_count", metricValue, time, MetricObject.MetricType.DELTA, COUNTER_NAME);
        }
    }
    String normalizedName = name.getKey().endsWith("count") ? name.getKey() : name.resolve("count").getKey();
    MetricObject metricObject = MetricObject.named(normalizedName).withTimestamp(guageTimestamp).withType(MetricObject.MetricType.COUNTER).withValue(counter.getCount()).withLevel(name.getMetricLevel()).withTags(merge(globalTags, name.getTags())).withMeterName(COUNTER_NAME).build();
    this.addMetric(metricObject);
}

19 Source : ClassifiedMetricsCollector.java
with Apache License 2.0
from alibaba

@Override
public void collect(MetricName name, ClusterHistogram clusterHistogram, long timestamp) {
    int interval = metricsCollectPeriodConfig.period(name.getMetricLevel()) * 1000;
    long startTime = lastTimestamp.get(name.getMetricLevel()) + interval;
    long endTime = (timestamp / interval - 1) * interval;
    startTime = adjustStartTime(startTime, endTime, interval, name.getMetricLevel());
    Map<Long, Map<Long, Long>> bucketValues = clusterHistogram.getBucketValues(startTime);
    for (long curTime = startTime; curTime <= endTime; curTime = curTime + interval) {
        if (!bucketValues.containsKey(curTime)) {
            continue;
        }
        Map<Long, Long> bucketAndValues = bucketValues.get(curTime);
        long[] buckets = clusterHistogram.getBuckets();
        for (long bucket : buckets) {
            this.addMetric(name.tagged("bucket", bucket == Long.MAX_VALUE ? "+Inf" : Long.toString(bucket)), "cluster_percentile", bucketAndValues.containsKey(bucket) ? bucketAndValues.get(bucket) : 0L, curTime, MetricObject.MetricType.PERCENTILE);
        }
    }
}

19 Source : ClassifiedMetricsCollector.java
with Apache License 2.0
from alibaba

@Override
public void collect(MetricName name, FastCompreplaced fastCompreplaced, long timestamp) {
    int intervalSeconds = metricsCollectPeriodConfig.period(name.getMetricLevel());
    int interval = metricsCollectPeriodConfig.period(name.getMetricLevel()) * 1000;
    long startTime = lastTimestamp.get(name.getMetricLevel()) + interval;
    long endTime = (timestamp / interval - 1) * interval;
    startTime = adjustStartTime(startTime, endTime, interval, name.getMetricLevel());
    long guageTimestamp = startTime;
    Map<String, Map<Long, Long>> countAndRtPerCategory = fastCompreplaced.getCountAndRtPerCategory(startTime);
    for (long time = startTime; time <= endTime; time = time + interval) {
        long totalCount = 0;
        long totalRt = 0;
        long successCount = 0;
        long hitCount = 0;
        long errorCount = 0;
        Map<Long, Long> hits = countAndRtPerCategory.get("hit");
        Map<Long, Long> successes = countAndRtPerCategory.get("success");
        Map<Long, Long> errors = countAndRtPerCategory.get("error");
        if (hits != null) {
            Long hitNum = hits.get(time);
            if (hitNum != null) {
                hitCount = getFastCompreplacedCount(hitNum);
                totalCount = totalCount + hitCount;
                totalRt = totalRt + getFastCompreplacedRt(hitNum);
            }
        }
        if (successes != null) {
            Long successNum = successes.get(time);
            if (successNum != null) {
                successCount = getFastCompreplacedCount(successNum);
                totalCount = totalCount + successCount;
                totalRt = totalRt + getFastCompreplacedRt(successNum);
            }
        }
        if (errors != null) {
            Long errorNum = errors.get(time);
            if (errorNum != null) {
                errorCount = getFastCompreplacedCount(errorNum);
                totalCount = totalCount + errorCount;
                totalRt = totalRt + getFastCompreplacedRt(errorNum);
            }
        }
        // 成功数为命中数加未命中数
        successCount = successCount + hitCount;
        this.addMetric(name, "bucket_count", totalCount, time, MetricObject.MetricType.DELTA, FASTCOMPreplaced_NAME);
        this.addMetric(name, "bucket_sum", totalRt, time, MetricObject.MetricType.DELTA, FASTCOMPreplaced_NAME);
        this.addMetric(name, "hit_bucket_count", hitCount, time, MetricObject.MetricType.DELTA, FASTCOMPreplaced_NAME);
        this.addMetric(name, "success_bucket_count", successCount, time, MetricObject.MetricType.DELTA, FASTCOMPreplaced_NAME);
        this.addMetric(name, "error_bucket_count", errorCount, time, MetricObject.MetricType.DELTA, FASTCOMPreplaced_NAME);
        this.addMetric(name, "qps", rate(totalCount, intervalSeconds), time, MetricObject.MetricType.GAUGE, FASTCOMPreplaced_NAME);
        this.addMetric(name, "rt", rate(totalRt, totalCount), time, MetricObject.MetricType.GAUGE, FASTCOMPreplaced_NAME);
        this.addMetric(name, "success_rate", ratio(successCount, totalCount), time, MetricObject.MetricType.GAUGE, FASTCOMPreplaced_NAME);
        if (hitCount >= 0) {
            // TODO special case for tair
            this.addMetric(name, "hit_rate", ratio(hitCount, successCount), time, MetricObject.MetricType.GAUGE, FASTCOMPreplaced_NAME);
        }
    }
}

18 Source : MetricsResource.java
with Apache License 2.0
from alibaba

@Path("/metrics")
public clreplaced MetricsResource {

    private final static Logger logger = LoggerFactory.getLogger(MetricsResource.clreplaced);

    private static IMetricManager manager = MetricManager.getIMetricManager();

    private static final double rateFactor = TimeUnit.SECONDS.toSeconds(1);

    private static final double durationFactor = 1.0 / TimeUnit.MILLISECONDS.toNanos(1);

    private static final String MULTI_GROUP_DELIM = ",";

    private static final MetricName baseName = new MetricName("middleware.metrics.rest.url");

    /**
     * list接口序列化MetricObject时过滤掉timestamp/value
     */
    private static final MetricObjectPropertyFilter filter = new MetricObjectPropertyFilter();

    @Path("/list")
    @GET
    @Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
    public Response listMetrics() {
        if (manager.isEnabled()) {
            Map<String, Set<MetricObject>> metrics = new LinkedHashMap<String, Set<MetricObject>>();
            for (String groupName : manager.listMetricGroups()) {
                MetricRegistry registry = manager.getMetricRegistryByGroup(groupName);
                Set<MetricObject> metricsPerRegistry = new LinkedHashSet<MetricObject>();
                metricsPerRegistry.addAll(buildMetricRegistry(registry));
                metrics.put(groupName, metricsPerRegistry);
            }
            try {
                String data = JSON.toJSONString(buildResultPojo(metrics, true, ""), filter);
                return Response.ok(data).build();
            } catch (Exception e) {
                return buildResult(null, false, e.toString());
            }
        } else {
            return buildResult(null, false, "Metrics has been disabled explicitly!");
        }
    }

    @GET
    @Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
    public Response getMetrics() {
        return getMetrics("all");
    }

    @GET
    @Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
    @Path("/{group}")
    public Response getMetrics(@DefaultValue("all") @PathParam("group") String group) {
        MetricName name = baseName.tagged("url", "/" + group).level(MetricLevel.TRIVIAL);
        Timer urlTimer = manager.getTimer("metrics", name, ReservoirType.BUCKET);
        Timer.Context context = urlTimer.time();
        try {
            if (!manager.isEnabled()) {
                return buildResult(null, false, "Metrics has been disabled explicitly!");
            }
            Map<String, List<MetricObject>> metricsData = new TreeMap<String, List<MetricObject>>();
            if ("all".equalsIgnoreCase(group) || group == null) {
                for (String groupName : manager.listMetricGroups()) {
                    try {
                        MetricRegistry registry = manager.getMetricRegistryByGroup(groupName);
                        metricsData.put(groupName, buildMetricRegistry(registry));
                    } catch (Throwable e) {
                        return buildResult(null, false, e.toString());
                    }
                }
                return buildResult(metricsData, true, "");
            } else if (group.contains(MULTI_GROUP_DELIM)) {
                String[] groups = group.split(MULTI_GROUP_DELIM);
                for (String groupName : groups) {
                    try {
                        // FIXME manager.getMetricRegistryByGroup will create one if group does not exist
                        if (!manager.listMetricGroups().contains(groupName)) {
                            continue;
                        }
                        MetricRegistry registry = manager.getMetricRegistryByGroup(groupName);
                        metricsData.put(groupName, buildMetricRegistry(registry));
                    } catch (Throwable e) {
                        return buildResult(null, false, e.toString());
                    }
                }
                return buildResult(metricsData, true, "");
            } else {
                // FIXME manager.getMetricRegistryByGroup will create one if group does not exist
                List<String> groups = manager.listMetricGroups();
                if (!groups.contains(group)) {
                    return buildResult(null, false, "The specified group is not found!");
                }
                MetricRegistry registry = manager.getMetricRegistryByGroup(group);
                return buildResult(buildMetricRegistry(registry), true, "");
            }
        } finally {
            context.stop();
        }
    }

    @GET
    @Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
    @Path("/{group}/level/{level}")
    public Response getMetricByLevel(@PathParam("group") final String group, @PathParam("level") final String level, @QueryParam("above") final boolean above) {
        if (!manager.isEnabled()) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        if (group.contains(MULTI_GROUP_DELIM)) {
            Map<String, List<MetricObject>> metricsData = new TreeMap<String, List<MetricObject>>();
            String[] groups = group.split(MULTI_GROUP_DELIM);
            String[] levels = level.split(MULTI_GROUP_DELIM);
            for (int i = 0; i < groups.length; i++) {
                try {
                    // FIXME manager.getMetricRegistryByGroup will create one if group does not exist
                    if (!manager.listMetricGroups().contains(groups[i])) {
                        continue;
                    }
                    MetricRegistry registry = manager.getMetricRegistryByGroup(groups[i]);
                    MetricLevelFilter levelFilter = new MetricLevelFilter(MetricLevel.valueOf(levels[i]), above);
                    metricsData.put(groups[i], buildMetricRegistry(registry, levelFilter));
                } catch (Throwable e) {
                    return buildResult(null, false, e.toString());
                }
            }
            return buildResult(metricsData, true, "");
        } else {
            // FIXME manager.getMetricRegistryByGroup will create one if group does not exist
            List<String> groups = manager.listMetricGroups();
            if (!groups.contains(group)) {
                return buildResult(null, false, "The specified group is not found!");
            }
            MetricRegistry registry = manager.getMetricRegistryByGroup(group);
            try {
                MetricLevelFilter levelFilter = new MetricLevelFilter(MetricLevel.valueOf(level), above);
                List<MetricObject> metricObjects = buildMetricRegistry(registry, levelFilter);
                if (metricObjects.isEmpty()) {
                    return buildResult(null, false, "No metric matching the specified level found!");
                }
                return buildResult(metricObjects);
            } catch (IllegalArgumentException e) {
                return buildResult(null, false, e.toString());
            }
        }
    }

    @GET
    @Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
    @Path("/{group}/{metric}")
    public Response getMetric(@PathParam("group") final String group, @PathParam("metric") final String metricName, @QueryParam("tagKey") final List<String> tagKeys, @QueryParam("tagValue") final List<String> tagValues) {
        if (!manager.isEnabled()) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        List<String> groups = manager.listMetricGroups();
        // FIXME manager.getMetricRegistryByGroup will create one if group does not exist
        if (!groups.contains(group)) {
            return buildResult(null, false, "The specified group is not found!");
        }
        MetricRegistry registry = manager.getMetricRegistryByGroup(group);
        List<MetricObject> metricObjects = buildMetricRegistry(registry, new MetricNameSetFilter(metricName));
        if (metricObjects.isEmpty()) {
            return buildResult(null, false, "The specified metric is not found!");
        }
        return buildResult(metricObjects);
    }

    @GET
    @Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
    @Path("/specific")
    public Response getMetric(@QueryParam("metric") final Set<String> metricNames, @QueryParam("zeroIgnore") boolean zeroIgnore) {
        if (!manager.isEnabled()) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        MetricName name = baseName.tagged("url", "/specific").level(MetricLevel.TRIVIAL);
        Timer urlTimer = manager.getTimer("metrics", name, ReservoirType.BUCKET);
        Timer.Context context = urlTimer.time();
        try {
            return getMetricsInternal(metricNames, zeroIgnore);
        } finally {
            context.stop();
        }
    }

    @POST
    @Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
    @Path("/specific")
    public Response getMetricsByPost(MultivaluedMap<String, String> params, @QueryParam("zeroIgnore") boolean zeroIgnore) {
        final Set<String> metricNames = new HashSet<String>(params.get("metric"));
        return getMetric(metricNames, zeroIgnore);
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
    @Path("/search")
    public Response searchMetrics(String metricsSearch, @HeaderParam("REMOTE_ADDR") String remoteAddr, @HeaderParam("X-Forwarded-For") String xForwardedFor, @Context HttpServletRequest httpServletRequest) {
        if (httpServletRequest != null) {
            logger.info("httpheader REMOTE_ADDR {}, httpheader X-Forwarded-For {};socket remoteaddr {}, port {}", remoteAddr, xForwardedFor, httpServletRequest.getRemoteAddr(), httpServletRequest.getRemotePort());
        } else {
            logger.info("httpheader REMOTE_ADDR {}, httpheader X-Forwarded-For {},httpServletRequest is null", remoteAddr, xForwardedFor);
        }
        if (!manager.isEnabled()) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        MetricName name = baseName.tagged("url", "/search").level(MetricLevel.TRIVIAL);
        Timer urlTimer = manager.getTimer("metrics", name, ReservoirType.BUCKET);
        Timer.Context context = urlTimer.time();
        try {
            MetricsSearchService service = MetricsSearchService.getInstance();
            return Response.ok(service.search(metricsSearch)).build();
        } catch (Throwable e) {
            logger.error("Error during handing search request: ", e);
            return Response.serverError().build();
        } finally {
            context.stop();
        }
    }

    private Response getMetricsInternal(final Set<String> metricNames, boolean zeroIgnore) {
        // FIXME manager.getMetricRegistryByGroup will create one if group does not exist
        List<String> groups = manager.listMetricGroups();
        MetricFilter keyFilter = new MetricNameSetFilter(metricNames);
        List<MetricObject> metricObjects = new ArrayList<MetricObject>();
        for (String group : groups) {
            MetricRegistry registry = manager.getMetricRegistryByGroup(group);
            metricObjects.addAll(buildMetricRegistry(registry, keyFilter));
        }
        if (metricObjects.isEmpty()) {
            return buildResult(null, false, "The specified metric is not found!");
        }
        if (zeroIgnore) {
            List<MetricObject> allMetricObjects = metricObjects;
            metricObjects = new ArrayList<MetricObject>();
            for (MetricObject o : allMetricObjects) {
                if ((o != null) && (!Utils.checkZero(o.getValue()))) {
                    metricObjects.add(o);
                }
            }
        }
        return buildResult(metricObjects);
    }

    private List<MetricObject> buildMetricRegistry(MetricRegistry registry) {
        return buildMetricRegistry(registry, null);
    }

    private List<MetricObject> buildMetricRegistry(MetricRegistry registry, MetricFilter filter) {
        long ts = System.currentTimeMillis();
        MetricsCollector collector = MetricsCollectorFactory.createNew(CollectLevel.NORMAL, rateFactor, durationFactor, filter);
        SortedMap<MetricName, Gauge> gauges = filter == null ? registry.getGauges() : registry.getGauges(filter);
        for (Map.Entry<MetricName, Gauge> entry : gauges.entrySet()) {
            collector.collect(entry.getKey(), entry.getValue(), ts);
        }
        SortedMap<MetricName, Counter> counters = filter == null ? registry.getCounters() : registry.getCounters(filter);
        for (Map.Entry<MetricName, Counter> entry : counters.entrySet()) {
            collector.collect(entry.getKey(), entry.getValue(), ts);
        }
        SortedMap<MetricName, Meter> meters = filter == null ? registry.getMeters() : registry.getMeters(filter);
        for (Map.Entry<MetricName, Meter> entry : meters.entrySet()) {
            collector.collect(entry.getKey(), entry.getValue(), ts);
        }
        SortedMap<MetricName, Histogram> histograms = filter == null ? registry.getHistograms() : registry.getHistograms(filter);
        for (Map.Entry<MetricName, Histogram> entry : histograms.entrySet()) {
            collector.collect(entry.getKey(), entry.getValue(), ts);
        }
        SortedMap<MetricName, Timer> timers = filter == null ? registry.getTimers() : registry.getTimers(filter);
        for (Map.Entry<MetricName, Timer> entry : timers.entrySet()) {
            collector.collect(entry.getKey(), entry.getValue(), ts);
        }
        SortedMap<MetricName, Compreplaced> compreplacedes = filter == null ? registry.getCompreplacedes() : registry.getCompreplacedes(filter);
        for (Map.Entry<MetricName, Compreplaced> entry : compreplacedes.entrySet()) {
            collector.collect(entry.getKey(), entry.getValue(), ts);
        }
        SortedMap<MetricName, FastCompreplaced> fastCompreplacedes = filter == null ? registry.getFastCompreplacedes() : registry.getFastCompreplacedes(filter);
        for (Map.Entry<MetricName, FastCompreplaced> entry : fastCompreplacedes.entrySet()) {
            collector.collect(entry.getKey(), entry.getValue(), ts);
        }
        SortedMap<MetricName, ClusterHistogram> clusterHistograms = filter == null ? registry.getClusterHistograms() : registry.getClusterHistograms(filter);
        for (Map.Entry<MetricName, ClusterHistogram> entry : clusterHistograms.entrySet()) {
            collector.collect(entry.getKey(), entry.getValue(), ts);
        }
        return collector.build();
    }
}

18 Source : MetricsResource.java
with Apache License 2.0
from alibaba

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
@Path("/search")
public Response searchMetrics(String metricsSearch, @HeaderParam("REMOTE_ADDR") String remoteAddr, @HeaderParam("X-Forwarded-For") String xForwardedFor, @Context HttpServletRequest httpServletRequest) {
    if (httpServletRequest != null) {
        logger.info("httpheader REMOTE_ADDR {}, httpheader X-Forwarded-For {};socket remoteaddr {}, port {}", remoteAddr, xForwardedFor, httpServletRequest.getRemoteAddr(), httpServletRequest.getRemotePort());
    } else {
        logger.info("httpheader REMOTE_ADDR {}, httpheader X-Forwarded-For {},httpServletRequest is null", remoteAddr, xForwardedFor);
    }
    if (!manager.isEnabled()) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }
    MetricName name = baseName.tagged("url", "/search").level(MetricLevel.TRIVIAL);
    Timer urlTimer = manager.getTimer("metrics", name, ReservoirType.BUCKET);
    Timer.Context context = urlTimer.time();
    try {
        MetricsSearchService service = MetricsSearchService.getInstance();
        return Response.ok(service.search(metricsSearch)).build();
    } catch (Throwable e) {
        logger.error("Error during handing search request: ", e);
        return Response.serverError().build();
    } finally {
        context.stop();
    }
}

18 Source : MetricsResource.java
with Apache License 2.0
from alibaba

@GET
@Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
@Path("/specific")
public Response getMetric(@QueryParam("metric") final Set<String> metricNames, @QueryParam("zeroIgnore") boolean zeroIgnore) {
    if (!manager.isEnabled()) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }
    MetricName name = baseName.tagged("url", "/specific").level(MetricLevel.TRIVIAL);
    Timer urlTimer = manager.getTimer("metrics", name, ReservoirType.BUCKET);
    Timer.Context context = urlTimer.time();
    try {
        return getMetricsInternal(metricNames, zeroIgnore);
    } finally {
        context.stop();
    }
}

18 Source : MetricsResource.java
with Apache License 2.0
from alibaba

@GET
@Produces({ Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML })
@Path("/{group}")
public Response getMetrics(@DefaultValue("all") @PathParam("group") String group) {
    MetricName name = baseName.tagged("url", "/" + group).level(MetricLevel.TRIVIAL);
    Timer urlTimer = manager.getTimer("metrics", name, ReservoirType.BUCKET);
    Timer.Context context = urlTimer.time();
    try {
        if (!manager.isEnabled()) {
            return buildResult(null, false, "Metrics has been disabled explicitly!");
        }
        Map<String, List<MetricObject>> metricsData = new TreeMap<String, List<MetricObject>>();
        if ("all".equalsIgnoreCase(group) || group == null) {
            for (String groupName : manager.listMetricGroups()) {
                try {
                    MetricRegistry registry = manager.getMetricRegistryByGroup(groupName);
                    metricsData.put(groupName, buildMetricRegistry(registry));
                } catch (Throwable e) {
                    return buildResult(null, false, e.toString());
                }
            }
            return buildResult(metricsData, true, "");
        } else if (group.contains(MULTI_GROUP_DELIM)) {
            String[] groups = group.split(MULTI_GROUP_DELIM);
            for (String groupName : groups) {
                try {
                    // FIXME manager.getMetricRegistryByGroup will create one if group does not exist
                    if (!manager.listMetricGroups().contains(groupName)) {
                        continue;
                    }
                    MetricRegistry registry = manager.getMetricRegistryByGroup(groupName);
                    metricsData.put(groupName, buildMetricRegistry(registry));
                } catch (Throwable e) {
                    return buildResult(null, false, e.toString());
                }
            }
            return buildResult(metricsData, true, "");
        } else {
            // FIXME manager.getMetricRegistryByGroup will create one if group does not exist
            List<String> groups = manager.listMetricGroups();
            if (!groups.contains(group)) {
                return buildResult(null, false, "The specified group is not found!");
            }
            MetricRegistry registry = manager.getMetricRegistryByGroup(group);
            return buildResult(buildMetricRegistry(registry), true, "");
        }
    } finally {
        context.stop();
    }
}

18 Source : MetricLevelFilter.java
with Apache License 2.0
from alibaba

public boolean matches(MetricName name, Metric metric) {
    if (matchLevelAbove) {
        return (level != null) && level.compareTo(name.getMetricLevel()) <= 0;
    } else {
        return (level != null) && level.toString().equalsIgnoreCase(name.getMetricLevel().toString());
    }
}

18 Source : Slf4jReporter.java
with Apache License 2.0
from alibaba

private void logMeter(MetricName name, Meter meter) {
    loggerProxy.log(marker, "type={}, name={}, count={}, mean_rate={}, m1={}, m5={}, m15={}, rate_unit={}", "METER", prefix(name), meter.getCount(), convertRate(meter.getMeanRate()), convertRate(meter.getOneMinuteRate()), convertRate(meter.getFiveMinuteRate()), convertRate(meter.getFifteenMinuteRate()), getRateUnit());
}

18 Source : Slf4jReporter.java
with Apache License 2.0
from alibaba

private void logGauge(MetricName name, Gauge gauge) {
    loggerProxy.log(marker, "type={}, name={}, value={}", "GAUGE", prefix(name), gauge.getValue());
}

18 Source : OpenTsdbReporter.java
with Apache License 2.0
from alibaba

private Set<OpenTsdbMetric> buildMeters(MetricName name, Meter meter, long timestamp) {
    final MetricsCollector collector = MetricsCollector.createNew(prefix(name.getKey()), merge(globalTags, name.getTags()), timestamp);
    return collector.addMetric("count", meter.getCount()).addMetric("mean_rate", convertRate(meter.getMeanRate())).addMetric("m1", convertRate(meter.getOneMinuteRate())).addMetric("m5", convertRate(meter.getFiveMinuteRate())).addMetric("m15", convertRate(meter.getFifteenMinuteRate())).build();
}

18 Source : OpenTsdbReporter.java
with Apache License 2.0
from alibaba

private OpenTsdbMetric buildGauge(MetricName name, Gauge gauge, long timestamp) {
    return OpenTsdbMetric.named(prefix(name.getKey(), "value")).withValue(gauge.getValue()).withTimestamp(timestamp).withTags(merge(globalTags, name.getTags())).build();
}

18 Source : FixedNameCsvFileProvider.java
with Apache License 2.0
from alibaba

private String sanitize(MetricName metricName) {
    // Forward slash character is definitely illegal in both Windows and Linux
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
    final String sanitizedName = metricName.getKey().replaceFirst("^/", "").replaceAll("/", ".");
    return sanitizedName;
}

18 Source : DefaultObjectNameFactory.java
with Apache License 2.0
from alibaba

public ObjectName createName(String type, String domain, MetricName metricName) {
    String name = metricName.getKey();
    try {
        ObjectName objectName = new ObjectName(domain, "name", name);
        if (objectName.isPattern()) {
            objectName = new ObjectName(domain, "name", ObjectName.quote(name));
        }
        return objectName;
    } catch (MalformedObjectNameException e) {
        try {
            return new ObjectName(domain, "name", ObjectName.quote(name));
        } catch (MalformedObjectNameException e1) {
            LOGGER.warn("Unable to register {} {}", type, name, e1);
            throw new RuntimeException(e1);
        }
    }
}

18 Source : CsvReporter.java
with Apache License 2.0
from alibaba

private void report(long timestamp, MetricName name, String header, String line, Object... values) {
    try {
        final File file = csvFileProvider.getFile(directory, name);
        final boolean fileAlreadyExists = file.exists();
        if (fileAlreadyExists || file.createNewFile()) {
            final PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, true), UTF_8));
            try {
                if (!fileAlreadyExists) {
                    out.println("t," + header);
                }
                out.printf(locale, String.format(locale, "%d,%s%n", timestamp, line), values);
            } finally {
                out.close();
            }
        }
    } catch (IOException e) {
        LOGGER.warn("Error writing to {}", name, e);
    }
}

18 Source : CsvReporter.java
with Apache License 2.0
from alibaba

private void reportMeter(long timestamp, MetricName name, Meter meter) {
    report(timestamp, name, "count,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit", "%d,%f,%f,%f,%f,events/%s", meter.getCount(), convertRate(meter.getMeanRate()), convertRate(meter.getOneMinuteRate()), convertRate(meter.getFiveMinuteRate()), convertRate(meter.getFifteenMinuteRate()), getRateUnit());
}

See More Examples