Java Code Examples for io.vertx.micrometer.backends.BackendRegistries#getDefaultNow()

The following examples show how to use io.vertx.micrometer.backends.BackendRegistries#getDefaultNow() . 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: PrometheusScrapingHandlerImpl.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext rc) {
  MeterRegistry registry;
  if (registryName == null) {
    registry = BackendRegistries.getDefaultNow();
  } else {
    registry = BackendRegistries.getNow(registryName);
  }
  if (registry instanceof PrometheusMeterRegistry) {
    PrometheusMeterRegistry prometheusMeterRegistry = (PrometheusMeterRegistry) registry;
    rc.response()
      .putHeader(HttpHeaders.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
      .end(prometheusMeterRegistry.scrape());
  } else {
    String statusMessage = "Invalid registry: " + (registry != null ? registry.getClass().getName() : null);
    rc.response()
      .setStatusCode(500).setStatusMessage(statusMessage)
      .end();
  }
}
 
Example 2
Source File: AmqpBridgeServer.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        Vertx vertx = Vertx.vertx();

        Map<String, Object> config = new HashMap<>();
        BridgeConfig bridgeConfig = BridgeConfig.fromMap(config);
        MeterRegistry meterRegistry = BackendRegistries.getDefaultNow();
        
        AmqpBridge bridge = new AmqpBridge(bridgeConfig, new MetricsReporter(null, meterRegistry));

        vertx.deployVerticle(bridge);

        try {
            System.in.read();
            vertx.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 3
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
public void customTimerExample() {
  MeterRegistry registry = BackendRegistries.getDefaultNow();
  Timer timer = Timer
    .builder("my.timer")
    .description("a description of what this timer does")
    .register(registry);

  vertx.setPeriodic(1000, l -> {
    timer.record(() -> {
      // Running here some operation to monitor
    });
  });
}
 
Example 4
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
public void instrumentJVM() {
  MeterRegistry registry = BackendRegistries.getDefaultNow();

  new ClassLoaderMetrics().bindTo(registry);
  new JvmMemoryMetrics().bindTo(registry);
  new JvmGcMetrics().bindTo(registry);
  new ProcessorMetrics().bindTo(registry);
  new JvmThreadMetrics().bindTo(registry);
}
 
Example 5
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
public void useMicrometerFilters() {
  MeterRegistry registry = BackendRegistries.getDefaultNow();
  Pattern pattern = Pattern.compile("/foo/bar/.*");

  registry.config().meterFilter(
    MeterFilter.replaceTagValues(Label.HTTP_PATH.toString(), actualPath -> {
      Matcher m = pattern.matcher(actualPath);
      if (m.matches()) {
        return "/foo/bar/:id";
      }
      return actualPath;
    }, ""));
}
 
Example 6
Source File: UserOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public UserOperator(String namespace,
                    UserOperatorConfig config,
                    KubernetesClient client,
                    KafkaUserOperator kafkaUserOperator) {
    log.info("Creating UserOperator for namespace {}", namespace);
    this.namespace = namespace;
    this.reconciliationInterval = config.getReconciliationIntervalMs();
    this.client = client;
    this.kafkaUserOperator = kafkaUserOperator;
    this.metrics = (PrometheusMeterRegistry) BackendRegistries.getDefaultNow();
}
 
Example 7
Source File: Session.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public Session(KubernetesClient kubeClient, Config config) {
    this.kubeClient = kubeClient;
    this.config = config;
    StringBuilder sb = new StringBuilder(System.lineSeparator());
    for (Config.Value<?> v: Config.keys()) {
        sb.append("\t").append(v.key).append(": ").append(Util.maskPassword(v.key, config.get(v).toString())).append(System.lineSeparator());
    }
    LOGGER.info("Using config:{}", sb.toString());
    this.metricsRegistry = (PrometheusMeterRegistry) BackendRegistries.getDefaultNow();
}
 
Example 8
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 4 votes vote down vote up
public void accessDefaultRegistry() {
  MeterRegistry registry = BackendRegistries.getDefaultNow();
}
 
Example 9
Source File: Application.java    From strimzi-kafka-bridge with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"checkstyle:NPathComplexity"})
public static void main(String[] args) {
    log.info("Strimzi Kafka Bridge {} is starting", Application.class.getPackage().getImplementationVersion());
    try {
        VertxOptions vertxOptions = new VertxOptions();
        JmxCollectorRegistry jmxCollectorRegistry = null;
        if (Boolean.valueOf(System.getenv(KAFKA_BRIDGE_METRICS_ENABLED))) {
            log.info("Metrics enabled and exposed on the /metrics endpoint");
            // setup Micrometer metrics options
            vertxOptions.setMetricsOptions(metricsOptions());
            jmxCollectorRegistry = getJmxCollectorRegistry();
        }
        Vertx vertx = Vertx.vertx(vertxOptions);
        // MeterRegistry default instance is just null if metrics are not enabled in the VertxOptions instance
        MeterRegistry meterRegistry = BackendRegistries.getDefaultNow();
        MetricsReporter metricsReporter = new MetricsReporter(jmxCollectorRegistry, meterRegistry);


        CommandLine commandLine = new DefaultParser().parse(generateOptions(), args);

        ConfigStoreOptions fileStore = new ConfigStoreOptions()
                .setType("file")
                .setFormat("properties")
                .setConfig(new JsonObject().put("path", absoluteFilePath(commandLine.getOptionValue("config-file"))).put("raw-data", true));

        ConfigStoreOptions envStore = new ConfigStoreOptions()
                .setType("env")
                .setConfig(new JsonObject().put("raw-data", true));

        ConfigRetrieverOptions options = new ConfigRetrieverOptions()
                .addStore(fileStore)
                .addStore(envStore);

        ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
        retriever.getConfig(ar -> {

            if (ar.succeeded()) {
                Map<String, Object> config = ar.result().getMap();
                BridgeConfig bridgeConfig = BridgeConfig.fromMap(config);

                int embeddedHttpServerPort = Integer.parseInt(config.getOrDefault(EMBEDDED_HTTP_SERVER_PORT, DEFAULT_EMBEDDED_HTTP_SERVER_PORT).toString());

                if (bridgeConfig.getAmqpConfig().isEnabled() && bridgeConfig.getAmqpConfig().getPort() == embeddedHttpServerPort) {
                    log.error("Embedded HTTP server port {} conflicts with configured AMQP port", embeddedHttpServerPort);
                    System.exit(1);
                }

                List<Future> futures = new ArrayList<>();
                futures.add(deployAmqpBridge(vertx, bridgeConfig, metricsReporter));
                futures.add(deployHttpBridge(vertx, bridgeConfig, metricsReporter));

                CompositeFuture.join(futures).onComplete(done -> {
                    if (done.succeeded()) {
                        HealthChecker healthChecker = new HealthChecker();
                        for (int i = 0; i < futures.size(); i++) {
                            if (done.result().succeeded(i) && done.result().resultAt(i) != null) {
                                healthChecker.addHealthCheckable(done.result().resultAt(i));
                                // when HTTP protocol is enabled, it handles healthy/ready endpoints as well,
                                // so it needs the checker for asking other protocols bridges status
                                if (done.result().resultAt(i) instanceof HttpBridge) {
                                    ((HttpBridge) done.result().resultAt(i)).setHealthChecker(healthChecker);
                                }
                            }
                        }

                        // when HTTP protocol is enabled, it handles healthy/ready/metrics endpoints as well,
                        // so no need for a standalone embedded HTTP server
                        if (!bridgeConfig.getHttpConfig().isEnabled()) {
                            EmbeddedHttpServer embeddedHttpServer =
                                    new EmbeddedHttpServer(vertx, healthChecker, metricsReporter, embeddedHttpServerPort);
                            embeddedHttpServer.start();
                        }

                        // register OpenTracing Jaeger tracer
                        if ("jaeger".equals(bridgeConfig.getTracing())) {
                            if (config.get(Configuration.JAEGER_SERVICE_NAME) != null) {
                                Tracer tracer = Configuration.fromEnv().getTracer();
                                GlobalTracer.registerIfAbsent(tracer);
                            } else {
                                log.error("Jaeger tracing cannot be initialized because {} environment variable is not defined", Configuration.JAEGER_SERVICE_NAME);
                            }
                        }
                    }
                });
            } else {
                log.error("Error starting the bridge", ar.cause());
                System.exit(1);
            }
        });
    } catch (Exception ex) {
        log.error("Error starting the bridge", ex);
        System.exit(1);
    }
}
 
Example 10
Source File: MicrometerMetricsProvider.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor of the Micrometer metrics provider
 */
public MicrometerMetricsProvider() {
    this.metrics = BackendRegistries.getDefaultNow();
}