io.prometheus.client.Collector Java Examples

The following examples show how to use io.prometheus.client.Collector. 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: CustomMappingSampleBuilderTest.java    From client_java with Apache License 2.0 6 votes vote down vote up
@Test
public void test_WHEN_OneMatch_THEN_ShouldReturnConverted() {
    final Map<String, String> labels = new HashMap<String, String>();
    labels.put("service", "${0}");
    final MapperConfig mapperConfig = new MapperConfig(
            "app.okhttpclient.client.HttpClient.*.total",
            "app.okhttpclient.client.HttpClient.total",
            labels
    );
    final List<MapperConfig> mapperConfigs = Arrays.asList(
            new MapperConfig("client-nope.*.*.*"),
            mapperConfig,
            new MapperConfig("not.even.this.*.*.*")
    );
    final CustomMappingSampleBuilder converter = new CustomMappingSampleBuilder(mapperConfigs);
    final Collector.MetricFamilySamples.Sample expectedResult = new Collector.MetricFamilySamples.Sample(
            "app_okhttpclient_client_HttpClient_total", Collections.singletonList("service"), Collections.singletonList("greatService"), 1d);

    final Collector.MetricFamilySamples.Sample result = converter.createSample(
            "app.okhttpclient.client.HttpClient.greatService.total", "", Collections.<String>emptyList(), Collections.<String>emptyList(), 1d);

    assertEquals(expectedResult, result);
}
 
Example #2
Source File: MetricSamplesTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void addAll() {
  MetricSamples lhs = new MetricSamples(Maps.newHashMap(ImmutableMap.<String, Collector.MetricFamilySamples>builder()
      .put("same", samples("same", Collector.Type.GAUGE, sample("same", 1.0), sample("same", 2.0)))
      .put("diff1", samples("diff1", Collector.Type.GAUGE, sample("diff1", 1.0)))
      .build()));

  MetricSamples rhs = new MetricSamples(Maps.newHashMap(ImmutableMap.<String, Collector.MetricFamilySamples>builder()
      .put("same", samples("test1", Collector.Type.GAUGE, sample("test1", 3.0), sample("test1", 4.0)))
      .put("diff2", samples("diff2", Collector.Type.GAUGE, sample("diff2", 1.0)))
      .build()));

  lhs.addAll(rhs);

  List<Collector.MetricFamilySamples> output = lhs.asList();

  validateMetricSamples(output, "same", Arrays.asList(1.0, 2.0, 3.0, 4.0));
  validateMetricSamples(output, "diff1", Collections.singletonList(1.0));
  validateMetricSamples(output, "diff2", Collections.singletonList(1.0));
}
 
Example #3
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleWithTimestampAndEmptyLine() {
	String textToParse = "# Minimalistic line:\n" + 
			"\n"+
			"metric_without_labels 12.47 123456789012345600\n";
	
	Parser subject = new Parser(textToParse);
	HashMap<String, Collector.MetricFamilySamples> resultMap = subject.parse();
	Enumeration<Collector.MetricFamilySamples> result = Collections.enumeration(resultMap.values());

	// creating expected result
	LinkedList<Collector.MetricFamilySamples> expectedList = new LinkedList<>();

	List<Sample> samples = new LinkedList<>();
	Sample sample = new Sample("metric_without_labels", new LinkedList<String>(), new LinkedList<String>(), 12.47);
	samples.add(sample);
	
	Collector.MetricFamilySamples expectedMFS = new Collector.MetricFamilySamples("metric_without_labels", Type.UNTYPED, "", samples);
	expectedList.add(expectedMFS);
	
	Enumeration<Collector.MetricFamilySamples> expected = Collections.enumeration(expectedList);
	
	// compare
	compareEMFS(expected, result);
}
 
Example #4
Source File: RegistryHelper.java    From java-grpc-prometheus with Apache License 2.0 6 votes vote down vote up
public static int countSamples(
    String metricName, String sampleName, CollectorRegistry collectorRegistry) {
  Enumeration<Collector.MetricFamilySamples> samples = collectorRegistry.metricFamilySamples();
  while (samples.hasMoreElements()) {
    Collector.MetricFamilySamples sample = samples.nextElement();
    if (sample.name.equals(metricName)) {
      int result = 0;
      for (Collector.MetricFamilySamples.Sample s : sample.samples) {
        if (s.name.equals(sampleName)) {
          ++result;
        }
      }
      return result;
    }
  }
  throw new IllegalArgumentException("Could not find sample family with name: " + metricName);
}
 
Example #5
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testHelpEscaping() {
	String textToParse = "# Simple metric without labels:\n" + 
			"# TYPE metric_without_labels counter\n" + 
			"# HELP metric_without_labels this is my help text with \\\\ backslashes escaped \\\\ and escaped newline \\n\n" + 
			"metric_without_labels 12.47 123456789012345600\n";
	
	Parser subject = new Parser(textToParse);
	HashMap<String, Collector.MetricFamilySamples> resultMap = subject.parse();
	Enumeration<Collector.MetricFamilySamples> result = Collections.enumeration(resultMap.values());

	// creating expected result
	LinkedList<Collector.MetricFamilySamples> expectedList = new LinkedList<>();

	List<Sample> samples = new LinkedList<>();
	Sample sample = new Sample("metric_without_labels", new LinkedList<String>(), new LinkedList<String>(), 12.47);
	samples.add(sample);
	
	Collector.MetricFamilySamples expectedMFS = new Collector.MetricFamilySamples("metric_without_labels", Type.COUNTER, "this is my help text with \\ backslashes escaped \\ and escaped newline \n", samples);
	expectedList.add(expectedMFS);
	
	Enumeration<Collector.MetricFamilySamples> expected = Collections.enumeration(expectedList);
	
	// compare
	compareEMFS(expected, result);
}
 
Example #6
Source File: Parser.java    From promregator with Apache License 2.0 6 votes vote down vote up
private Type determineType(String metricName) {
	Collector.Type type = null;
	// first check if the metric is typed natively.
	type = this.mapTypes.get(metricName);
	if (type != null) {
		return type;
	}
	
	// try to get the baseMetricName
	String baseMetricName = determineBaseMetricName(metricName);
	type = this.mapTypes.get(baseMetricName);
	// check that this also really makes sense and is a type, which requires baseMetricNames
	if (type == Type.HISTOGRAM || type == Type.SUMMARY) {
		return type;
	}
	
	// we have no clue what this metric is all about
	return Collector.Type.UNTYPED;
}
 
Example #7
Source File: AbstractPrometheusReporter.java    From flink with Apache License 2.0 6 votes vote down vote up
private Collector createCollector(Metric metric, List<String> dimensionKeys, List<String> dimensionValues, String scopedMetricName, String helpString) {
	Collector collector;
	if (metric instanceof Gauge || metric instanceof Counter || metric instanceof Meter) {
		collector = io.prometheus.client.Gauge
			.build()
			.name(scopedMetricName)
			.help(helpString)
			.labelNames(toArray(dimensionKeys))
			.create();
	} else if (metric instanceof Histogram) {
		collector = new HistogramSummaryProxy((Histogram) metric, scopedMetricName, helpString, dimensionKeys, dimensionValues);
	} else {
		log.warn("Cannot create collector for unknown metric type: {}. This indicates that the metric type is not supported by this reporter.",
			metric.getClass().getName());
		collector = null;
	}
	return collector;
}
 
Example #8
Source File: TestAlibabaMetricsExports.java    From metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportGauge() {
    AlibabaMetricsExports exports = new AlibabaMetricsExports(clock);
    final double random = Math.random();
    Gauge<Double> gauge = new Gauge<Double>() {
        @Override
        public Double getValue() {
            return random;
        }

        @Override
        public long lastUpdateTime() {
            return 0;
        }
    };
    MetricManager.getIMetricManager().register("test",
            MetricName.build("prom.test.gauge"), gauge);

    List<Collector.MetricFamilySamples> samples = exports.collect();
    Assert.assertEquals(1, samples.size());
    Assert.assertEquals("prom_test_gauge", samples.get(0).name);
    Assert.assertEquals(random, samples.get(0).samples.get(0).value, 0.0001d);
}
 
Example #9
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGaugeWithTimestampAndEmptyLine() {
	String textToParse = "# Simple metric without labels:\n" + 
			"# TYPE metric_without_labels gauge\n" + 
			"\n"+
			"metric_without_labels 12.47 123456789012345600\n";
	
	Parser subject = new Parser(textToParse);
	HashMap<String, Collector.MetricFamilySamples> resultMap = subject.parse();
	Enumeration<Collector.MetricFamilySamples> result = Collections.enumeration(resultMap.values());

	// creating expected result
	LinkedList<Collector.MetricFamilySamples> expectedList = new LinkedList<>();

	List<Sample> samples = new LinkedList<>();
	Sample sample = new Sample("metric_without_labels", new LinkedList<String>(), new LinkedList<String>(), 12.47);
	samples.add(sample);
	
	Collector.MetricFamilySamples expectedMFS = new Collector.MetricFamilySamples("metric_without_labels", Type.GAUGE, "", samples);
	expectedList.add(expectedMFS);
	
	Enumeration<Collector.MetricFamilySamples> expected = Collections.enumeration(expectedList);
	
	// compare
	compareEMFS(expected, result);
}
 
Example #10
Source File: CustomMappingSampleBuilderTest.java    From client_java with Apache License 2.0 6 votes vote down vote up
@Test
public void test_WHEN_MetricNameSuffixRequested_THEN_ShouldReturnCorrectSample() {
    final Map<String, String> labels = new HashMap<String, String>();
    labels.put("service", "${0}");
    labels.put("status", "s_${1}");
    final MapperConfig mapperConfig = new MapperConfig(
            "app.okhttpclient.client.HttpClient.*.*",
            "app.okhttpclient.client.HttpClient.${0}",
            labels
    );
    final List<MapperConfig> mapperConfigs = Arrays.asList(
            new MapperConfig("client-nope.*.*.*"),
            mapperConfig,
            new MapperConfig("app.okhttpclient.client.HttpClient.*.total") // this matches as well
    );
    final CustomMappingSampleBuilder converter = new CustomMappingSampleBuilder(mapperConfigs);
    final Collector.MetricFamilySamples.Sample expectedResult = new Collector.MetricFamilySamples.Sample(
            "app_okhttpclient_client_HttpClient_greatService_suffix", Arrays.asList("service", "status"), Arrays.asList("greatService", "s_400"), 1d);

    final Collector.MetricFamilySamples.Sample result = converter.createSample(
            "app.okhttpclient.client.HttpClient.greatService.400", "_suffix", Collections.<String>emptyList(), Collections.<String>emptyList(), 1d);

    assertEquals(expectedResult, result);
}
 
Example #11
Source File: FsImageUpdateHandler.java    From hadoop-hdfs-fsimage-exporter with Apache License 2.0 6 votes vote down vote up
/**
 * Collects MFS.
 *
 * @param mfs the sampled metrics
 * @return true if error occurred
 */
public boolean collectFsImageSamples(List<Collector.MetricFamilySamples> mfs) {
    // Switch report
    synchronized (this) {
        final FsImageReporter.Report latestReport = getFsImageReport();
        if (latestReport != currentReport) {
            currentReport = latestReport;
        }
    }

    mfs.addAll(metricLoadDuration.collect());
    mfs.addAll(metricVisitDuration.collect());
    mfs.addAll(metricLoadSize.collect());

    return updateMetricsFromReport(mfs);
}
 
Example #12
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 #13
Source File: AbstractPrometheusReporter.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private Collector createCollector(Metric metric, List<String> dimensionKeys, List<String> dimensionValues, String scopedMetricName, String helpString) {
	Collector collector;
	if (metric instanceof Gauge || metric instanceof Counter || metric instanceof Meter) {
		collector = io.prometheus.client.Gauge
			.build()
			.name(scopedMetricName)
			.help(helpString)
			.labelNames(toArray(dimensionKeys))
			.create();
	} else if (metric instanceof Histogram) {
		collector = new HistogramSummaryProxy((Histogram) metric, scopedMetricName, helpString, dimensionKeys, dimensionValues);
	} else {
		log.warn("Cannot create collector for unknown metric type: {}. This indicates that the metric type is not supported by this reporter.",
			metric.getClass().getName());
		collector = null;
	}
	return collector;
}
 
Example #14
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleNaN() {
	String textToParse = "# Minimalistic line:\n" + 
			"\n"+
			"metric_without_labels NaN 123456789012345600\n";
	
	Parser subject = new Parser(textToParse);
	HashMap<String, Collector.MetricFamilySamples> resultMap = subject.parse();
	Enumeration<Collector.MetricFamilySamples> result = Collections.enumeration(resultMap.values());

	// compareEMFS does not properly work with NaN values
	// Thus, we have to check this explicitly here
	
	MetricFamilySamples mfs = result.nextElement();
	Assert.assertFalse(result.hasMoreElements());
	
	Assert.assertEquals("metric_without_labels", mfs.name);
	
	Assert.assertEquals(1, mfs.samples.size());
	Sample actualSample = mfs.samples.get(0);
	Assert.assertEquals("metric_without_labels", actualSample.name);
	Assert.assertTrue(Double.isNaN(actualSample.value));
}
 
Example #15
Source File: JmxMetricEvaluatorImpl.java    From prom-confluence-exporter with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public List<Collector.MetricFamilySamples> metrics() {
    indexStatistics();
    systemStatistics();
    requestStatistics();
    cacheStatistics();

    List<Collector.MetricFamilySamples> res = new ArrayList<>();
    // index
    res.addAll(indexStatFlushing.collect());
    res.addAll(indexStatLastDuration.collect());
    res.addAll(indexStatTaskQueueLength.collect());
    res.addAll(indexStatReIndexing.collect());
    // system
    res.addAll(systemStatDbLatency.collect());
    // requests
    res.addAll(requestAvgExecTimeForLastTenRequests.collect());
    res.addAll(requestCurrentNumberOfRequestsBeingServed.collect());
    res.addAll(requestErrorCount.collect());
    res.addAll(requestNumberInLastTenSeconds.collect());
    return res;
}
 
Example #16
Source File: CollectorElement.java    From jmeter-prometheus-plugin with Apache License 2.0 6 votes vote down vote up
protected void makeNewCollectors() {
	this.clearCollectors();

	CollectionProperty collectorDefs = this.getCollectorConfigs();
	PropertyIterator iter = collectorDefs.iterator();

	while (iter.hasNext()) {

		try {
			@SuppressWarnings("unchecked")
			C config = (C) iter.next().getObjectValue();
			Collector collector = registry.getOrCreateAndRegister(config);

			this.collectors.put(config, collector);
			log.debug("added " + config.getMetricName() + " to list of collectors");
		} catch (Exception e) {
			log.error("Didn't create new collector because of error, ", e);
		}

	}

}
 
Example #17
Source File: MonitoringClientInterceptorIntegrationTest.java    From java-grpc-prometheus with Apache License 2.0 6 votes vote down vote up
@Test
public void bidiStreamRpcMetrics() throws Throwable {
  StreamObserver<HelloProto.HelloRequest> requestStream =
      createClientStub(CHEAP_METRICS).sayHelloBidiStream(responseRecorder);
  requestStream.onNext(REQUEST);
  requestStream.onNext(REQUEST);
  requestStream.onCompleted();

  responseRecorder.awaitCompletion();

  assertThat(extractMetricValue("grpc_client_started_total")).isWithin(0).of(1);
  assertThat(extractMetricValue("grpc_client_msg_received_total")).isWithin(0).of(2);
  assertThat(extractMetricValue("grpc_client_msg_sent_total")).isWithin(0).of(2);

  Collector.MetricFamilySamples handled = findRecordedMetricOrThrow("grpc_client_completed");
  assertThat(handled.samples).hasSize(1);
  assertThat(handled.samples.get(0).labelValues).containsExactly(
      "BIDI_STREAMING",
      HelloServiceImpl.SERVICE_NAME,
      HelloServiceImpl.BIDI_STREAM_METHOD_NAME,
      "OK");
  assertThat(handled.samples.get(0).value).isWithin(0).of(1);
}
 
Example #18
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 #19
Source File: MonitoringClientInterceptorIntegrationTest.java    From java-grpc-prometheus with Apache License 2.0 6 votes vote down vote up
@Test
public void serverStreamRpcMetrics() throws Throwable {
  createClientStub(CHEAP_METRICS).sayHelloServerStream(REQUEST, responseRecorder);
  responseRecorder.awaitCompletion();

  assertThat(extractMetricValue("grpc_client_started_total")).isWithin(0).of(1);
  assertThat(extractMetricValue("grpc_client_msg_received_total")).isWithin(0).of(1);
  assertThat(findRecordedMetricOrThrow("grpc_client_msg_sent_total").samples).isEmpty();

  Collector.MetricFamilySamples handled = findRecordedMetricOrThrow("grpc_client_completed");
  assertThat(handled.samples).hasSize(1);
  assertThat(handled.samples.get(0).labelValues).containsExactly(
      "SERVER_STREAMING",
      HelloServiceImpl.SERVICE_NAME,
      HelloServiceImpl.SERVER_STREAM_METHOD_NAME,
      "OK");
  assertThat(handled.samples.get(0).value).isWithin(0).of(1);
}
 
Example #20
Source File: PromagentCollectorRegistry.java    From promagent with Apache License 2.0 5 votes vote down vote up
@Override
public void register(Collector metric) {
    super.register(metric);
    try {
        ManagementFactory.getPlatformMBeanServer().registerMBean(new Metric(metric), makeObjectName((SimpleCollector) metric));
    } catch (Exception e) {
        throw new RuntimeException("Failed to register Prometheus metric: " + e.getMessage(), e);
    }
}
 
Example #21
Source File: AbstractPrometheusReporter.java    From flink with Apache License 2.0 5 votes vote down vote up
private void addMetric(Metric metric, List<String> dimensionValues, Collector collector) {
	if (metric instanceof Gauge) {
		((io.prometheus.client.Gauge) collector).setChild(gaugeFrom((Gauge) metric), toArray(dimensionValues));
	} else if (metric instanceof Counter) {
		((io.prometheus.client.Gauge) collector).setChild(gaugeFrom((Counter) metric), toArray(dimensionValues));
	} else if (metric instanceof Meter) {
		((io.prometheus.client.Gauge) collector).setChild(gaugeFrom((Meter) metric), toArray(dimensionValues));
	} else if (metric instanceof Histogram) {
		((HistogramSummaryProxy) collector).addChild((Histogram) metric, dimensionValues);
	} else {
		log.warn("Cannot add unknown metric type: {}. This indicates that the metric type is not supported by this reporter.",
			metric.getClass().getName());
	}
}
 
Example #22
Source File: HibernateStatisticsCollector.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Collector> T register(CollectorRegistry registry) {
  if (sessionFactories.isEmpty()) {
    throw new IllegalStateException("You must register at least one SessionFactory.");
  }
  return super.register(registry);
}
 
Example #23
Source File: Parser.java    From promregator with Apache License 2.0 5 votes vote down vote up
private void parseTypeLine(String line) {
	Matcher m = PATTERN_PARSE_TYPE.matcher(line);
	if (!m.matches()) {
		log.warn("TYPE line could not be properly matched: "+line);
		return;
	}
	
	String metricName = Utils.unescapeToken(m.group(1));
	String typeString = m.group(2);
	
	Collector.Type type = null;
	if (typeString.equalsIgnoreCase("gauge")) {
		type = Collector.Type.GAUGE;
	} else if (typeString.equalsIgnoreCase("counter")) {
		type = Collector.Type.COUNTER;
	} else if (typeString.equalsIgnoreCase("summary")) {
		type = Collector.Type.SUMMARY;
	} else if (typeString.equalsIgnoreCase("histogram")) {
		type = Collector.Type.HISTOGRAM;
	} else if (typeString.equalsIgnoreCase("untyped")) {
		type = Collector.Type.UNTYPED;
	} else {
		log.warn("Unable to parse type from TYPE line: "+line);
		return;
	}
	
	this.mapTypes.put(metricName, type);
}
 
Example #24
Source File: PrometheusListenerTest.java    From jmeter-prometheus-plugin with Apache License 2.0 5 votes vote down vote up
protected void assertOnSummary(Collector collector, double expectedSum, double expectedCount,
		double expectedValue) {

	List<MetricFamilySamples> metrics = collector.collect();
	Assert.assertEquals(1, metrics.size());
	MetricFamilySamples family = metrics.get(0);
	Assert.assertEquals(5, family.samples.size()); // 3 quantiles + count + sum

	for (Sample sample : family.samples) {
		List<String> values = sample.labelValues;
		List<String> names = sample.labelNames;

		for (int i = 0; i < TestUtilities.TEST_LABELS.length; i++) {
			Assert.assertEquals(TestUtilities.TEST_LABELS[i], names.get(i));
			Assert.assertEquals(TestUtilities.EXPECTED_LABELS[i], values.get(i));
		}

		// _sum and _count don't have an 'le' label
		if (sample.name.endsWith("count")) {
			Assert.assertEquals(values.size(), TestUtilities.EXPECTED_LABELS.length);
			Assert.assertEquals(names.size(), TestUtilities.TEST_LABELS.length);

			Assert.assertEquals(expectedCount, sample.value, 0.1);

		} else if (sample.name.endsWith("sum")) {
			Assert.assertEquals(expectedSum, sample.value, 0.1);
		} else {
			Assert.assertEquals(values.size(), TestUtilities.EXPECTED_LABELS.length + 1);
			Assert.assertEquals(values.size(), TestUtilities.EXPECTED_LABELS.length + 1);

			Assert.assertEquals(expectedValue, sample.value, 0.1);
		}
	}

}
 
Example #25
Source File: Parser.java    From promregator with Apache License 2.0 5 votes vote down vote up
public HashMap<String, Collector.MetricFamilySamples> parse() {
	this.reset();
	
	StringTokenizer lines = new StringTokenizer(this.textFormat004data, "\n");
	
	while(lines.hasMoreTokens()) {
		String line = lines.nextToken();
		
		// warning! Order of IF tests matter!
		if (this.isEmptyLine(line)) {
			continue;
		} else if (this.isHelpLine(line)) {
			this.parseHelpLine(line);
			continue;
		} else if (this.isTypeLine(line)) {
			this.parseTypeLine(line);
			continue;
		} else if (this.isCommentLine(line)) {
			continue;
		}
		
		// we need to assume that this is a metric line
		this.parseMetric(line);
	}
	
	return this.mapMFS;
}
 
Example #26
Source File: AbstractMetricFamilySamplesEnricher.java    From promregator with Apache License 2.0 5 votes vote down vote up
public HashMap<String, Collector.MetricFamilySamples> determineEnumerationOfMetricFamilySamples(HashMap<String, Collector.MetricFamilySamples> emfs) {
	
	if (emfs == null) {
		return null;
	}
	
	HashMap<String, Collector.MetricFamilySamples> newMap = new HashMap<>();
	
	for (Entry<String, MetricFamilySamples> entry : emfs.entrySet()) {
		MetricFamilySamples mfs = entry.getValue();
		
		List<Collector.MetricFamilySamples.Sample> newSamples = new LinkedList<>();
		for (Collector.MetricFamilySamples.Sample sample : mfs.samples) {
			Collector.MetricFamilySamples.Sample newSample = new Collector.MetricFamilySamples.Sample(
					sample.name,
					this.getEnrichedLabelNames(sample.labelNames),
					this.getEnrichedLabelValues(sample.labelValues),
					sample.value);
			newSamples.add(newSample);
		}
		
		Collector.MetricFamilySamples newEntry = new Collector.MetricFamilySamples(
				mfs.name,
				mfs.type, 
				mfs.help,
				newSamples
				);
		newMap.put(entry.getKey(), newEntry);
	}
	
	return newMap;
}
 
Example #27
Source File: GenericMetricFamilySamplesPrefixRewriter.java    From promregator with Apache License 2.0 5 votes vote down vote up
public HashMap<String, Collector.MetricFamilySamples> determineEnumerationOfMetricFamilySamples(HashMap<String, Collector.MetricFamilySamples> emfs) {
	
	if (emfs == null) {
		return null;
	}
	
	HashMap<String, Collector.MetricFamilySamples> newMap = new HashMap<>();
	
	for (Entry<String, MetricFamilySamples> entry : emfs.entrySet()) {
		MetricFamilySamples mfs = entry.getValue();
		
		List<Collector.MetricFamilySamples.Sample> newSamples = new LinkedList<>();
		for (Collector.MetricFamilySamples.Sample sample : mfs.samples) {
			Collector.MetricFamilySamples.Sample newSample = new Collector.MetricFamilySamples.Sample(
					this.ensureWithPrefix(sample.name),
					sample.labelNames,
					sample.labelValues,
					sample.value);
			newSamples.add(newSample);
		}
		
		Collector.MetricFamilySamples newEntry = new Collector.MetricFamilySamples(
				this.ensureWithPrefix(mfs.name),
				mfs.type, 
				mfs.help,
				newSamples
				);
		newMap.put(this.ensureWithPrefix(entry.getKey()), newEntry);
	}
	
	return newMap;
}
 
Example #28
Source File: TextFormat.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
public void writeSample(@Nullable final Map<String, String> labels, double value)
{
    sb.append(currentSection);
    if (labels != null && !labels.isEmpty()) {
        sb.append('{');
        sb.append(formatLabels(labels));
        sb.append("}");
    }
    sb.append(' ');
    sb.append(Collector.doubleToGoString(value));
    sb.append("\n");
}
 
Example #29
Source File: RocksDbStats.java    From teku with Apache License 2.0 5 votes vote down vote up
private Collector histogramToCollector(
    final MetricCategory metricCategory, final Statistics stats, final HistogramType histogram) {
  return new Collector() {
    final String metricName =
        metricCategory.getApplicationPrefix().orElse("")
            + metricCategory.getName()
            + "_"
            + histogram.name().toLowerCase();

    @Override
    public List<MetricFamilySamples> collect() {
      return ifOpen(
          () -> {
            final HistogramData data = stats.getHistogramData(histogram);
            return Collections.singletonList(
                new MetricFamilySamples(
                    metricName,
                    Type.SUMMARY,
                    "RocksDB histogram for " + metricName,
                    Arrays.asList(
                        new MetricFamilySamples.Sample(
                            metricName, LABELS, LABEL_50, data.getMedian()),
                        new MetricFamilySamples.Sample(
                            metricName, LABELS, LABEL_95, data.getPercentile95()),
                        new MetricFamilySamples.Sample(
                            metricName, LABELS, LABEL_99, data.getPercentile99()))));
          },
          Collections.emptyList());
    }
  };
}
 
Example #30
Source File: FsImageCollectorTest.java    From hadoop-hdfs-fsimage-exporter with Apache License 2.0 5 votes vote down vote up
@Test
public void testCollect() {
    Config config = new Config();
    config.setFsImagePath("src/test/resources");
    FsImageCollector fsImageCollector = new FsImageCollector(config);
    final List<Collector.MetricFamilySamples> metricFamilySamples = fsImageCollector.collect();

    assertThat(getMetricFamilySamples(metricFamilySamples, "fsimage_scrape_requests_total"))
            .hasTypeOfCounter()
            .hasSampleValue(1.0);
    assertThat(getMetricFamilySamples(metricFamilySamples, "fsimage_scrape_requests_total")).hasTypeOfCounter()
            .hasSampleValue(1);
    assertThat(getMetricFamilySamples(metricFamilySamples, "fsimage_compute_stats_duration_seconds"))
            .hasTypeOfSummary()
            .hasSampleCountValue(1)
            .hasSampleSumValue(da -> da.isGreaterThan(0).isLessThan(1));
    assertThat(getMetricFamilySamples(metricFamilySamples, "fsimage_scrape_duration_seconds")).hasTypeOfGauge()
            .hasSampleValue(da -> da.isGreaterThan(0).isLessThan(1));
    assertThat(getMetricFamilySamples(metricFamilySamples, "fsimage_load_file_size_bytes")).hasTypeOfGauge()
            .hasSampleValue(2420);
    assertThat(getMetricFamilySamples(metricFamilySamples, "fsimage_scrape_errors_total")).hasTypeOfCounter()
            .hasSampleValue(0.0);
    assertThat(getMetricFamilySamples(metricFamilySamples, "fsimage_load_duration_seconds"))
            .hasTypeOfSummary()
            .hasSampleSumValue(da -> da.isGreaterThan(0).isLessThan(1))
            .hasSampleCountValue(1.0);
}