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; }
@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; }
@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)); }
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); } }
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); }
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); } }
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); } } }
@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()); }
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()); } }
@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()); }
/** * 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); }
/** * {@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(); } }
@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; }
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()); } } }
@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; }
@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()); }
@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; }
@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); }
@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); }
@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); }
@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"); }
@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()); }
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()); } } }
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; }
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; }
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; }
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; }
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; }
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; }
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()); } } }
public static void resetMetrics(){ RegistryHolder.REGISTRY.removeMatching(new MetricFilter(){ @Override public boolean matches(String name, Metric metric) { return true; }}); RegistryHolder.registerSysStats(); }
private synchronized void removeOldMetrics() { registry.removeMatching(new MetricFilter() { @Override public boolean matches(String name, Metric metric) { return name.startsWith("drill.allocator."); } }); }
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()); } } }
@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); }
/** * 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(); }
/** * 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(); }
/** * 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())); }
@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)); } }); }
/** * 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; }
/** * 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); }