io.prometheus.client.GaugeMetricFamily Java Examples

The following examples show how to use io.prometheus.client.GaugeMetricFamily. 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: RetryMetricsCollector.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    GaugeMetricFamily retryCallsFamily = new GaugeMetricFamily(
        names.getCallsMetricName(),
        "The number of calls",
        LabelNames.NAME_AND_KIND
    );

    for (Retry retry : retryRegistry.getAllRetries()) {
        retryCallsFamily.addMetric(asList(retry.getName(), "successful_without_retry"),
            retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
        retryCallsFamily.addMetric(asList(retry.getName(), "successful_with_retry"),
            retry.getMetrics().getNumberOfSuccessfulCallsWithRetryAttempt());
        retryCallsFamily.addMetric(asList(retry.getName(), "failed_without_retry"),
            retry.getMetrics().getNumberOfFailedCallsWithoutRetryAttempt());
        retryCallsFamily.addMetric(asList(retry.getName(), "failed_with_retry"),
            retry.getMetrics().getNumberOfFailedCallsWithRetryAttempt());

    }

    return Collections.singletonList(retryCallsFamily);
}
 
Example #2
Source File: EntryCollector.java    From canal with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
    GaugeMetricFamily delay = new GaugeMetricFamily(DELAY,
            DELAY_HELP, DEST_LABELS_LIST);
    CounterMetricFamily transactions = new CounterMetricFamily(TRANSACTION,
            TRANSACTION_HELP, DEST_LABELS_LIST);
    for (EntryMetricsHolder emh : instances.values()) {
        long now = System.currentTimeMillis();
        long latest = emh.latestExecTime.get();
        // execTime > now,delay显示为0
        long d = (now >= latest) ? (now - latest) : 0;
        delay.addMetric(emh.destLabelValues, d);
        transactions.addMetric(emh.destLabelValues, emh.transactionCounter.doubleValue());
    }
    mfs.add(delay);
    mfs.add(transactions);
    return mfs;
}
 
Example #3
Source File: AlibabaMetricsExports.java    From metrics with Apache License 2.0 6 votes vote down vote up
private void fromSnapshot(List<MetricFamilySamples> samples, MetricName metricName, Snapshot snapshot,
                          double factor, String helpMessage) {
    List<MetricFamilySamples.Sample> snapshotSamples = Arrays.asList(
            sampleBuilder.createSample(metricName, "_summary", Arrays.asList("quantile"), Arrays.asList("0.5"),
                    snapshot.getMedian() * factor),
            sampleBuilder.createSample(metricName, "_summary", Arrays.asList("quantile"), Arrays.asList("0.75"),
                    snapshot.get75thPercentile() * factor),
            sampleBuilder.createSample(metricName, "_summary", Arrays.asList("quantile"), Arrays.asList("0.95"),
                    snapshot.get95thPercentile() * factor),
            sampleBuilder.createSample(metricName, "_summary", Arrays.asList("quantile"), Arrays.asList("0.99"),
                    snapshot.get99thPercentile() * factor)
    );
    samples.add(new MetricFamilySamples(snapshotSamples.get(0).name, Type.SUMMARY, helpMessage, snapshotSamples));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey() + "_min"), helpMessage, snapshot.getMin() * factor));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey() + "_max"), helpMessage, snapshot.getMax() * factor));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey() + "_mean"), helpMessage, snapshot.getMean() * factor));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey() + "_stddev"), helpMessage, snapshot.getStdDev() * factor));
}
 
Example #4
Source File: AlibabaMetricsExports.java    From metrics with Apache License 2.0 6 votes vote down vote up
public void fromMeter(List<MetricFamilySamples> samples, MetricName metricName, Metered meter, long timestamp,
                      boolean collectBucketCount) {
    samples.add(new CounterMetricFamily(normalizeName(metricName.getKey()) + "_count",
            getHelpMessage(metricName.getKey(), meter), meter.getCount()));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_m1",
            getHelpMessage(metricName.getKey(), meter), meter.getOneMinuteRate()));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_m5",
            getHelpMessage(metricName.getKey(), meter), meter.getFiveMinuteRate()));
    samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_m15",
            getHelpMessage(metricName.getKey(), meter), meter.getFifteenMinuteRate()));

    if (!collectBucketCount) {
        return;
    }

    long start = getNormalizedStartTime(timestamp, meter.getInstantCountInterval());
    if (meter.getInstantCount().containsKey(start)) {
        samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_bucket_count",
                getHelpMessage(metricName.getKey(), meter), meter.getInstantCount().get(start)));
    } else {
        samples.add(new GaugeMetricFamily(normalizeName(metricName.getKey()) + "_bucket_count",
                getHelpMessage(metricName.getKey(), meter), 0));
    }
}
 
Example #5
Source File: EntryCollector.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
    GaugeMetricFamily delay = new GaugeMetricFamily(DELAY,
            DELAY_HELP, DEST_LABELS_LIST);
    CounterMetricFamily transactions = new CounterMetricFamily(TRANSACTION,
            TRANSACTION_HELP, DEST_LABELS_LIST);
    for (EntryMetricsHolder emh : instances.values()) {
        long now = System.currentTimeMillis();
        long latest = emh.latestExecTime.get();
        // execTime > now,delay显示为0
        long d = (now >= latest) ? (now - latest) : 0;
        delay.addMetric(emh.destLabelValues, d);
        transactions.addMetric(emh.destLabelValues, emh.transactionCounter.doubleValue());
    }
    mfs.add(delay);
    mfs.add(transactions);
    return mfs;
}
 
Example #6
Source File: VersionInfoExports.java    From client_java with Apache License 2.0 6 votes vote down vote up
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();

    GaugeMetricFamily jvmInfo = new GaugeMetricFamily(
            "jvm_info",
            "JVM version info",
            Arrays.asList("version", "vendor", "runtime"));
    jvmInfo.addMetric(
            Arrays.asList(
                System.getProperty("java.runtime.version", "unknown"),
                System.getProperty("java.vm.vendor", "unknown"),
                System.getProperty("java.runtime.name", "unknown")),
                1L);
    mfs.add(jvmInfo);

    return mfs;
}
 
Example #7
Source File: MetaCollector.java    From canal with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
    GaugeMetricFamily instanceInfo = new GaugeMetricFamily(INSTANCE,
            INSTANCE_HELP, INFO_LABELS_LIST);
    GaugeMetricFamily subsInfo = new GaugeMetricFamily(SUBSCRIPTION,
            SUBSCRIPTION_HELP, DEST_LABELS_LIST);
    for (Map.Entry<String, MetaMetricsHolder> nme : instances.entrySet()) {
        final String destination = nme.getKey();
        final MetaMetricsHolder nmh = nme.getValue();
        instanceInfo.addMetric(nmh.infoLabelValues, 1);
        List<ClientIdentity> subs = nmh.metaManager.listAllSubscribeInfo(destination);
        int count = subs == null ? 0 : subs.size();
        subsInfo.addMetric(nmh.destLabelValues, count);
    }
    mfs.add(instanceInfo);
    mfs.add(subsInfo);
    return mfs;
}
 
Example #8
Source File: MetaCollector.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
    GaugeMetricFamily instanceInfo = new GaugeMetricFamily(INSTANCE,
            INSTANCE_HELP, INFO_LABELS_LIST);
    GaugeMetricFamily subsInfo = new GaugeMetricFamily(SUBSCRIPTION,
            SUBSCRIPTION_HELP, DEST_LABELS_LIST);
    for (Map.Entry<String, MetaMetricsHolder> nme : instances.entrySet()) {
        final String destination = nme.getKey();
        final MetaMetricsHolder nmh = nme.getValue();
        instanceInfo.addMetric(nmh.infoLabelValues, 1);
        List<ClientIdentity> subs = nmh.metaManager.listAllSubscribeInfo(destination);
        int count = subs == null ? 0 : subs.size();
        subsInfo.addMetric(nmh.destLabelValues, count);
    }
    mfs.add(instanceInfo);
    mfs.add(subsInfo);
    return mfs;
}
 
Example #9
Source File: BuildInfoCollector.java    From jmx_exporter with Apache License 2.0 6 votes vote down vote up
public List<Collector.MetricFamilySamples> collect() {
  List<Collector.MetricFamilySamples> mfs = new ArrayList<Collector.MetricFamilySamples>();

  GaugeMetricFamily artifactInfo = new GaugeMetricFamily(
          "jmx_exporter_build_info",
          "A metric with a constant '1' value labeled with the version of the JMX exporter.",
          asList("version", "name"));

  Package pkg = this.getClass().getPackage();
  String version = pkg.getImplementationVersion();
  String name = pkg.getImplementationTitle();

  artifactInfo.addMetric(asList(
          version != null ? version : "unknown",
          name != null ? name : "unknown"
  ), 1L);
  mfs.add(artifactInfo);

  return mfs;
}
 
Example #10
Source File: RateLimiterMetricsCollector.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    GaugeMetricFamily availablePermissionsFamily = new GaugeMetricFamily(
        names.getAvailablePermissionsMetricName(),
        "The number of available permissions",
        LabelNames.NAME
    );
    GaugeMetricFamily waitingThreadsFamily = new GaugeMetricFamily(
        names.getWaitingThreadsMetricName(),
        "The number of waiting threads",
        LabelNames.NAME
    );

    for (RateLimiter rateLimiter : rateLimiterRegistry.getAllRateLimiters()) {
        List<String> nameLabel = singletonList(rateLimiter.getName());
        availablePermissionsFamily
            .addMetric(nameLabel, rateLimiter.getMetrics().getAvailablePermissions());
        waitingThreadsFamily
            .addMetric(nameLabel, rateLimiter.getMetrics().getNumberOfWaitingThreads());
    }

    return asList(availablePermissionsFamily, waitingThreadsFamily);
}
 
Example #11
Source File: ThreadPoolBulkheadMetricsCollector.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    GaugeMetricFamily availableCallsFamily = new GaugeMetricFamily(
        names.getCurrentThreadPoolSizeName(),
        "The number of currently used bulkhead threads",
        LabelNames.NAME
    );
    GaugeMetricFamily maxAllowedCallsFamily = new GaugeMetricFamily(
        names.getAvailableQueueCapacityName(),
        "The number of available bulkhead queue slots",
        LabelNames.NAME
    );

    for (ThreadPoolBulkhead bulkhead : bulkheadRegistry.getAllBulkheads()) {
        List<String> labelValues = singletonList(bulkhead.getName());
        availableCallsFamily.addMetric(labelValues, bulkhead.getMetrics().getThreadPoolSize());
        maxAllowedCallsFamily
            .addMetric(labelValues, bulkhead.getMetrics().getRemainingQueueCapacity());
    }

    return asList(availableCallsFamily, maxAllowedCallsFamily);
}
 
Example #12
Source File: BulkheadMetricsCollector.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    GaugeMetricFamily availableCallsFamily = new GaugeMetricFamily(
        names.getAvailableConcurrentCallsMetricName(),
        "The number of available concurrent calls",
        LabelNames.NAME
    );
    GaugeMetricFamily maxAllowedCallsFamily = new GaugeMetricFamily(
        names.getMaxAllowedConcurrentCallsMetricName(),
        "The maximum number of allowed concurrent calls",
        LabelNames.NAME
    );

    for (Bulkhead bulkhead : bulkheadRegistry.getAllBulkheads()) {
        List<String> labelValues = singletonList(bulkhead.getName());
        availableCallsFamily
            .addMetric(labelValues, bulkhead.getMetrics().getAvailableConcurrentCalls());
        maxAllowedCallsFamily
            .addMetric(labelValues, bulkhead.getMetrics().getMaxAllowedConcurrentCalls());
    }

    return asList(availableCallsFamily, maxAllowedCallsFamily);
}
 
Example #13
Source File: BuildInfoExporter.java    From hadoop-hdfs-fsimage-exporter with Apache License 2.0 6 votes vote down vote up
/**
 * @param metricPrefix the metric name prefix
 * @param appName      the application name to report this metric for.
 */
public BuildInfoExporter(String metricPrefix, String appName) {
    super();
    this.appName = appName;

    metricFamily = new GaugeMetricFamily(metricPrefix + "app_info",
            "Application build info",
            Arrays.asList("appName", "appVersion", "buildTime", "buildScmVersion", "buildScmBranch"));
    metricFamily.addMetric(
            Arrays.asList(
                    getAppName(),
                    getAppVersion(),
                    getBuildTimeStamp(),
                    getBuildScmVersion(),
                    getBuildScmBranch()
            ), 1.0D);
}
 
Example #14
Source File: JVMResourceCollector.java    From feast with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
  List<MetricFamilySamples> samples = new ArrayList<>();

  samples.add(
      new GaugeMetricFamily(
          "feast_core_max_memory_bytes",
          "Max amount of memory the Java virtual machine will attempt to use",
          runtime.maxMemory()));
  samples.add(
      new GaugeMetricFamily(
          "feast_core_total_memory_bytes",
          "Total amount of memory in the Java virtual machine",
          runtime.totalMemory()));
  samples.add(
      new GaugeMetricFamily(
          "feast_core_free_memory_bytes",
          "Total amount of free memory in the Java virtual machine",
          runtime.freeMemory()));

  SummaryMetricFamily gcMetricFamily =
      new SummaryMetricFamily(
          "feast_core_gc_collection_seconds",
          "Time spent in a given JVM garbage collector in seconds",
          Collections.singletonList("gc"));
  for (final GarbageCollectorMXBean gc : garbageCollectors) {
    gcMetricFamily.addMetric(
        Collections.singletonList(gc.getName()),
        gc.getCollectionCount(),
        gc.getCollectionTime() / MILLISECONDS_PER_SECOND);
  }
  samples.add(gcMetricFamily);

  return samples;
}
 
Example #15
Source File: ConnectionCount.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<>();

    GaugeMetricFamily labeledGauge = new GaugeMetricFamily("maestro_connection_count",
            "Connection count", Arrays.asList("peer", "type"));

    logger.trace("Number of values to process: {}", records.values().size());

    for (StatsResponse stats : records.values()) {
        labeledGauge.addMetric(Arrays.asList(stats.getPeerInfo().peerName(), stats.getPeerInfo().peerHost()), stats.getChildCount());

    }

    mfs.add(labeledGauge);
    records.clear();
    return mfs;
}
 
Example #16
Source File: MessageCount.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
public List<Collector.MetricFamilySamples> collect() {
    List<Collector.MetricFamilySamples> mfs = new ArrayList<>();

    GaugeMetricFamily labeledGauge = new GaugeMetricFamily("maestro_message_count",
            "Message count", Arrays.asList("peer", "type"));

    logger.trace("Number of values to process: {}", records.values().size());

    for (StatsResponse stats : records.values()) {
        logger.trace("Adding record for {}/{}", stats.getPeerInfo().prettyName(), stats.getId());
        labeledGauge.addMetric(Arrays.asList(stats.getPeerInfo().peerName(), stats.getPeerInfo().peerName()), stats.getCount());
    }

    mfs.add(labeledGauge);
    records.clear();
    return mfs;
}
 
Example #17
Source File: PingInfo.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<>();

    GaugeMetricFamily labeledGauge = new GaugeMetricFamily("maestro_ping",
            "Ping", Arrays.asList("peer", "type"));

    logger.trace("Number of values to process: {}", records.values().size());
    for (PingResponse pingResponse : records.values()) {

        logger.trace("Adding record for {}/{}", pingResponse.getPeerInfo().prettyName(), pingResponse.getId());
        labeledGauge.addMetric(Arrays.asList(pingResponse.getPeerInfo().peerName(), pingResponse.getPeerInfo().peerHost()),
                pingResponse.getElapsed());
    }

    mfs.add(labeledGauge);
    records.clear();
    return mfs;
}
 
Example #18
Source File: RateCount.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
public List<Collector.MetricFamilySamples> collect() {
    List<Collector.MetricFamilySamples> mfs = new ArrayList<>();

    GaugeMetricFamily labeledGauge = new GaugeMetricFamily("maestro_rate",
            "Rate", Arrays.asList("peer", "type"));

    logger.trace("Number of values to process: {}", records.values().size());
    for (StatsResponse stats : records.values()) {

        logger.trace("Adding record for {}/{}", stats.getPeerInfo().prettyName(), stats.getId());
        labeledGauge.addMetric(Arrays.asList(stats.getPeerInfo().peerName(), stats.getPeerInfo().peerHost()), stats.getRate());
    }

    mfs.add(labeledGauge);
    records.clear();
    return mfs;
}
 
Example #19
Source File: BotCollector.java    From FlareBot with MIT License 6 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {

    List<MetricFamilySamples> familySamples = new ArrayList<>();

    GaugeMetricFamily jdaEntities = new GaugeMetricFamily("flarebot_jda_entities_total", "Amount of JDA entities",
            Collections.singletonList("entity"));
    familySamples.add(jdaEntities);

    GaugeMetricFamily playerInfo = new GaugeMetricFamily("flarebot_player_info",
            "Amount of players, playing players and songs queued", Collections.singletonList("amount"));
    familySamples.add(playerInfo);

    if (botMetrics.count()) {
        jdaEntities.addMetric(Collections.singletonList("guilds"), botMetrics.getGuildCount());
        jdaEntities.addMetric(Collections.singletonList("users"), botMetrics.getUserCount());
        jdaEntities.addMetric(Collections.singletonList("text_channels"), botMetrics.getTextChannelCount());
        jdaEntities.addMetric(Collections.singletonList("voice_channels"), botMetrics.getVoiceChannelCount());

        playerInfo.addMetric(Collections.singletonList("connected_voice_channels"), Getters.getConnectedVoiceChannels());
        playerInfo.addMetric(Collections.singletonList("active_voice_channels"), Getters.getActiveVoiceChannels());
        playerInfo.addMetric(Collections.singletonList("songs_queued"), Getters.getSongsQueued());
    }

    return familySamples;
}
 
Example #20
Source File: ConnectionCounterCollector.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private static GaugeMetricFamily countCurrentProxyBackend() {
    GaugeMetricFamily gaugeMetricFamily = new GaugeMetricFamily("native_mysql_connection", "mysql naivte backend connection",
            ImmutableList.of("type", "reactor", "datasource"));
    for (MycatReactorThread i : Optional.ofNullable(MycatCore.INSTANCE.getReactorManager())
            .map(ReactorThreadManager::getList)
            .orElse(Collections.emptyList())) {
        MySQLSessionManager mySQLSessionManager = i.getMySQLSessionManager();
        List<MySQLClientSession> allSessions = mySQLSessionManager.getAllSessions();
        Map<String, Long> totalMap = allSessions.stream().collect(Collectors.groupingBy(j -> j.getDatasourceName(), Collectors.counting()));
        totalMap.forEach((k, v) -> {
            gaugeMetricFamily.addMetric(ImmutableList.of(Type.TOTAL.getName(),i.getName(), k), v);
        });
        Map<String, Long>   idleMap = mySQLSessionManager.getAllSessions().stream().filter(j -> j.isIdle()).collect(Collectors.groupingBy(j -> j.getDatasourceName(), Collectors.counting()));
        idleMap.forEach((k, v) -> {
            gaugeMetricFamily.addMetric(ImmutableList.of(Type.IDLE.getName(),i.getName(), k), v);
        });
        Map<String, Long>   useMap = allSessions.stream().filter(j -> !j.isIdle()).collect(Collectors.groupingBy(j -> j.getDatasourceName(), Collectors.counting()));
        useMap.forEach((k, v) -> {
            gaugeMetricFamily.addMetric(ImmutableList.of(Type.USE.getName(),i.getName(), k), v);
        });
    }
    return gaugeMetricFamily;
}
 
Example #21
Source File: ParserCollector.java    From canal with Apache License 2.0 5 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<>();
    CounterMetricFamily bytesCounter = new CounterMetricFamily(RECEIVED_BINLOG,
            RECEIVED_BINLOG_HELP, parserLabels);
    GaugeMetricFamily modeGauge = new GaugeMetricFamily(PARSER_MODE,
            MODE_HELP, modeLabels);
    CounterMetricFamily blockingCounter = new CounterMetricFamily(PUBLISH_BLOCKING,
            PUBLISH_BLOCKING_HELP, parserLabels);
    for (ParserMetricsHolder emh : instances.values()) {
        if (emh instanceof GroupParserMetricsHolder) {
            GroupParserMetricsHolder group = (GroupParserMetricsHolder) emh;
            for (ParserMetricsHolder semh :  group.holders) {
                singleCollect(bytesCounter, blockingCounter, modeGauge, semh);
            }
        }
        else {
            singleCollect(bytesCounter, blockingCounter, modeGauge, emh);
        }
    }
    mfs.add(bytesCounter);
    mfs.add(modeGauge);
    if (!blockingCounter.samples.isEmpty()) {
        mfs.add(blockingCounter);
    }
    return mfs;
}
 
Example #22
Source File: MemoryPoolsExports.java    From client_java with Apache License 2.0 5 votes vote down vote up
void addMemoryPoolMetrics(List<MetricFamilySamples> sampleFamilies) {
  GaugeMetricFamily used = new GaugeMetricFamily(
      "jvm_memory_pool_bytes_used",
      "Used bytes of a given JVM memory pool.",
      Collections.singletonList("pool"));
  sampleFamilies.add(used);
  GaugeMetricFamily committed = new GaugeMetricFamily(
      "jvm_memory_pool_bytes_committed",
      "Committed bytes of a given JVM memory pool.",
      Collections.singletonList("pool"));
  sampleFamilies.add(committed);
  GaugeMetricFamily max = new GaugeMetricFamily(
      "jvm_memory_pool_bytes_max",
      "Max bytes of a given JVM memory pool.",
      Collections.singletonList("pool"));
  sampleFamilies.add(max);
  GaugeMetricFamily init = new GaugeMetricFamily(
      "jvm_memory_pool_bytes_init",
      "Initial bytes of a given JVM memory pool.",
      Collections.singletonList("pool"));
  sampleFamilies.add(init);
  for (final MemoryPoolMXBean pool : poolBeans) {
    MemoryUsage poolUsage = pool.getUsage();
    used.addMetric(
        Collections.singletonList(pool.getName()),
        poolUsage.getUsed());
    committed.addMetric(
        Collections.singletonList(pool.getName()),
        poolUsage.getCommitted());
    max.addMetric(
        Collections.singletonList(pool.getName()),
        poolUsage.getMax());
    init.addMetric(
        Collections.singletonList(pool.getName()),
        poolUsage.getInit());
  }
}
 
Example #23
Source File: MemoryPoolsExports.java    From client_java with Apache License 2.0 5 votes vote down vote up
void addMemoryAreaMetrics(List<MetricFamilySamples> sampleFamilies) {
  MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
  MemoryUsage nonHeapUsage = memoryBean.getNonHeapMemoryUsage();

  GaugeMetricFamily used = new GaugeMetricFamily(
      "jvm_memory_bytes_used",
      "Used bytes of a given JVM memory area.",
      Collections.singletonList("area"));
  used.addMetric(Collections.singletonList("heap"), heapUsage.getUsed());
  used.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getUsed());
  sampleFamilies.add(used);

  GaugeMetricFamily committed = new GaugeMetricFamily(
      "jvm_memory_bytes_committed",
      "Committed (bytes) of a given JVM memory area.",
      Collections.singletonList("area"));
  committed.addMetric(Collections.singletonList("heap"), heapUsage.getCommitted());
  committed.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getCommitted());
  sampleFamilies.add(committed);

  GaugeMetricFamily max = new GaugeMetricFamily(
      "jvm_memory_bytes_max",
      "Max (bytes) of a given JVM memory area.",
      Collections.singletonList("area"));
  max.addMetric(Collections.singletonList("heap"), heapUsage.getMax());
  max.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getMax());
  sampleFamilies.add(max);

  GaugeMetricFamily init = new GaugeMetricFamily(
      "jvm_memory_bytes_init",
      "Initial bytes of a given JVM memory area.",
      Collections.singletonList("area"));
  init.addMetric(Collections.singletonList("heap"), heapUsage.getInit());
  init.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getInit());
  sampleFamilies.add(init);
}
 
Example #24
Source File: BufferPoolsExports.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
    GaugeMetricFamily used = new GaugeMetricFamily(
            "jvm_buffer_pool_used_bytes",
            "Used bytes of a given JVM buffer pool.",
            Collections.singletonList("pool"));
    mfs.add(used);
    GaugeMetricFamily capacity = new GaugeMetricFamily(
            "jvm_buffer_pool_capacity_bytes",
            "Bytes capacity of a given JVM buffer pool.",
            Collections.singletonList("pool"));
    mfs.add(capacity);
    GaugeMetricFamily buffers = new GaugeMetricFamily(
            "jvm_buffer_pool_used_buffers",
            "Used buffers of a given JVM buffer pool.",
            Collections.singletonList("pool"));
    mfs.add(buffers);
    for (final Object pool : bufferPoolMXBeans) {
        used.addMetric(
                Collections.singletonList(getName(pool)),
                callLongMethond(getMemoryUsed,pool));
        capacity.addMetric(
                Collections.singletonList(getName(pool)),
                callLongMethond(getTotalCapacity,pool));
        buffers.addMetric(
                Collections.singletonList(getName(pool)),
                callLongMethond(getCount,pool));
    }
    return mfs;
}
 
Example #25
Source File: ClassLoadingExports.java    From client_java with Apache License 2.0 5 votes vote down vote up
void addClassLoadingMetrics(List<MetricFamilySamples> sampleFamilies) {
  sampleFamilies.add(new GaugeMetricFamily(
        "jvm_classes_loaded",
        "The number of classes that are currently loaded in the JVM",
        clBean.getLoadedClassCount()));
  sampleFamilies.add(new CounterMetricFamily(
        "jvm_classes_loaded_total",
        "The total number of classes that have been loaded since the JVM has started execution",
        clBean.getTotalLoadedClassCount()));
  sampleFamilies.add(new CounterMetricFamily(
        "jvm_classes_unloaded_total",
        "The total number of classes that have been unloaded since the JVM has started execution",
        clBean.getUnloadedClassCount()));
}
 
Example #26
Source File: ParserCollector.java    From canal with Apache License 2.0 5 votes vote down vote up
private void singleCollect(CounterMetricFamily bytesCounter, CounterMetricFamily blockingCounter, GaugeMetricFamily modeGauge, ParserMetricsHolder holder) {
    if (holder.isParallel) {
        blockingCounter.addMetric(holder.parserLabelValues, (holder.eventsPublishBlockingTime.doubleValue() / NANO_PER_MILLI));
    }
    modeGauge.addMetric(holder.modeLabelValues, 1);
    bytesCounter.addMetric(holder.parserLabelValues, holder.receivedBinlogBytes.doubleValue());
}
 
Example #27
Source File: SqlStatCollector.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    try {
        GaugeMetricFamily gaugeMetricFamily = new GaugeMetricFamily("sql_stat",
                "sql_stat",
                ImmutableList.of("statement", "time_type"));
        Map<String, List<SqlRecord>> recordList = SqlRecorderRuntime.INSTANCE.getRecordList();
        for (Map.Entry<String, List<SqlRecord>> entry : recordList.entrySet()) {
            String sql = normalie(entry.getKey());
            for (SqlRecord record : entry.getValue()) {
                if (record.getStatement() != null) {
                    double v = record.getEndTime() - record.getStartTime();
                    if (v > 0) {
                        gaugeMetricFamily.addMetric(ImmutableList.of(sql, "TOTAL_TIME"), v);
                        gaugeMetricFamily.addMetric(ImmutableList.of(sql, "COMPILE_TIME"), record.getCompileTime());
                        gaugeMetricFamily.addMetric(ImmutableList.of(sql, "RBO_TIME"), record.getCboTime());
                        gaugeMetricFamily.addMetric(ImmutableList.of(sql, "CBO_TIME"), record.getRboTime());
                        gaugeMetricFamily.addMetric(ImmutableList.of(sql, "CONNECTION_POOL_TIME"), record.getConnectionPoolTime());
                        gaugeMetricFamily.addMetric(ImmutableList.of(sql, "CONNECTION_QUERY_TIME"), record.getConnectionQueryTime());
                        gaugeMetricFamily.addMetric(ImmutableList.of(sql, "EXECUTION_TIME"), record.getExecutionTime());
                    }
                }
            }
        }
        return ImmutableList.of(gaugeMetricFamily);
    } catch (Throwable e) {
        LOGGER.error("", e);
        throw e;
    }
}
 
Example #28
Source File: BufferPoolCollector.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {
    try {
        GaugeMetricFamily gaugeMetricFamily = new GaugeMetricFamily("buffer_pool_counter",
                "buffer_pool",
                ImmutableList.of("name",  "chunkSize","capacity"));
        for (MycatReactorThread mycatReactorThread : Optional.ofNullable(MycatCore.INSTANCE.getReactorManager())
                .map(i -> i.getList()).orElse(Collections.emptyList())) {
            BufferPool bufPool = mycatReactorThread.getBufPool();

            if (bufPool != null) {
                String name = bufPool.getClass().getName();
                long capacity = bufPool.capacity();
                int chunkSize = bufPool.chunkSize();
                int trace = bufPool.trace();
                gaugeMetricFamily.addMetric(ImmutableList.of(String.valueOf(name),
                        String.valueOf(chunkSize),
                        String.valueOf(capacity)),
                        trace);
            }
        }

        return ImmutableList.of(gaugeMetricFamily);
    } catch (Throwable e) {
        LOGGER.error("", e);
        throw e;
    }
}
 
Example #29
Source File: QueuedThreadPoolStatisticsCollector.java    From client_java with Apache License 2.0 5 votes vote down vote up
private GaugeMetricFamily buildGauge(String metric, String help,
    Function<QueuedThreadPool, Integer> metricValueProvider) {
  final GaugeMetricFamily metricFamily = new GaugeMetricFamily(metric, help, LABEL_NAMES);
  queuedThreadPoolMap.forEach((key, value) -> metricFamily.addMetric(
      Collections.singletonList(key),
      metricValueProvider.apply(value)
  ));
  return metricFamily;
}
 
Example #30
Source File: CPULoadCollector.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public List<MetricFamilySamples> collect() {
        SystemInfo systemInfo = new SystemInfo();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
//        List<CentralProcessor.LogicalProcessor> logicalProcessors = processor.getLogicalProcessors();
        long[][] pTickList = processor.getProcessorCpuLoadTicks();

        GaugeMetricFamily gaugeMetricFamily = new GaugeMetricFamily("mycat_cpu_utility", "mycat_cpu_utility", ImmutableList.of("index"));

        long[][] tickList = processor.getProcessorCpuLoadTicks();
        for (int i = 0; i < pTickList.length; i++) {
            long[] prevTicks = pTickList[i];
            long[] ticks = tickList[i];

            long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
            long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
            long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
            long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
            long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
            long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
            long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
            long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
            long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

            double utility  = 1.0 - (idle * 1.0 / totalCpu);
            if (!Double.isInfinite(utility)) {
                utility = 0;
            }
            gaugeMetricFamily.addMetric(ImmutableList.of(String.valueOf(i)),utility);

        }




        return ImmutableList.of(gaugeMetricFamily);
    }