Java 类com.codahale.metrics.Metric 实例源码

项目:ja-micro    文件:MetricBuilder.java   
public synchronized GoTimer buildTimer() {
    String name = generateName("timing");
    GoTimer timer = getExistingTimer(name);
    if (timer == null) {
        timer = new GoTimer(name);
        Map<String, Metric> map = new HashMap<>(1);
        map.put(name, timer);
        MetricSet set = () -> map;
        try {
            registry.registerAll(set);
        } catch (Exception ex) {
            //I haven't figured out a good solution around this...
        }
    }
    return timer;
}
项目:r2cloud    文件:Metrics.java   
@Override
public ModelAndView doGet(IHTTPSession session) {
    ModelAndView result = new ModelAndView();
    JsonArray array = new JsonArray();
    for (Entry<String, Metric> cur : ru.r2cloud.metrics.Metrics.REGISTRY.getMetrics().entrySet()) {
        JsonObject curObject = new JsonObject();
        curObject.add("id", cur.getKey());
        curObject.add("url", "/admin/static/rrd/" + cur.getKey() + ".rrd");
        if (cur.getValue() instanceof FormattedCounter) {
            curObject.add("format", ((FormattedCounter) cur.getValue()).getFormat().toString());
        }
        if (cur.getValue() instanceof FormattedGauge<?>) {
            curObject.add("format", ((FormattedGauge<?>) cur.getValue()).getFormat().toString());
        }
        array.add(curObject);
    }
    result.setData(array.toString());
    return result;
}
项目:lambda-monitoring    文件:LambdaMetricSetTest.java   
@Test
public void testMetricSetAnnotations() {
    Map<String, Metric> metrics = new TestLambdaMetricSet().getMetrics();

    // Prove that the defaults fall back to the classname as namespace, and field name as metric name.
    assertThat(metrics.get("io.symphonia.lambda.metrics.LambdaMetricSetTest.TestLambdaMetricSet/fooCounter"),
            instanceOf(Counter.class));

    // Prove we can override the name via the annotation
    assertThat(metrics.get("io.symphonia.lambda.metrics.LambdaMetricSetTest.TestLambdaMetricSet/myBarCounter"),
            instanceOf(Counter.class));

    // Prove we can override the namespace via the annotation
    assertThat(metrics.get("test.namespace/bazCounter"), instanceOf(Counter.class));

    // Prove we can override the namespace and name via the annotation
    assertThat(metrics.get("test.namespace/myBingCounter"), instanceOf(Counter.class));

    // Prove we can override the namespace via a class-level annotation
    assertThat(new NamespaceTestLambdaMetricSet().getMetrics().get("test.namespace/fooCounter"),
            instanceOf(Counter.class));
}
项目:hashsdn-controller    文件:MeteredBoundedMailbox.java   
static <T extends Metric> void registerMetric(final scala.Option<ActorRef> owner, final String metricName,
        final T metric) {
    if (owner.isEmpty()) {
       // there's no actor to monitor
        return;
    }

    String actorName = owner.get().path().toStringWithoutAddress();
    String fullName = MetricRegistry.name(actorName, metricName);

    MetricRegistry registry = MetricsReporter.getInstance(MeteringBehavior.DOMAIN).getMetricsRegistry();

    if (registry.getMetrics().containsKey(fullName)) {
        // already registered
        return;
    }

    try {
        registry.register(fullName, metric);
    } catch (IllegalArgumentException e) {
        // already registered - shouldn't happen here since we check above...
        LOG.debug("Unable to register '{}' in metrics registry: {}", e);
    }
}
项目:HeliosStreams    文件:SharedMetricsRegistry.java   
protected synchronized void installMXBean(final ObjectName objectName, final String name, String description, final Metric metric) {
    if(objectName==null) throw new IllegalArgumentException("The passed ObjectName was null");
    if(name==null || name.trim().isEmpty()) throw new IllegalArgumentException("The passed name was null or empty");
    if(metric==null) throw new IllegalArgumentException("The passed Metric was null");

    DropWizardMetrics dwm = objectNameMetrics.putIfAbsent(objectName, PLACEHOLDER);
    if(dwm==null || dwm==PLACEHOLDER) {
        dwm = new DropWizardMetrics(objectName, description);
        objectNameMetrics.replace(objectName, dwm);
        try {
            JMXHelper.registerMBean(dwm, objectName);
        } catch (Exception ex) {
            /* No Op ? */
            log.error("Error registering DWM: [{}]", objectName, ex);
        }
    }
    dwm.addMetric(metric, name, description);
}
项目:monitoring-center    文件:MonitoringCenterServlet.java   
private void handleMetrics(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
    String format = StringUtils.trimToNull(httpServletRequest.getParameter("format"));
    String[] startsWithFilters = httpServletRequest.getParameterValues("startsWithFilter");

    if (FORMAT_GRAPHITE.equalsIgnoreCase(format)) {
        httpServletResponse.setContentType(CONTENT_TYPE_TEXT_PLAIN);

        try (PrintWriter printWriter = httpServletResponse.getWriter()) {
            SortedMap<String, Metric> metricsByNames = MonitoringCenter.getMetricsByNames(true, startsWithFilters);
            printWriter.write(graphiteMetricFormatter.format(metricsByNames));
        }
    } else {
        boolean appendPrefix = Boolean.TRUE.toString().equalsIgnoreCase(StringUtils.trimToNull(httpServletRequest.getParameter("appendPrefix")));

        Map<String, SortedMap<String, ? extends Metric>> responseMap = new LinkedHashMap<>();
        responseMap.put("gauges", MonitoringCenter.getGaugesByNames(appendPrefix, startsWithFilters));
        responseMap.put("counters", MonitoringCenter.getCountersByNames(appendPrefix, startsWithFilters));
        responseMap.put("histograms", MonitoringCenter.getHistogramsByNames(appendPrefix, startsWithFilters));
        responseMap.put("meters", MonitoringCenter.getMetersByNames(appendPrefix, startsWithFilters));
        responseMap.put("timers", MonitoringCenter.getTimersByNames(appendPrefix, startsWithFilters));

        writeAsJson(httpServletRequest, httpServletResponse, responseMap);
    }
}
项目:haven-platform    文件:WatchdogAnnotationPostProcessor.java   
private <A extends Annotation, T extends Metric> void processMetric(Class<?> targetClass,
                                                                    Method method,
                                                                    WatchdogRule rule,
                                                                    MetricAnnotationAccessor<A> annotationAccessor,
                                                                    MetricAdapter<T> metricAdapter) {
    A meteredAnn = method.getAnnotation(annotationAccessor.getAnnotationType());
    if(meteredAnn != null) {
        String name = MetricNameUtil.chooseName(annotationAccessor.getName(meteredAnn), annotationAccessor.isAbsoluteName(meteredAnn), targetClass, method);
        T meter = metricAdapter.getOrCreate(metricRegistry, name);
        if(meter == null) {
            LOG.warn("Can not find meter for name '{}'", name);
        } else {
            addLimitChecker(meter, rule, name);
        }
    }
}
项目:quarks    文件:MetricsEverywhereTest.java   
@Test
public void automaticMetricCleanup2() throws Exception {
    // Declare topology with custom metric oplet
    Topology t = newTopology();
    AtomicInteger n = new AtomicInteger(0);
    TStream<Integer> ints = t.poll(() -> n.incrementAndGet(), 10, TimeUnit.MILLISECONDS);
    TStream<Integer> ints2 = ints.pipe(new TestOplet<Integer>());
    ints2.pipe(new TestOplet<Integer>());

    // Submit job
    Future<? extends Job> fj = getSubmitter().submit(t);
    Job job = fj.get();
    Thread.sleep(TimeUnit.MILLISECONDS.toMillis(50));

    // Each test oplet registers two metrics 
    Map<String, Metric> all = metricRegistry.getMetrics();
    assertEquals(4, all.size());

    // After close all metrics have been unregistered 
    job.stateChange(Job.Action.CLOSE);
    assertEquals(0, all.size());
}
项目:semantic-metrics    文件:SemanticMetricRegistry.java   
private void notifyListenerOfAddedMetric(
    final SemanticMetricRegistryListener listener, final Metric metric, final MetricId name
) {
    if (metric instanceof Gauge) {
        listener.onGaugeAdded(name, (Gauge<?>) metric);
    } else if (metric instanceof Counter) {
        listener.onCounterAdded(name, (Counter) metric);
    } else if (metric instanceof Histogram) {
        listener.onHistogramAdded(name, (Histogram) metric);
    } else if (metric instanceof Meter) {
        listener.onMeterAdded(name, (Meter) metric);
    } else if (metric instanceof Timer) {
        listener.onTimerAdded(name, (Timer) metric);
    } else if (metric instanceof DerivingMeter) {
        listener.onDerivingMeterAdded(name, (DerivingMeter) metric);
    } else {
        throw new IllegalArgumentException("Unknown metric type: " + metric.getClass());
    }
}
项目:metrics-jvm-extras    文件:NativeMemoryUsageGaugeSetUnit0Test.java   
@SuppressWarnings("rawtypes")
@Test
public void testGetMetrics() throws Exception {
    when(smaps.get(KEY.VSS)).thenReturn(1L);
    when(smaps.get(KEY.RSS)).thenReturn(2L);
    when(smaps.get(KEY.PSS)).thenReturn(3L);
    when(smaps.get(KEY.SWAP)).thenReturn(4L);
    when(smaps.get(KEY.SWAPPSS)).thenReturn(5L);

    final NativeMemoryUsageGaugeSet uut = new NativeMemoryUsageGaugeSet(smaps);

    final Map<String, Metric> metrics = uut.getMetrics();

    assertNotNull(metrics);
    assertEquals(5, metrics.keySet().size());
    assertTrue(metrics.keySet()
            .containsAll(Arrays.asList("vss", "rss", "pss", "swap", "swappss")));

    assertEquals(1L, ((Gauge) metrics.get("vss")).getValue());
    assertEquals(2L, ((Gauge) metrics.get("rss")).getValue());
    assertEquals(3L, ((Gauge) metrics.get("pss")).getValue());
    assertEquals(4L, ((Gauge) metrics.get("swap")).getValue());
    assertEquals(5L, ((Gauge) metrics.get("swappss")).getValue());
}
项目:HttpSessionReplacer    文件:RedisSessionRepository.java   
/**
 * This method starts a separate thread that listens to key expirations
 * events.
 *
 * @param sessionManager
 */
@Override
public void setSessionManager(final SessionManager sessionManager) {
  this.sessionManager = sessionManager;
  MetricRegistry metrics = sessionManager.getMetrics();
  if (metrics != null) {
    // Cleanup old metrics related to this namespace
    metrics.removeMatching(new MetricFilter() {
      @Override
      public boolean matches(String name, Metric metric) {
        return name.startsWith(name(RedisConfiguration.METRIC_PREFIX, "redis"));
      }
    });
    if (sticky) {
      failoverMetrics = metrics.meter(name(RedisConfiguration.METRIC_PREFIX, namespace, "redis", "failover"));
    }

    redis.startMonitoring(metrics);
  }
  expirationManager.startExpiredSessionsTask(sessionManager);
}
项目:HeliosStreams    文件:MetricType.java   
/**
 * {@inheritDoc}
 * @see com.heliosapm.streams.jmx.metrics.MetricType.AttributeAdapter#invoke(com.codahale.metrics.Metric)
 */
@Override
public Object invoke(final Metric metric) {
    final Meter m = (Meter)metric;
    switch(this) {
        case RATE15M:
            return m.getFifteenMinuteRate();
        case RATE1M:
            return m.getOneMinuteRate();
        case RATE5M:
            return m.getFiveMinuteRate();
        case RATECOUNT:
            return m.getCount();
        case RATEMEAN:
            return m.getMeanRate();
        default:
            throw new RuntimeException();
    }
}
项目:graphite-monitor-example    文件:OperatingSystemGaugeSet.java   
@SuppressWarnings("boxing")
@Override
public Map<String, Metric> getMetrics() {
  final Map<String, Metric> gauges = new HashMap<>();

  gauges.put("committedVirtualMemorySize", (Gauge<Long>) () -> invokeLong(committedVirtualMemorySize));
  gauges.put("totalSwapSpaceSize", (Gauge<Long>) () -> invokeLong(totalSwapSpaceSize));
  gauges.put("freeSwapSpaceSize", (Gauge<Long>) () -> invokeLong(freeSwapSpaceSize));
  gauges.put("processCpuTime", (Gauge<Long>) () -> invokeLong(processCpuTime));
  gauges.put("freePhysicalMemorySize", (Gauge<Long>) () -> invokeLong(freePhysicalMemorySize));
  gauges.put("totalPhysicalMemorySize", (Gauge<Long>) () -> invokeLong(totalPhysicalMemorySize));
  gauges.put("fd.usage", (Gauge<Double>) () -> invokeRatio(openFileDescriptorCount, maxFileDescriptorCount));
  gauges.put("systemCpuLoad", (Gauge<Double>) () -> invokeDouble(systemCpuLoad));
  gauges.put("processCpuLoad", (Gauge<Double>) () -> invokeDouble(processCpuLoad));

  return gauges;
}
项目:monitoring-center    文件:MetricCollectorImpl.java   
private void registerMetricSetImpl(MetricSet metricSet, String namespace) {
    for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
        if (entry.getValue() == null) {
            continue;
        }

        if (MetricSet.class.isInstance(entry.getValue())) {
            MetricSet innerMetricSet = MetricSet.class.cast(entry.getValue());
            if (namespace == null) {
                registerMetricSet(innerMetricSet, entry.getKey());
            } else {
                registerMetricSetImpl(innerMetricSet, MetricNamingUtil.join(namespace, entry.getKey()));
            }
        } else {
            String name = null;
            if (namespace == null) {
                name = entry.getKey();
            } else {
                name = MetricNamingUtil.join(namespace, entry.getKey());
            }
            name = addPostfixIfNeeded(name, getPostfixForMetric(entry.getValue()));
            metricRegistry.register(name, entry.getValue());
        }
    }
}
项目:inbot-es-http-client    文件:RedisCache.java   
@Override
public Map<String, Metric> getMetrics() {
    // these metrics are interesting to keep track of the effectiveness of the cache
    Map<String, Metric> metrics = new HashMap<>();
    String prefix = "redis."+keyPrefix.replace('/', '.');
    metrics.put(prefix+".get", getTimer);
    metrics.put(prefix+".mget", mgetTimer);
    metrics.put(prefix+".put", putTimer);
    metrics.put(prefix+".del", delTimer);
    metrics.put(prefix+".miss", missMeter);
    metrics.put(prefix+".hit", hitMeter);
    metrics.put(prefix+".notfound", notFoundMeter);
    Gauge<Double> hitRatioGauge = new Gauge<Double>() {

        @Override
        public Double getValue() {
            double getCount = getTimer.getCount();
            double hitCount = hitMeter.getCount();
            return hitCount/getCount;
        }
    };
    metrics.put(prefix+".hitratio", hitRatioGauge);

    return metrics;
}
项目:quarks    文件:MetricsEverywhereTest.java   
@Test
public void automaticMetricCleanup1() throws Exception {
    // Declare topology with custom metric oplet
    Topology t = newTopology();
    AtomicInteger n = new AtomicInteger(0);
    TStream<Integer> ints = t.poll(() -> n.incrementAndGet(), 10, TimeUnit.MILLISECONDS);
    ints.pipe(new TestOplet<Integer>());

    // Submit job
    Future<? extends Job> fj = getSubmitter().submit(t);
    Job job = fj.get();
    Thread.sleep(TimeUnit.MILLISECONDS.toMillis(50));

    // At least one tuple was processed
    int tupleCount = n.get(); 
    assertTrue("Expected more tuples than "+ tupleCount, tupleCount > 0);

    // Each test oplet registers two metrics 
    Map<String, Metric> all = metricRegistry.getMetrics();
    assertEquals(2, all.size());

    // After close all metrics have been unregistered 
    job.stateChange(Job.Action.CLOSE);
    assertEquals(0, all.size());
}
项目:emodb    文件:EmoGarbageCollectorMetricSet.java   
@Override
public Map<String, Metric> getMetrics() {
    final Map<String, Metric> metrics = new HashMap();
    for (final GarbageCollectorMXBean garbageCollectorMXBean : _garbageCollectorMXBeans) {
        final String collectorName = garbageCollectorMXBean.getName().replaceAll("[\\s]+", "_");
        String timeName = String.format("time[collector:%s]", collectorName);
        metrics.put(timeName, new Gauge<Long>() {
            @Override
            public Long getValue() {
                return garbageCollectorMXBean.getCollectionTime();
            }
        });

        String runsName = String.format("runs[collector:%s]", collectorName);
        metrics.put(runsName, new Gauge<Long>() {
            @Override
            public Long getValue() {
                return garbageCollectorMXBean.getCollectionCount();
            }
        });
    }
    return metrics;
}
项目:riposte    文件:SignalFxAwareCodahaleMetricsCollectorTest.java   
@DataProvider(value = {
    "null",
    "0",
    "1",
    "2"
}, splitBy = "\\|")
@Test
public void getNamedMetric_with_varargs_dimensions_creates_dimensioned_metric_using_sfx_mechanisms(
    Integer numDimensions
) {
    // given
    String metricName = UUID.randomUUID().toString();
    Pair<String, String>[] varargDims = generateVarargDimensions(numDimensions);
    List<Pair<String, String>> dimsAsList = (varargDims == null) ? null : Arrays.asList(varargDims);

    // when
    Metric result = sfxImpl.getNamedMetric(metricName, genericMetricBuilderMock, varargDims);

    // then
    verifyMetricCreation(genericMetricBuilderMock, genericMetricTaggerMock, metricName, dimsAsList, genericMetricMock, result);
}
项目:riposte    文件:SignalFxAwareCodahaleMetricsCollectorTest.java   
@DataProvider(value = {
    "null",
    "0",
    "1",
    "2"
}, splitBy = "\\|")
@Test
public void getNamedMetric_with_iterable_dimensions_creates_dimensioned_metric_using_sfx_mechanisms(
    Integer numDimensions
) {
    // given
    String metricName = UUID.randomUUID().toString();
    List<Pair<String, String>> iterableDims = generateIterableDimensions(numDimensions);

    // when
    Metric result = sfxImpl.getNamedMetric(metricName, genericMetricBuilderMock, iterableDims);

    // then
    verifyMetricCreation(genericMetricBuilderMock, genericMetricTaggerMock, metricName, iterableDims, genericMetricMock, result);
}
项目:riposte    文件:SignalFxEndpointMetricsHandlerTest.java   
@DataProvider(value = {
    "true   |   true",
    "false  |   false"
}, splitBy = "\\|")
@Test
public void RollingWindowTimerBuilder_isInstance_works_as_expected(boolean useTimer, boolean expectedResult) {
    // given
    Metric metric = (useTimer) ? mock(Timer.class) : mock(Gauge.class);
    RollingWindowTimerBuilder rwtb = new RollingWindowTimerBuilder(42, TimeUnit.DAYS);

    // when
    boolean result = rwtb.isInstance(metric);

    // then
    assertThat(result).isEqualTo(expectedResult);
}
项目:mongoose-base    文件:CustomMetricRegistry.java   
@SuppressWarnings("unchecked")
private <T extends Metric> T getOrAdd(final String name, final MetricBuilder<T> builder) {
    final Metric metric = metrics.get(name);
    if(builder.isInstance(metric)) {
        return (T) metric;
    } else if(metric == null) {
        try {
            return register(name, builder.newMetric());
        } catch (IllegalArgumentException e) {
            final Metric added = metrics.get(name);
            if(builder.isInstance(added)) {
                return (T) added;
            }
        }
    }
    throw new IllegalArgumentException(name + " is already used for a different type of metric");
}
项目:metrics-jvm-extras    文件:ProcessMemoryUsageGaugeSetUnit0Test.java   
@SuppressWarnings("rawtypes")
@Test
public void testGetMetrics() throws Exception {
    when(smaps.get(KEY.VSS)).thenReturn(1L);
    when(smaps.get(KEY.RSS)).thenReturn(2L);
    when(smaps.get(KEY.PSS)).thenReturn(3L);
    when(smaps.get(KEY.SWAP)).thenReturn(4L);
    when(smaps.get(KEY.SWAPPSS)).thenReturn(5L);

    final ProcessMemoryUsageGaugeSet uut = new ProcessMemoryUsageGaugeSet(smaps);

    final Map<String, Metric> metrics = uut.getMetrics();

    assertNotNull(metrics);
    assertEquals(5, metrics.keySet().size());
    assertTrue(metrics.keySet()
            .containsAll(Arrays.asList("vss", "rss", "pss", "swap", "swappss")));

    assertEquals(1L, ((Gauge) metrics.get("vss")).getValue());
    assertEquals(2L, ((Gauge) metrics.get("rss")).getValue());
    assertEquals(3L, ((Gauge) metrics.get("pss")).getValue());
    assertEquals(4L, ((Gauge) metrics.get("swap")).getValue());
    assertEquals(5L, ((Gauge) metrics.get("swappss")).getValue());
}
项目:drinkwater-java    文件:JVMMetricsBean.java   
private void registerAll(String prefix, MetricSet metricSet, MetricRegistry registry) {
    for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
        if (entry.getValue() instanceof MetricSet) {
            registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue(), registry);
        } else {
            registry.register(prefix + "." + entry.getKey(), entry.getValue());
        }
    }
}
项目:ja-micro    文件:MetricBuilder.java   
public synchronized GoCounter buildCounter() {
    String name = generateName("counter");
    GoCounter counter = getExistingCounter(name);
    if (counter == null) {
        counter = new GoCounter(name);
        Map<String, Metric> map = new HashMap<>();
        map.put(name, counter);
        MetricSet set = () -> map;
        registry.registerAll(set);
    }
    return counter;
}
项目:ja-micro    文件:MetricBuilder.java   
public synchronized GoGauge buildGauge() {
    String name = generateName("gauge");
    GoGauge gauge = getExistingGauge(name);
    if (gauge == null) {
        gauge = new GoGauge(name);
        Map<String, Metric> map = new HashMap<>();
        map.put(name, gauge);
        MetricSet set = () -> map;
        registry.registerAll(set);
    }
    return gauge;
}
项目:ja-micro    文件:MetricBuilder.java   
private GoTimer getExistingTimer(String name) {
    Metric m = registry.getMetrics().get(name);
    if (m instanceof GoTimer) {
        return (GoTimer) m;
    } else if (m != null) {
        logger.warn("Existing metric with name {} is not a GoTimer", name);
    }
    return null;
}
项目:ja-micro    文件:MetricBuilder.java   
private GoCounter getExistingCounter(String name) {
    Metric m = registry.getMetrics().get(name);
    if (m instanceof GoCounter) {
        return (GoCounter) m;
    } else if (m != null) {
        logger.warn("Existing metric with name {} is not a GoCounter", name);
    }
    return null;
}
项目:ja-micro    文件:MetricBuilder.java   
private GoGauge getExistingGauge(String name) {
    Metric m = registry.getMetrics().get(name);
    if (m instanceof GoGauge) {
        return (GoGauge) m;
    } else if (m != null) {
        logger.warn("Existing metric with name {} is not a GoGauge", name);
    }
    return null;
}
项目:JInsight    文件:FileDescriptorMetrics.java   
public Map<String, Metric> getMetrics() {
  final Map<String, Metric> gauges = new HashMap<>();
  if (osMxBean instanceof UnixOperatingSystemMXBean) {
    gauges.put("open", (Gauge<Long>) () -> getMetricLong("getOpenFileDescriptorCount"));
    gauges.put("max", (Gauge<Long>) () -> getMetricLong("getMaxFileDescriptorCount"));
  }
  return gauges;
}
项目:QDrill    文件:DrillMetrics.java   
private static void registerAll(String prefix, MetricSet metricSet, MetricRegistry registry) {
  for (Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
    if (entry.getValue() instanceof MetricSet) {
      registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue(), registry);
    } else {
      registry.register(prefix + "." + entry.getKey(), entry.getValue());
    }
  }
}
项目:QDrill    文件:DrillMetrics.java   
public static void resetMetrics(){
  RegistryHolder.REGISTRY.removeMatching(new MetricFilter(){
    @Override
    public boolean matches(String name, Metric metric) {
      return true;
    }});
  RegistryHolder.registerSysStats();
}
项目:QDrill    文件:PooledByteBufAllocatorL.java   
private synchronized void removeOldMetrics() {
  registry.removeMatching(new MetricFilter() {
    @Override
    public boolean matches(String name, Metric metric) {
      return name.startsWith("drill.allocator.");
    }
  });
}
项目:easyhbase    文件:CollectorMetric.java   
private void initRegistry() {
    // add JVM statistics
    metricRegistry.register("jvm.memory", new MemoryUsageGaugeSet());
    metricRegistry.register("jvm.vm", new JvmAttributeGaugeSet());
    metricRegistry.register("jvm.garbage-collectors", new GarbageCollectorMetricSet());
    metricRegistry.register("jvm.thread-states", new ThreadStatesGaugeSet());

    if (hBaseAsyncOperationMetrics != null) {
        Map<String, Metric> metrics = hBaseAsyncOperationMetrics.getMetrics();
        for (Map.Entry<String, Metric> metric : metrics.entrySet()) {
            metricRegistry.register(metric.getKey(), metric.getValue());
        }
    }
}
项目:easyhbase    文件:HBaseAsyncOperationMetrics.java   
@Override
public Map<String, Metric> getMetrics() {
    if (!hBaseAsyncOperation.isAvailable()) {
        return Collections.emptyMap();
    }

    final Map<String, Metric> gauges = new HashMap<>(3);
    gauges.put(COUNT, new Gauge<Long>() {
        @Override
        public Long getValue() {
            return hBaseAsyncOperation.getOpsCount();
        }
    });
    gauges.put(REJECTED_COUNT, new Gauge<Long>() {
        @Override
        public Long getValue() {
            return hBaseAsyncOperation.getOpsRejectedCount();
        }
    });
    gauges.put(FAILED_COUNT, new Gauge<Long>() {
        @Override
        public Long getValue() {
            return hBaseAsyncOperation.getOpsFailedCount();
        }
    });
    gauges.put(WAITING_COUNT, new Gauge<Long>() {
        @Override
        public Long getValue() {
            return hBaseAsyncOperation.getCurrentOpsCount();
        }
    });
    gauges.put(AVERAGE_LATENCY, new Gauge<Long>() {
        @Override
        public Long getValue() {
            return hBaseAsyncOperation.getOpsAverageLatency();
        }
    });

    return Collections.unmodifiableMap(gauges);
}
项目:athena    文件:MetricsWebResource.java   
/**
 * Gets stats information of all metrics. Returns array of all information for
 * all metrics.
 *
 * @return 200 OK with metric information as array
 * @onos.rsModel Metrics
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllMetrics() {
    ArrayNode metricsNode = root.putArray("metrics");
    service.getMetrics().forEach((name, metric) -> {
        ObjectNode item = mapper().createObjectNode();
        item.put("name", name);
        item.set("metric", codec(Metric.class).encode(metric, this));
        metricsNode.add(item);
    });

    return ok(root).build();
}
项目:athena    文件:MetricsWebResource.java   
/**
 * Gets stats information of a metric. Returns array of all information for the
 * specified metric.
 *
 * @param metricName metric name
 * @return 200 OK with metric information as array
 * @onos.rsModel Metric
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{metricName}")
public Response getMetricByName(@PathParam("metricName") String metricName) {
    ObjectNode metricNode = root.putObject("metric");
    MetricFilter filter = metricName != null ? (name, metric) -> name.equals(metricName) : MetricFilter.ALL;
    TreeMultimap<String, Metric> matched = listMetrics(service, filter);

    matched.asMap().get(metricName).forEach(m -> {
        metricNode.set(metricName, codec(Metric.class).encode(m, this));
    });

    return ok(root).build();
}
项目:athena    文件:MetricsResourceTest.java   
/**
 * Tests GetAllMetrics method.
 */
@Test
public void testGetAllMetrics() {
    Counter onosCounter = new Counter();
    onosCounter.inc();

    Meter onosMeter = new Meter();
    onosMeter.mark();

    Timer onosTimer = new Timer();
    onosTimer.update(1, TimeUnit.MILLISECONDS);

    ImmutableMap<String, Metric> metrics =
            new ImmutableMap.Builder<String, Metric>()
                    .put("onosCounter", onosCounter)
                    .put("onosMeter", onosMeter)
                    .put("onosTimer", onosTimer)
                    .build();

    expect(mockMetricsService.getMetrics())
            .andReturn(metrics)
            .anyTimes();

    replay(mockMetricsService);

    WebTarget wt = target();
    String response = wt.path("metrics").request().get(String.class);
    assertThat(response, containsString("{\"metrics\":["));

    JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    JsonArray jsonMetrics = result.get("metrics").asArray();
    assertThat(jsonMetrics, notNullValue());
    assertThat(jsonMetrics.size(), is(3));

    assertTrue(matchesMetric(metrics.get("onosCounter")).matchesSafely(jsonMetrics.get(0).asObject()));
    assertTrue(matchesMetric(metrics.get("onosMeter")).matchesSafely(jsonMetrics.get(1).asObject()));
    assertTrue(matchesMetric(metrics.get("onosTimer")).matchesSafely(jsonMetrics.get(2).asObject()));
}
项目:athena    文件:MetricsListCommand.java   
@Override
protected void execute() {
    MetricsService metricsService = get(MetricsService.class);

    MetricFilter filter = metricName != null ? (name, metric) -> name.equals(metricName) : MetricFilter.ALL;

    TreeMultimap<String, Metric> matched = listMetrics(metricsService, filter);
    matched.asMap().forEach((name, metrics) -> {
        if (outputJson()) {
            metrics.forEach(metric -> print("%s", json(metric)));
        } else {
            metrics.forEach(metric -> printMetric(name, metric));
        }
    });
}
项目:athena    文件:MetricsListCommand.java   
/**
 * Creates a json object for a certain metric.
 *
 * @param metric metric object
 * @return json object
 */
private ObjectNode json(Metric metric) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode objectNode = mapper.createObjectNode();
    ObjectNode dataNode = mapper.createObjectNode();

    if (metric instanceof Counter) {
        dataNode.put(COUNTER, ((Counter) metric).getCount());
        objectNode.set(COUNTER, dataNode);
    } else if (metric instanceof Gauge) {
        objectNode.put(VALUE, ((Gauge) metric).getValue().toString());
        objectNode.set(GAUGE, dataNode);
    } else if (metric instanceof Meter) {
        dataNode.put(COUNTER, ((Meter) metric).getCount());
        dataNode.put(MEAN_RATE, ((Meter) metric).getMeanRate());
        dataNode.put(ONE_MIN_RATE, ((Meter) metric).getOneMinuteRate());
        dataNode.put(FIVE_MIN_RATE, ((Meter) metric).getFiveMinuteRate());
        dataNode.put(FIFT_MIN_RATE, ((Meter) metric).getFifteenMinuteRate());
        objectNode.set(METER, dataNode);
    } else if (metric instanceof Histogram) {
        dataNode.put(COUNTER, ((Histogram) metric).getCount());
        dataNode.put(MEAN, ((Histogram) metric).getSnapshot().getMean());
        dataNode.put(MIN, ((Histogram) metric).getSnapshot().getMin());
        dataNode.put(MAX, ((Histogram) metric).getSnapshot().getMax());
        dataNode.put(STDDEV, ((Histogram) metric).getSnapshot().getStdDev());
        objectNode.set(HISTOGRAM, dataNode);
    } else if (metric instanceof Timer) {
        dataNode.put(COUNTER, ((Timer) metric).getCount());
        dataNode.put(MEAN_RATE, ((Timer) metric).getMeanRate());
        dataNode.put(ONE_MIN_RATE, ((Timer) metric).getOneMinuteRate());
        dataNode.put(FIVE_MIN_RATE, ((Timer) metric).getFiveMinuteRate());
        dataNode.put(FIFT_MIN_RATE, ((Timer) metric).getFifteenMinuteRate());
        dataNode.put(MEAN, nanoToMs(((Timer) metric).getSnapshot().getMean()));
        dataNode.put(MIN, nanoToMs(((Timer) metric).getSnapshot().getMin()));
        dataNode.put(MAX, nanoToMs(((Timer) metric).getSnapshot().getMax()));
        dataNode.put(STDDEV, nanoToMs(((Timer) metric).getSnapshot().getStdDev()));
        objectNode.set(TIMER, dataNode);
    }
    return objectNode;
}
项目:athena    文件:MetricCodecTest.java   
/**
 * Sets up for each test.  Creates a context and fetches the metric codec.
 */
@Before
public void setUp() {
    context = new MockCodecContext();
    metricCodec = context.codec(Metric.class);
    assertThat(metricCodec, notNullValue());

    replay(mockCoreService);
    context.registerService(CoreService.class, mockCoreService);
}