Java Code Examples for com.codahale.metrics.Meter#mark()

The following examples show how to use com.codahale.metrics.Meter#mark() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DiagnosticModeTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5000)
public void test_metric_logging() throws Exception {
    new DiagnosticMode(diagnosticData, systemInformation, metricRegistry).init();
    final File diagnosticsFolder = new File(hivemqHomeFolder, DiagnosticMode.FILE_NAME_DIAGNOSTICS_FOLDER);
    assertTrue(diagnosticsFolder.isDirectory());

    final Meter meter = metricRegistry.meter("request");
    meter.mark();

    final File metricFile = new File(diagnosticsFolder, DiagnosticMode.FILE_NAME_METRIC_LOG);
    assertTrue(metricFile.exists());

    while (FileUtils.readFileToString(metricFile, Charset.defaultCharset()).isEmpty()) {
        Thread.sleep(10);
    }
}
 
Example 2
Source File: KVStoreStateMachine.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
private int batchApplyAndRecycle(final byte opByte, final KVStateOutputList kvStates) {
    try {
        final int size = kvStates.size();

        if (size == 0) {
            return 0;
        }

        if (!KVOperation.isValidOp(opByte)) {
            throw new IllegalKVOperationException("Unknown operation: " + opByte);
        }

        // metrics: op qps
        final Meter opApplyMeter = KVMetrics.meter(STATE_MACHINE_APPLY_QPS, String.valueOf(this.region.getId()),
            KVOperation.opName(opByte));
        opApplyMeter.mark(size);
        this.batchWriteHistogram.update(size);

        // do batch apply
        batchApply(opByte, kvStates);

        return size;
    } finally {
        RecycleUtil.recycle(kvStates);
    }
}
 
Example 3
Source File: UrlRouter.java    From xrpc with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  ServerContext xctx = ctx.channel().attr(ServerContext.ATTRIBUTE_KEY).get();
  xctx.requestMeter().mark();

  if (ctx.channel().hasAttr(XrpcConstants.XRPC_SOFT_RATE_LIMITED)) {
    ctx.writeAndFlush(
            Recipes.newResponse(
                HttpResponseStatus.TOO_MANY_REQUESTS,
                Unpooled.wrappedBuffer(XrpcConstants.RATE_LIMIT_RESPONSE),
                Recipes.ContentType.Text_Plain))
        .addListener(ChannelFutureListener.CLOSE);
    xctx.metersByStatusCode().get(HttpResponseStatus.TOO_MANY_REQUESTS).mark();
    return;
  }

  if (msg instanceof FullHttpRequest) {
    FullHttpRequest request = (FullHttpRequest) msg;
    String path = XUrl.path(request.uri());
    CompiledRoutes.Match match = xctx.routes().match(path, request.method());

    XrpcRequest xrpcRequest = new XrpcRequest(request, xctx, match.getGroups(), ctx.channel());

    HttpResponse resp = match.getHandler().handle(xrpcRequest);

    // TODO(jkinkead): Per issue #152, this should track ALL response codes.
    Meter meter = xctx.metersByStatusCode().get(resp.status());
    if (meter != null) {
      meter.mark();
    }

    ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
  }
  ctx.fireChannelRead(msg);
}
 
Example 4
Source File: MetricsResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * 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()));
}
 
Example 5
Source File: StatusCodeHandler.java    From StubbornJava with MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    /**
     * Call the underlying handler first since it may be setting the status code.
     * Assume there are no exceptions.  We should catch and handle them before this.
     */
    handler.handleRequest(exchange);

    int code = exchange.getStatusCode();
    Meter meter = Metrics.meter(prefix, String.valueOf(code));
    meter.mark();
}
 
Example 6
Source File: MeteredInterceptor.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
private Object meteredCallable(InvocationContext context, Executable executable) throws Exception {
    String name = resolver.metered(bean.getBeanClass(), executable).metricName();
    Meter meter = (Meter) registry.getMetrics().get(name);
    if (meter == null)
        throw new IllegalStateException("No meter with name [" + name + "] found in registry [" + registry + "]");

    meter.mark();
    return context.proceed();
}
 
Example 7
Source File: StreamingConsumerChannel.java    From kylin with Apache License 2.0 5 votes vote down vote up
protected void recordConsumeMetric(Integer partitionId, Map<String, Object> eventParams) {
    Meter partitionEventConsumeMeter = eventConsumeMeters.get(partitionId);
    if (partitionEventConsumeMeter == null) {
        partitionEventConsumeMeter = StreamingMetrics.newMeter(
                MetricRegistry.name(StreamingMetrics.CONSUME_RATE_PFX, cubeName, String.valueOf(partitionId)));
        eventConsumeMeters.put(partitionId, partitionEventConsumeMeter);
    }
    partitionEventConsumeMeter.mark();
}
 
Example 8
Source File: MetricTypesExample.java    From semantic-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * A meter measures the rate of events over time (e.g., “requests per second”). In addition to
 * the mean rate, meters also track 1-, 5-, and 15-minute moving averages.
 * <p>
 * We have an endpoint that we want to measure how frequent we receive requests for it. this
 * method demonstrates how to do that.
 */
private static void reportMeter() {
    // Create or fetch (if it is already created) the metric.
    final Meter meter = registry.meter(
        APP_PREFIX.tagged("what", "incoming-requests").tagged("endpoint", "/v1/list"));

    // Now a request comes and it's time to mark the meter
    meter.mark();

    // That's it! The rest will be automatically done inside semantic metrics library. The
    // reported measurements will be kept in the registry.
    // Every time the reporter wants to report, different stats and aggregations (1-, 5-, and
    // 15-minute moving averages) will be calculated and
    // datapoints will be created and reported.
}
 
Example 9
Source File: StatusCodeHandler.java    From StubbornJava with MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    /**
     * Call the underlying handler first since it may be setting the status code.
     * Assume there are no exceptions.  We should catch and handle them before this.
     */
    handler.handleRequest(exchange);

    int code = exchange.getStatusCode();
    Meter meter = Metrics.meter(prefix, String.valueOf(code));
    meter.mark();
}
 
Example 10
Source File: CompiledRoutes.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns compiled routes built from the given route map.
 *
 * @param metricRegistry the registry to generate per-(route,method) rate statistics in
 */
public CompiledRoutes(
    Map<RoutePath, Map<HttpMethod, Handler>> rawRoutes, MetricRegistry metricRegistry) {
  // Build a sorted map of the routes.
  ImmutableSortedMap.Builder<RoutePath, ImmutableMap<HttpMethod, Handler>> routesBuilder =
      ImmutableSortedMap.naturalOrder();
  for (Map.Entry<RoutePath, Map<HttpMethod, Handler>> routeEntry : rawRoutes.entrySet()) {
    ImmutableMap.Builder<HttpMethod, Handler> handlers = new ImmutableMap.Builder<>();
    RoutePath route = routeEntry.getKey();
    for (Map.Entry<HttpMethod, Handler> methodHandlerEntry : routeEntry.getValue().entrySet()) {
      HttpMethod method = methodHandlerEntry.getKey();

      // Wrap the user-provided handler in one that tracks request rates.
      String metricName = MetricRegistry.name("routes", method.name(), route.toString());
      String timerName = MetricRegistry.name("routeLatency", method.name(), route.toString());
      final Handler userHandler = methodHandlerEntry.getValue();
      final Meter meter = metricRegistry.meter(metricName);
      final Timer timer = metricRegistry.timer(timerName);

      // TODO (AD): Pull this out into an adapted handler in a separate class.
      Handler adaptedHandler =
          request -> {
            meter.mark();
            try {
              return timer.time(() -> userHandler.handle(request));
            } catch (Exception e) {
              return request.connectionContext().exceptionHandler().handle(request, e);
            }
          };
      handlers.put(method, adaptedHandler);
    }

    routesBuilder.put(route, handlers.build());
  }

  this.routes = routesBuilder.build();
}
 
Example 11
Source File: ExceptionMeteredInterceptor.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
private Object meteredCallable(InvocationContext context, Executable executable) throws Throwable {
    MetricResolver.Of<ExceptionMetered> exceptionMetered = resolver.exceptionMetered(bean.getBeanClass(), executable);
    Meter meter = (Meter) registry.getMetrics().get(exceptionMetered.metricName());
    if (meter == null)
        throw new IllegalStateException("No meter with name [" + exceptionMetered.metricName() + "] found in registry [" + registry + "]");

    try {
        return context.proceed();
    } catch (Throwable throwable) {
        if (exceptionMetered.metricAnnotation().cause().isInstance(throwable))
            meter.mark();

        throw throwable;
    }
}
 
Example 12
Source File: RateBasedLimiterTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrottling() throws InterruptedException {
  Meter meter = new Meter();
  for (int i = 0; i < 100; i++) {
    Assert.assertTrue(this.limiter.acquirePermits(1) != null);
    meter.mark();
    Thread.sleep((RANDOM.nextInt() & Integer.MAX_VALUE) % 10);
  }

  // Assert a fuzzy equal with 5% of tolerance
  Assert.assertTrue(DoubleMath.fuzzyEquals(meter.getMeanRate(), 20d, 20d * 0.05));
}
 
Example 13
Source File: SendToLocalInfluxDB.java    From dropwizard-metrics-influxdb with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    InfluxDbReporter influxDbReporter = null;
    ScheduledReporter consoleReporter = null;
    Timer.Context context = null;
    try {
        final MetricRegistry registry = new MetricRegistry();
        consoleReporter = startConsoleReporter(registry);
        influxDbReporter = startInfluxDbReporter(registry, GetHttpSender());

        final Meter myMeter = registry.meter(MetricRegistry.name(SendToLocalInfluxDB.class, "testMetric"));

        final Timer myTimer = registry.timer("testTimer");
        context = myTimer.time();
        for (int i = 0; i < 5000; i++) {
            myMeter.mark();
            myMeter.mark(Math.round(Math.random() * 100.0));
            Thread.sleep(2000);
        }
    } catch (Exception exc) {
        exc.printStackTrace();
        System.exit(1);
    } finally {
        if (context != null) {
            context.stop();
        }
        if (influxDbReporter != null) {
            influxDbReporter.report();
            influxDbReporter.stop();
        }
        if (consoleReporter != null) {
            consoleReporter.report();
            consoleReporter.stop();
        }
        System.out.println("Finished");
    }
}
 
Example 14
Source File: CodahaleMetrics.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void markMeter(String name) {
    String key = name;
    try {
        metersLock.lock();
        Meter meter = meters.get(name);
        meter.mark();
    } catch (ExecutionException e) {
        throw new IllegalStateException("Error retrieving meter " + name + " from the metric registry ", e);
    } finally {
        metersLock.unlock();
    }
}
 
Example 15
Source File: GraphiteReporterTest.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Test
public void testWithoutTags() throws IOException {
  try (
      MetricContext metricContext =
          MetricContext.builder(this.getClass().getCanonicalName() + ".testGraphiteReporter").build();

      GraphiteReporter graphiteReporter =
          GraphiteReporter.Factory.newBuilder()
              .withGraphitePusher(graphitePusher)
              .withMetricContextName(CONTEXT_NAME)
              .build(new Properties());) {

    ContextAwareGauge<Long> contextAwareGauge =
        metricContext.newContextAwareGauge("com.linkedin.example.gauge", new Gauge<Long>() {
          @Override
          public Long getValue() {
            return 1000l;
          }
        });

    metricContext.register(MetricRegistry.name(METRIC_PREFIX, GAUGE), contextAwareGauge);
    Counter counter = metricContext.counter(MetricRegistry.name(METRIC_PREFIX, COUNTER));
    Meter meter = metricContext.meter(MetricRegistry.name(METRIC_PREFIX, METER));
    Histogram histogram = metricContext.histogram(MetricRegistry.name(METRIC_PREFIX, HISTOGRAM));
    Timer timer = metricContext.timer(MetricRegistry.name(METRIC_PREFIX, TIMER));

    counter.inc(3l);
    meter.mark(1l);
    meter.mark(2l);
    meter.mark(3l);
    histogram.update(1);
    histogram.update(1);
    histogram.update(2);
    timer.update(1, TimeUnit.SECONDS);
    timer.update(2, TimeUnit.SECONDS);
    timer.update(3, TimeUnit.SECONDS);

    graphiteReporter.report(metricContext.getGauges(), metricContext.getCounters(), metricContext.getHistograms(),
        metricContext.getMeters(), metricContext.getTimers(), metricContext.getTagMap());

    Assert.assertEquals(getMetricValue(COUNTER, Measurements.COUNT), Long.toString(3l));

    Assert.assertEquals(getMetricValue(GAUGE, null), Long.toString(1000l));
    Assert.assertTrue(getMetricTimestamp(GAUGE, null) <= System.currentTimeMillis() / 1000l);

    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.PERCENTILE_75TH), Double.toString(2d));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.PERCENTILE_98TH), Double.toString(2d));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.PERCENTILE_99TH), Double.toString(2d));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.PERCENTILE_999TH), Double.toString(2d));

    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.COUNT), Long.toString(3l));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.MIN), Long.toString(1l));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.MAX), Long.toString(2l));
    Assert.assertEquals(getMetricValue(HISTOGRAM, Measurements.MEDIAN), Double.toString(1d));
    Assert.assertTrue(Double.valueOf(getMetricValue(HISTOGRAM, Measurements.MEAN)) > 1d);
    Assert.assertTrue(Double.valueOf(getMetricValue(HISTOGRAM, Measurements.STDDEV)) < 0.5d);

    Assert.assertEquals(getMetricValue(METER, Measurements.RATE_1MIN), Double.toString(0d));
    Assert.assertEquals(getMetricValue(METER, Measurements.RATE_5MIN), Double.toString(0d));
    Assert.assertEquals(getMetricValue(METER, Measurements.COUNT), Long.toString(6l));
    Assert.assertTrue(Double.valueOf(getMetricValue(METER, Measurements.MEAN_RATE)) > 0d);

    Assert.assertEquals(getMetricValue(TIMER, Measurements.RATE_1MIN), Double.toString(0d));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.RATE_5MIN), Double.toString(0d));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.PERCENTILE_75TH), Double.toString(3000d));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.PERCENTILE_98TH), Double.toString(3000d));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.PERCENTILE_99TH), Double.toString(3000d));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.PERCENTILE_999TH), Double.toString(3000d));

    Assert.assertEquals(getMetricValue(TIMER, Measurements.COUNT), Long.toString(3l));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.MIN), Double.toString(1000d));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.MAX), Double.toString(3000d));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.MEAN), Double.toString(2000d));
    Assert.assertEquals(getMetricValue(TIMER, Measurements.MEDIAN), Double.toString(2000d));
    Assert.assertTrue(Double.valueOf(getMetricValue(TIMER, Measurements.MEAN_RATE)) > 0d);
    Assert.assertTrue(Double.valueOf(getMetricValue(TIMER, Measurements.STDDEV)) > 0d);

  }
}
 
Example 16
Source File: GraphiteReporterTest.java    From styx with Apache License 2.0 4 votes vote down vote up
private static Meter meter(int mark) {
    Meter okMeter = new Meter();
    okMeter.mark(mark);
    return okMeter;
}
 
Example 17
Source File: LimiterServerResource.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/**
 * Request permits from the limiter server. The returned {@link PermitAllocation} specifies the number of permits
 * that the client can use.
 */
@Override
@RestMethod.Get
public void get(
    ComplexResourceKey<PermitRequest, EmptyRecord> key,
    @CallbackParam final Callback<PermitAllocation> callback) {
  try (Closeable context = this.requestTimer == null ? NoopCloseable.INSTANCE : this.requestTimer.time()) {
    long startNanos = System.nanoTime();

    PermitRequest request = key.getKey();
    String resourceId = request.getResource();

    MetricContext resourceContext = (MetricContext) broker.getSharedResource(new MetricContextFactory(),
        new SubTaggedMetricContextKey(resourceId, ImmutableMap.of(RESOURCE_ID_TAG, resourceId)));
    Meter permitsRequestedMeter = resourceContext.meter(PERMITS_REQUESTED_METER_NAME);
    Meter permitsGrantedMeter = resourceContext.meter(PERMITS_GRANTED_METER_NAME);
    Timer limiterTimer = resourceContext.timer(LIMITER_TIMER_NAME);

    permitsRequestedMeter.mark(request.getPermits());

    if (this.leaderFinderOpt.isPresent() && !this.leaderFinderOpt.get().isLeader()) {
      URI leaderUri = this.leaderFinderOpt.get().getLeaderMetadata().getUri();

      RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_301_MOVED_PERMANENTLY,
          String.format("New leader <a href=\"%s\">%s</a>", leaderUri, leaderUri));
      exception.setErrorDetails(new DataMap(ImmutableMap.of(LOCATION_301, leaderUri.toString())));
      throw exception;
    } else {
      ThrottlingPolicy policy = (ThrottlingPolicy) this.broker.getSharedResource(new ThrottlingPolicyFactory(),
          new SharedLimiterKey(request.getResource()));

      PermitAllocation allocation;
      try (Closeable thisContext = limiterTimer.time()) {
        allocation = policy.computePermitAllocation(request);
      }

      if (request.getVersion(GetMode.DEFAULT) < ThrottlingProtocolVersion.WAIT_ON_CLIENT.ordinal()) {
        // If the client does not understand "waitForPermitsUse", delay the response at the server side.
        // This has a detrimental effect to server performance
        long wait = allocation.getWaitForPermitUseMillis(GetMode.DEFAULT);
        allocation.setWaitForPermitUseMillis(0);
        if (wait > 0) {
          try {
            this.sleeper.sleep(wait);
          } catch (InterruptedException ie) {
            allocation.setPermits(0);
          }
        }
      }

      permitsGrantedMeter.mark(allocation.getPermits());

      log.debug("Request: {}, allocation: {}, elapsedTime: {} ns", request, allocation, System.nanoTime() - startNanos);

      callback.onSuccess(allocation);
    }


  } catch (NotConfiguredException nce) {
    throw new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, "No configuration for the requested resource.");
  } catch (IOException ioe) {
    // Failed to close timer context. This should never happen
    throw new RuntimeException(ioe);
  }

}
 
Example 18
Source File: NewAPIHadoopCounterReporterTest.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Test
public void testReportMetrics() {
  Gauge<Integer> queueSizeGauge = new Gauge<Integer>() {
    @Override
    public Integer getValue() {
      return 1000;
    }
  };

  com.codahale.metrics.Counter recordsProcessedCounter = new com.codahale.metrics.Counter();
  recordsProcessedCounter.inc(10l);

  Histogram recordSizeDistributionHistogram = new Histogram(new ExponentiallyDecayingReservoir());
  recordSizeDistributionHistogram.update(1);
  recordSizeDistributionHistogram.update(2);
  recordSizeDistributionHistogram.update(3);

  Meter recordProcessRateMeter = new Meter();
  recordProcessRateMeter.mark(1l);
  recordProcessRateMeter.mark(2l);
  recordProcessRateMeter.mark(3l);

  Timer totalDurationTimer = new Timer();
  totalDurationTimer.update(1, TimeUnit.SECONDS);
  totalDurationTimer.update(2, TimeUnit.SECONDS);
  totalDurationTimer.update(3, TimeUnit.SECONDS);

  SortedMap<String, com.codahale.metrics.Counter> counters =
      ImmutableSortedMap.<String, com.codahale.metrics.Counter>naturalOrder()
      .put(RECORDS_PROCESSED, recordsProcessedCounter).build();
  SortedMap<String, Gauge> gauges = ImmutableSortedMap.<String, Gauge>naturalOrder()
      .put(QUEUE_SIZE, queueSizeGauge).build();
  SortedMap<String, Histogram> histograms = ImmutableSortedMap.<String, Histogram>naturalOrder()
      .put(RECORD_SIZE_DISTRIBUTION, recordSizeDistributionHistogram).build();
  SortedMap<String, Meter> meters = ImmutableSortedMap.<String, Meter>naturalOrder()
      .put(RECORD_PROCESS_RATE, recordProcessRateMeter).build();
  SortedMap<String, Timer> timers = ImmutableSortedMap.<String, Timer>naturalOrder()
      .put(TOTAL_DURATION, totalDurationTimer).build();

  this.hadoopCounterReporter.report(gauges, counters, histograms, meters, timers);

  Mockito.verify(this.recordsProcessedCount).increment(10l);
  Mockito.verify(this.recordProcessRateCount).increment(6l);
  Mockito.verify(this.recordSizeDistributionCount).increment(3l);
  Mockito.verify(this.totalDurationCount).increment(3l);
  Mockito.verify(this.queueSize).setValue(1000);

  recordsProcessedCounter.inc(5l);
  recordSizeDistributionHistogram.update(4);
  recordProcessRateMeter.mark(4l);
  totalDurationTimer.update(4, TimeUnit.SECONDS);

  this.hadoopCounterReporter.report(gauges, counters, histograms, meters, timers);

  Mockito.verify(this.recordsProcessedCount).increment(5l);
  Mockito.verify(this.recordProcessRateCount).increment(4l);
  Mockito.verify(this.recordSizeDistributionCount).increment(1l);
  Mockito.verify(this.totalDurationCount).increment(1l);
}
 
Example 19
Source File: SimpleAvroInDevTest.java    From hermes with Apache License 2.0 4 votes vote down vote up
@Test
public void simpleAvroMessageTest() throws IOException {
	String topic = "kafka.SimpleAvroTopic";
	String group = "kafka.SimpleAvroTopic.group";
	MetricRegistry metrics = HermesMetricsRegistry.getMetricRegistryByT(topic);
	final Meter sent = metrics.meter("sent");
	final Meter received = metrics.meter("received");

	Producer producer = Producer.getInstance();

	ConsumerHolder consumer = Consumer.getInstance().start(topic, group, new BaseMessageListener<AvroVisitEvent>() {

		@Override
		protected void onMessage(ConsumerMessage<AvroVisitEvent> msg) {
			AvroVisitEvent body = msg.getBody();
			System.out.println("Receive: " + body);
			received.mark();
		}
	});

	System.out.println("Starting consumer...");

	try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
		while (true) {
			String line = in.readLine();
			if ("q".equals(line)) {
				break;
			}

			AvroVisitEvent proMsg = KafkaAvroTest.generateEvent();
			MessageHolder holder = producer.message(topic, proMsg.getIp().toString(), proMsg);
			holder.send();
			System.out.println("Sent: " + proMsg);
			sent.mark();
		}
	}

	consumer.close();
	System.out.println(MetricsUtils.printMeter("sent", sent));
	System.out.println(MetricsUtils.printMeter("received", received));
}
 
Example 20
Source File: PerformanceEntityWriteTest.java    From usergrid with Apache License 2.0 2 votes vote down vote up
@Test
public void addToMultipleOwners() throws Exception {


    final EntityManager em = app.getEntityManager();

    final String meterName = this.getClass().getSimpleName() + ".addToMultipleOwners";
    final Meter meter = registry.meter( meterName );


    final long stopTime = System.currentTimeMillis() + RUNTIME;


    final DynamicEntity toCreate = new DynamicEntity();
    toCreate.setType( "toCreate" );


    //now create the first entity
    final Entity owner1 = em.create( "1owner", new HashMap<String, Object>() {{
        put( "key", "owner1" );
    }} );
    final Entity owner2 = em.create( "2owner", new HashMap<String, Object>() {{
        put( "key", "owner2" );
    }} );


    final Map<String, Object> addToCollectionEntity = new HashMap<>();
    addToCollectionEntity.put( "key1", 1000 );
    addToCollectionEntity.put( "key2", 2000 );
    addToCollectionEntity.put( "key3", "Some value" );

    final List<EntityRef> owners = Arrays.<EntityRef>asList( owner1, owner2 );

    int i = 0;


    while ( System.currentTimeMillis() < stopTime ) {

        addToCollectionEntity.put( "key", i );

        final Entity created = em.create( "testType", addToCollectionEntity );

        em.addToCollections( owners, "test", created );

        meter.mark();

        i++;
    }

    registry.remove( meterName );
}