Java Code Examples for com.codahale.metrics.MetricRegistry

The following are top voted examples for showing how to use com.codahale.metrics.MetricRegistry. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: QDrill   File: TestSimpleLimit.java   View source code 6 votes vote down vote up
@Test
@Ignore
// The testcase is not valid. "test4.json" using increasingBigInt(0) to generate a list of increasing number starting from 0, and verify the sum.
// However, when evaluate the increasingBitInt(0), if the outgoing batch could not hold the new value, doEval() return false, and start the
// next batch. But the value has already been increased by 1 in the prior failed try. Therefore, the sum of the generated number could be different,
// depending on the size of each outgoing batch, and when the batch could not hold any more values.
public void testLimitAcrossBatches(@Injectable final DrillbitContext bitContext, @Injectable UserServer.UserClientConnection connection) throws Throwable {
  new NonStrictExpectations(){{
    bitContext.getMetrics(); result = new MetricRegistry();
    bitContext.getAllocator(); result = RootAllocatorFactory.newRoot(c);
    bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(c);
    bitContext.getConfig(); result = c;
    bitContext.getCompiler(); result = CodeCompiler.getTestCompiler(c);
  }};

  verifyLimitCount(bitContext, connection, "test2.json", 69999);
  final long start = 30000;
  final long end = 100000;
  final long expectedSum = (end - start) * (end + start - 1) / 2; //Formula for sum of series

  verifySum(bitContext, connection, "test4.json", 70000, expectedSum);


}
 
Example 2
Project: cruise-control   File: KafkaCruiseControl.java   View source code 6 votes vote down vote up
/**
 * Construct the Cruise Control
 *
 * @param config the configuration of Cruise Control.
 */
public KafkaCruiseControl(KafkaCruiseControlConfig config) {
  _config = config;
  _time = new SystemTime();
  // initialize some of the static state of Kafka Cruise Control;
  Load.init(config);
  ModelUtils.init(config);
  ModelParameters.init(config);
  _dropwizardMetricRegistry = new MetricRegistry();
  _reporter = JmxReporter.forRegistry(_dropwizardMetricRegistry).inDomain(_metricsPrefix).build();

  // Instantiate the components.
  _loadMonitor = new LoadMonitor(config, _time, _dropwizardMetricRegistry);
  _goalOptimizerExecutor =
      Executors.newSingleThreadExecutor(new KafkaCruiseControlThreadFactory("GoalOptimizerExecutor", true, null));
  _goalOptimizer = new GoalOptimizer(config, _loadMonitor, _time, _dropwizardMetricRegistry);
  _executor = new Executor(config, _time, _dropwizardMetricRegistry);
  _anomalyDetector = new AnomalyDetector(config, _loadMonitor, this, _time, _dropwizardMetricRegistry);
}
 
Example 3
Project: micrometer   File: GraphiteMeterRegistry.java   View source code 6 votes vote down vote up
private static GraphiteReporter defaultGraphiteReporter(GraphiteConfig config, MetricRegistry metricRegistry) {
    GraphiteSender sender;
    switch (config.protocol()) {
        case Plaintext:
            sender = new Graphite(new InetSocketAddress(config.host(), config.port()));
            break;
        case Udp:
            sender = new GraphiteUDP(new InetSocketAddress(config.host(), config.port()));
            break;
        case Pickled:
        default:
            sender = new PickledGraphite(new InetSocketAddress(config.host(), config.port()));
    }

    return GraphiteReporter.forRegistry(metricRegistry)
        .convertRatesTo(config.rateUnits())
        .convertDurationsTo(config.durationUnits())
        .build(sender);
}
 
Example 4
Project: QDrill   File: TestHashTable.java   View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
private SimpleRootExec doTest(final DrillbitContext bitContext, UserClientConnection connection, String plan_path) throws Exception{
    new NonStrictExpectations() {{
      bitContext.getMetrics(); result = new MetricRegistry();
      bitContext.getAllocator(); result = RootAllocatorFactory.newRoot(c);
      bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(c);
      bitContext.getConfig(); result = c;
      bitContext.getCompiler(); result = CodeCompiler.getTestCompiler(c);
    }};

    final PhysicalPlanReader reader = new PhysicalPlanReader(c, c.getMapper(), CoordinationProtos.DrillbitEndpoint.getDefaultInstance());
    final PhysicalPlan plan = reader.readPhysicalPlan(Files.toString(FileUtils.getResourceAsFile(plan_path), Charsets.UTF_8));
    final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(c);
    final FragmentContext context = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
    final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
    return exec;
  }
 
Example 5
Project: sentry   File: DatadogConfiguration.java   View source code 6 votes vote down vote up
private DatadogReporter enableDatadogMetrics(MetricRegistry registry) {
    log.info("Initializing Datadog reporter on host: {} with period: {} seconds",
        getHost() == null ? "localhost" : getHost(), getPeriod());
    Transport transport = getApiKey() == null ?
        new UdpTransport.Builder().build() : new HttpTransport.Builder().withApiKey(getApiKey()).build();
    DatadogReporter reporter = DatadogReporter.forRegistry(registry)
        .withHost(getHost())
        .withTransport(transport)
        .withExpansions(expansions())
        .withTags(getTags())
        .withPrefix(getPrefix())
        .filter(getFilter())
        .withMetricNameFormatter(new CustomMetricNameFormatter())
        .build();
    reporter.start(getPeriod(), TimeUnit.SECONDS);
    log.info("Datadog reporter successfully initialized");
    return reporter;
}
 
Example 6
Project: ja-micro   File: JsonHandlerTest.java   View source code 6 votes vote down vote up
@Before
public void setup() throws RpcCallException {
    handlerDictionary = new MethodHandlerDictionary();
    handlerDictionary.put("a", null);
    ServiceMethodHandlerUnderTest mockHandlerThrowsRpcCallEx = new ServiceMethodHandlerUnderTest();

    handlerDictionary.put("jsonRpcWithException", mockHandlerThrowsRpcCallEx);

    metricRegistry = mock(MetricRegistry.class);
    when(metricRegistry.counter(anyString())).thenReturn(mock(Counter.class));
    when(metricRegistry.timer(anyString())).thenReturn(mock(Timer.class));

    handlerMetrics = mock(RpcHandlerMetrics.class);
    when(handlerMetrics.getMethodTimer(any(), any(), any())).thenReturn(mock(GoTimer.class));

    servlet = new JsonHandler(handlerDictionary, metricRegistry, handlerMetrics, new ServiceProperties(), null);
}
 
Example 7
Project: jboot   File: CSVReporter.java   View source code 6 votes vote down vote up
@Override
public void report(MetricRegistry metricRegistry) {

    JbootMetricsCVRReporterConfig cvrReporterConfig = Jboot.config(JbootMetricsCVRReporterConfig.class);

    if (StringUtils.isBlank(cvrReporterConfig.getPath())) {
        throw new NullPointerException("csv reporter path must not be null, please config jboot.metrics.reporter.cvr.path in you properties.");
    }

    final CsvReporter reporter = CsvReporter.forRegistry(metricRegistry)
            .formatFor(Locale.US)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build(new File(cvrReporterConfig.getPath()));

    reporter.start(1, TimeUnit.SECONDS);
}
 
Example 8
Project: verify-hub   File: MatchingServiceHealthCheckClient.java   View source code 6 votes vote down vote up
public MatchingServiceHealthCheckResponseDto sendHealthCheckRequest(
        final Element matchingServiceHealthCheckRequest,
        final URI matchingServiceUri) {

    // Use a custom timer so that we get separate metrics for each matching service
    final String scope = matchingServiceUri.toString().replace(':','_').replace('/', '_');
    final Timer timer = metricsRegistry.timer(MetricRegistry.name(MatchingServiceHealthCheckClient.class, "sendHealthCheckRequest", scope));
    final Timer.Context context = timer.time();
    HealthCheckResponse healthCheckResponse;
    try {
        healthCheckResponse = client.makeSoapRequestForHealthCheck(matchingServiceHealthCheckRequest, matchingServiceUri);
    } catch(ApplicationException ex) {
        final String errorMessage = MessageFormat.format("Failed to complete matching service health check to {0}.", matchingServiceUri);
        LOG.warn(errorMessage, ex);
        return new MatchingServiceHealthCheckResponseDto(Optional.<String>absent(), Optional.<String>absent());
    } finally {
        context.stop();
    }

    return new MatchingServiceHealthCheckResponseDto(
                Optional.of(XmlUtils.writeToString(healthCheckResponse.getResponseElement())),
                healthCheckResponse.getVersionNumber());
}
 
Example 9
Project: outland   File: DefaultGroupStorage.java   View source code 6 votes vote down vote up
@Inject
public DefaultGroupStorage(
    AmazonDynamoDB amazonDynamoDB,
    TableConfiguration tableConfiguration,
    @Named("dynamodbGroupWriteHystrix") HystrixConfiguration dynamodbGroupWriteHystrix,
    @Named("dynamodbGraphWriteHystrix") HystrixConfiguration dynamodbGraphWriteHystrix,
    @Named("dynamodbNamespaceGraphQueryHystrix")
        HystrixConfiguration dynamodbNamespaceGraphQueryHystrix,
    MetricRegistry metrics
) {
  this.amazonDynamoDB = amazonDynamoDB;
  this.dynamoDB = new DynamoDB(this.amazonDynamoDB);
  this.groupTableName = tableConfiguration.outlandGroupsTable;
  this.groupGraphTableName = tableConfiguration.outlandAppGraphTable;
  this.dynamodbGroupWriteHystrix = dynamodbGroupWriteHystrix;
  this.dynamodbGraphWriteHystrix = dynamodbGraphWriteHystrix;
  this.dynamodbNamespaceGraphQueryHystrix = dynamodbNamespaceGraphQueryHystrix;
  this.metrics = metrics;
}
 
Example 10
Project: redisson-benchmark   File: ListAddBenchmark.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    Bench<JedisPool> bench = new JedisBench() {
        @Override
        public void executeOperation(String data, JedisPool benchInstance, int threadNumber, int iteration,
                MetricRegistry metrics) {
            Jedis jedis = benchInstance.getResource();

            Timer.Context time = metrics.timer("list").time();
            String key = "list_" + threadNumber;
            jedis.rpush(key, data);
            time.stop();

            jedis.close();
        }
    };
    
    Benchmark benchmark = new Benchmark(bench);
    benchmark.run(args);
}
 
Example 11
Project: incubator-ratis   File: RaftLogWorker.java   View source code 6 votes vote down vote up
RaftLogWorker(RaftPeerId selfId, RaftServerImpl raftServer, RaftStorage storage,
              RaftProperties properties) {
  this.name = selfId + "-" + getClass().getSimpleName();
  LOG.info("new {} for {}", name, storage);

  this.raftServer = raftServer;
  this.stateMachine = raftServer != null? raftServer.getStateMachine(): null;

  this.storage = storage;
  this.segmentMaxSize =
      RaftServerConfigKeys.Log.segmentSizeMax(properties).getSize();
  this.preallocatedSize =
      RaftServerConfigKeys.Log.preallocatedSize(properties).getSize();
  this.bufferSize =
      RaftServerConfigKeys.Log.writeBufferSize(properties).getSizeInt();
  this.forceSyncNum = RaftServerConfigKeys.Log.forceSyncNum(properties);
  this.workerThread = new Thread(this, name);

  // Server Id can be null in unit tests
  Supplier<String> serverId = () -> raftServer == null || raftServer.getId() == null
      ? "null" : raftServer.getId().toString();
  this.logFlushTimer = JavaUtils.memoize(() -> RatisMetricsRegistry.getRegistry()
      .timer(MetricRegistry.name(RaftLogWorker.class, serverId.get(),
          "flush-time")));
}
 
Example 12
Project: circus-train   File: DistCpCopier.java   View source code 5 votes vote down vote up
public DistCpCopier(
    Configuration conf,
    Path sourceDataBaseLocation,
    List<Path> sourceDataLocations,
    Path replicaDataLocation,
    Map<String, Object> copierOptions,
    MetricRegistry registry) {
  this(conf, sourceDataBaseLocation, sourceDataLocations, replicaDataLocation, copierOptions, DistCpExecutor.DEFAULT,
      registry);
}
 
Example 13
Project: jhipster-microservices-example   File: WebConfigurerTest.java   View source code 5 votes vote down vote up
@Before
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(new MockFilterRegistration())
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(new MockServletRegistration())
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props, new MockHazelcastInstance());
    metricRegistry = new MetricRegistry();
    webConfigurer.setMetricRegistry(metricRegistry);
}
 
Example 14
Project: geode-exposing-metrics-via-JMX   File: DemoInitializer.java   View source code 5 votes vote down vote up
private void checkForMatchAndAdd(StatisticsType type, String[] statsRegularExpression, Statistics currStatistics, StatisticDescriptor currDesciptor) {
    for (String currRegex : statsRegularExpression) {
        if (Pattern.matches(currRegex, currDesciptor.getName())) {
            MyInternalGauge gauge = new MyInternalGauge(currStatistics, currDesciptor);
            metricRegistry.register(MetricRegistry.name(type.getName(), currStatistics.getTextId(), currDesciptor.getName()), gauge);
        }
    }
}
 
Example 15
Project: dropwizard-hikaricp-benchmark   File: HikariDataSourceFactory.java   View source code 5 votes vote down vote up
@Override
public ManagedDataSource build(final MetricRegistry metricRegistry, final String name) {
    final Properties properties = new Properties();
    for (final Map.Entry<String, String> property : this.properties.entrySet()) {
        properties.setProperty(property.getKey(), property.getValue());
    }

    final HikariConfig config = new HikariConfig();
    config.setMetricRegistry(metricRegistry);
    if (healthCheckRegistry != null) {
        config.setHealthCheckRegistry(healthCheckRegistry);
    }

    config.setAutoCommit(autoCommit);
    config.setDataSourceProperties(properties);
    if (datasourceClassName != null) {
        config.setDataSourceClassName(datasourceClassName);
    } else {
        config.setDriverClassName(driverClass);
    }

    config.setMaximumPoolSize(maxSize);
    minSize.ifPresent(config::setMinimumIdle);
    config.setPoolName(name);
    config.setUsername(user);
    config.setPassword(user != null && password == null ? "" : password);
    return new HikariManagedPooledDataSource(config);
}
 
Example 16
Project: dropwizard-influxdb-reporter   File: InfluxDbHttpWriter.java   View source code 5 votes vote down vote up
public InfluxDbWriter build(final MetricRegistry metrics) {
  final Client client = new io.dropwizard.client.JerseyClientBuilder(metrics)
    .using(jersey)
    .using(new ObjectMapper())
    .using(Executors.newSingleThreadExecutor())
    .build("influxdb-http-writer");

  try {
    final String query = "/write?db=" + URLEncoder.encode(database, "UTF-8");
    final URL endpoint = new URL("http", host, port, query);
    return new InfluxDbHttpWriter(client, endpoint.toString());
  } catch (MalformedURLException | UnsupportedEncodingException e) {
    throw new IllegalArgumentException(e);
  }
}
 
Example 17
Project: jhipster-microservices-example   File: WebConfigurerTest.java   View source code 5 votes vote down vote up
@Before
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(new MockFilterRegistration())
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(new MockServletRegistration())
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props);
    metricRegistry = new MetricRegistry();
    webConfigurer.setMetricRegistry(metricRegistry);
}
 
Example 18
Project: dropwizard-vavr   File: EitherMessageBodyWriterTest.java   View source code 5 votes vote down vote up
@Override
protected Application configure() {
    forceSet(TestProperties.CONTAINER_PORT, "0");
    return DropwizardResourceConfig.forTesting(new MetricRegistry())
            .register(EitherMessageBodyWriter.class)
            .register(EmptyValueExceptionMapper.class)
            .register(TestResource.class);
}
 
Example 19
Project: minebox   File: NbdStatsReporter.java   View source code 5 votes vote down vote up
@Inject
public NbdStatsReporter(MetricRegistry metrics) {
    ScheduledReporter reporter = Slf4jReporter.forRegistry(metrics)
            .withLoggingLevel(Slf4jReporter.LoggingLevel.DEBUG)
            .outputTo(LOGGER)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
    reporter.start(5, TimeUnit.SECONDS);
}
 
Example 20
Project: redisson-benchmark   File: BinaryBenchmark.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    Bench<RedissonClient> bench = new RedissonBench() {
        @Override
        public void executeOperation(String data, RedissonClient benchInstance, int threadNumber, int iteration,
                MetricRegistry metrics) {
            RBucket<Object> bucket = benchInstance.getBucket("bucket_" + threadNumber + "_" + iteration);
            Timer.Context time = metrics.timer("bucket").time();
            bucket.set(value);
            time.stop();
        }
    };
    
    Benchmark benchmark = new Benchmark(bench);
    benchmark.run(args);
}
 
Example 21
Project: athena   File: DefaultGangliaMetricsReporter.java   View source code 5 votes vote down vote up
/**
 * Filters the metrics to only include a set of the given metrics.
 *
 * @param metricRegistry original metric registry
 * @return filtered metric registry
 */
protected MetricRegistry filter(MetricRegistry metricRegistry) {
    if (!monitorAll) {
        final MetricRegistry filtered = new MetricRegistry();
        metricRegistry.getNames().stream().filter(name ->
                containsName(name, metricNames)).forEach(name ->
                filtered.register(name, metricRegistry.getMetrics().get(name)));
        return filtered;
    } else {
        return metricRegistry;
    }
}
 
Example 22
Project: cruise-control   File: LoadMonitor.java   View source code 5 votes vote down vote up
/**
 * Construct a load monitor.
 *
 * @param config The load monitor configuration.
 * @param time   The time object.
 * @param dropwizardMetricRegistry the sensor registry for Cruise Control
 */
public LoadMonitor(KafkaCruiseControlConfig config,
                   Time time,
                   MetricRegistry dropwizardMetricRegistry) {
  this(config,
       new MetadataClient(config,
                          new Metadata(5000L, config.getLong(KafkaCruiseControlConfig.METADATA_MAX_AGE_CONFIG)),
                          METADATA_TTL,
                          time),
       time,
       dropwizardMetricRegistry);
}
 
Example 23
Project: micrometer   File: DropwizardMeterRegistry.java   View source code 5 votes vote down vote up
public DropwizardMeterRegistry(DropwizardConfig config, MetricRegistry registry, HierarchicalNameMapper nameMapper, Clock clock) {
    super(clock);
    this.dropwizardConfig = config;
    this.dropwizardClock = new DropwizardClock(clock);
    this.registry = registry;
    this.nameMapper = nameMapper;
    this.config().namingConvention(NamingConvention.camelCase);
}
 
Example 24
Project: cruise-control   File: Executor.java   View source code 5 votes vote down vote up
/**
 * The executor class that execute the proposals generated by optimizer.
 *
 * @param config The configurations for Cruise Control.
 */
public Executor(KafkaCruiseControlConfig config, Time time, MetricRegistry dropwizardMetricRegistry) {
  _executionTaskManager =
      new ExecutionTaskManager(config.getInt(KafkaCruiseControlConfig.NUM_CONCURRENT_PARTITION_MOVEMENTS_PER_BROKER_CONFIG),
                               config.getInt(KafkaCruiseControlConfig.NUM_CONCURRENT_LEADER_MOVEMENTS_CONFIG),
                               dropwizardMetricRegistry);
  _zkConnect = config.getString(KafkaCruiseControlConfig.ZOOKEEPER_CONNECT_CONFIG);
  _metadataClient = new MetadataClient(config, new Metadata(), -1L, time);
  _statusCheckingIntervalMs = config.getLong(KafkaCruiseControlConfig.EXECUTION_PROGRESS_CHECK_INTERVAL_MS_CONFIG);
  _excludedTopics = Pattern.compile(config.getString(KafkaCruiseControlConfig.TOPICS_EXCLUDED_FROM_PARTITION_MOVEMENT_CONFIG));
  _proposalExecutor =
      Executors.newSingleThreadExecutor(new KafkaCruiseControlThreadFactory("ProposalExecutor", false, LOG));
  _state = new AtomicReference<>(ExecutorState.State.NO_TASK_IN_PROGRESS);
  _stopRequested = false;
}
 
Example 25
Project: cruise-control   File: ExecutionTaskManager.java   View source code 5 votes vote down vote up
/**
 * The constructor of The Execution task manager.
 *
 * @param partitionMovementConcurrency The maximum number of concurrent partition movements per broker.
 */
public ExecutionTaskManager(int partitionMovementConcurrency,
                            int leaderMovementConcurrency,
                            MetricRegistry dropwizardMetricRegistry) {
  _inProgressPartMovementsByBrokerId = new HashMap<>();
  _inProgressPartitions = new HashSet<>();
  _executionTaskTracker = new ExecutionTaskTracker();
  _executionTaskPlanner = new ExecutionTaskPlanner();
  _partitionMovementConcurrency = partitionMovementConcurrency;
  _leaderMovementConcurrency = leaderMovementConcurrency;
  _brokersToSkipConcurrencyCheck = new HashSet<>();

  // Register gauge sensors.
  registerGaugeSensors(dropwizardMetricRegistry);
}
 
Example 26
Project: QDrill   File: TestTraceMultiRecordBatch.java   View source code 5 votes vote down vote up
@Test
public void testFilter(@Injectable final DrillbitContext bitContext, @Injectable UserClientConnection connection) throws Throwable {
  new NonStrictExpectations() {{
    bitContext.getMetrics(); result = new MetricRegistry();
    bitContext.getAllocator(); result = RootAllocatorFactory.newRoot(c);
    bitContext.getConfig(); result = c;
    bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(c);
    bitContext.getCompiler(); result = CodeCompiler.getTestCompiler(c);
  }};

  final PhysicalPlanReader reader = new PhysicalPlanReader(c, c.getMapper(), CoordinationProtos.DrillbitEndpoint.getDefaultInstance());
  final PhysicalPlan plan = reader.readPhysicalPlan(Files.toString(FileUtils.getResourceAsFile("/trace/multi_record_batch_trace.json"), Charsets.UTF_8));
  final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(c);
  final FragmentContext context = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
  final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));

  while(exec.next()) {
    for(final ValueVector vv: exec){
      vv.clear();
    }
  }

  exec.close();

  if(context.getFailureCause() != null) {
    throw context.getFailureCause();
  }
  assertTrue(!context.isFailed());
}
 
Example 27
Project: circus-train   File: S3S3CopierFactory.java   View source code 5 votes vote down vote up
@Autowired
public S3S3CopierFactory(
    AmazonS3ClientFactory clientFactory,
    ListObjectsRequestFactory listObjectsRequestFactory,
    TransferManagerFactory transferManagerFactory,
    MetricRegistry runningMetricsRegistry) {
  this.clientFactory = clientFactory;
  this.listObjectsRequestFactory = listObjectsRequestFactory;
  this.transferManagerFactory = transferManagerFactory;
  this.runningMetricsRegistry = runningMetricsRegistry;
}
 
Example 28
Project: cruise-control   File: LoadMonitorTaskRunnerTest.java   View source code 5 votes vote down vote up
@Test
public void testSamplingError() {
  KafkaCruiseControlConfig config = new KafkaCruiseControlConfig(getLoadMonitorProperties());
  Metadata metadata = new Metadata();
  MetadataClient metadataClient = new MetadataClient(config, metadata, -1L, TIME);
  MockMetricSampleAggregator mockMetricSampleAggregator = new MockMetricSampleAggregator(config, metadata);
  List<MetricSampler> samplers = new ArrayList<>();
  MetricRegistry dropwizardMetricRegistry = new MetricRegistry();
  for (int i = 0; i < NUM_METRIC_FETCHERS; i++) {
    samplers.add(new MockSampler(i));
  }
  MetricFetcherManager fetcherManager = new MetricFetcherManager(config, mockMetricSampleAggregator, metadataClient,
                                                                 TIME, dropwizardMetricRegistry, samplers);
  LoadMonitorTaskRunner loadMonitorTaskRunner =
      new LoadMonitorTaskRunner(config, fetcherManager, mockMetricSampleAggregator, metadataClient, TIME);
  while (metadata.fetch().topics().size() < 100) {
    metadataClient.refreshMetadata();
  }
  loadMonitorTaskRunner.start(true);

  int numSamples = 0;
  long startMs = System.currentTimeMillis();
  BlockingQueue<PartitionMetricSample> sampleQueue = mockMetricSampleAggregator.metricSampleQueue();
  while (numSamples < (NUM_PARTITIONS * NUM_TOPICS) * 10 && System.currentTimeMillis() < startMs + 10000) {
    PartitionMetricSample sample = sampleQueue.poll();
    if (sample != null) {
      numSamples++;
    }
  }
  // We should have NUM_METRIC_FETCHER rounds of sampling. The first round only has one metric fetcher returns
  // samples, two fetchers return samples for the second round, three for the third and four for the forth round.
  // So the first round only has 1/4 of the total samples, then 2/4, 3/4 and all the samples.
  int expectedNumSamples = 0;
  for (int i = 0; i < NUM_METRIC_FETCHERS; i++) {
    expectedNumSamples += (NUM_TOPICS * NUM_PARTITIONS) * (i + 1) / NUM_METRIC_FETCHERS;
  }
  assertEquals("Only see " + numSamples + " samples. Expecting " + expectedNumSamples + " samples",
      expectedNumSamples, numSamples);
  fetcherManager.shutdown();
}
 
Example 29
Project: dust-api   File: AuthenticatorFeature.java   View source code 5 votes vote down vote up
public AuthenticatorFeature(
        final MetricRegistry metricRegistry,
        final AuthConfig authConfig
) {
    this.metricRegistry = metricRegistry;
    this.authConfig = authConfig;
}
 
Example 30
Project: Spring-5.0-Cookbook   File: TestDbPool.java   View source code 5 votes vote down vote up
@Before
public void init() {
    MetricRegistry metricRegistry = new MetricRegistry();
    
    this.logReporter = ConsoleReporter
            .forRegistry(metricRegistry)
            .build();
    logReporter.start(1, TimeUnit.MINUTES); 
    timer = metricRegistry.timer("connection");
}
 
Example 31
Project: QDrill   File: TestSimpleFunctions.java   View source code 5 votes vote down vote up
@Test
public void testSubstring(@Injectable final DrillbitContext bitContext,
                          @Injectable UserServer.UserClientConnection connection) throws Throwable {
  new NonStrictExpectations(){{
    bitContext.getMetrics(); result = new MetricRegistry();
    bitContext.getAllocator(); result = RootAllocatorFactory.newRoot(c);
    bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(c);
    bitContext.getConfig(); result = c;
    bitContext.getCompiler(); result = CodeCompiler.getTestCompiler(c);
  }};

  final PhysicalPlanReader reader = new PhysicalPlanReader(c, c.getMapper(), CoordinationProtos.DrillbitEndpoint.getDefaultInstance());
  final PhysicalPlan plan = reader.readPhysicalPlan(Files.toString(FileUtils.getResourceAsFile("/functions/testSubstring.json"), Charsets.UTF_8));
  final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(c);
  final FragmentContext context = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
  final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));

  while(exec.next()) {
    final NullableVarCharVector c1 = exec.getValueVectorById(new SchemaPath("col3", ExpressionPosition.UNKNOWN), NullableVarCharVector.class);
    final NullableVarCharVector.Accessor a1 = c1.getAccessor();

    int count = 0;
    for(int i = 0; i < c1.getAccessor().getValueCount(); i++) {
      if (!a1.isNull(i)) {
        final NullableVarCharHolder holder = new NullableVarCharHolder();
        a1.get(i, holder);
        assertEquals("aaaa", StringFunctionHelpers.toStringFromUTF8(holder.start,  holder.end,  holder.buffer));
        ++count;
      }
    }
    assertEquals(50, count);
  }

  if(context.getFailureCause() != null) {
    throw context.getFailureCause();
  }
  assertTrue(!context.isFailed());
}
 
Example 32
Project: QDrill   File: TestOptiqPlans.java   View source code 5 votes vote down vote up
private SimpleRootExec doLogicalTest(final BootStrapContext context, UserClientConnection connection, String file,
    ClusterCoordinator coord, DataConnectionCreator com, Controller controller, WorkEventBus workBus) throws Exception {
  new NonStrictExpectations() {
    {
      context.getMetrics();
      result = new MetricRegistry();
      context.getAllocator();
      result = RootAllocatorFactory.newRoot(config);
      context.getConfig();
      result = config;
    }
  };
  final RemoteServiceSet lss = RemoteServiceSet.getLocalServiceSet();
  final DrillbitContext bitContext = new DrillbitContext(DrillbitEndpoint.getDefaultInstance(), context, coord, controller,
      com, workBus, new LocalPStoreProvider(config), null);
  final QueryContext qc = new QueryContext(UserSession.Builder.newBuilder().setSupportComplexTypes(true).build(),
      bitContext);
  final PhysicalPlanReader reader = bitContext.getPlanReader();
  final LogicalPlan plan = reader.readLogicalPlan(Files.toString(FileUtils.getResourceAsFile(file), Charsets.UTF_8));
  final PhysicalPlan pp = new BasicOptimizer(qc, connection).optimize(new BasicOptimizer.BasicOptimizationContext(qc), plan);

  final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(config);
  final FragmentContext fctxt = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
  final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(fctxt, (FragmentRoot) pp.getSortedOperators(false)
      .iterator().next()));
  return exec;

}
 
Example 33
Project: JInsight   File: ApptuitReporter.java   View source code 5 votes vote down vote up
protected ApptuitReporter(MetricRegistry registry, MetricFilter filter, TimeUnit rateUnit,
    TimeUnit durationUnit, Map<String, String> globalTags, String key, URL apiUrl,
    ReportingMode reportingMode) {
  super(registry, REPORTER_NAME, filter, rateUnit, durationUnit);

  this.buildReportTimer = registry.timer("apptuit.reporter.report.build");
  this.sendReportTimer = registry.timer("apptuit.reporter.report.send");

  if (reportingMode == null) {
    reportingMode = DEFAULT_REPORTING_MODE;
  }

  switch (reportingMode) {
    case NO_OP:
      this.dataPointsReporter = dataPoints -> {
      };
      break;
    case SYS_OUT:
      this.dataPointsReporter = dataPoints -> {
        dataPoints.forEach(dp -> dp.toTextLine(System.out, globalTags));
      };
      break;
    case API_PUT:
    default:
      ApptuitPutClient putClient = new ApptuitPutClient(key, globalTags, apiUrl);
      this.dataPointsReporter = putClient::put;
      break;
  }
}
 
Example 34
Project: Re-Collector   File: MetricsModule.java   View source code 5 votes vote down vote up
@Override
protected void configure() {
    bind(MetricRegistry.class).in(Scopes.SINGLETON);
    bind(MetricServiceConfiguration.class);

    registerService(MetricService.class);
}
 
Example 35
Project: circus-train   File: MetricsConf.java   View source code 5 votes vote down vote up
@Bean
ScheduledReporterFactory runningScheduledReporterFactory(
    MetricRegistry runningMetricRegistry,
    ValidatedGraphite validatedGraphite) {
  if (validatedGraphite.isEnabled()) {
    return new GraphiteScheduledReporterFactory(runningMetricRegistry, validatedGraphite.getHost(),
        validatedGraphite.getFormattedPrefix());
  }
  return new LoggingScheduledReporterFactory(runningMetricRegistry);
}
 
Example 36
Project: QDrill   File: TestCastFunctions.java   View source code 5 votes vote down vote up
@Test(expected = NumberFormatException.class)
public void testCastNumException(@Injectable final DrillbitContext bitContext,
                          @Injectable UserServer.UserClientConnection connection) throws Throwable {
  final BufferAllocator allocator = RootAllocatorFactory.newRoot(c);

  new NonStrictExpectations() {{
    bitContext.getMetrics(); result = new MetricRegistry();
    bitContext.getAllocator(); result = allocator;
    bitContext.getConfig(); result = c;
    bitContext.getCompiler(); result = CodeCompiler.getTestCompiler(c);
    bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(c);
  }};

  final PhysicalPlanReader reader = new PhysicalPlanReader(c, c.getMapper(), CoordinationProtos.DrillbitEndpoint.getDefaultInstance());
  final PhysicalPlan plan = reader.readPhysicalPlan(Files.toString(FileUtils.getResourceAsFile("/functions/cast/testCastNumException.json"), Charsets.UTF_8));
  final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(c);
  final FragmentContext context = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
  final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));

  while(exec.next()) {
  }

  exec.close();

  context.close();
  allocator.close();

  assertTrue(context.isFailed());

  if(context.getFailureCause() != null) {
    throw context.getFailureCause();
  }
}
 
Example 37
Project: spring-io   File: WebConfigurerTest.java   View source code 5 votes vote down vote up
@Before
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(new MockFilterRegistration())
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(new MockServletRegistration())
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props);
    metricRegistry = new MetricRegistry();
    webConfigurer.setMetricRegistry(metricRegistry);
}
 
Example 38
Project: graphiak   File: MetricStore.java   View source code 5 votes vote down vote up
/**
 * Constructor
 *
 * @param client
 *            Riak client
 */
public MetricStore(@Nonnull final RiakClient client) {
    this.client = Objects.requireNonNull(client);

    final MetricRegistry registry = SharedMetricRegistries
            .getOrCreate("default");
    this.queryTimer = registry
            .timer(MetricRegistry.name(MetricStore.class, "query"));
    this.storeTimer = registry
            .timer(MetricRegistry.name(MetricStore.class, "store"));
    this.deleteTimer = registry
            .timer(MetricRegistry.name(MetricStore.class, "delete"));
}
 
Example 39
Project: metrics-feign   File: FeignOutboundMetricsDecorator.java   View source code 5 votes vote down vote up
public ExceptionMeterMetric(final MetricRegistry registry, final Method method,
        final ExceptionMetered exceptionMetered) {
    final String name = chooseName(exceptionMetered.name(), exceptionMetered.absolute(), method,
            ExceptionMetered.DEFAULT_NAME_SUFFIX);
    this.meter = registry.meter(name);
    this.cause = exceptionMetered.cause();
}
 
Example 40
Project: Lagerta   File: IgniteNodeOverloadReporter.java   View source code 5 votes vote down vote up
/** */
private Builder(MetricRegistry registry) {
    this.registry = registry;
    this.rateUnit = TimeUnit.SECONDS;
    this.durationUnit = TimeUnit.MILLISECONDS;
    this.filter = MetricFilter.ALL;
}