io.prometheus.client.Collector.MetricFamilySamples.Sample Java Examples

The following examples show how to use io.prometheus.client.Collector.MetricFamilySamples.Sample. 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: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleWithEFormat() {
	String textToParse = "# Minimalistic line:\n" + 
			"\n"+
			"metric_without_labels 1.7560473e+07\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>(), 1.7560473e+07);
	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 #2
Source File: MetricLine.java    From promregator with Apache License 2.0 6 votes vote down vote up
public Sample parse() throws ParseException {
	this.rest = line;

	final String metricName = this.parseMetricName();
	this.skipSpacesIfThereAre();
	
	// check if the metric has an optional block of labels
	final Labels labels = this.parseLabels();
	
	final double value = this.parseValue();
	/*
	 * The timestamp is optional.
	 * Note that timestamps for metrics are currently not supported by the java Simpleclient!
	 * Yet it is defined the official protocol specification. 
	 */
	final double timestamp = this.parseTimestamp();
	
	final List<String> labelNames = labels == null ? new LinkedList<>() : labels.getNames();
	final List<String> labelValues = labels == null ? new LinkedList<>() : labels.getValues();
	
	return new Sample(metricName, labelNames, labelValues, value);
}
 
Example #3
Source File: GenericMetricFamilySamplesPrefixRewriterTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrefixesProperly() {
	GenericMetricFamilySamplesPrefixRewriter subject = new GenericMetricFamilySamplesPrefixRewriter("prefix");
	
	List<Sample> samples = new LinkedList<>();
	Sample s = new Sample("dummyname", Arrays.asList(new String[] { "labelName" }), Arrays.asList(new String[] {"labelValue"}), 1.0);
	samples.add(s);
	
	MetricFamilySamples mfs = new MetricFamilySamples("dummyname", Type.GAUGE, "dummyHelp", samples);
	
	HashMap<String, MetricFamilySamples> map = new HashMap<>();
	map.put("metricName", mfs);

	HashMap<String,MetricFamilySamples> result = subject.determineEnumerationOfMetricFamilySamples(map);
	
	MetricFamilySamples mfsResult = result.get("prefix_metricName");
	Assert.assertNotNull(mfsResult);
	Assert.assertEquals("prefix_dummyname", mfsResult.name);
	
	Assert.assertEquals(1, mfsResult.samples.size());
	Sample sampleResult = mfsResult.samples.get(0);
	Assert.assertEquals("prefix_dummyname", sampleResult.name);
}
 
Example #4
Source File: GenericMetricFamilySamplesPrefixRewriterTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotPrefixIfNotNeeded() {
	GenericMetricFamilySamplesPrefixRewriter subject = new GenericMetricFamilySamplesPrefixRewriter("prefix");
	
	List<Sample> samples = new LinkedList<>();
	Sample s = new Sample("prefix_dummyname", Arrays.asList(new String[] { "labelName" }), Arrays.asList(new String[] {"labelValue"}), 1.0);
	samples.add(s);
	
	MetricFamilySamples mfs = new MetricFamilySamples("prefix_dummyname", Type.GAUGE, "dummyHelp", samples);
	
	HashMap<String, MetricFamilySamples> map = new HashMap<>();
	map.put("prefix_metricName", mfs);

	HashMap<String,MetricFamilySamples> result = subject.determineEnumerationOfMetricFamilySamples(map);
	
	MetricFamilySamples mfsResult = result.get("prefix_metricName");
	Assert.assertNotNull(mfsResult);
	Assert.assertEquals("prefix_dummyname", mfsResult.name);
	
	Assert.assertEquals(1, mfsResult.samples.size());
	Sample sampleResult = mfsResult.samples.get(0);
	Assert.assertEquals("prefix_dummyname", sampleResult.name);
}
 
Example #5
Source File: Parser.java    From promregator with Apache License 2.0 6 votes vote down vote up
private void storeComplexType(Sample sample, final String metricName, Collector.Type type) {
	String baseMetricName = determineBaseMetricName(metricName);

	// is this already in our Map?
	Collector.MetricFamilySamples mfs = this.mapMFS.get(baseMetricName);
	if (mfs == null) {
		// no, we have to create a new one
		
		String docString = this.mapHelps.get(baseMetricName);
		/*
		 * mfs.help must not be empty - see also  https://github.com/promregator/promregator/issues/73
		 */
		if (docString == null) {
			docString = "";
		}
		
		mfs = new Collector.MetricFamilySamples(baseMetricName, type, docString, new LinkedList<>());
		this.mapMFS.put(baseMetricName, mfs);
	}
	
	mfs.samples.add(sample);
}
 
Example #6
Source File: PrometheusExportUtils.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
static MetricFamilySamples createDescribableMetricFamilySamples(
    MetricDescriptor metricDescriptor, String namespace) {
  String name = getNamespacedName(metricDescriptor.getName(), namespace);
  Type type = getType(metricDescriptor.getType());
  List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys());

  if (containsDisallowedLeLabelForHistogram(labelNames, type)) {
    throw new IllegalStateException(
        "Prometheus Histogram cannot have a label named 'le', "
            + "because it is a reserved label for bucket boundaries. "
            + "Please remove this key from your view.");
  }

  if (containsDisallowedQuantileLabelForSummary(labelNames, type)) {
    throw new IllegalStateException(
        "Prometheus Summary cannot have a label named 'quantile', "
            + "because it is a reserved label. Please remove this key from your view.");
  }

  return new MetricFamilySamples(
      name, type, metricDescriptor.getDescription(), Collections.<Sample>emptyList());
}
 
Example #7
Source File: PrometheusExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createDescribableMetricFamilySamples() {
  assertThat(
          PrometheusExportUtils.createDescribableMetricFamilySamples(
              CUMULATIVE_METRIC_DESCRIPTOR, ""))
      .isEqualTo(
          new MetricFamilySamples(
              METRIC_NAME, Type.COUNTER, METRIC_DESCRIPTION, Collections.<Sample>emptyList()));
  assertThat(
          PrometheusExportUtils.createDescribableMetricFamilySamples(
              SUMMARY_METRIC_DESCRIPTOR, ""))
      .isEqualTo(
          new MetricFamilySamples(
              METRIC_NAME2, Type.SUMMARY, METRIC_DESCRIPTION, Collections.<Sample>emptyList()));
  assertThat(
          PrometheusExportUtils.createDescribableMetricFamilySamples(
              HISTOGRAM_METRIC_DESCRIPTOR, ""))
      .isEqualTo(
          new MetricFamilySamples(
              METRIC_NAME3, Type.HISTOGRAM, METRIC_DESCRIPTION, Collections.<Sample>emptyList()));
}
 
Example #8
Source File: PrometheusExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createDescribableMetricFamilySamples_WithNamespace() {
  String namespace1 = "myorg";
  assertThat(
          PrometheusExportUtils.createDescribableMetricFamilySamples(
              CUMULATIVE_METRIC_DESCRIPTOR, namespace1))
      .isEqualTo(
          new MetricFamilySamples(
              namespace1 + '_' + METRIC_NAME,
              Type.COUNTER,
              METRIC_DESCRIPTION,
              Collections.<Sample>emptyList()));

  String namespace2 = "opencensus/";
  assertThat(
          PrometheusExportUtils.createDescribableMetricFamilySamples(
              CUMULATIVE_METRIC_DESCRIPTOR, namespace2))
      .isEqualTo(
          new MetricFamilySamples(
              "opencensus_" + METRIC_NAME,
              Type.COUNTER,
              METRIC_DESCRIPTION,
              Collections.<Sample>emptyList()));
}
 
Example #9
Source File: MetricAdapter.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
private static void addSummarySamples(
    SummaryPoint summaryPoint,
    String name,
    List<String> labelNames,
    List<String> labelValues,
    List<Sample> samples) {
  samples.add(
      new Sample(name + SAMPLE_SUFFIX_COUNT, labelNames, labelValues, summaryPoint.getCount()));
  samples.add(
      new Sample(name + SAMPLE_SUFFIX_SUM, labelNames, labelValues, summaryPoint.getSum()));
  List<ValueAtPercentile> valueAtPercentiles = summaryPoint.getPercentileValues();
  List<String> labelNamesWithQuantile = new ArrayList<>(labelNames.size());
  labelNamesWithQuantile.addAll(labelNames);
  labelNamesWithQuantile.add(LABEL_NAME_QUANTILE);
  for (ValueAtPercentile valueAtPercentile : valueAtPercentiles) {
    List<String> labelValuesWithQuantile = new ArrayList<>(labelValues.size());
    labelValuesWithQuantile.addAll(labelValues);
    labelValuesWithQuantile.add(doubleToGoString(valueAtPercentile.getPercentile()));
    samples.add(
        new Sample(
            name, labelNamesWithQuantile, labelValuesWithQuantile, valueAtPercentile.getValue()));
  }
}
 
Example #10
Source File: PrometheusTextFormatUtil.java    From pulsar with Apache License 2.0 6 votes vote down vote up
static void writeMetricsCollectedByPrometheusClient(Writer w, CollectorRegistry registry) throws IOException {
    Enumeration<MetricFamilySamples> metricFamilySamples = registry.metricFamilySamples();
    while (metricFamilySamples.hasMoreElements()) {
        MetricFamilySamples metricFamily = metricFamilySamples.nextElement();

        for (int i = 0; i < metricFamily.samples.size(); i++) {
            Sample sample = metricFamily.samples.get(i);
            w.write(sample.name);
            w.write('{');
            for (int j = 0; j < sample.labelNames.size(); j++) {
                if (j != 0) {
                    w.write(", ");
                }
                w.write(sample.labelNames.get(j));
                w.write("=\"");
                w.write(sample.labelValues.get(j));
                w.write('"');
            }

            w.write("} ");
            w.write(Collector.doubleToGoString(sample.value));
            w.write('\n');
        }
    }
}
 
Example #11
Source File: PrometheusMetricsSystem.java    From besu with Apache License 2.0 6 votes vote down vote up
private Observation convertSummarySampleNamesToLabels(
    final MetricCategory category, final Sample sample, final MetricFamilySamples familySamples) {
  final List<String> labelValues = new ArrayList<>(sample.labelValues);
  if (sample.name.endsWith("_sum")) {
    labelValues.add("sum");
  } else if (sample.name.endsWith("_count")) {
    labelValues.add("count");
  } else {
    labelValues.add(labelValues.size() - 1, "quantile");
  }
  return new Observation(
      category,
      convertFromPrometheusName(category, familySamples.name),
      sample.value,
      labelValues);
}
 
Example #12
Source File: DropwizardMeterRegistriesTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void filteredGaugesDoNotAffectOthers() {
    final CompositeMeterRegistry micrometer = new CompositeMeterRegistry();
    final PrometheusMeterRegistry prometheus = PrometheusMeterRegistries.newRegistry();
    final DropwizardMeterRegistry dropwizard = DropwizardMeterRegistries.newRegistry();
    micrometer.add(prometheus).add(dropwizard);
    final DistributionSummary summary = DistributionSummary.builder("summary")
                                                           .publishPercentiles(0.5, 0.99)
                                                           .register(micrometer);
    summary.record(42);

    // Make sure Dropwizard registry does not have unwanted gauges.
    assertThat(dropwizard.getDropwizardRegistry().getMetrics()).containsOnlyKeys("summary");

    // Make sure Prometheus registry collects all samples.
    final MetricFamilySamples prometheusSamples = findPrometheusSample(prometheus, "summary");
    assertThat(prometheusSamples.samples).containsExactly(
            new Sample("summary", ImmutableList.of("quantile"), ImmutableList.of("0.5"), 42),
            new Sample("summary", ImmutableList.of("quantile"), ImmutableList.of("0.99"), 42),
            new Sample("summary_count", ImmutableList.of(), ImmutableList.of(), 1),
            new Sample("summary_sum", ImmutableList.of(), ImmutableList.of(), 42));
}
 
Example #13
Source File: PrometheusExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createMetricFamilySamples_WithNamespace() {
  String namespace = "opencensus_";
  assertThat(PrometheusExportUtils.createMetricFamilySamples(LONG_METRIC, namespace))
      .isEqualTo(
          new MetricFamilySamples(
              namespace + METRIC_NAME,
              Type.COUNTER,
              METRIC_DESCRIPTION,
              Collections.singletonList(
                  new Sample(
                      namespace + METRIC_NAME,
                      Arrays.asList("k1", "k2"),
                      Arrays.asList("v1", "v2"),
                      123456789))));
}
 
Example #14
Source File: PrometheusMetricsReporterTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithCustomLabel() {
    MetricLabel metricLabel = new BaggageMetricLabel(METRIC_LABEL_NAME, METRIC_LABEL_VALUE);
    PrometheusMetricsReporter reporter = PrometheusMetricsReporter.newMetricsReporter()
            .withName("MyName")
            .withCollectorRegistry(collectorRegistry)
            .withCustomLabel(metricLabel)
            .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT) // Override the default, to make sure span metrics reported
            .build();

    SpanData spanData = mock(SpanData.class);
    when(spanData.getOperationName()).thenReturn("testop");
    when(spanData.getTags()).thenReturn(Collections.<String,Object>emptyMap());
    when(spanData.getDuration()).thenReturn(100000L);

    reporter.reportSpan(spanData);

    List<MetricFamilySamples> samples = reporter.getHistogram().collect();
    assertEquals(1, samples.size());

    for (Sample sample : samples.get(0).samples) {
        assertTrue("Expected MetricLabel with name " + METRIC_LABEL_NAME, sample.labelNames.contains(METRIC_LABEL_NAME));
        assertTrue("Expected MetricLabel with value " + METRIC_LABEL_VALUE , sample.labelValues.contains(METRIC_LABEL_VALUE));
    }
}
 
Example #15
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 #16
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimple() {
	String textToParse = "# Minimalistic line:\n" + 
			"metric_without_timestamp_and_labels 12.47\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_timestamp_and_labels", new LinkedList<String>(), new LinkedList<String>(), 12.47);
	samples.add(sample);
	
	Collector.MetricFamilySamples expectedMFS = new Collector.MetricFamilySamples("metric_without_timestamp_and_labels", Type.UNTYPED, "", samples);
	expectedList.add(expectedMFS);
	
	Enumeration<Collector.MetricFamilySamples> expected = Collections.enumeration(expectedList);
	
	// compare
	compareEMFS(expected, result);
}
 
Example #17
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimplePlusInf() {
	String textToParse = "# Minimalistic line:\n" + 
			"\n"+
			"metric_without_labels +Inf 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>(), Double.POSITIVE_INFINITY);
	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 #18
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleMinusInf() {
	String textToParse = "# Minimalistic line:\n" + 
			"\n"+
			"metric_without_labels -Inf 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>(), Double.NEGATIVE_INFINITY);
	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 #19
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 #20
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 #21
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 #22
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCounterWithTimestampAndEmptyLine() {
	String textToParse = "# Simple metric without labels:\n" + 
			"# TYPE metric_without_labels counter\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, "", samples);
	expectedList.add(expectedMFS);
	
	Enumeration<Collector.MetricFamilySamples> expected = Collections.enumeration(expectedList);
	
	// compare
	compareEMFS(expected, result);
}
 
Example #23
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testHelp() {
	String textToParse = "# Simple metric without labels:\n" + 
			"# TYPE metric_without_labels counter\n" + 
			"# HELP metric_without_labels this is my help text\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", samples);
	expectedList.add(expectedMFS);
	
	Enumeration<Collector.MetricFamilySamples> expected = Collections.enumeration(expectedList);
	
	// compare
	compareEMFS(expected, result);
}
 
Example #24
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 #25
Source File: PrometheusPublisher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public List<MetricFamilySamples> describe() {
  List<MetricFamilySamples> familySamples = new ArrayList<>();
  if (globalRegistry == null) {
    return familySamples;
  }

  List<Sample> samples = new ArrayList<>();
  for (Registry registry : globalRegistry.getRegistries()) {
    for (Meter meter : registry) {
      meter.measure().forEach(measurement -> {
        Sample sample = convertMeasurementToSample(measurement);
        samples.add(sample);
      });
    }
  }

  familySamples.add(new MetricFamilySamples("ServiceComb_Metrics", Type.UNTYPED, "ServiceComb Metrics", samples));

  return familySamples;
}
 
Example #26
Source File: MetricsEndpointTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue52() {
	Assert.assertNotNull(subject);
	
	String response = subject.getMetrics().getBody();
	
	Assert.assertNotNull(response);
	Assert.assertNotEquals("", response);
	
	Parser parser = new Parser(response);
	HashMap<String, MetricFamilySamples> mapMFS = parser.parse();
	
	Assert.assertNotNull(mapMFS.get("metric_unittestapp"));
	Assert.assertNotNull(mapMFS.get("metric_unittestapp2"));
	
	MetricFamilySamples mfs = mapMFS.get("promregator_scrape_duration_seconds");
	Assert.assertNotNull(mfs);
	Assert.assertEquals(1, mfs.samples.size());
	
	Sample sample = mfs.samples.get(0);
	Assert.assertTrue(sample.labelNames.isEmpty());
	Assert.assertTrue(sample.labelValues.isEmpty());
}
 
Example #27
Source File: RatisNameRewriteSampleBuilder.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
public Sample createSample(String dropwizardName, String nameSuffix,
    List<String> additionalLabelNames, List<String> additionalLabelValues,
    double value) {
  //this is a ratis metrics, where the second part is an instance id.
  if (dropwizardName.startsWith(RATIS_APPLICATION_NAME_METRICS)) {
    List<String> names = new ArrayList<>(additionalLabelNames);
    List<String> values = new ArrayList<>(additionalLabelValues);
    String name = normalizeRatisMetric(dropwizardName, names, values);

    if (LOG.isTraceEnabled()) {
      LOG.trace(
          "Ratis dropwizard {} metrics are converted to {} with tag "
              + "keys/values {},{}", dropwizardName, name, names, values);
    }
    return super
        .createSample(name, nameSuffix,
            names,
            values, value);

  } else {
    return super
        .createSample(dropwizardName, nameSuffix, additionalLabelNames,
            additionalLabelValues, value);
  }
}
 
Example #28
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
private static Sample createSampleForHistogramWithDummyLabel(String bucketMetricName, String leValue, double value, boolean firstPosition) {
	List<String> labelNames = new LinkedList<>();
	if (firstPosition) {
		labelNames.add("name");
	}
	labelNames.add("le");
	if (!firstPosition) {
		labelNames.add("name");
	}
	
	List<String> labelValues = new LinkedList<>();
	if (firstPosition) {
		labelValues.add("value");
	}
	labelValues.add(leValue);
	if (!firstPosition) {
		labelValues.add("value");
	}
	
	Sample sample = new Sample(bucketMetricName, labelNames, labelValues, value); 
	return sample;
}
 
Example #29
Source File: SingleTargetMetricsEndpointTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue52() {
	Assert.assertNotNull(subject);
	
	String response = subject.getMetrics("faedbb0a-2273-4cb4-a659-bd31331f7daf", "0").getBody();
	
	Assert.assertNotNull(response);
	Assert.assertNotEquals("", response);
	
	Parser parser = new Parser(response);
	HashMap<String, MetricFamilySamples> mapMFS = parser.parse();
	
	Assert.assertNotNull(mapMFS.get("metric_unittestapp"));
	Assert.assertNull(mapMFS.get("metric_unittestapp2"));
	
	MetricFamilySamples mfs = mapMFS.get("promregator_scrape_duration_seconds");
	Assert.assertNotNull(mfs);
	Assert.assertEquals(1, mfs.samples.size());
	
	Sample sample = mfs.samples.get(0);
	Assert.assertEquals("[org_name, space_name, app_name, cf_instance_id, cf_instance_number]", sample.labelNames.toString()); 
	Assert.assertEquals("[unittestorg, unittestspace, unittestapp, faedbb0a-2273-4cb4-a659-bd31331f7daf:0, 0]", sample.labelValues.toString()); 
}
 
Example #30
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
private static Sample createSampleForSummaryWithDummyLabel(String bucketMetricName, String quantileValue, double value, boolean firstPosition) {
	List<String> labelNames = new LinkedList<>();
	if (firstPosition) {
		labelNames.add("name");
	}
	labelNames.add("quantile");
	if (!firstPosition) {
		labelNames.add("name");
	}
	List<String> labelValues = new LinkedList<>();
	if (firstPosition) {
		labelValues.add("value");
	}
	labelValues.add(quantileValue);
	if (!firstPosition) {
		labelValues.add("value");
	}
	
	Sample sample = new Sample(bucketMetricName, labelNames, labelValues, value); 
	return sample;
}