io.prometheus.client.Gauge Java Examples

The following examples show how to use io.prometheus.client.Gauge. 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: MetricsEndpoint.java    From promregator with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleScrapeDuration(CollectorRegistry requestRegistry, Duration duration) {
	/* Note:
	 * The metric in this method intends to describe how much time has passed 
	 * for the *entire* scraping process. It's not the intention of this metric
	 * to drill-down to each scraping request.
	 * That is why it does not have additional labels, i.e. it does not have labels
	 * which are depending on the target.
	 * 
	 * See also the description of "promregator_scrape_duration_seconds" in
	 * https://github.com/promregator/promregator/blob/4b2ca289b624328e7e0b3838112e31a908a55c58/docs/enrichment.md
	 */
	Gauge scrapeDuration = Gauge.build("promregator_scrape_duration_seconds", "Duration in seconds indicating how long scraping of all metrics took")
			.register(requestRegistry);
	
	scrapeDuration.set(duration.toMillis() / 1000.0);
}
 
Example #2
Source File: MetricsServletTest.java    From client_java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriterFiltersBasedOnParameter() throws IOException, ServletException {
  CollectorRegistry registry = new CollectorRegistry();
  Gauge.build("a", "a help").register(registry);
  Gauge.build("b", "a help").register(registry);
  Gauge.build("c", "a help").register(registry);

  HttpServletRequest req = mock(HttpServletRequest.class);
  when(req.getParameterValues("name[]")).thenReturn(new String[]{"a", "b", "oneTheDoesntExist", ""});
  HttpServletResponse resp = mock(HttpServletResponse.class);
  StringWriter stringWriter = new StringWriter();
  PrintWriter writer = new PrintWriter(stringWriter);
  when(resp.getWriter()).thenReturn(writer);

  new MetricsServlet(registry).doGet(req, resp);

  assertThat(stringWriter.toString()).contains("a 0.0");
  assertThat(stringWriter.toString()).contains("b 0.0");
  assertThat(stringWriter.toString()).doesNotContain("c 0.0");
}
 
Example #3
Source File: MetricsServletTest.java    From client_java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriterIsClosedOnException() throws IOException, ServletException {
  HttpServletRequest req = mock(HttpServletRequest.class);
  HttpServletResponse resp = mock(HttpServletResponse.class);
  PrintWriter writer = mock(PrintWriter.class);
  when(resp.getWriter()).thenReturn(writer);
  doThrow(new RuntimeException()).when(writer).write(any(char[].class), anyInt(), anyInt());
  CollectorRegistry registry = new CollectorRegistry();
  Gauge a = Gauge.build("a", "a help").register(registry);

  try {
    new MetricsServlet(registry).doGet(req, resp);
    fail("Exception expected");
  } catch (Exception e) {
  }

  verify(writer).close();
}
 
Example #4
Source File: TxleMetrics.java    From txle with Apache License 2.0 6 votes vote down vote up
public void endMarkTxDuration(TxEvent event) {
    if (!isEnableMonitor(event)) {
        return;
    }
    String globalOrLocalTxId = "";
    if (SagaEndedEvent.name().equals(event.type())) {
        globalOrLocalTxId = event.globalTxId();
    } else if (TxEndedEvent.name().equals(event.type())) {
        globalOrLocalTxId = event.localTxId();
    }
    Gauge.Timer gaugeTimerOfTxId = txIdAndGaugeTimer.get(globalOrLocalTxId);
    if (gaugeTimerOfTxId != null) {
        gaugeTimerOfTxId.setDuration();
        txIdAndGaugeTimer.remove(globalOrLocalTxId);
        if (txIdAndGaugeTimer.isEmpty()) {
            txIdAndGaugeTimer.clear();
        }
    }
}
 
Example #5
Source File: PrometheusHttpConsumerMetrics.java    From garmadon with Apache License 2.0 6 votes vote down vote up
protected static void exposeKafkaMetrics() {
    try {
        for (Map.Entry<ObjectName, BiFunction<ObjectName, MBeanAttributeInfo, Gauge.Child>> entry : kafkaJmxNameToPrometheusLabeler.entrySet()) {
            // jmx object to expose
            ObjectName baseKafkaJmxName = entry.getKey();
            // callback to build a prometheus metric with labels
            BiFunction<ObjectName, MBeanAttributeInfo, Gauge.Child> prometheusMetricLabelsFromObjectNameAndAttr = entry.getValue();

            for (ObjectName name : MBS.queryNames(baseKafkaJmxName, null)) {
                MBeanInfo info = MBS.getMBeanInfo(name);
                MBeanAttributeInfo[] attrInfo = info.getAttributes();
                for (MBeanAttributeInfo attr : attrInfo) {
                    if (attr.isReadable() && attr.getType().equals("double")) {
                        // create metrics target labels and set the corresponding value
                        prometheusMetricLabelsFromObjectNameAndAttr.apply(name, attr)
                                .set((Double) MBS.getAttribute(name, attr.getName()));
                    }
                }
            }
        }
    } catch (InstanceNotFoundException | IntrospectionException | ReflectionException | MBeanException | AttributeNotFoundException e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example #6
Source File: PrometheusServlet.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Override
public void handleEvent(Event event) {
    for (String property : event.getPropertyNames()) {
        if (event.getProperty(property) instanceof Long || event.getProperty(property) instanceof Integer) {
            String convertedProperty = property.replace(".", "_");
            Gauge gauge = gauges.get(convertedProperty);
            if (gauge == null) {
                gauge = Gauge.build().name(convertedProperty).help(property).register();
                gauges.put(convertedProperty, gauge);
            }
            if (event.getProperty(property) instanceof Long) {
                gauge.set((Long) event.getProperty(property));
            } else if (event.getProperty(property) instanceof Integer) {
                gauge.set((Integer) event.getProperty(property));
            }
        }
    }
}
 
Example #7
Source File: ReaderFactory.java    From garmadon with Apache License 2.0 6 votes vote down vote up
private GarmadonReader.GarmadonMessageHandler buildGarmadonMessageHandler(PartitionedWriter<Message> writer,
                                                                          String eventName) {
    return msg -> {
        final CommittableOffset offset = msg.getCommittableOffset();
        final Counter.Child messagesWritingFailures = PrometheusMetrics.messageWritingFailuresCounter(eventName, offset.getPartition());
        final Counter.Child messagesWritten = PrometheusMetrics.messageWrittenCounter(eventName, offset.getPartition());

        Gauge.Child gauge = PrometheusMetrics.currentRunningOffsetsGauge(eventName, offset.getPartition());
        gauge.set(offset.getOffset());

        try {
            writer.write(Instant.ofEpochMilli(msg.getTimestamp()), offset, msg.toProto());

            messagesWritten.inc();
        } catch (IOException e) {
            // We accept losing messages every now and then, but still log failures
            messagesWritingFailures.inc();
            LOGGER.warn("Couldn't write a message", e);
        }
    };
}
 
Example #8
Source File: FsImageCollector.java    From hadoop-hdfs-fsimage-exporter with Apache License 2.0 6 votes vote down vote up
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<>();

    try (Gauge.Timer timer = scrapeDuration.startTimer()) {
        scapeRequests.inc();

        if (fsImageReportUpdater.collectFsImageSamples(mfs)) {
            scrapeErrors.inc();
        }
    } catch (Exception e) {
        scrapeErrors.inc();
        LOGGER.error("FSImage scrape failed", e);
    }

    mfs.addAll(scrapeDuration.collect());
    mfs.addAll(scapeRequests.collect());
    mfs.addAll(scrapeErrors.collect());

    return mfs;
}
 
Example #9
Source File: PrometheusGaugeMetrics.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void setValue(double value) {
    Gauge.Child metrics = this.getMetric();
    if (metrics != null) {
        metrics.set(value);
    }
}
 
Example #10
Source File: TextFormatTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testHelpEscaped() throws IOException {
  Gauge noLabels = Gauge.build().name("nolabels").help("ąćčęntěd h\"e\\l\np").register(registry);
  noLabels.inc();
  TextFormat.write004(writer, registry.metricFamilySamples());
  assertEquals("# HELP nolabels ąćčęntěd h\"e\\\\l\\np\n"
               + "# TYPE nolabels gauge\n"
               + "nolabels 1.0\n", writer.toString());
}
 
Example #11
Source File: BasicAuthPushGatewayTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  registry = new CollectorRegistry();
  gauge = Gauge.build().name("g").help("help").create();
  pushGateway = new PushGateway("localhost:" + mockServerRule.getHttpPort());
  pushGateway.setConnectionFactory(new BasicAuthHttpConnectionFactory("testUser", "testPwd"));
}
 
Example #12
Source File: PushGatewayTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  registry = new CollectorRegistry();
  gauge = (Gauge) Gauge.build().name("g").help("help").create();
  pg = new PushGateway("localhost:" + mockServerRule.getHttpPort());
  groupingKey = new TreeMap<String, String>();
  groupingKey.put("l", "v");
}
 
Example #13
Source File: TextFormatTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testLabelValuesEscaped() throws IOException {
  Gauge labels = Gauge.build().name("labels").help("help").labelNames("l").register(registry);
  labels.labels("ąćčęntěd a\nb\\c\"d").inc();
  TextFormat.write004(writer, registry.metricFamilySamples());
  assertEquals("# HELP labels help\n"
               + "# TYPE labels gauge\n"
               + "labels{l=\"ąćčęntěd a\\nb\\\\c\\\"d\",} 1.0\n", writer.toString());
}
 
Example #14
Source File: TestHTTPServer.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws IOException {
  CollectorRegistry registry = new CollectorRegistry();
  Gauge.build("a", "a help").register(registry);
  Gauge.build("b", "a help").register(registry);
  Gauge.build("c", "a help").register(registry);
  s = new HTTPServer(new InetSocketAddress(0), registry);
}
 
Example #15
Source File: TextFormatTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGaugeOutput() throws IOException {
  Gauge noLabels = Gauge.build().name("nolabels").help("help").register(registry);
  noLabels.inc();
  TextFormat.write004(writer, registry.metricFamilySamples());
  assertEquals("# HELP nolabels help\n"
               + "# TYPE nolabels gauge\n"
               + "nolabels 1.0\n", writer.toString());
}
 
Example #16
Source File: TextFormatTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValueInfinity() throws IOException {
  Gauge noLabels = Gauge.build().name("nolabels").help("help").register(registry);
  noLabels.set(Double.POSITIVE_INFINITY);
  TextFormat.write004(writer, registry.metricFamilySamples());
  assertEquals("# HELP nolabels help\n"
               + "# TYPE nolabels gauge\n"
               + "nolabels +Inf\n", writer.toString());
}
 
Example #17
Source File: BulletinMetricsRegistry.java    From nifi with Apache License 2.0 5 votes vote down vote up
public BulletinMetricsRegistry() {
    nameToGaugeMap.put("BULLETIN", Gauge.build()
            .name("nifi_bulletin")
            .help("Bulletin reported by the NiFi instance")
            .labelNames("instance", "component_type", "component_id", "parent_id",
                    "node_address", "category", "source_name", "source_id", "level")
            .register(registry));
}
 
Example #18
Source File: PrometheusGaugeMetrics.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void dec() {
    Gauge.Child metrics = this.getMetric();
    if (metrics != null) {
        metrics.dec();
    }
}
 
Example #19
Source File: GraphiteTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testPush() throws Exception {
  // Create a metric.
  CollectorRegistry registry = new CollectorRegistry();
  Gauge labels = Gauge.build().name("labels").help("help").labelNames("l").register(registry);
  labels.labels("fo*o").inc();


  // Server to accept push.
  final ServerSocket ss = new ServerSocket(0);
  final StringBuilder result = new StringBuilder();
  Thread t = new Thread() {
    public void run() {
      try {
        Socket s = ss.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        result.append(reader.readLine());
        s.close();
      } catch (Exception e) {
        e.printStackTrace();
        fail();
      }
    }
  };
  t.start();

  // Push.
  Graphite g = new Graphite("localhost", ss.getLocalPort());
  g.push(registry);
  t.join();
  ss.close();

  // Check result.
  String[] parts = result.toString().split(" ");
  assertEquals(3, parts.length);
  assertEquals("labels.l.fo_o", parts[0]);
  assertEquals("1.0", parts[1]);
  Integer.parseInt(parts[2]);  // This shouldn't throw an exception.
}
 
Example #20
Source File: PrometheusGaugeMetrics.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void inc(double value) {
    Gauge.Child metrics = this.getMetric();
    if (metrics != null) {
        metrics.inc(value);
    }
}
 
Example #21
Source File: PrometheusGaugeMetrics.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void inc() {
    Gauge.Child metrics = this.getMetric();
    if (metrics != null) {
        metrics.inc();
    }
}
 
Example #22
Source File: SessionContainerProvider.java    From cineast with MIT License 5 votes vote down vote up
public SessionContainerProvider() {
  if (Config.sharedConfig().getMonitoring().enablePrometheus) {
    LOGGER.debug("Enabling prometheus monitoring for paths in queue {}", queueNumber.get());
    instance = queueNumber.getAndIncrement();
    pathsInQueue = Gauge.build().name("cineast_item_in_queue_" + instance)
        .help("Paths currently in Queue " + instance).register();
    pathsCompleted = Counter.build().name("cineast_item_completed_queue_" + instance)
        .help("Paths completed in Queue " + instance).register();
  } else {
    instance = 0;
  }
}
 
Example #23
Source File: PrometheusMetricsCatalog.java    From elasticsearch-prometheus-exporter with Apache License 2.0 5 votes vote down vote up
public void registerNodeGauge(String metric, String help, String... labels) {
    Gauge gauge = Gauge.build().
            name(metricPrefix + metric).
            help(help).
            labelNames(getExtendedNodeLabelNames(labels)).
            register(registry);

    metrics.put(metric, gauge);

    logger.debug(String.format(Locale.ENGLISH, "Registered new node gauge %s", metric));
}
 
Example #24
Source File: PrometheusMetricsCatalog.java    From elasticsearch-prometheus-exporter with Apache License 2.0 5 votes vote down vote up
public void registerClusterGauge(String metric, String help, String... labels) {
    Gauge gauge = Gauge.build().
            name(metricPrefix + metric).
            help(help).
            labelNames(getExtendedClusterLabelNames(labels)).
            register(registry);

    metrics.put(metric, gauge);

    logger.debug(String.format(Locale.ENGLISH, "Registered new cluster gauge %s", metric));
}
 
Example #25
Source File: FsImageUpdateHandler.java    From hadoop-hdfs-fsimage-exporter with Apache License 2.0 5 votes vote down vote up
FsMetrics(String prefix, String[] labelNames) {
    sumDirs = Gauge.build()
            .name(prefix + METRIC_POSTFIX_DIRS)
            .labelNames(labelNames)
            .help(HELP_NUMBER_OF_DIRECTORIES).create();
    sumLinks = Gauge.build()
            .name(prefix + METRIC_POSTFIX_LINKS)
            .labelNames(labelNames)
            .help(HELP_NUMBER_OF_SYM_LINKS).create();
    sumBlocks = Gauge.build()
            .name(prefix + METRIC_POSTFIX_BLOCKS)
            .labelNames(labelNames)
            .help(HELP_NUMBER_OF_BLOCKS).create();
}
 
Example #26
Source File: MetricsServletTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriterIsClosedNormally() throws IOException, ServletException {
  HttpServletRequest req = mock(HttpServletRequest.class);
  HttpServletResponse resp = mock(HttpServletResponse.class);
  PrintWriter writer = mock(PrintWriter.class);
  when(resp.getWriter()).thenReturn(writer);
  CollectorRegistry registry = new CollectorRegistry();
  Gauge a = Gauge.build("a", "a help").register(registry);

  new MetricsServlet(registry).doGet(req, resp);
  verify(writer).close();
}
 
Example #27
Source File: JMeterCollectorRegistry.java    From jmeter-prometheus-plugin with Apache License 2.0 5 votes vote down vote up
protected ThreadCollector() {
	BaseCollectorConfig cfg = getConfig();
	
	innerCollector = Gauge.build()
			.name(cfg.getMetricName())
			.labelNames(cfg.getLabels())
			.help(cfg.getHelp())
			.create();
}
 
Example #28
Source File: MetricsFetcherSimulatorTest.java    From promregator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCall() throws Exception {
	AbstractMetricFamilySamplesEnricher mfse = new CFAllLabelsMetricFamilySamplesEnricher("testOrgName", "testSpaceName", "testapp", "testinstance1:0");
	
	Gauge up = Gauge.build("up_test", "help test").labelNames(CFAllLabelsMetricFamilySamplesEnricher.getEnrichingLabelNames()).create();
	Child upChild = up.labels(mfse.getEnrichedLabelValues(new LinkedList<>()).toArray(new String[0]));
	
	MetricsFetcherSimulator subject = new MetricsFetcherSimulator("accessUrl", 
			new NullEnricher(), mfse , 
			Mockito.mock(MetricsFetcherMetrics.class), upChild);
	
	HashMap<String, MetricFamilySamples> result = subject.call();
	
	Assert.assertEquals(3, result.size());
}
 
Example #29
Source File: Metric.java    From paraflow with Apache License 2.0 5 votes vote down vote up
public Metric(String gateWayUrl, String id, String name, String help, String job)
{
    this.id = id;
    this.job = job;
    this.gateway = new PushGateway(gateWayUrl);
    this.metric = Gauge.build().name(name).help(help).labelNames("id").register(registry);
}
 
Example #30
Source File: PrometheusGaugeMetrics.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void dec(double value) {
    Gauge.Child metrics = this.getMetric();
    if (metrics != null) {
        metrics.dec(value);
    }
}