Java Code Examples for io.vertx.core.VertxOptions#setMetricsOptions()

The following examples show how to use io.vertx.core.VertxOptions#setMetricsOptions() . 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: DropwizardHelper.java    From okapi with Apache License 2.0 6 votes vote down vote up
/**
 * Configure Dropwizard helper.
 * @param graphiteHost graphite server host
 * @param port  graphits server port
 * @param tu time unit
 * @param period reporting period
 * @param vopt Vert.x options
 * @param hostName logical hostname for this node (reporting)
 */
public static void config(String graphiteHost, int port, TimeUnit tu,
        int period, VertxOptions vopt, String hostName) {
  final String registryName = "okapi";
  MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);

  DropwizardMetricsOptions metricsOpt = new DropwizardMetricsOptions();
  metricsOpt.setEnabled(true).setRegistryName(registryName);
  vopt.setMetricsOptions(metricsOpt);
  Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, port));
  final String prefix = "folio.okapi." + hostName;
  GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
          .prefixedWith(prefix)
          .build(graphite);
  reporter.start(period, tu);

  logger.info("Metrics remote {}:{} this {}", graphiteHost, port, prefix);
}
 
Example 2
Source File: VertxProperties.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Configures the Vert.x options based on this object's property values.
 *
 * @param options The options to configure.
 * @return The (updated) options.
 */
public VertxOptions configureVertx(final VertxOptions options) {

    options.setPreferNativeTransport(this.preferNative);

    if (this.enableMetrics) {
        options.setMetricsOptions(new MetricsOptions().setEnabled(true));
    }

    options.setMaxEventLoopExecuteTime(maxEventLoopExecuteTimeMillis * 1000000L);
    options.setWarningExceptionTime(maxEventLoopExecuteTimeMillis * 1500000L);
    options.setAddressResolverOptions(new AddressResolverOptions()
            .setCacheNegativeTimeToLive(0) // discard failed DNS lookup results immediately
            .setCacheMaxTimeToLive(0) // support DNS based service resolution
            .setQueryTimeout(dnsQueryTimeout));
    return options;
}
 
Example 3
Source File: RestLauncher.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeStartingVertx(VertxOptions options) {
  // TODO Auto-generated method stub
  super.beforeStartingVertx(options);

  System.out.println("starting rest verticle service..........");
  options.setBlockedThreadCheckInterval(1500000);
  options.setWarningExceptionTime(1500000);
  boolean enabled = options.getMetricsOptions().isEnabled();
  options.setMetricsOptions(new DropwizardMetricsOptions().setEnabled(enabled).addMonitoredHttpServerUri(
      new Match().setValue("/.*").setType(MatchType.REGEX)));
}
 
Example 4
Source File: VertxProperties.java    From vertx-spring-boot with Apache License 2.0 4 votes vote down vote up
public VertxOptions toVertxOptions() {
    VertxOptions vertxOptions = new VertxOptions();
    vertxOptions.setEventLoopPoolSize(eventLoopPoolSize);
    vertxOptions.setWorkerPoolSize(workerPoolSize);
    vertxOptions.setInternalBlockingPoolSize(internalBlockingPoolSize);
    vertxOptions.setBlockedThreadCheckInterval(blockedThreadCheckInterval);
    vertxOptions.setMaxEventLoopExecuteTime(maxEventLoopExecuteTime);
    vertxOptions.setMaxWorkerExecuteTime(maxWorkerExecuteTime);
    vertxOptions.setHAEnabled(haEnabled);
    vertxOptions.setQuorumSize(quorumSize);
    vertxOptions.setHAGroup(haGroup);
    vertxOptions.setWarningExceptionTime(warningExceptionTime);
    vertxOptions.setPreferNativeTransport(preferNativeTransport);
    vertxOptions.setMaxEventLoopExecuteTimeUnit(maxEventLoopExecuteTimeUnit);
    vertxOptions.setMaxWorkerExecuteTimeUnit(maxWorkerExecuteTimeUnit);
    vertxOptions.setWarningExceptionTimeUnit(warningExceptionTimeUnit);
    vertxOptions.setBlockedThreadCheckIntervalUnit(blockedThreadCheckIntervalUnit);

    MetricsOptions metricsOptions = new MetricsOptions();
    metricsOptions.setEnabled(metricsEnabled);
    vertxOptions.setMetricsOptions(metricsOptions);

    FileSystemOptions fileSystemOptions = new FileSystemOptions();
    fileSystemOptions.setClassPathResolvingEnabled(fileSystem.isClassPathResolvingEnabled());
    fileSystemOptions.setFileCachingEnabled(fileSystem.isFileCachingEnabled());
    vertxOptions.setFileSystemOptions(fileSystemOptions);

    AddressResolverOptions addressResolverOptions = new AddressResolverOptions();
    addressResolverOptions.setHostsPath(addressResolver.getHostsPath());
    addressResolverOptions.setHostsValue(addressResolver.getHostsValue());
    addressResolverOptions.setServers(addressResolver.getServers());
    addressResolverOptions.setOptResourceEnabled(addressResolver.isOptResourceEnabled());
    addressResolverOptions.setCacheMinTimeToLive(addressResolver.getCacheMinTimeToLive());
    addressResolverOptions.setCacheMaxTimeToLive(addressResolver.getCacheMaxTimeToLive());
    addressResolverOptions.setCacheNegativeTimeToLive(addressResolver.getCacheNegativeTimeToLive());
    addressResolverOptions.setQueryTimeout(addressResolver.getQueryTimeout());
    addressResolverOptions.setMaxQueries(addressResolver.getMaxQueries());
    addressResolverOptions.setRdFlag(addressResolver.isRdFlag());
    addressResolverOptions.setSearchDomains(addressResolver.getSearchDomains());
    addressResolverOptions.setNdots(addressResolver.getNdots());
    addressResolverOptions.setRotateServers(addressResolver.isRotateServers());
    vertxOptions.setAddressResolverOptions(addressResolverOptions);

    return vertxOptions;
}
 
Example 5
Source File: Main.java    From quarantyne with Apache License 2.0 4 votes vote down vote up
public static void main(String...args) {
  InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);

  ConfigArgs configArgs = ConfigArgs.parse(args);

  // load assets or die
  try {
    weakOrBreachedPwBf = BloomFilters.deserialize(AssetRegistry.getCompromisedPasswords());
    disposableMxBf = BloomFilters.deserialize(AssetRegistry.getDisposableEmails());
    awsIpMembership = new CidrMembership<>(AssetRegistry.getAwsIps(), "aws");
    gcpIpMembership = new CidrMembership<>(AssetRegistry.getGcpIps(), "gcp");
  } catch (AssetException ex) {
    log.error("error while reading asset", ex);
    System.exit(-1);
  }

  final GeoIp4j geoIp4j = new GeoIp4jImpl();

  log.info("{} <= quarantyne => {}", configArgs.getIngress().toHuman(), configArgs.getEgress().toHuman());

  configArgs.getAdminIpPort().ifPresent(ipPort -> {
    log.info("==> admin @ http://{}:{}", ipPort.getIp(), ipPort.getPort());
  });

  log.info("see available options with --help");
  int numCpus = CpuCoreSensor.availableProcessors();

  VertxOptions vertxOptions = new VertxOptions();
  vertxOptions.setPreferNativeTransport(true);
  vertxOptions.setMetricsOptions(
      new DropwizardMetricsOptions().setEnabled(true)
  );

  log.debug("==> event loop size is {}", vertxOptions.getEventLoopPoolSize());
  log.debug("==> detected {} cpus core", numCpus);
  Vertx vertx = Vertx.vertx(vertxOptions);

  ConfigSupplier configSupplier;
  if (configArgs.getConfigFile().isPresent()) {
    configSupplier = new ConfigSupplier(vertx,
        new ConfigRetrieverOptionsSupplier(configArgs.getConfigFile().get()));
  } else {
    log.info("No configuration file was specified, using default settings");
    configSupplier = new ConfigSupplier();
  }

  // quarantyne classifiers
  List<HttpRequestClassifier> httpRequestClassifierList = Lists.newArrayList(
      new FastAgentClassifier(),
      new IpRotationClassifier(),
      new SuspiciousRequestHeadersClassifier(),
      new SuspiciousUserAgentClassifier(),
      new LargeBodySizeClassifier(),
      new CompromisedPasswordClassifier(weakOrBreachedPwBf, configSupplier),
      new DisposableEmailClassifier(disposableMxBf, configSupplier),
      new GeoDiscrepancyClassifier(geoIp4j, configSupplier),
      new PublicCloudExecutionClassifier(awsIpMembership, gcpIpMembership)
      // new SuspiciousLoginActivityClassifier(geoIp4j)
  );

  MainClassifier mainClassifier = new MainClassifier(httpRequestClassifierList);

  if (configArgs.getAdminIpPort().isPresent()) {
    vertx.deployVerticle(new AdminVerticle(configArgs.getAdminIpPort().get()));
  }

  vertx.deployVerticle(() -> new ProxyVerticle(configArgs, mainClassifier,
          configSupplier),
      new DeploymentOptions().setInstances(numCpus * 2 + 1));

  vertx.deployVerticle(() -> new WarmupVerticle(configArgs),
      new DeploymentOptions(),
      warmupVerticle -> {
        vertx.undeploy(warmupVerticle.result());
      });

  vertx.exceptionHandler(ex -> {
    log.error("uncaught exception", ex);
  });
}
 
Example 6
Source File: VxApiLauncher.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
/**
 * 初始化vert.x的配置文件<br>
 * This method copy from the {@link io.vertx.core.VertxOptionsConverter}
 * fromJson
 * 
 * @param json
 * @param obj
 */
public void initVertxConfig(JsonObject json, VertxOptions obj) {

	if (json.getValue("addressResolverOptions") instanceof JsonObject) {
		obj.setAddressResolverOptions(new io.vertx.core.dns.AddressResolverOptions((JsonObject) json.getValue("addressResolverOptions")));
	}
	if (json.getValue("blockedThreadCheckInterval") instanceof Number) {
		obj.setBlockedThreadCheckInterval(((Number) json.getValue("blockedThreadCheckInterval")).longValue());
	}
	if (json.getValue("clusterHost") instanceof String) {
		obj.setClusterHost((String) json.getValue("clusterHost"));
	}
	if (json.getValue("clusterPingInterval") instanceof Number) {
		obj.setClusterPingInterval(((Number) json.getValue("clusterPingInterval")).longValue());
	}
	if (json.getValue("clusterPingReplyInterval") instanceof Number) {
		obj.setClusterPingReplyInterval(((Number) json.getValue("clusterPingReplyInterval")).longValue());
	}
	if (json.getValue("clusterPort") instanceof Number) {
		obj.setClusterPort(((Number) json.getValue("clusterPort")).intValue());
	}
	if (json.getValue("clusterPublicHost") instanceof String) {
		obj.setClusterPublicHost((String) json.getValue("clusterPublicHost"));
	}
	if (json.getValue("clusterPublicPort") instanceof Number) {
		obj.setClusterPublicPort(((Number) json.getValue("clusterPublicPort")).intValue());
	}
	if (json.getValue("clustered") instanceof Boolean) {
		obj.setClustered((Boolean) json.getValue("clustered"));
	}
	if (json.getValue("eventBusOptions") instanceof JsonObject) {
		obj.setEventBusOptions(new io.vertx.core.eventbus.EventBusOptions((JsonObject) json.getValue("eventBusOptions")));
	}
	if (json.getValue("eventLoopPoolSize") instanceof Number) {
		obj.setEventLoopPoolSize(((Number) json.getValue("eventLoopPoolSize")).intValue());
	}
	if (json.getValue("fileResolverCachingEnabled") instanceof Boolean) {
		obj.setFileResolverCachingEnabled((Boolean) json.getValue("fileResolverCachingEnabled"));
	}
	if (json.getValue("haEnabled") instanceof Boolean) {
		obj.setHAEnabled((Boolean) json.getValue("haEnabled"));
	}
	if (json.getValue("haGroup") instanceof String) {
		obj.setHAGroup((String) json.getValue("haGroup"));
	}
	if (json.getValue("internalBlockingPoolSize") instanceof Number) {
		obj.setInternalBlockingPoolSize(((Number) json.getValue("internalBlockingPoolSize")).intValue());
	}
	if (json.getValue("maxEventLoopExecuteTime") instanceof Number) {
		obj.setMaxEventLoopExecuteTime(((Number) json.getValue("maxEventLoopExecuteTime")).longValue());
	}
	if (json.getValue("maxWorkerExecuteTime") instanceof Number) {
		obj.setMaxWorkerExecuteTime(((Number) json.getValue("maxWorkerExecuteTime")).longValue());
	}
	if (json.getValue("metricsOptions") instanceof JsonObject) {
		obj.setMetricsOptions(new io.vertx.core.metrics.MetricsOptions((JsonObject) json.getValue("metricsOptions")));
	}
	if (json.getValue("preferNativeTransport") instanceof Boolean) {
		obj.setPreferNativeTransport((Boolean) json.getValue("preferNativeTransport"));
	}
	if (json.getValue("quorumSize") instanceof Number) {
		obj.setQuorumSize(((Number) json.getValue("quorumSize")).intValue());
	}
	if (json.getValue("warningExceptionTime") instanceof Number) {
		obj.setWarningExceptionTime(((Number) json.getValue("warningExceptionTime")).longValue());
	}
	if (json.getValue("workerPoolSize") instanceof Number) {
		obj.setWorkerPoolSize(((Number) json.getValue("workerPoolSize")).intValue());
	}

}
 
Example 7
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);
    }
}