Java Code Examples for com.codahale.metrics.Timer#getCount()

The following examples show how to use com.codahale.metrics.Timer#getCount() . 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: InstrumentedInvokerFactoryTest.java    From dropwizard-jaxws with Apache License 2.0 6 votes vote down vote up
@Test
public void noAnnotation() {

    Timer timer = testMetricRegistry.timer("timed");
    Meter meter = testMetricRegistry.meter("metered");
    when(mockMetricRegistry.timer(anyString())).thenReturn(timer);
    when(mockMetricRegistry.meter(anyString())).thenReturn(meter);

    long oldtimervalue = timer.getCount();
    long oldmetervalue = meter.getCount();

    Invoker invoker = invokerBuilder.create(instrumentedService, new FooInvoker());
    this.setTargetMethod(exchange, "foo"); // simulate CXF behavior

    Object result = invoker.invoke(exchange, null);
    assertEquals("fooReturn", result);

    assertThat(timer.getCount(), is(oldtimervalue));
    assertThat(meter.getCount(), is(oldmetervalue));
}
 
Example 2
Source File: InstrumentedInvokerFactoryTest.java    From dropwizard-jaxws with Apache License 2.0 6 votes vote down vote up
@Test
public void meteredAnnotation() {

    Timer timer = testMetricRegistry.timer("timed");
    Meter meter = testMetricRegistry.meter("metered");
    when(mockMetricRegistry.timer(anyString())).thenReturn(timer);
    when(mockMetricRegistry.meter(anyString())).thenReturn(meter);

    long oldtimervalue = timer.getCount();
    long oldmetervalue = meter.getCount();

    Invoker invoker = invokerBuilder.create(instrumentedService, new MeteredInvoker());
    this.setTargetMethod(exchange, "metered"); // simulate CXF behavior

    Object result = invoker.invoke(exchange, null);
    assertEquals("meteredReturn", result);

    assertThat(timer.getCount(), is(oldtimervalue));
    assertThat(meter.getCount(), is(1 + oldmetervalue));
}
 
Example 3
Source File: InstrumentedInvokerFactoryTest.java    From dropwizard-jaxws with Apache License 2.0 6 votes vote down vote up
@Test
public void timedAnnotation() {

    Timer timer = testMetricRegistry.timer("timed");
    Meter meter = testMetricRegistry.meter("metered");
    when(mockMetricRegistry.timer(anyString())).thenReturn(timer);
    when(mockMetricRegistry.meter(anyString())).thenReturn(meter);

    long oldtimervalue = timer.getCount();
    long oldmetervalue = meter.getCount();

    Invoker invoker = invokerBuilder.create(instrumentedService, new TimedInvoker());
    this.setTargetMethod(exchange, "timed"); // simulate CXF behavior

    Object result = invoker.invoke(exchange, null);
    assertEquals("timedReturn", result);

    assertThat(timer.getCount(), is(1 + oldtimervalue));
    assertThat(meter.getCount(), is(oldmetervalue));
}
 
Example 4
Source File: SolrMetricsIntegrationTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigureReporter() throws Exception {
  Random random = random();

  String metricName = SolrMetricManager.mkName(METRIC_NAME, HANDLER_CATEGORY.toString(), HANDLER_NAME);
  SolrCoreMetricManager coreMetricManager = h.getCore().getCoreMetricManager();
  Timer timer = metricManager.timer(null, coreMetricManager.getRegistryName(), metricName);

  long initialCount = timer.getCount();

  int iterations = TestUtil.nextInt(random, 0, MAX_ITERATIONS);
  for (int i = 0; i < iterations; ++i) {
    h.query(req("*"));
  }

  long finalCount = timer.getCount();
  assertEquals("metric counter incorrect", iterations, finalCount - initialCount);
  Map<String, SolrMetricReporter> reporters = metricManager.getReporters(coreMetricManager.getRegistryName());
  assertEquals(RENAMED_REPORTERS.length + jmxReporter, reporters.size());

  // SPECIFIC and MULTIREGISTRY were skipped because they were
  // specific to collection1
  for (String reporterName : RENAMED_REPORTERS) {
    SolrMetricReporter reporter = reporters.get(reporterName + "@" + tag);
    assertNotNull("Reporter " + reporterName + " was not found.", reporter);
    assertTrue(reporter instanceof MockMetricReporter);

    MockMetricReporter mockReporter = (MockMetricReporter) reporter;
    assertTrue("Reporter " + reporterName + " was not initialized: " + mockReporter, mockReporter.didInit);
    assertTrue("Reporter " + reporterName + " was not validated: " + mockReporter, mockReporter.didValidate);
    assertFalse("Reporter " + reporterName + " was incorrectly closed: " + mockReporter, mockReporter.didClose);
  }
}
 
Example 5
Source File: MetricsTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void incrementProcessOffersDuration() {
    Timer timer = Metrics.getRegistry().timer(Metrics.PROCESS_OFFERS);
    long val = timer.getCount();
    Metrics.getProcessOffersDurationTimer().stop();
    Assert.assertEquals(1, timer.getCount() - val);
}
 
Example 6
Source File: DynamoDbDelegate.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 5 votes vote down vote up
public int estimateCapacityUnits(final String apiName, final String tableName) {
    int cu = 1;
    final Meter apiCcuMeter = getConsumedCapacityMeter(apiName, tableName);
    final Timer apiTimer = getTimer(apiName, tableName);

    if (apiCcuMeter != null && apiTimer != null && apiTimer.getCount() > 0) {
        cu = (int) Math.round(Math.max(1.0, (double) apiCcuMeter.getCount() / (double) apiTimer.getCount()));
    }
    return cu;
}
 
Example 7
Source File: AbstractUpsertOutputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the metrics that can be sent to Application master.
 * Note that some of the metrics are computed in the cassandra driver itself and hence just
 * extracted from the driver state itself.
 */
@Override
public void endWindow()
{
  super.endWindow();
  Timer timerForThisWindow = session.getCluster().getMetrics().getRequestsTimer();
  totalWriteRequestsAttempted += timerForThisWindow.getCount();
  numberOfHostsWrittenTo = uniqueHostsWrittenToInCurrentWindow.size();
  fifteenMinuteWriteRateLatency = timerForThisWindow.getFifteenMinuteRate();
  fiveMinuteWriteRateLatency = timerForThisWindow.getFiveMinuteRate();
  oneMinuteWriteRateLatency = timerForThisWindow.getOneMinuteRate();
  meanWriteRateLatency = timerForThisWindow.getMeanRate();
  Metrics.Errors errors = session.getCluster().getMetrics().getErrorMetrics();
  totalIgnoresInThisWindow = errors.getIgnores().getCount() - totalIgnoresSinceStart;
  totalIgnoresSinceStart = errors.getIgnores().getCount();
  totalWriteTimeoutsInThisWindow = errors.getWriteTimeouts().getCount() - totalWriteTimeoutsSinceStart;
  totalWriteTimeoutsSinceStart = errors.getWriteTimeouts().getCount();
  totalWriteRetriesInThisWindow =  errors.getRetriesOnWriteTimeout().getCount() - totalWriteRetriesSinceStart;
  totalWriteRetriesSinceStart = errors.getRetriesOnWriteTimeout().getCount();
  try {
    // we do not need any particular state and hence reusing the window id itself
    windowDataManager.save(currentWindowId,currentWindowId);
  } catch (IOException e) {
    LOG.error("Error while persisting the current window state " + currentWindowId + " because " + e.getMessage());
    throw new RuntimeException(e.getMessage());
  }
}
 
Example 8
Source File: RaftSnapshotBaseTest.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
/**
 * Basic test for install snapshot: start a one node cluster and let it
 * generate a snapshot. Then delete the log and restart the node, and add more
 * nodes as followers.
 */
@Test
public void testBasicInstallSnapshot() throws Exception {
  final List<LogPathAndIndex> logs;
  int i = 0;
  try {
    RaftTestUtil.waitForLeader(cluster);
    final RaftPeerId leaderId = cluster.getLeader().getId();

    try(final RaftClient client = cluster.createClient(leaderId)) {
      for (; i < SNAPSHOT_TRIGGER_THRESHOLD * 2 - 1; i++) {
        RaftClientReply reply = client.send(new SimpleMessage("m" + i));
        Assert.assertTrue(reply.isSuccess());
      }
    }

    // wait for the snapshot to be done
    RaftStorageDirectory storageDirectory = cluster.getLeader().getState()
        .getStorage().getStorageDir();

    final long nextIndex = cluster.getLeader().getState().getLog().getNextIndex();
    LOG.info("nextIndex = {}", nextIndex);
    final List<File> snapshotFiles = getSnapshotFiles(cluster, nextIndex - SNAPSHOT_TRIGGER_THRESHOLD, nextIndex);
    JavaUtils.attemptRepeatedly(() -> {
      Assert.assertTrue(snapshotFiles.stream().anyMatch(RaftSnapshotBaseTest::exists));
      return null;
    }, 10, ONE_SECOND, "snapshotFile.exist", LOG);
    verifyTakeSnapshotMetric(cluster.getLeader());
    logs = storageDirectory.getLogSegmentFiles();
  } finally {
    cluster.shutdown();
  }

  // delete the log segments from the leader
  for (LogPathAndIndex path : logs) {
    FileUtils.delete(path.getPath());
  }

  // restart the peer
  LOG.info("Restarting the cluster");
  cluster.restart(false);
  try {
    assertLeaderContent(cluster);

    // generate some more traffic
    try(final RaftClient client = cluster.createClient(cluster.getLeader().getId())) {
      Assert.assertTrue(client.send(new SimpleMessage("m" + i)).isSuccess());
    }

    // add two more peers
    MiniRaftCluster.PeerChanges change = cluster.addNewPeers(
        new String[]{"s3", "s4"}, true);
    // trigger setConfiguration
    cluster.setConfiguration(change.allPeersInNewConf);

    // Verify installSnapshot counter on leader before restart.
    verifyInstallSnapshotMetric(cluster.getLeader());
    RaftServerTestUtil.waitAndCheckNewConf(cluster, change.allPeersInNewConf, 0, null);

    Timer timer = getTakeSnapshotTimer(cluster.getLeader());
    long count = timer.getCount();

    // restart the peer and check if it can correctly handle conf change
    cluster.restartServer(cluster.getLeader().getId(), false);
    assertLeaderContent(cluster);

    // verify that snapshot was taken when stopping the server
    Assert.assertTrue(count < timer.getCount());
  } finally {
    cluster.shutdown();
  }
}
 
Example 9
Source File: TestCloudRecovery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Test
// commented 4-Sep-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Jul-2018
public void leaderRecoverFromLogOnStartupTest() throws Exception {
  AtomicInteger countReplayLog = new AtomicInteger(0);
  TestInjection.skipIndexWriterCommitOnClose = true;
  UpdateLog.testing_logReplayFinishHook = countReplayLog::incrementAndGet;

  CloudSolrClient cloudClient = cluster.getSolrClient();
  cloudClient.add(COLLECTION, sdoc("id", "1"));
  cloudClient.add(COLLECTION, sdoc("id", "2"));
  cloudClient.add(COLLECTION, sdoc("id", "3"));
  cloudClient.add(COLLECTION, sdoc("id", "4"));

  ModifiableSolrParams params = new ModifiableSolrParams();
  params.set("q", "*:*");
  QueryResponse resp = cloudClient.query(COLLECTION, params);
  assertEquals(0, resp.getResults().getNumFound());

  ChaosMonkey.stop(cluster.getJettySolrRunners());

  
  for (JettySolrRunner jettySolrRunner : cluster.getJettySolrRunners()) {
    cluster.waitForJettyToStop(jettySolrRunner);
  }
  assertTrue("Timeout waiting for all not live", ClusterStateUtil.waitForAllReplicasNotLive(cloudClient.getZkStateReader(), 45000));
  ChaosMonkey.start(cluster.getJettySolrRunners());
  
  cluster.waitForAllNodes(30);
  
  assertTrue("Timeout waiting for all live and active", ClusterStateUtil.waitForAllActiveAndLiveReplicas(cloudClient.getZkStateReader(), COLLECTION, 120000));

  resp = cloudClient.query(COLLECTION, params);
  assertEquals(4, resp.getResults().getNumFound());
  // Make sure all nodes is recover from tlog
  if (onlyLeaderIndexes) {
    // Leader election can be kicked off, so 2 tlog replicas will replay its tlog before becoming new leader
    assertTrue( countReplayLog.get() >=2);
  } else {
    assertEquals(4, countReplayLog.get());
  }

  // check metrics
  int replicationCount = 0;
  int errorsCount = 0;
  int skippedCount = 0;
  for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
    SolrMetricManager manager = jetty.getCoreContainer().getMetricManager();
    List<String> registryNames = manager.registryNames().stream()
        .filter(s -> s.startsWith("solr.core.")).collect(Collectors.toList());
    for (String registry : registryNames) {
      Map<String, Metric> metrics = manager.registry(registry).getMetrics();
      Timer timer = (Timer)metrics.get("REPLICATION.peerSync.time");
      Counter counter = (Counter)metrics.get("REPLICATION.peerSync.errors");
      Counter skipped = (Counter)metrics.get("REPLICATION.peerSync.skipped");
      replicationCount += timer.getCount();
      errorsCount += counter.getCount();
      skippedCount += skipped.getCount();
    }
  }
  if (onlyLeaderIndexes) {
    assertTrue(replicationCount >= 2);
  } else {
    assertEquals(2, replicationCount);
  }
}
 
Example 10
Source File: MetricRuleEvaluatorHelper.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public static Object getTimerValue(Timer t, MetricElement metricElement) {
  Object value = null;
  if (t != null) {
    switch (metricElement) {
      case TIMER_COUNT:
        value = t.getCount();
        break;
      case TIMER_M15_RATE:
        value = t.getFifteenMinuteRate();
        break;
      case TIMER_M1_RATE:
        value = t.getOneMinuteRate();
        break;
      case TIMER_M5_RATE:
        value = t.getFiveMinuteRate();
        break;
      case TIMER_MAX:
        value = t.getSnapshot().getMax();
        break;
      case TIMER_MEAN:
        value = t.getSnapshot().getMean();
        break;
      case TIMER_MEAN_RATE:
        value = t.getMeanRate();
        break;
      case TIMER_MIN:
        value = t.getSnapshot().getMin();
        break;
      case TIMER_P50:
        value = t.getSnapshot().getMedian();
        break;
      case TIMER_P75:
        value = t.getSnapshot().get75thPercentile();
        break;
      case TIMER_P95:
        value = t.getSnapshot().get95thPercentile();
        break;
      case TIMER_P98:
        value = t.getSnapshot().get98thPercentile();
        break;
      case TIMER_P99:
        value = t.getSnapshot().get99thPercentile();
        break;
      case TIMER_P999:
        value = t.getSnapshot().get999thPercentile();
        break;
      case TIMER_STD_DEV:
        value = t.getSnapshot().getStdDev();
        break;
      default:
        throw new IllegalArgumentException("Unexpected metric element " + metricElement);
    }
  }
  return value;
}
 
Example 11
Source File: InstrumentedInvokerFactoryTest.java    From dropwizard-jaxws with Apache License 2.0 4 votes vote down vote up
@Test
public void exceptionMeteredAnnotation() {

    Timer timer = testMetricRegistry.timer("timed");
    Meter meter = testMetricRegistry.meter("metered");
    Meter exceptionmeter = testMetricRegistry.meter("exceptionMeteredExceptions");
    when(mockMetricRegistry.timer(anyString())).thenReturn(timer);
    when(mockMetricRegistry.meter(contains("metered"))).thenReturn(meter);
    when(mockMetricRegistry.meter(contains("exceptionMetered"))).thenReturn(exceptionmeter);

    long oldtimervalue = timer.getCount();
    long oldmetervalue = meter.getCount();
    long oldexceptionmetervalue = exceptionmeter.getCount();

    // Invoke InstrumentedResource.exceptionMetered without exception beeing thrown

    Invoker invoker = invokerBuilder.create(instrumentedService, new ExceptionMeteredInvoker(false));
    this.setTargetMethod(exchange, "exceptionMetered", boolean.class); // simulate CXF behavior

    Object result = invoker.invoke(exchange, null);
    assertEquals("exceptionMeteredReturn", result);

    assertThat(timer.getCount(), is(oldtimervalue));
    assertThat(meter.getCount(), is(oldmetervalue));
    assertThat(exceptionmeter.getCount(), is(oldexceptionmetervalue));

    // Invoke InstrumentedResource.exceptionMetered with exception beeing thrown

    invoker = invokerBuilder.create(instrumentedService, new ExceptionMeteredInvoker(true));

    try {
        invoker.invoke(exchange, null);
        fail("Exception shall be thrown here");
    }
    catch (Exception e) {
        assertThat(e, is(instanceOf(RuntimeException.class)));
    }

    assertThat(timer.getCount(), is(oldtimervalue));
    assertThat(meter.getCount(), is(oldmetervalue));
    assertThat(exceptionmeter.getCount(), is(1 + oldexceptionmetervalue));

}