下面列出了怎么用com.codahale.metrics.MetricRegistry的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testMoveCanceledAfterPromote()
throws Exception {
InMemoryDataStore backingStore = newBackingStore(new MetricRegistry());
Date fct = new Date(0);
AstyanaxTableDAO tableDAO = newTableDAO(backingStore, DC_US, mock(DataCopyDAO.class), mock(DataPurgeDAO.class), fct);
tableDAO.create(TABLE, newOptions(PL_US), ImmutableMap.<String, Object>of(), newAudit());
// Perform an initial move.
tableDAO.move(TABLE, PL_GLOBAL, Optional.<Integer>absent(), newAudit(), MoveType.SINGLE_TABLE);
TableJson table = tableDAO.readTableJson(TABLE, true);
String srcUuid = checkNotNull(table.getUuidString());
String destUuid = checkNotNull(table.getMasterStorage().getMoveTo().getUuidString());
// Hack the table JSON to get to the state where promote has occurred.
advanceActivatedToPromoted(destUuid, tableDAO, backingStore, fct);
try {
tableDAO.move(TABLE, PL_US, Optional.<Integer>absent(), newAudit(), MoveType.SINGLE_TABLE);
fail();
} catch (IllegalArgumentException e) {
assertEquals(e.getMessage(), "This table name is currently undergoing maintenance and therefore cannot be modified: my:table");
}
}
public static HikariDataSource getDataSourceFromConfig(
Config conf
, MetricRegistry metricRegistry
, HealthCheckRegistry healthCheckRegistry) {
HikariConfig jdbcConfig = new HikariConfig();
jdbcConfig.setPoolName(conf.getString("poolName"));
jdbcConfig.setMaximumPoolSize(conf.getInt("maximumPoolSize"));
jdbcConfig.setMinimumIdle(conf.getInt("minimumIdle"));
jdbcConfig.setJdbcUrl(conf.getString("jdbcUrl"));
jdbcConfig.setUsername(conf.getString("username"));
jdbcConfig.setPassword(conf.getString("password"));
jdbcConfig.addDataSourceProperty("cachePrepStmts", conf.getBoolean("cachePrepStmts"));
jdbcConfig.addDataSourceProperty("prepStmtCacheSize", conf.getInt("prepStmtCacheSize"));
jdbcConfig.addDataSourceProperty("prepStmtCacheSqlLimit", conf.getInt("prepStmtCacheSqlLimit"));
jdbcConfig.addDataSourceProperty("useServerPrepStmts", conf.getBoolean("useServerPrepStmts"));
// Add HealthCheck
jdbcConfig.setHealthCheckRegistry(healthCheckRegistry);
// Add Metrics
jdbcConfig.setMetricRegistry(metricRegistry);
return new HikariDataSource(jdbcConfig);
}
/**
* Configure Dropwizard helper.
* @param graphiteHost graphite server host
* @param port graphits server port
* @param tu time unit
* @param period reporting period
* @param vopt Vert.x options
* @param hostName logical hostname for this node (reporting)
*/
public static void config(String graphiteHost, int port, TimeUnit tu,
int period, VertxOptions vopt, String hostName) {
final String registryName = "okapi";
MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);
DropwizardMetricsOptions metricsOpt = new DropwizardMetricsOptions();
metricsOpt.setEnabled(true).setRegistryName(registryName);
vopt.setMetricsOptions(metricsOpt);
Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, port));
final String prefix = "folio.okapi." + hostName;
GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
.prefixedWith(prefix)
.build(graphite);
reporter.start(period, tu);
logger.info("Metrics remote {}:{} this {}", graphiteHost, port, prefix);
}
@Inject
CompactionControlMonitorManager(LifeCycleRegistry lifeCycle,
@LocalCompactionControl CompactionControlSource compactionControlSource,
@GlobalFullConsistencyZooKeeper CuratorFramework curator,
@SelfHostAndPort HostAndPort self,
Clock clock,
LeaderServiceTask dropwizardTask,
final MetricRegistry metricRegistry) {
LeaderService leaderService = new LeaderService(
curator,
"/leader/compaction-control-monitor",
self.toString(),
"Leader-CompactionControlMonitor",
30, TimeUnit.MINUTES,
() -> new CompactionControlMonitor(compactionControlSource, clock, metricRegistry)
);
ServiceFailureListener.listenTo(leaderService, metricRegistry);
dropwizardTask.register("stash-runtime-monitor", leaderService);
lifeCycle.manage(new ManagedGuavaService(leaderService));
}
@Override
public String getNameFor(String name, HttpRequest request) {
try {
String context = "";
Header header = request.getFirstHeader("X-Forwarded-Context");
if (header != null) {
context = header.getValue();
}
RequestLine requestLine = request.getRequestLine();
URIBuilder uriBuilder = new URIBuilder(requestLine.getUri());
String resourcePath = InstrUtils.getResourcePath(uriBuilder.removeQuery().build().toString());
return MetricRegistry.name("service", name, context + resourcePath, methodNameString(request));
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
public UserTaskManager(KafkaCruiseControlConfig config,
MetricRegistry dropwizardMetricRegistry,
Map<EndPoint, Timer> successfulRequestExecutionTimer,
Purgatory purgatory) {
_purgatory = purgatory;
_sessionKeyToUserTaskIdMap = new HashMap<>();
List<CruiseControlEndpointType> endpointTypes = Collections.unmodifiableList(Arrays.asList(CruiseControlEndpointType.values()));
_uuidToCompletedUserTaskInfoMap = new HashMap<>(endpointTypes.size());
_completedUserTaskRetentionTimeMs = new HashMap<>(endpointTypes.size());
initCompletedUserTaskRetentionPolicy(config, endpointTypes);
_sessionExpiryMs = config.getLong(WebServerConfig.WEBSERVER_SESSION_EXPIRY_MS_CONFIG);
_maxActiveUserTasks = config.getInt(WebServerConfig.MAX_ACTIVE_USER_TASKS_CONFIG);
_uuidToActiveUserTaskInfoMap = new LinkedHashMap<>(_maxActiveUserTasks);
_time = Time.SYSTEM;
_uuidGenerator = new UUIDGenerator();
_userTaskScannerExecutor.scheduleAtFixedRate(new UserTaskScanner(),
USER_TASK_SCANNER_INITIAL_DELAY_SECONDS,
USER_TASK_SCANNER_PERIOD_SECONDS,
TimeUnit.SECONDS);
dropwizardMetricRegistry.register(MetricRegistry.name("UserTaskManager", "num-active-sessions"),
(Gauge<Integer>) _sessionKeyToUserTaskIdMap::size);
dropwizardMetricRegistry.register(MetricRegistry.name("UserTaskManager", "num-active-user-tasks"),
(Gauge<Integer>) _uuidToActiveUserTaskInfoMap::size);
_successfulRequestExecutionTimer = successfulRequestExecutionTimer;
}
@Test
public void test_startup_singleton() {
final Injector injector = Guice.createInjector(
new PersistenceMigrationModule(new MetricRegistry(), persistenceConfigurationService),
new AbstractModule() {
@Override
protected void configure() {
bind(SystemInformation.class).toInstance(systemInformation);
bindScope(LazySingleton.class, LazySingletonScope.get());
bind(MqttConfigurationService.class).toInstance(mqttConfigurationService);
}
});
final PersistenceStartup instance1 = injector.getInstance(PersistenceStartup.class);
final PersistenceStartup instance2 = injector.getInstance(PersistenceStartup.class);
assertSame(instance1, instance2);
}
@Test
public void testMetrics() {
MetricRegistry metrics = mock(MetricRegistry.class);
Client client = mock(Client.class);
when(client.getHost()).thenReturn("myhost");
when(jedis.getClient()).thenReturn(client);
when(pool.getNumActive()).thenReturn(1);
when(pool.getNumIdle()).thenReturn(2);
when(pool.getNumWaiters()).thenReturn(3);
rf.startMonitoring(metrics);
@SuppressWarnings("rawtypes")
ArgumentCaptor<Gauge> gauge = ArgumentCaptor.forClass(Gauge.class);
verify(metrics).register(eq("com.amadeus.session.redis.myhost.active"), gauge.capture());
verify(metrics).register(eq("com.amadeus.session.redis.myhost.idle"), gauge.capture());
verify(metrics).register(eq("com.amadeus.session.redis.myhost.waiting"), gauge.capture());
assertEquals(1, gauge.getAllValues().get(0).getValue());
assertEquals(2, gauge.getAllValues().get(1).getValue());
assertEquals(3, gauge.getAllValues().get(2).getValue());
}
@Inject
public CloudWatchLogsInput(@Assisted Configuration configuration,
MetricRegistry metricRegistry,
KinesisTransport.Factory transport,
LocalMetricRegistry localRegistry,
CloudWatchRawLogCodec.Factory codec,
Config config,
Descriptor descriptor,
ServerStatus serverStatus) {
super(
metricRegistry,
configuration,
transport.create(configuration),
localRegistry,
codec.create(configuration),
config,
descriptor,
serverStatus
);
}
@Test
public void get() throws Exception {
final MetricsLibratoReporterConfiguration configuration = new MetricsLibratoReporterConfiguration() {
@Override
public String getUsername() {
return "username";
}
@Override
public String getToken() {
return "token";
}
};
final LibratoReporterProvider provider = new LibratoReporterProvider(configuration, new MetricRegistry());
final LibratoReporter reporter = provider.get();
assertNotNull(reporter);
}
@Override
public void report(MetricRegistry metricRegistry) {
JbootMetricCVRReporterConfig cvrReporterConfig = Jboot.config(JbootMetricCVRReporterConfig.class);
if (StrUtil.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);
}
public static Metric getMetric(MetricRegistry metrics, String metricId, MetricType metricType) {
Metric metric;
switch (metricType) {
case HISTOGRAM:
metric = MetricsConfigurator.getHistogram(metrics, metricId);
break;
case METER:
metric = MetricsConfigurator.getMeter(metrics, metricId);
break;
case COUNTER:
metric = MetricsConfigurator.getCounter(metrics, metricId);
break;
case TIMER:
metric = MetricsConfigurator.getTimer(metrics, metricId);
break;
case GAUGE:
metric = MetricsConfigurator.getGauge(metrics, metricId);
break;
default :
throw new IllegalArgumentException(Utils.format("Unknown metric type '{}'", metricType));
}
return metric;
}
private KafkaTopicRepository createKafkaTopicRepository() {
final KafkaZookeeper kafkaZookeeper = Mockito.mock(KafkaZookeeper.class);
Mockito.when(kafkaZookeeper.getZookeeperConnectionString()).thenReturn(ZOOKEEPER_URL);
final Consumer<byte[], byte[]> consumer = Mockito.mock(Consumer.class);
Mockito.when(consumer.partitionsFor(any())).thenReturn(new ArrayList<>());
final KafkaFactory factory = Mockito.mock(KafkaFactory.class);
Mockito.when(factory.getConsumer()).thenReturn(consumer);
final KafkaLocationManager kafkaLocationManager = Mockito.mock(KafkaLocationManager.class);
Mockito
.doReturn(kafkaHelper.createProducer())
.when(factory)
.takeProducer();
return new KafkaTopicRepository.Builder()
.setKafkaZookeeper(kafkaZookeeper)
.setKafkaFactory(factory)
.setNakadiSettings(nakadiSettings)
.setKafkaSettings(kafkaSettings)
.setZookeeperSettings(zookeeperSettings)
.setKafkaTopicConfigFactory(kafkaTopicConfigFactory)
.setKafkaLocationManager(kafkaLocationManager)
.setMetricRegistry(new MetricRegistry())
.build();
}
@Before
public void setUp() throws SQLException {
mBeanServer=ManagementFactory.getPlatformMBeanServer();
metricRegistry = new MetricRegistry();
jmxReporter = JmxReporter.forRegistry(metricRegistry)
.registerWith(mBeanServer)
.createsObjectNamesWith(new SqlObjectNameFactory())
.build();
jmxReporter.start();
proxyFactory = new JdbcProxyFactory(metricRegistry);
rawDataSource = H2DbUtil.createDataSource();
try(Connection connection = rawDataSource.getConnection()) {
H2DbUtil.initTable(connection);
}
dataSource = proxyFactory.wrapDataSource(rawDataSource);
}
@Test
public void perNodeDataEventHandlerAddRemoveTest() {
DataEventManager eventManager = new DataEventManager(new MetricRegistry());
UpdateNodeDataEventHandler nodeDataEventHandler = (nodeId, key, oldValue, newValue) -> {
};
eventManager.registerPerNodeDataSubscriber(nodeDataEventHandler);
Assert.assertEquals(1, eventManager.getPerNodeSubscribersSize());
eventManager.unregisterPerNodeDataSubscriber(nodeDataEventHandler);
Assert.assertEquals(0, eventManager.getPerNodeSubscribersSize());
}
public static void main(String[] args) throws Exception {
Random random = new Random(System.nanoTime());
Config config = new Config.Builder().directory(TestFileHelper.TEMP_PATH).compactionStrategy
(CompactionStrategies.SIZE_TIERED_COMPACTION_STRATEGY).tableCacheSize(512000000).indexCacheSize
(64000000).maxWriteRate(Integer.MAX_VALUE).build();
MetricRegistry metrics = new MetricRegistry();
ConsoleReporter reporter = PerformanceHelper.consoleReporter(metrics);
Timer readTimer = metrics.register("reads", new Timer(new ExponentiallyDecayingReservoir()));
DB db = HeftyDB.open(config);
db.compact().get();
//Read
for (int i = 0; i < RECORD_COUNT * 10; i++) {
String key = random.nextInt(RECORD_COUNT) + "";
Timer.Context watch = readTimer.time();
db.get(ByteBuffers.fromString(key));
watch.stop();
}
reporter.report();
db.logMetrics();
db.close();
System.exit(0);
}
@Test
public void get() throws Exception {
final MetricsOpenTsdbReporterConfiguration configuration = new MetricsOpenTsdbReporterConfiguration();
final OpenTsdb openTsdb = OpenTsdb.forService("http://localhost:4242/").create();
final OpenTsdbReporterProvider provider = new OpenTsdbReporterProvider(configuration, openTsdb, new MetricRegistry());
final OpenTsdbReporter reporter = provider.get();
assertNotNull(reporter);
}
@AssistedInject
public HttpMonitorInput(MetricRegistry metricRegistry, @Assisted Configuration configuration,
HttpMonitorTransport.Factory factory, LocalMetricRegistry localRegistry,
GelfCodec.Factory codecFactory,
Config config, Descriptor descriptor, ServerStatus serverStatus) {
super(metricRegistry, configuration, factory.create(configuration),
localRegistry, codecFactory.create(configuration), config, descriptor, serverStatus);
}
/**
* Tests starting up a {@link HelixAccountService}, when the corresponding {@code ZooKeeper} does not have any
* {@link ZNRecord} on it but local backup files exists.
* @throws Exception Any unexpected exception
*/
@Test
public void testStartWithBackupFiles() throws Exception {
// use testUpdateAccount function to create backups and then delete helixStore data.
testUpdateAccount();
if (accountService != null) {
accountService.close();
}
deleteStoreIfExists();
// should have some backup files.
if (helixConfigProps.containsKey(HelixAccountServiceConfig.BACKUP_DIRECTORY_KEY)) {
File[] files = accountBackupDir.toFile()
.listFiles(path -> BackupFileManager.versionFilenamePattern.matcher(path.getName()).find());
assertTrue("UpdateAccount should create backup files", files.length > 0);
helixConfigProps.put(HelixAccountServiceConfig.ENABLE_SERVE_FROM_BACKUP, "true");
vHelixConfigProps = new VerifiableProperties(helixConfigProps);
storeConfig = new HelixPropertyStoreConfig(vHelixConfigProps);
String updaterThreadPrefix = UUID.randomUUID().toString();
MockHelixAccountServiceFactory mockHelixAccountServiceFactory =
new MockHelixAccountServiceFactory(vHelixConfigProps, new MetricRegistry(), notifier, updaterThreadPrefix,
mockRouter);
accountService = mockHelixAccountServiceFactory.getAccountService();
assertNotNull("Backup files should have data", accountService.getAllAccounts());
assertEquals("Number of accounts from backup mismatch", accountService.getAllAccounts().size(),
1 + NUM_REF_ACCOUNT);
}
}
/**
* Builds reporter with the given graphite config.
*
* @param graphiteCfg graphite config
* @return reporter
*/
private GraphiteReporter buildReporter(Graphite graphiteCfg) {
MetricRegistry metricRegistry = metricsService.getMetricRegistry();
return GraphiteReporter.forRegistry(filter(metricRegistry))
.prefixedWith(metricNamePrefix)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build(graphiteCfg);
}
public StoreToolsMetrics(MetricRegistry registry) {
dumpIndexTimeMs = registry.timer(MetricRegistry.name(DumpIndexTool.class, "DumpIndexTimeMs"));
dumpReplicaIndexesTimeMs = registry.timer(MetricRegistry.name(DumpIndexTool.class, "DumpReplicaIndexesTimeMs"));
dumpLogTimeMs = registry.timer(MetricRegistry.name(DumpLogTool.class, "DumpLogTimeMs"));
findAllEntriesPerIndexTimeMs =
registry.timer(MetricRegistry.name(DumpIndexTool.class, "FindAllEntriesPerIndexTimeMs"));
readSingleBlobRecordFromLogTimeMs =
registry.timer(MetricRegistry.name(DumpDataTool.class, "ReadSingleBlobRecordFromLogTimeMs"));
readFromLogAndVerifyTimeMs = registry.timer(MetricRegistry.name(DumpDataTool.class, "ReadFromLogAndVerifyTimeMs"));
compareIndexFileToLogTimeMs =
registry.timer(MetricRegistry.name(DumpDataTool.class, "CompareIndexFileToLogTimeMs"));
compareReplicaIndexFilesToLogTimeMs =
registry.timer(MetricRegistry.name(DumpDataTool.class, "CompareReplicaIndexFilesToLogTimeMs"));
logDeserializationError = registry.counter(MetricRegistry.name(DumpLogTool.class, "LogDeserializationErrorCount"));
endOfFileOnDumpLogError = registry.counter(MetricRegistry.name(DumpLogTool.class, "EndOfFileOnDumpLogErrorCount"));
unknownErrorOnDumpIndex =
registry.counter(MetricRegistry.name(DumpIndexTool.class, "UnknownErrorOnDumpIndexCount"));
unknownErrorOnDumpLog = registry.counter(MetricRegistry.name(DumpLogTool.class, "UnknownErrorOnDumpLogCount"));
indexToLogDeleteFlagMisMatchError =
registry.counter(MetricRegistry.name(DumpDataTool.class, "IndexToLogDeleteFlagMisMatchErrorCount"));
indexToLogExpiryMisMatchError =
registry.counter(MetricRegistry.name(DumpDataTool.class, "IndexToLogExpiryMisMatchErrorCount"));
indexToLogBlobIdMisMatchError =
registry.counter(MetricRegistry.name(DumpDataTool.class, "IndexToLogBlobIdMisMatchErrorCount"));
indexToLogBlobRecordComparisonFailure =
registry.counter(MetricRegistry.name(DumpDataTool.class, "IndexToLogBlobRecordComparisonFailureCount"));
logRangeNotFoundInIndexError =
registry.counter(MetricRegistry.name(DumpDataTool.class, "LogRangeNotFoundInIndexErrorCount"));
indexLogEndOffsetMisMatchError =
registry.counter(MetricRegistry.name(DumpDataTool.class, "IndexLogEndOffsetMisMatchErrorCount"));
}
@Override protected void run(Bootstrap<KeywhizConfig> bootstrap, Namespace namespace,
KeywhizConfig config) throws Exception {
if (!config.getEnvironment().equals("development")) {
throw new IllegalArgumentException("cannot call db-seed in non-development environment");
}
DataSource dataSource = config.getDataSourceFactory()
.build(new MetricRegistry(), "db-seed-datasource");
DSLContext dslContext = DSLContexts.databaseAgnostic(dataSource);
doImport(dslContext);
}
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.class))
.when(servletContext).addFilter(anyString(), any(Filter.class));
doReturn(mock(ServletRegistration.Dynamic.class))
.when(servletContext).addServlet(anyString(), any(Servlet.class));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
/**
* Remove metric object (regardless of it's type)
*/
private static boolean remove(final MetricRegistry metrics, final String name, String pipelineName, String pipelineRev) {
final String jmxNamePrefix = jmxPipelinePrefix(pipelineName, pipelineRev);
final MetricRegistry metricRegistry = sdcMetrics;
if (metricRegistry != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
metricRegistry.remove(jmxNamePrefix + name);
return null;
}
});
}
return metrics.remove(name);
}
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.class))
.when(servletContext).addFilter(anyString(), any(Filter.class));
doReturn(mock(ServletRegistration.Dynamic.class))
.when(servletContext).addServlet(anyString(), any(Servlet.class));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
private Builder(MetricRegistry registry) {
this.registry = registry;
this.clock = defaultClock();
this.prefix = null;
this.rateUnit = SECONDS;
this.durationUnit = MILLISECONDS;
this.filter = ALL;
}
/**
* Common test method to be able to check security from any authentication plugin
* @param cluster the MiniSolrCloudCluster to fetch metrics from
* @param prefix the metrics key prefix, currently "SECURITY./authentication." for basic auth and "SECURITY./authentication/pki." for PKI
* @param keys what keys to examine
*/
Map<String,Long> countSecurityMetrics(MiniSolrCloudCluster cluster, String prefix, List<String> keys) {
List<Map<String, Metric>> metrics = new ArrayList<>();
cluster.getJettySolrRunners().forEach(r -> {
MetricRegistry registry = r.getCoreContainer().getMetricManager().registry("solr.node");
assertNotNull(registry);
metrics.add(registry.getMetrics());
});
Map<String,Long> counts = new HashMap<>();
keys.forEach(k -> {
counts.put(k, sumCount(prefix, k, metrics));
});
return counts;
}
public static Gauge<Map<String, Object>> createStageGauge(MetricRegistry metrics, String nameSuffix, Comparator<String> comparator, final String pipelineName, final String pipelineRev) {
String name = metricName(nameSuffix, GAUGE_SUFFIX);
if(metrics.getGauges().containsKey(name)) {
return metrics.getGauges().get(name);
}
return createGauge(metrics, nameSuffix, comparator, pipelineName, pipelineRev);
}
public MegabusRefProducer(MegabusRefProducerConfiguration config, DatabusEventStore eventStore,
RateLimitedLogFactory logFactory, MetricRegistry metricRegistry,
Producer<String, JsonNode> producer, ObjectMapper objectMapper, Topic topic,
String subscriptionName, String partitionIdentifier) {
this(config, eventStore, logFactory, metricRegistry, null, producer, objectMapper,
topic, subscriptionName, partitionIdentifier, null);
}
private Builder(MetricRegistry registry) {
this.registry = registry;
this.clock = Clock.defaultClock();
this.prefix = null;
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.filter = MetricFilter.ALL;
}