/** * Package private constructor for unit test. */ AnomalyDetector(LinkedBlockingDeque<Anomaly> anomalies, long anomalyDetectionIntervalMs, KafkaCruiseControl kafkaCruiseControl, AnomalyNotifier anomalyNotifier, GoalViolationDetector goalViolationDetector, BrokerFailureDetector brokerFailureDetector, ScheduledExecutorService detectorScheduler) { _anomalies = anomalies; _anomalyDetectionIntervalMs = anomalyDetectionIntervalMs; _anomalyNotifier = anomalyNotifier; _goalViolationDetector = goalViolationDetector; _brokerFailureDetector = brokerFailureDetector; _kafkaCruiseControl = kafkaCruiseControl; _detectorScheduler = detectorScheduler; _shutdown = false; _brokerFailureRate = new Meter(); _goalViolationRate = new Meter(); }
TrainingFetcher(MetricSampler metricSampler, Cluster cluster, SampleStore sampleStore, Set<TopicPartition> assignedPartitions, long startTimeMs, long endTimeMs, Timer fetcherTimer, Meter fetcherFailureRate) { _cluster = cluster; _sampleStore = sampleStore; _metricSampler = metricSampler; _startTimeMs = startTimeMs; _endTimeMs = endTimeMs; _assignedPartitions = assignedPartitions; _fetcherTimer = fetcherTimer; _fetcherFailureRate = fetcherFailureRate; }
SamplingFetcher(MetricSampler metricSampler, Cluster cluster, MetricSampleAggregator metricSampleAggregator, SampleStore sampleStore, Set<TopicPartition> assignedPartitions, long startTimeMs, long endTimeMs, boolean leaderValidation, boolean useLinearRegressionModel, Timer fetchTimer, Meter fetchFailureRate) { _metricSampler = metricSampler; _cluster = cluster; _metricSampleAggregator = metricSampleAggregator; _sampleStore = sampleStore; _assignedPartitions = assignedPartitions; _startTimeMs = startTimeMs; _endTimeMs = endTimeMs; _leaderValidation = leaderValidation; _useLinearRegressionModel = useLinearRegressionModel; _fetchTimer = fetchTimer; _fetchFailureRate = fetchFailureRate; }
@Test public void testMetersRetrievedAndMarkIsDelegated() throws Exception { // ARRANGE SystemStatus systemStatus = mock(SystemStatus.class); Meter meter = mock(Meter.class); doReturn(meter).when(systemStatus).meter(anyString(), any()); AbstractMeteredLoadProcessorImpl processor = spy(new AbstractMeteredLoadProcessorImpl(0, null, 0, null)); processor.setSystemStatus(systemStatus); // ACT processor.succeeded(); processor.failed(); processor.authenticationFailure(); // ASSERT verify(processor, times(3)).meterName(); // FindBugs: RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT - IGNORE verify(systemStatus, times(3)).meter(anyString(), any()); verify(meter, times(3)).mark(); }
@Test public void testMetersRetrievedAndMarkIsDelegated() throws Exception { // ARRANGE SystemStatus systemStatus = mock(SystemStatus.class); Meter meter = mock(Meter.class); doReturn(meter).when(systemStatus).meter(anyString(), any()); processor.setSystemStatus(systemStatus); // ACT processor.succeeded(); processor.failed(); processor.noData(); processor.authenticationFailure(); // ASSERT verify(processor, times(4)).meterName(); // FindBugs: RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT - IGNORE verify(systemStatus, times(4)).meter(anyString(), any()); verify(meter, times(4)).mark(); }
@Test(expected = FeignException.class) public void exception() { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(400))); MyClientWithAnnotationOnMethodLevel target = Feign.builder().invocationHandlerFactory( new FeignOutboundMetricsDecorator(new InvocationHandlerFactory.Default(), metricRegistry)) .target(MyClientWithAnnotationOnMethodLevel.class, String.format("http://localhost:%d", wireMockRule.port())); try { target.myMethod(); } finally { assertMetrics(); Set<Map.Entry<String, Meter>> entries = metricRegistry.getMeters().entrySet(); entries.forEach(entry -> { if (entry.getKey().endsWith(ExceptionMetered.DEFAULT_NAME_SUFFIX)) { assertEquals(String.format("wrong number of invocations in metric %s", entry.getKey()), 1, entry.getValue().getCount()); } }); } }
private void assertMetrics() { Timer timer = metricRegistry.getTimers().values().iterator().next(); assertEquals("wrong number of invocations in metric.", 1, timer.getCount()); assertTrue("wrong value of mean in metric.", timer.getMeanRate() > 0); assertEquals("wrong number of meter metrics.", 2, metricRegistry.getMeters().values().size()); Set<Map.Entry<String, Meter>> entries = metricRegistry.getMeters().entrySet(); entries.forEach(entry -> { if (entry.getKey().endsWith("Metered")) { assertEquals(String.format("wrong number of invocations in metric %s", entry.getKey()), 1, entry.getValue().getCount()); } }); }
@Override public void report(final SortedMap<String, Gauge> gauges, final SortedMap<String, Counter> counters, final SortedMap<String, Histogram> histograms, final SortedMap<String, Meter> meters, final SortedMap<String, Timer> timers) { final long timestamp = clock.instant().toEpochMilli(); final ImmutableList<InfluxDbMeasurement> influxDbMeasurements = ImmutableList.<InfluxDbMeasurement>builder() .addAll(transformer.fromGauges(gauges, timestamp)) .addAll(transformer.fromCounters(counters, timestamp)) .addAll(transformer.fromHistograms(histograms, timestamp)) .addAll(transformer.fromMeters(meters, timestamp)) .addAll(transformer.fromTimers(timers, timestamp)) .build(); sender.send(influxDbMeasurements); }
/** * Build an {@link InfluxDbMeasurement} from a meter. */ @VisibleForTesting InfluxDbMeasurement fromMeter(final String metricName, final Meter mt, final long timestamp) { final DropwizardMeasurement measurement = parser.parse(metricName); final Map<String, String> tags = new HashMap<>(baseTags); tags.putAll(measurement.tags()); return new InfluxDbMeasurement.Builder(measurement.name(), timestamp) .putTags(tags) .putField("count", mt.getCount()) .putField("one-minute", convertRate(mt.getOneMinuteRate())) .putField("five-minute", convertRate(mt.getFiveMinuteRate())) .putField("fifteen-minute", convertRate(mt.getFifteenMinuteRate())) .putField("mean-minute", convertRate(mt.getMeanRate())) .build(); }
@Override public void serialize(JsonMeter jsonMeter, JsonGenerator json, SerializerProvider provider) throws IOException { json.writeStartObject(); json.writeStringField("name", jsonMeter.name()); json.writeObjectField(timestampFieldname, jsonMeter.timestampAsDate()); Meter meter = jsonMeter.value(); json.writeNumberField("count", meter.getCount()); json.writeNumberField("m1_rate", meter.getOneMinuteRate() * rateFactor); json.writeNumberField("m5_rate", meter.getFiveMinuteRate() * rateFactor); json.writeNumberField("m15_rate", meter.getFifteenMinuteRate() * rateFactor); json.writeNumberField("mean_rate", meter.getMeanRate() * rateFactor); json.writeStringField("units", rateUnit); addOneOpsMetadata(json); json.writeEndObject(); }
/** * Generates an OpenFlow message aggregator instance. * The instance is for aggregating a specific OpenFlow message * type of an OpenFlow switch. * * @param metricsService metrics service reference object * @param providerService control message provider service reference object * @param deviceId device identification */ public OpenFlowControlMessageAggregator(MetricsService metricsService, ControlMessageProviderService providerService, DeviceId deviceId) { MetricsComponent mc = metricsService.registerComponent(deviceId.toString()); OF_TYPE_SET.forEach(type -> { MetricsFeature metricsFeature = mc.registerFeature(type.toString()); Meter rateMeter = metricsService.createMeter(mc, metricsFeature, RATE_NAME); Meter countMeter = metricsService.createMeter(mc, metricsFeature, COUNT_NAME); rateMeterMap.put(type, rateMeter); countMeterMap.put(type, countMeter); }); this.deviceId = deviceId; this.providerService = providerService; metricsService.notifyReporters(); }
/** * Prints an Event Metric. * * @param operationStr the string with the intent operation to print * @param eventMetric the Event Metric to print */ private void printEventMetric(String operationStr, EventMetric eventMetric) { Gauge<Long> gauge = eventMetric.lastEventTimestampGauge(); Meter meter = eventMetric.eventRateMeter(); TimeUnit rateUnit = TimeUnit.SECONDS; double rateFactor = rateUnit.toSeconds(1); // Print the Gauge print(FORMAT_GAUGE, operationStr, gauge.getValue()); // Print the Meter print(FORMAT_METER, operationStr, meter.getCount(), meter.getMeanRate() * rateFactor, meter.getOneMinuteRate() * rateFactor, meter.getFiveMinuteRate() * rateFactor, meter.getFifteenMinuteRate() * rateFactor); }
/** * Tests encoding of a Metric object. */ @Test public void testMetricEncode() { Counter counter = new Counter(); Meter meter = new Meter(); Timer timer = new Timer(); counter.inc(); meter.mark(); timer.update(1, TimeUnit.MILLISECONDS); ObjectNode counterJson = metricCodec.encode(counter, context); assertThat(counterJson.get("counter"), matchesMetric(counter)); ObjectNode meterJson = metricCodec.encode(meter, context); assertThat(meterJson.get("meter"), matchesMetric(meter)); ObjectNode timerJson = metricCodec.encode(timer, context); assertThat(timerJson.get("timer"), matchesMetric(timer)); }
private static ExecutorService defaultCleanupExecutor(String metricsGroup, LifeCycleRegistry lifeCycle, MetricRegistry metricRegistry) { final Meter meter = metricRegistry.meter(MetricRegistry.name(metricsGroup, "AstyanaxEventReaderDAO", "discarded_slab_cleanup")); String nameFormat = "Events Slab Reader Cleanup-" + metricsGroup.substring(metricsGroup.lastIndexOf('.') + 1) + "-%d"; ExecutorService executor = new ThreadPoolExecutor( NUM_CLEANUP_THREADS, NUM_CLEANUP_THREADS, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(MAX_CLEANUP_QUEUE_LENGTH), new ThreadFactoryBuilder().setNameFormat(nameFormat).build(), new ThreadPoolExecutor.DiscardPolicy() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { meter.mark(); } }); lifeCycle.manage(new ExecutorServiceManager(executor, Duration.seconds(5), nameFormat)); return executor; }
private void notifyListenerOfRemovedMetric( final MetricId name, final Metric metric, final SemanticMetricRegistryListener listener ) { if (metric instanceof Gauge) { listener.onGaugeRemoved(name); } else if (metric instanceof Counter) { listener.onCounterRemoved(name); } else if (metric instanceof Histogram) { listener.onHistogramRemoved(name); } else if (metric instanceof Meter) { listener.onMeterRemoved(name); } else if (metric instanceof Timer) { listener.onTimerRemoved(name); } else if (metric instanceof DerivingMeter) { listener.onDerivingMeterRemoved(name); } else { throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); } }
@Test public void reportsCounters() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); reporter.report(this.<Gauge>map(), this.<Counter>map("counter", counter), this.<Histogram>map(), this.<Meter>map(), this.<Timer>map()); final InOrder inOrder = inOrder(transport, request); inOrder.verify(transport).prepare(); inOrder.verify(request).addGauge(new CirconusGauge("counter", 100L, timestamp, HOST, tags)); inOrder.verify(request).send(); verify(transport).prepare(); verify(request).send(); verifyNoMoreInteractions(transport, request); }
@Test public void shouldUseFailoverMaxRequests() throws IOException, InterruptedException { String metricName = randomName(); HawkularReporter reporter = HawkularReporter.builder(registry, defaultTenant) .uri("http://invalid:999") .failoverCacheMaxSize(3) .build(); Meter meter = registry.meter(metricName); meter.mark(1000); Thread.sleep(100); meter.mark(1000); reporter.report(); // 6 requests (6 = 5 tags + 1 metric), but majored by 3 assertThat(((JdkHawkularHttpClient) reporter.getHawkularClient()).getFailoverCacheSize()).isEqualTo(3); }
/** * Creates a new RateLimitRequestToken. * * @param count The atomic reference that holds the amount of in-flight requests the user owns * @param userName The user who launched the request * @param isUIQuery Whether or not this query was generated from the UI * @param requestLimit The limit of requests the user is allowed to launch * @param requestMeter Meter tracking the amount of requests that have been launched * @param rejectMeter Meter tracking the amount of requests that have been rejected * * @return a new RateLimitRequestToken, representing an in-flight (or rejected) request that is tracked by the * RateLimiter */ protected RateLimitRequestToken createNewRateLimitRequestToken(AtomicInteger count, String userName, boolean isUIQuery, int requestLimit, Meter requestMeter, Meter rejectMeter) { if (!incrementAndCheckCount(globalCount, requestLimitGlobal)) { rejectRequest(rejectMeter, true, isUIQuery, userName); return REJECT_REQUEST_TOKEN; } // Bind to the user if (!incrementAndCheckCount(count, requestLimit)) { // Decrement the global count that had already been incremented globalCount.decrementAndGet(); rejectRequest(rejectMeter, false, isUIQuery, userName); return REJECT_REQUEST_TOKEN; } // Measure the accepted request and current open connections requestMeter.mark(); requestGlobalCounter.inc(); // Return new request token RateLimitCleanupOnRequestComplete callback = generateCleanupClosure(count, userName); return new CallbackRateLimitRequestToken(true, callback); }
@DataProvider(value = { "null", "0", "1", "2" }, splitBy = "\\|") @Test public void getNamedMeter_with_iterable_dimensions_creates_dimensioned_meter_using_sfx_mechanisms( Integer numDimensions ) { // given String meterName = UUID.randomUUID().toString(); List<Pair<String, String>> iterableDims = generateIterableDimensions(numDimensions); // when Meter result = sfxImpl.getNamedMeter(meterName, iterableDims); // then verifyMetricCreation(MetricBuilder.METERS, meterTaggerMock, meterName, iterableDims, meterMock, result); }
private final void rateMeter(String[] data) throws Exception { Topology t = newTopology(); TStream<String> s = t.strings(data); s = Metrics.rateMeter(s); waitUntilComplete(t, s, data); if (metricRegistry != null) { SortedMap<String, Meter> meters = metricRegistry.getMeters(); assertEquals(1, meters.size()); Collection<Meter> values = meters.values(); for (Meter v : values) { assertEquals(data.length, v.getCount()); } } }
private void notifyListenerOfAddedMetric( final MetricRegistryListener listener, final Metric metric, final String 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 { throw new IllegalArgumentException("Unsupported metric type: " + metric.getClass()); } }
private void notifyListenerOfRemovedMetric( final String name, final Metric metric, final MetricRegistryListener listener ) { if(metric instanceof Gauge) { listener.onGaugeRemoved(name); } else if(metric instanceof Counter) { listener.onCounterRemoved(name); } else if(metric instanceof Histogram) { listener.onHistogramRemoved(name); } else if(metric instanceof Meter) { listener.onMeterRemoved(name); } else if(metric instanceof Timer) { listener.onTimerRemoved(name); } else { throw new IllegalArgumentException("Unsupported metric type: " + metric.getClass()); } }
default <T> T metric(Timer timer, Meter meter, Supplier<T> supplier) { Timer.Context time = timer.time(); try { meter.mark(); return supplier.get(); } finally { time.stop(); } }
DropwizardFunctionCounter(Id id, Clock clock, T obj, ToDoubleFunction<T> f) { super(id); this.ref = new WeakReference<>(obj); this.f = f; this.rate = new DropwizardRate(clock); this.dropwizardMeter = new Meter(new DropwizardClock(clock)) { @Override public double getFifteenMinuteRate() { count(); return rate.getFifteenMinuteRate(); } @Override public double getFiveMinuteRate() { count(); return rate.getFiveMinuteRate(); } @Override public double getOneMinuteRate() { count(); return rate.getOneMinuteRate(); } @Override public long getCount() { return (long) count(); } }; }
public MethodHandlerDecorator(final Method method, final MethodHandler methodHandler, final ConcurrentMap<Method, Meter> meters, final ConcurrentMap<Method, ExceptionMeterMetric> exceptionMeters, final ConcurrentMap<Method, Timer> timers) { this.method = method; this.methodHandler = methodHandler; this.meters = meters; this.exceptionMeters = exceptionMeters; this.timers = timers; }
@Override public Object invoke(Object[] argv) throws Throwable { try { final Meter meter = this.meters.get(method); if (meter != null) { meter.mark(); } final Timer timer = this.timers.get(method); if (timer != null) { this.context = timer.time(); } return methodHandler.invoke(argv); } catch (Exception e) { final FeignOutboundMetricsDecorator.ExceptionMeterMetric metric = (method != null) ? this.exceptionMeters.get(method) : null; if (metric != null && (metric.cause.isAssignableFrom(e.getClass()) || (e.getCause() != null && metric.cause.isAssignableFrom(e.getCause().getClass())))) { metric.meter.mark(); } throw e; } finally { if (this.context != null) { this.context.close(); } } }
@Override public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) { DataPointCollector collector = new DataPointCollector(System.currentTimeMillis() / 1000); buildReportTimer.time(() -> { debug("################"); debug(">>>>>>>> Guages <<<<<<<<<"); gauges.forEach(collector::collectGauge); debug(">>>>>>>> Counters <<<<<<<<<"); counters.forEach(collector::collectCounter); debug(">>>>>>>> Histograms <<<<<<<<<"); histograms.forEach(collector::collectHistogram); debug(">>>>>>>> Meters <<<<<<<<<"); meters.forEach(collector::collectMeter); debug(">>>>>>>> Timers <<<<<<<<<"); timers.forEach(collector::collectTimer); debug("################"); }); sendReportTimer.time(() -> { Collection<DataPoint> dataPoints = collector.dataPoints; dataPointsReporter.put(dataPoints); //dataPoints.forEach(System.out::println); }); }
@Test public void testFromMeter() { final Set<String> fieldKeys = ImmutableSet.of( "count", "one-minute", "five-minute", "fifteen-minute", "mean-minute" ); final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class); final DropwizardTransformer transformer = transformerWithParser(parser, true); when(parser.parse("some.metric.name")).thenReturn( DropwizardMeasurement.create("Measurement", MEASUREMENT_TAGS, Optional.empty()) ); final Meter meter = new Meter(); meter.mark(50L); meter.mark(64L); meter.mark(80L); final InfluxDbMeasurement measurement = transformer.fromMeter("some.metric.name", meter, 90210L); assertEquals("should parse name from full metric key", "Measurement", measurement.name()); assertEquals("should add global and measurement tags", ALL_TAGS, measurement.tags()); assertEquals("should timestamp measurement", 90210L, measurement.timestamp()); assertEquals("should add all meter fields", fieldKeys, measurement.fields().keySet()); }
public static Meter getMeter(Class clazz, String key) { Meter meter = _metrics.getMeters() != null ? _metrics.getMeters().get(MetricRegistry.name(clazz, key)) : null; if (meter == null) { return _metrics.meter(MetricRegistry.name(clazz, key)); } return meter; }
/** */ private void reportMeter(String timestamp, String 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()); }
@Override public void report( SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers ) { if (firstReportTime < 0) { firstReportTime = System.currentTimeMillis(); } if (System.currentTimeMillis() - firstReportTime < warmupDuration) { return; } reportStatistics(gauges, counters, histograms, meters, timers); }
protected abstract void reportStatistics( SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers );
/** * Receive a message from JMS and update the internal data structure * * @param msgType * Message Type * @param messageVersion * the message version (may be null) * @param traconID * Tracon ID * @param messageText * Message Text */ @Transactional public void receiveMessage(String msgType, String messageVersion, String traconID, String messageText) { inputLogger.info(msgType + "," + messageVersion + "," + traconID + "," + messageText); Meter meter = metricRegistry.meter("controller."+traconID+"."+msgType); meter.mark(); timeOfLastMessageReceipt = System.currentTimeMillis(); gaugeService.submit("controller.lastUpdate", timeOfLastMessageReceipt); StatusMessageParser parser = null; // check for versions if (messageVersion.equals(StatusMessageParserV3.VERSION_NUMBER)) { log.debug("V3 parser: " + messageText); parser = new StatusMessageParserV3(traconRepo, notificationRepo); } else if (messageVersion.equals(StatusMessageParserV4.VERSION_NUMBER)) { log.debug("V4 parser: " + messageText); parser = new StatusMessageParserV4(traconRepo, notificationRepo); } else { log.error("Unknown version number: " + messageVersion + " for message: " + messageText); } if (parser != null) { parser.parseMessage(msgType, traconID, messageText); } }
public void writeMeter(String dropwizardName, Meter meter) throws IOException { String name = sanitizeMetricName(dropwizardName) + "_total"; writer.writeHelp(name, getHelpMessage(dropwizardName, meter)); writer.writeType(name, MetricType.COUNTER); writer.writeSample(name, emptyMap(), meter.getCount()); writeMetered(dropwizardName, meter); }
/** * Intercept all GRPC calls * @param serverCall * @param metadata * @param serverCallHandler * @param <ReqT> * @param <RespT> * @return */ @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) { Timer.Context timer = metricRegistry.timer(metricName(M_REQ_TIME, serverCall.getMethodDescriptor().getFullMethodName().replace("/", "."))).time(); Histogram histogram = metricRegistry.histogram(metricName(M_RESPONSE_SIZE, serverCall.getMethodDescriptor().getFullMethodName().replace("/", "."))); SimpleForwardingServerCall<ReqT, RespT> nextCall = new SimpleForwardingServerCall<ReqT, RespT>(serverCall) { @Override public void close(Status status, Metadata trailers) { Meter errorMeter = metricRegistry.meter(metricName(ERROR_METRIC, getMethodDescriptor().getFullMethodName().replace("/", "."))); if (!status.isOk()) { errorMeter.mark(); log.error("An error occured with {}", serverCall.getMethodDescriptor()); } timer.stop(); super.close(status, trailers); } @Override public void sendMessage(RespT message) { super.sendMessage(message); if (message instanceof MessageLite) { histogram.update(((MessageLite) message).getSerializedSize()); log.info("Message sent size = {}", ((MessageLite) message).getSerializedSize()); } } }; return serverCallHandler.startCall(nextCall, metadata); }
/** * 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())); }
/** * 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; }
private Map<ControlMetricType, Meter> getMeterMap(Set<ControlMetricType> types, MetricsComponent component, MetricsService service) { Map<ControlMetricType, Meter> meterMap = Maps.newHashMap(); types.forEach(type -> { MetricsFeature metricsFeature = component.registerFeature(type.toString()); Meter meter = service.createMeter(component, metricsFeature, DEFAULT_METER_SUFFIX); meterMap.putIfAbsent(type, meter); }); return meterMap; }
/** * Produces JSON node for an Event Metric. * * @param mapper the JSON object mapper to use * @param objectNode the JSON object node to use * @param propertyPrefix the property prefix to use * @param eventMetric the Event Metric with the data * @return JSON object node for the Event Metric */ private ObjectNode json(ObjectMapper mapper, ObjectNode objectNode, String propertyPrefix, EventMetric eventMetric) { String gaugeName = propertyPrefix + "Timestamp"; String meterName = propertyPrefix + "Rate"; Gauge<Long> gauge = eventMetric.lastEventTimestampGauge(); Meter meter = eventMetric.eventRateMeter(); objectNode.set(gaugeName, json(mapper, gauge)); objectNode.set(meterName, json(mapper, meter)); return objectNode; }