io.prometheus.client.Collector.MetricFamilySamples Java Examples

The following examples show how to use io.prometheus.client.Collector.MetricFamilySamples. 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 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 #2
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 #3
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 #4
Source File: CFMetricsFetcher.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Override
public HashMap<String, MetricFamilySamples> call() throws Exception {
	log.debug(String.format("Reading metrics from %s for instance %s", this.endpointUrl, this.instanceId));
	
	HttpGet httpget = setupRequest();

	String result = performRequest(httpget);
	if (result == null) {
		return null;
	}
	
	log.debug(String.format("Successfully received metrics from %s for instance %s", this.endpointUrl, this.instanceId));
	
	if (this.mfm.getRequestSize() != null) {
		this.mfm.getRequestSize().observe(result.length());
	}
	
	Parser parser = new Parser(result);
	HashMap<String, MetricFamilySamples> emfs = parser.parse();
	
	emfs = this.mfse.determineEnumerationOfMetricFamilySamples(emfs);
	
	return emfs;
}
 
Example #5
Source File: MonitoringServerInterceptorIntegrationTest.java    From java-grpc-prometheus with Apache License 2.0 6 votes vote down vote up
@Test
public void serverStreamRpcMetrics() throws Throwable {
  startGrpcServer(CHEAP_METRICS);
  ImmutableList<HelloResponse> responses =
      ImmutableList.copyOf(createGrpcBlockingStub().sayHelloServerStream(REQUEST));

  assertThat(findRecordedMetricOrThrow("grpc_server_started_total").samples).hasSize(1);
  assertThat(findRecordedMetricOrThrow("grpc_server_msg_received_total").samples).isEmpty();
  assertThat(findRecordedMetricOrThrow("grpc_server_msg_sent_total").samples).hasSize(1);

  MetricFamilySamples handled = findRecordedMetricOrThrow("grpc_server_handled_total");
  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);

  MetricFamilySamples messagesSent = findRecordedMetricOrThrow("grpc_server_msg_sent_total");
  assertThat(messagesSent.samples.get(0).labelValues).containsExactly(
      "SERVER_STREAMING",
      HelloServiceImpl.SERVICE_NAME,
      HelloServiceImpl.SERVER_STREAM_METHOD_NAME);
  assertThat(messagesSent.samples.get(0).value).isWithin(0).of(responses.size());
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: MetricsFetcherTestTLSPKIX.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testPKIXErrorOnSelfSignedCertificateInDefaultMode() throws Exception {
	String instanceId = "abcd:4";
	NullMetricFamilySamplesEnricher dummymfse = new NullMetricFamilySamplesEnricher("dummy", "dummy", "dummy", "dummy:0");
	List<String> labelValues = dummymfse.getEnrichedLabelValues(new LinkedList<>());
	String[] ownTelemetryLabelValues = labelValues.toArray(new String[0]);
	
	MetricsFetcherMetrics mfm = new MetricsFetcherMetrics(ownTelemetryLabelValues, false);
	UUID currentUUID = UUID.randomUUID();
	
	CFMetricsFetcherConfig config = new CFMetricsFetcherConfig();
	config.setMetricFamilySamplesEnricher(dummymfse);
	config.setMetricsFetcherMetrics(mfm);
	config.setPromregatorInstanceIdentifier(currentUUID);
	config.setConnectionTimeoutInMillis(5000);
	config.setSocketReadTimeoutInMillis(5000);
	
	CFMetricsFetcher subject = new CFMetricsFetcher("https://localhost:9003/metrics", instanceId, config);
	
	this.mems.getMetricsEndpointHandler().setResponse(DUMMY_METRICS_LIST);
	
	HashMap<String, MetricFamilySamples> response = subject.call();
	
	Assert.assertNull(response);
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
Source File: MonitoringServerInterceptorIntegrationTest.java    From java-grpc-prometheus with Apache License 2.0 6 votes vote down vote up
@Test
public void bidiStreamRpcMetrics() throws Throwable {
  startGrpcServer(CHEAP_METRICS);
  StreamRecorder<HelloResponse> streamRecorder = StreamRecorder.create();
  StreamObserver<HelloRequest> requestStream =
      createGrpcStub().sayHelloBidiStream(streamRecorder);
  requestStream.onNext(REQUEST);
  requestStream.onNext(REQUEST);
  requestStream.onCompleted();

  // Not a blocking stub, so we need to wait.
  streamRecorder.awaitCompletion();

  assertThat(findRecordedMetricOrThrow("grpc_server_started_total").samples).hasSize(1);
  assertThat(findRecordedMetricOrThrow("grpc_server_msg_received_total").samples).hasSize(1);
  assertThat(findRecordedMetricOrThrow("grpc_server_msg_sent_total").samples).hasSize(1);

  MetricFamilySamples handled = findRecordedMetricOrThrow("grpc_server_handled_total");
  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 #17
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 #18
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 #19
Source File: KafkaCollectorTest.java    From kafka-topic-exporter with Apache License 2.0 6 votes vote down vote up
public void testAddMetricWithLabel() throws IOException {
    KafkaCollector collector = new KafkaCollector(emptyConfig);
    final String logRecord = "{\"name\":\"foo\", \"labels\": { \"label1\": \"v1\", \"lable2\": \"v2\" }, \"value\": 9}";
    final String topic = "test.hoge";
    KafkaExporterLogEntry jsonRecord = mapper.readValue(logRecord, KafkaExporterLogEntry.class);
    
    collector.add(topic, logRecord);
    List<MetricFamilySamples> mfsList = collector.collect();
    MetricFamilySamples mfs = mfsList.get(0);
    Map<String, String> labelMap = MetricUtil.getLabelMapFromSample(mfs.samples.get(0));
    
    assertEquals("test_hoge_foo", mfs.name);
    assertEquals(Collector.Type.GAUGE, mfs.type);
    assertEquals("", mfs.help);
    assertEquals(jsonRecord.getLabels(), labelMap);
    assertEquals(9.0, mfs.samples.get(0).value);
}
 
Example #20
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 #21
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 #22
Source File: ParserTest.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue104() throws IOException, URISyntaxException {
	String textToParse = new String(Files.readAllBytes(Paths.get(getClass().getResource("issue104.txt").toURI())));
	
	Parser subject = new Parser(textToParse);
	HashMap<String, Collector.MetricFamilySamples> resultMap = subject.parse();
	
	Assert.assertEquals(1, resultMap.keySet().size());
	
	MetricFamilySamples mfs = resultMap.get("http_server_requests_seconds");
	Assert.assertNotNull(mfs);
	
	// this file contains multiple samples for the same metric
	Assert.assertEquals(66, mfs.samples.size());
	
	Assert.assertEquals(0.034350549,  mfs.samples.get(65).value, 0.001);
}
 
Example #23
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 #24
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 #25
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 #26
Source File: KafkaCollectorTest.java    From kafka-topic-exporter with Apache License 2.0 6 votes vote down vote up
public void testMetricExpire() throws IOException {
    PropertyConfig config = new PropertyConfig();
    config.set("exporter.metric.expire.seconds", "120");

    KafkaCollector collector = new KafkaCollector(config);
    LocalDateTime setDate1 = LocalDateTime.of(2016, 9, 20, 10, 0);
    LocalDateTime setDate2 = LocalDateTime.of(2016, 9, 20, 10, 9);
    LocalDateTime getDate = LocalDateTime.of(2016, 9, 20, 10, 10);

    final String logRecord1 = "{\"name\":\"foo\", \"labels\": { \"label1\": \"v1\", \"lable2\": \"v2\" }, \"value\": 9}";
    final String logRecord2 = "{\"name\":\"foo\", \"labels\": { \"label1\": \"aa1\", \"lable2\": \"bb2\" }, \"value\": 10}";
    final String topic = "test.hoge";
    KafkaExporterLogEntry jsonRecord = mapper.readValue(logRecord2, KafkaExporterLogEntry.class);

    collector.add(topic, logRecord1, setDate1);
    collector.add(topic, logRecord2, setDate2);

    List<MetricFamilySamples> mfsList = collector.collect(getDate);
    MetricFamilySamples mfs = mfsList.get(0);
    List<MetricFamilySamples.Sample> samples = mfs.samples;

    assertEquals(1, samples.size());
    assertEquals(jsonRecord.getLabels(), MetricUtil.getLabelMapFromSample(samples.get(0)));
    assertEquals(10.0, samples.get(0).value);
}
 
Example #27
Source File: PrometheusMetricsReporterConfigurationWithNameTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsReporterName() {
    // sanity test
    assertFalse(testCollectorRegistry.metricFamilySamples().hasMoreElements());

    // prepare
    SpanData metricSpanData = Mockito.mock(SpanData.class);

    Mockito.when(metricSpanData.getOperationName())
            .thenReturn("testOp");

    Mockito.when(metricSpanData.getTags())
            .thenReturn(Collections.<String, Object>singletonMap(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT));

    Mockito.when(metricSpanData.getDuration())
            .thenReturn(500L);

    // test
    metricsReporter.reportSpan(metricSpanData);

    // verify
    MetricFamilySamples samples = testCollectorRegistry.metricFamilySamples().nextElement();
    assertTrue(samples.name.startsWith(METRICS_NAME));
}
 
Example #28
Source File: PrometheusMetricsReporterConfigurationTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsReporter() {
    // prepare
    SpanData metricSpanData = Mockito.mock(SpanData.class);

    Mockito.when(metricSpanData.getOperationName())
            .thenReturn("testOp");

    Mockito.when(metricSpanData.getTags())
            .thenReturn(Collections.<String, Object>singletonMap(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT));

    Mockito.when(metricSpanData.getDuration())
            .thenReturn(500L);

    // test
    metricsReporter.reportSpan(metricSpanData);

    // verify
    MetricFamilySamples samples = testCollectorRegistry.metricFamilySamples().nextElement();
    assertFalse(samples.samples.isEmpty());
}
 
Example #29
Source File: PrometheusMetricsReporterTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithCustomMetricTypeNames() {
    PrometheusMetricsReporter reporter = PrometheusMetricsReporter.newMetricsReporter()
            .withName("MyName")
            .withCollectorRegistry(collectorRegistry)
            .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);

    // Check span duration
    List<MetricFamilySamples> samples = reporter.getHistogram().collect();
    assertEquals(1, samples.size());
    assertEquals("MyName", samples.get(0).name);
}
 
Example #30
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));
    }
}