io.prometheus.client.CollectorRegistry Java Examples

The following examples show how to use io.prometheus.client.CollectorRegistry. 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: PrometheusMetricsUtil.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static CollectorRegistry createJvmMetrics(JvmMetricsRegistry jvmMetricsRegistry, JvmMetrics jvmMetrics, String instId) {
    final String instanceId = StringUtils.isEmpty(instId) ? DEFAULT_LABEL_STRING : instId;
    jvmMetricsRegistry.setDataPoint(jvmMetrics.heapUsed(DataUnit.B), "JVM_HEAP_USED", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.heapUsage(), "JVM_HEAP_USAGE", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.nonHeapUsage(), "JVM_HEAP_NON_USAGE", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.threadCount(), "JVM_THREAD_COUNT", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.daemonThreadCount(), "JVM_DAEMON_THREAD_COUNT", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.uptime(), "JVM_UPTIME", instanceId);
    jvmMetricsRegistry.setDataPoint(jvmMetrics.fileDescriptorUsage(), "JVM_FILE_DESCRIPTOR_USAGE", instanceId);

    jvmMetrics.garbageCollectors()
            .forEach((name, stat) -> {
                jvmMetricsRegistry.setDataPoint(stat.getRuns(), "JVM_GC_RUNS", instanceId, name);
                jvmMetricsRegistry.setDataPoint(stat.getTime(TimeUnit.MILLISECONDS), "JVM_GC_TIME", instanceId, name);
            });

    return jvmMetricsRegistry.getRegistry();
}
 
Example #2
Source File: PushDemo.java    From sofa-lookout with Apache License 2.0 6 votes vote down vote up
static void executeBatchJob() throws Exception {
    CollectorRegistry registry = CollectorRegistry.defaultRegistry;
    Counter requests = Counter.build()
            .name("my_library_requests_total").help("Total requests.")
            .labelNames("method").register();
    requests.labels("get").inc();


    PushGateway pushgateway = new PushGateway("127.0.0.1:7200/prom");
    // pushgateway.setConnectionFactory(new BasicAuthHttpConnectionFactory("my_user", "my_password"));
    Map<String, String> groupingkeys = new HashMap<>();
    groupingkeys.put("app", "xx");
    pushgateway.pushAdd(registry, "my_batch_job", groupingkeys);
    //  pushgateway.pushAdd(registry, "my_batch_job");
}
 
Example #3
Source File: CircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    registry = new CollectorRegistry();
    circuitBreakerMetricsPublisher = new CircuitBreakerMetricsPublisher();
    circuitBreakerMetricsPublisher.register(registry);
    circuitBreakerRegistry = CircuitBreakerRegistry
        .of(CircuitBreakerConfig.ofDefaults(), circuitBreakerMetricsPublisher);

    CircuitBreakerConfig configWithSlowCallThreshold = CircuitBreakerConfig.custom()
        .slowCallDurationThreshold(Duration.ofSeconds(1)).build();
    circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("backendA", configWithSlowCallThreshold);

    // record some basic stats
    // SLOW_SUCCESS
    circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(100, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
    circuitBreaker.transitionToOpenState();
}
 
Example #4
Source File: CircuitBreakerMetricsCollectorTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    registry = new CollectorRegistry();
    circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();

    CircuitBreakerConfig configWithSlowCallThreshold = CircuitBreakerConfig.custom()
        .slowCallDurationThreshold(Duration.ofSeconds(1)).build();
    circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("backendA", configWithSlowCallThreshold);

    CircuitBreakerMetricsCollector.ofCircuitBreakerRegistry(circuitBreakerRegistry)
        .register(registry);

    // record some basic stats
    // SLOW_SUCCESS
    circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(100, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
    circuitBreaker.transitionToOpenState();
}
 
Example #5
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 #6
Source File: StandardExportsTest.java    From client_java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStandardExports() {
  CollectorRegistry registry = new CollectorRegistry();
  new StandardExports(new StatusReaderTest(), osBean, runtimeBean).register(registry);

  assertEquals(123 / 1.0E9,
      registry.getSampleValue("process_cpu_seconds_total", new String[]{}, new String[]{}), .0000001);
  assertEquals(10,
      registry.getSampleValue("process_open_fds", new String[]{}, new String[]{}), .001);
  assertEquals(20,
      registry.getSampleValue("process_max_fds", new String[]{}, new String[]{}), .001);
  assertEquals(456 / 1.0E3,
      registry.getSampleValue("process_start_time_seconds", new String[]{}, new String[]{}), .0000001);
  assertEquals(5900 * 1024,
      registry.getSampleValue("process_virtual_memory_bytes", new String[]{}, new String[]{}), .001);
  assertEquals(360 * 1024,
      registry.getSampleValue("process_resident_memory_bytes", new String[]{}, new String[]{}), .001);
}
 
Example #7
Source File: TimeLimiterMetricsCollectorTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void customMetricNamesOverrideDefaultOnes() {
    TimeLimiterMetricsCollector.MetricNames names = TimeLimiterMetricsCollector.MetricNames
        .custom()
        .callsMetricName("custom_calls")
        .build();
    CollectorRegistry customRegistry = new CollectorRegistry();
    TimeLimiterMetricsCollector.ofTimeLimiterRegistry(names, timeLimiterRegistry)
        .register(customRegistry);
    timeLimiter.onSuccess();
    timeLimiter.onError(new RuntimeException());
    timeLimiter.onError(new TimeoutException());

    Double successfulCalls = getSampleValue(customRegistry, "custom_calls", KIND_SUCCESSFUL);
    Double failedCalls = getSampleValue(customRegistry, "custom_calls", KIND_FAILED);
    Double timeoutCalls = getSampleValue(customRegistry, "custom_calls", KIND_TIMEOUT);

    assertThat(successfulCalls).isNotNull();
    assertThat(failedCalls).isNotNull();
    assertThat(timeoutCalls).isNotNull();
}
 
Example #8
Source File: PrometheusReporterTaskScopeTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void removingSingleInstanceOfMetricDoesNotBreakOtherInstances() throws UnirestException {
	Counter counter1 = new SimpleCounter();
	counter1.inc(1);
	Counter counter2 = new SimpleCounter();
	counter2.inc(2);

	taskMetricGroup1.counter("my_counter", counter1);
	taskMetricGroup2.counter("my_counter", counter2);

	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_counter", LABEL_NAMES, labelValues1),
		equalTo(1.));
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_counter", LABEL_NAMES, labelValues2),
		equalTo(2.));

	taskMetricGroup2.close();
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_counter", LABEL_NAMES, labelValues1),
		equalTo(1.));

	taskMetricGroup1.close();
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_counter", LABEL_NAMES, labelValues1),
		nullValue());
}
 
Example #9
Source File: PrometheusMetricsFactory.java    From nifi-prometheus-reporter with Apache License 2.0 6 votes vote down vote up
public static CollectorRegistry createNifiMetrics(ProcessGroupStatus status, String applicationId) {
    String processGroupName = status.getName();
    AMOUNT_FLOWFILES_TOTAL.labels("sent", applicationId, processGroupName).set(status.getFlowFilesSent());
    AMOUNT_FLOWFILES_TOTAL.labels("transferred", applicationId, processGroupName).set(status.getFlowFilesTransferred());
    AMOUNT_FLOWFILES_TOTAL.labels("received", applicationId, processGroupName).set(status.getFlowFilesReceived());

    AMOUNT_BYTES_TOTAL.labels("sent", applicationId, processGroupName).set(status.getBytesSent());
    AMOUNT_BYTES_TOTAL.labels("read", applicationId, processGroupName).set(status.getBytesRead());
    AMOUNT_BYTES_TOTAL.labels("written", applicationId, processGroupName).set(status.getBytesWritten());
    AMOUNT_BYTES_TOTAL.labels("received", applicationId, processGroupName).set(status.getBytesReceived());
    AMOUNT_BYTES_TOTAL.labels("transferred", applicationId, processGroupName).set(status.getBytesTransferred());

    SIZE_CONTENT_TOTAL.labels("output", applicationId, processGroupName).set(status.getOutputContentSize());
    SIZE_CONTENT_TOTAL.labels("input", applicationId, processGroupName).set(status.getInputContentSize());
    SIZE_CONTENT_TOTAL.labels("queued", applicationId, processGroupName).set(status.getQueuedContentSize());

    AMOUNT_ITEMS.labels("output", applicationId, processGroupName).set(status.getOutputCount());
    AMOUNT_ITEMS.labels("input", applicationId, processGroupName).set(status.getInputCount());
    AMOUNT_ITEMS.labels("queued", applicationId, processGroupName).set(status.getQueuedCount());

    AMOUNT_THREADS_TOTAL.labels("nano", applicationId, processGroupName).set(status.getActiveThreadCount());

    return NIFI_METRICS_REGISTRY;
}
 
Example #10
Source File: JavaInstanceStarter.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private void registerDefaultCollectors(CollectorRegistry registry) {
    // Add the JMX exporter for functionality similar to the kafka connect JMX metrics
    try {
        new JmxCollector("{}").register(registry);
    } catch (MalformedObjectNameException ex) {
        System.err.println(ex);
    }
    // Add the default exports from io.prometheus.client.hotspot.DefaultExports
    new StandardExports().register(registry);
    new MemoryPoolsExports().register(registry);
    new BufferPoolsExports().register(registry);
    new GarbageCollectorExports().register(registry);
    new ThreadExports().register(registry);
    new ClassLoadingExports().register(registry);
    new VersionInfoExports().register(registry);
}
 
Example #11
Source File: PrometheusPublisher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) {
  this.globalRegistry = globalRegistry;

  //prometheus default port allocation is here : https://github.com/prometheus/prometheus/wiki/Default-port-allocations
  String address =
      DynamicPropertyFactory.getInstance().getStringProperty(METRICS_PROMETHEUS_ADDRESS, "0.0.0.0:9696").get();

  try {
    InetSocketAddress socketAddress = getSocketAddress(address);
    register();
    this.httpServer = new HTTPServer(socketAddress, CollectorRegistry.defaultRegistry, true);

    LOGGER.info("Prometheus httpServer listened : {}.", address);
  } catch (Exception e) {
    throw new ServiceCombException("create http publish server failed,may bad address : " + address, e);
  }
}
 
Example #12
Source File: PrometheusReporterTaskScopeTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void gaugesCanBeAddedSeveralTimesIfTheyDifferInLabels() throws UnirestException {
	Gauge<Integer> gauge1 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 3;
		}
	};
	Gauge<Integer> gauge2 = new Gauge<Integer>() {
		@Override
		public Integer getValue() {
			return 4;
		}
	};

	taskMetricGroup1.gauge("my_gauge", gauge1);
	taskMetricGroup2.gauge("my_gauge", gauge2);

	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_gauge", LABEL_NAMES, labelValues1),
		equalTo(3.));
	assertThat(CollectorRegistry.defaultRegistry.getSampleValue("flink_taskmanager_job_task_my_gauge", LABEL_NAMES, labelValues2),
		equalTo(4.));
}
 
Example #13
Source File: PrometheusServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("PrometheusServer Do get called");
    }

    ServletOutputStream response = resp.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(response);

    for(Function<ReportingContext, CollectorRegistry> mc : metricsCollectors) {
        CollectorRegistry collectorRegistry = mc.apply(getReportingContext());
        TextFormat.write004(osw, collectorRegistry.metricFamilySamples());
    }

    osw.flush();
    osw.close();
    response.flush();
    response.close();
    resp.setHeader("Content-Type", TextFormat.CONTENT_TYPE_004);
    resp.setStatus(HttpURLConnection.HTTP_OK);
    resp.flushBuffer();
}
 
Example #14
Source File: Graphite.java    From client_java with Apache License 2.0 6 votes vote down vote up
/**
 * Push samples from the given registry to Graphite.
 */
public void push(CollectorRegistry registry) throws IOException {
  Socket s = new Socket(host, port);
  BufferedWriter writer = new BufferedWriter(new PrintWriter(s.getOutputStream()));
  Matcher m = INVALID_GRAPHITE_CHARS.matcher("");
  long now = System.currentTimeMillis() / 1000;
  for (Collector.MetricFamilySamples metricFamilySamples: Collections.list(registry.metricFamilySamples())) {
    for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) {
      m.reset(sample.name);
      writer.write(m.replaceAll("_"));
      for (int i = 0; i < sample.labelNames.size(); ++i) {
        m.reset(sample.labelValues.get(i));
        writer.write("." + sample.labelNames.get(i) + "." + m.replaceAll("_"));
      }
      writer.write(" " + sample.value + " " + now + "\n");
    }
  }
  writer.close();
  s.close();
}
 
Example #15
Source File: PrometheusServlet.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String securityToken =
      (String) getServletContext().getAttribute(SECURITY_TOKEN);
  if (securityToken != null) {
    String authorizationHeader = req.getHeader("Authorization");
    if (authorizationHeader == null
        || !authorizationHeader.startsWith(BEARER)
        || !securityToken.equals(
            authorizationHeader.substring(BEARER.length() + 1))) {
      resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
      return;
    }
  }
  DefaultMetricsSystem.instance().publishMetricsNow();
  PrintWriter writer = resp.getWriter();
  getPrometheusSink().writeMetrics(writer);
  writer.write("\n\n#Dropwizard metrics\n\n");
  //print out dropwizard metrics used by ratis.
  TextFormat.write004(writer,
      CollectorRegistry.defaultRegistry.metricFamilySamples());
  writer.flush();
}
 
Example #16
Source File: PrometheusMetric.java    From athenz with Apache License 2.0 5 votes vote down vote up
/**
 * @param registry CollectorRegistry of all metrics
 * @param exporter Prometheus metrics exporter
 * @param namespace prefix of all metrics
 * @param isLabelRequestDomainNameEnable enable requestDomainName label
 * @param isLabelPrincipalDomainNameEnable enable principalDomainName label
 */
public PrometheusMetric(CollectorRegistry registry, ConcurrentMap<String, Collector> namesToCollectors, PrometheusExporter exporter, String namespace, boolean isLabelRequestDomainNameEnable, boolean isLabelPrincipalDomainNameEnable) {
    this.registry = registry;
    this.namesToCollectors = namesToCollectors;
    this.exporter = exporter;
    this.namespace = namespace;

    this.isLabelRequestDomainNameEnable = isLabelRequestDomainNameEnable;
    this.isLabelPrincipalDomainNameEnable = isLabelPrincipalDomainNameEnable;
}
 
Example #17
Source File: InternalMetrics.java    From promregator with Apache License 2.0 5 votes vote down vote up
@PostConstruct
@SuppressWarnings("PMD.UnusedPrivateMethod")
// method is required and called by the Spring Framework
private void registerMetrics() {
	if (!this.enabled)
		return;
	
	this.latencyCFFetch = Histogram.build("promregator_cffetch_latency", "Latency on retrieving CF values")
			.labelNames("request_type").linearBuckets(0.1, 0.1, 50).register();
	
	this.autoRefreshingCacheMapSize = Gauge.build("promregator_autorefreshingcachemap_size", "The size of objects stored in an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	
	this.autoRefreshingCacheMapExpiry = Counter.build("promregator_autorefreshingcachemap_expiry", "The number of objects having expired so far in an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	this.autoRefreshingCacheMapRefreshSuccess = Counter.build("promregator_autorefreshingcachemap_refresh_success", "The number of successful refreshes of object so far in an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	this.autoRefreshingCacheMapRefreshFailure = Counter.build("promregator_autorefreshingcachemap_refresh_failure", "The number of failed refreshes of object so far in an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	
	this.autoRefreshingCacheMapErroneousEntryDisplaced = Counter.build("promregator_autorefreshingcachemap_erroneous_entry_displaced", "The number of cache items displaced in an AutoRefreshingCacheMap, because they were detected to be erroneous")
			.labelNames(CACHE_MAP_NAME).register();

	this.autoRefreshingCacheMapLastScan = Gauge.build("promregator_autorefreshingcachemap_scantimestamp", "The timestamp of the last execution of the RefreshThread execution of an AutoRefreshingCacheMap")
			.labelNames(CACHE_MAP_NAME).register();
	
	this.connectionWatchdogReconnects = Counter.build("promregator_connection_watchdog_reconnect", "The number of reconnection attempts made by the Connection Watchdog")
			.register();
	
	this.caffeineCacheMetricsCollector = new CacheMetricsCollector().register();
	
	this.rateLimitWaitTime = Histogram.build("promregator_cffetch_ratelimit_waittime", "Wait time due to CFCC rate limiting")
			.labelNames("request_type").linearBuckets(0.0, 0.05, 50).register();
	
	CollectorRegistry.defaultRegistry.register(new InternalCollector());
}
 
Example #18
Source File: OMetricsResource.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private WriteCallback createWriteCallback(CollectorRegistry registry, Set<String> metrics) {
    return new WriteCallback() {
        @Override
        public void writeData(IResource.Attributes attributes) throws IOException {
try(OutputStreamWriter writer = new OutputStreamWriter(attributes.getResponse().getOutputStream(), "UTF8")) {
	TextFormat.write004(writer, registry.filteredMetricFamilySamples(metrics));
	writer.flush();
}
        }
    };
}
 
Example #19
Source File: QueuedThreadPoolStatisticsCollector.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 (queuedThreadPoolMap.isEmpty()) {
    throw new IllegalStateException("You must register at least one QueuedThreadPool.");
  }
  return super.register(registry);
}
 
Example #20
Source File: MethodTimerTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testOverloadedMethodName() throws Exception {
    final int sleep1 = 100, sleep2 = 200;

    SameMethodNameTest r = getProxy(new SameMethodNameTest() {
        @Override
        @PrometheusTimeMethod(name="dosomething_one_test_seconds", help = "halp")
        public void doSomething() throws Exception {
            Thread.sleep(sleep1);
        }

        @Override
        @PrometheusTimeMethod(name = "dosomething_two_test_seconds", help = "also halp")
        public void doSomething(String s) throws Exception {
            Thread.sleep(sleep2);
        }
    });

    r.doSomething();
    r.doSomething("foobar");

    final Double tot1 = CollectorRegistry.defaultRegistry.getSampleValue("dosomething_one_test_seconds_sum");
    final Double tot2 = CollectorRegistry.defaultRegistry.getSampleValue("dosomething_two_test_seconds_sum");

    assertEquals(.001*sleep2, tot2,.01);
    assertEquals(.001*sleep1, tot1, .01);
}
 
Example #21
Source File: HTTPServer.java    From client_java with Apache License 2.0 5 votes vote down vote up
/**
 * Start a HTTP server serving Prometheus metrics from the given registry using the given {@link HttpServer}.
 * The {@code httpServer} is expected to already be bound to an address
 */
public HTTPServer(HttpServer httpServer, CollectorRegistry registry, boolean daemon) throws IOException {
    if (httpServer.getAddress() == null)
        throw new IllegalArgumentException("HttpServer hasn't been bound to an address");

    server = httpServer;
    HttpHandler mHandler = new HTTPMetricHandler(registry);
    server.createContext("/", mHandler);
    server.createContext("/metrics", mHandler);
    server.createContext("/-/healthy", mHandler);
    executorService = Executors.newFixedThreadPool(5, NamedDaemonThreadFactory.defaultThreadFactory(daemon));
    server.setExecutor(executorService);
    start(daemon);
}
 
Example #22
Source File: ClientMetrics.java    From java-grpc-prometheus with Apache License 2.0 5 votes vote down vote up
Factory(Configuration configuration) {
  CollectorRegistry registry = configuration.getCollectorRegistry();
  this.rpcStarted = rpcStartedBuilder.register(registry);
  this.rpcCompleted = rpcCompletedBuilder.register(registry);
  this.streamMessagesReceived = streamMessagesReceivedBuilder.register(registry);
  this.streamMessagesSent = streamMessagesSentBuilder.register(registry);

  if (configuration.isIncludeLatencyHistograms()) {
    this.completedLatencySeconds = Optional.of(ClientMetrics.completedLatencySecondsBuilder
        .buckets(configuration.getLatencyBuckets())
        .register(registry));
  } else {
    this.completedLatencySeconds = Optional.empty();
  }
}
 
Example #23
Source File: AbstractPrometheusReporter.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void notifyOfRemovedMetric(final Metric metric, final String metricName, final MetricGroup group) {

	List<String> dimensionValues = new LinkedList<>();
	for (final Map.Entry<String, String> dimension : group.getAllVariables().entrySet()) {
		dimensionValues.add(labelValueCharactersFilter.filterCharacters(dimension.getValue()));
	}

	final String scopedMetricName = getScopedName(metricName, group);
	synchronized (this) {
		final AbstractMap.SimpleImmutableEntry<Collector, Integer> collectorWithCount = collectorsWithCountByMetricName.get(scopedMetricName);
		final Integer count = collectorWithCount.getValue();
		final Collector collector = collectorWithCount.getKey();

		removeMetric(metric, dimensionValues, collector);

		if (count == 1) {
			try {
				CollectorRegistry.defaultRegistry.unregister(collector);
			} catch (Exception e) {
				log.warn("There was a problem unregistering metric {}.", scopedMetricName, e);
			}
			collectorsWithCountByMetricName.remove(scopedMetricName);
		} else {
			collectorsWithCountByMetricName.put(scopedMetricName, new AbstractMap.SimpleImmutableEntry<>(collector, count - 1));
		}
	}
}
 
Example #24
Source File: AbstractMetricsEndpoint.java    From promregator with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void setupOwnRequestScopedMetrics() {
	this.requestRegistry = new CollectorRegistry();
	
	Builder builder = Gauge.build("promregator_up", "Indicator, whether the target of promregator is available");
	
	if (this.isLabelEnrichmentEnabled()) {
		builder = builder.labelNames(CFAllLabelsMetricFamilySamplesEnricher.getEnrichingLabelNames());
	} else {
		builder = builder.labelNames(NullMetricFamilySamplesEnricher.getEnrichingLabelNames());
	}
	
	this.up = builder.register(this.requestRegistry);
}
 
Example #25
Source File: TestHTTPServer.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnbound() throws IOException {
  CollectorRegistry registry = new CollectorRegistry();
  try {
    HTTPServer s = new HTTPServer(HttpServer.create(), registry, true);
    s.stop();
    fail("Should refuse to use an unbound HttpServer");
  } catch (IllegalArgumentException expected) {
  }
}
 
Example #26
Source File: DMNResultMetricsBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    registry = CollectorRegistry.defaultRegistry;
}
 
Example #27
Source File: AbstractPrometheusReporter.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void notifyOfRemovedMetric(final Metric metric, final String metricName, final MetricGroup group) {

	List<String> dimensionValues = new LinkedList<>();
	for (final Map.Entry<String, String> dimension : group.getAllVariables().entrySet()) {
		dimensionValues.add(labelValueCharactersFilter.filterCharacters(dimension.getValue()));
	}

	final String scopedMetricName = getScopedName(metricName, group);
	synchronized (this) {
		final AbstractMap.SimpleImmutableEntry<Collector, Integer> collectorWithCount = collectorsWithCountByMetricName.get(scopedMetricName);
		final Integer count = collectorWithCount.getValue();
		final Collector collector = collectorWithCount.getKey();

		removeMetric(metric, dimensionValues, collector);

		if (count == 1) {
			try {
				CollectorRegistry.defaultRegistry.unregister(collector);
			} catch (Exception e) {
				log.warn("There was a problem unregistering metric {}.", scopedMetricName, e);
			}
			collectorsWithCountByMetricName.remove(scopedMetricName);
		} else {
			collectorsWithCountByMetricName.put(scopedMetricName, new AbstractMap.SimpleImmutableEntry<>(collector, count - 1));
		}
	}
}
 
Example #28
Source File: StandardExportsTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@Test
public void testBrokenProcStatusReturnsOtherStats() {
  class StatusReaderBroken extends StandardExports.StatusReader {
    BufferedReader procSelfStatusReader() throws FileNotFoundException {
      return new BufferedReader(new StringReader("Name:   cat\nVmSize:\n"));
    }
  }

  CollectorRegistry registry = new CollectorRegistry();
  new StandardExports(new StatusReaderBroken(), osBean, runtimeBean).register(registry);

  assertEquals(123 / 1.0E9,
    registry.getSampleValue("process_cpu_seconds_total", new String[]{}, new String[]{}), .0000001);
  assertNull(registry.getSampleValue("process_resident_memory_bytes", new String[]{}, new String[]{}));
}
 
Example #29
Source File: HystrixCommandTest.java    From prometheus-hystrix with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldIncrementTotalsForFailure() {
    // given
    final TestHystrixCommand command = new TestHystrixCommand("shouldIncrementCounterHistogram").willFail();

    // when
    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() {
            command.execute();
        }
    }).isExactlyInstanceOf(HystrixRuntimeException.class);

    // then
    assertThat(CollectorRegistry.defaultRegistry
            .getSampleValue("exampleapp_hystrix_command_total",
                    new String[]{"command_group", "command_name"},
                    new String[]{"group_shouldIncrementCounterHistogram",
                            "command_shouldIncrementCounterHistogram"}))
            .describedAs("counter of all executions in the histogram")
            .isEqualTo(1);

    assertThat(CollectorRegistry.defaultRegistry
            .getSampleValue("exampleapp_hystrix_command_error_total",
                    new String[]{"command_group", "command_name"},
                    new String[]{"group_shouldIncrementCounterHistogram",
                            "command_shouldIncrementCounterHistogram"}))
            .describedAs("counter of all executions in the histogram")
            .isEqualTo(1);

}
 
Example #30
Source File: RateLimiterMetricsCollectorTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    registry = new CollectorRegistry();
    rateLimiterRegistry = RateLimiterRegistry.ofDefaults();
    rateLimiter = rateLimiterRegistry.rateLimiter("backendA");

    RateLimiterMetricsCollector.ofRateLimiterRegistry(rateLimiterRegistry).register(registry);
}