io.prometheus.client.exporter.MetricsServlet Java Examples

The following examples show how to use io.prometheus.client.exporter.MetricsServlet. 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: IrisMetricsExporter.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void start() {
   logger.info("Starting metrics server on port {}", config.getMetricsHttpPort());

   this.executor.execute(() -> {
      Server server = new Server(this.config.getMetricsHttpPort());
      ServletContextHandler context = new ServletContextHandler();
      context.setContextPath("/");
      server.setHandler(context);
      context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");

      try {
         server.start();
         server.join();
      } catch (Exception e) { // server.start throws Exception, so can't be more general here.
         logger.error("Failed to start metrics exporter", e);
      }
   });
}
 
Example #2
Source File: ProxyServiceStarter.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public static void addWebServerHandlers(WebServer server,
                                 ProxyConfiguration config,
                                 ProxyService service,
                                 BrokerDiscoveryProvider discoveryProvider) {
    server.addServlet("/metrics", new ServletHolder(MetricsServlet.class), Collections.emptyList(), config.isAuthenticateMetricsEndpoint());
    server.addRestResources("/", VipStatus.class.getPackage().getName(),
            VipStatus.ATTRIBUTE_STATUS_FILE_PATH, config.getStatusFilePath());
    server.addRestResources("/proxy-stats", ProxyStats.class.getPackage().getName(), ProxyStats.ATTRIBUTE_PULSAR_PROXY_NAME, service);

    AdminProxyHandler adminProxyHandler = new AdminProxyHandler(config, discoveryProvider);
    ServletHolder servletHolder = new ServletHolder(adminProxyHandler);
    servletHolder.setInitParameter("preserveHost", "true");
    server.addServlet("/admin", servletHolder);
    server.addServlet("/lookup", servletHolder);

    for (ProxyConfiguration.HttpReverseProxyConfig revProxy : config.getHttpReverseProxyConfigs()) {
        log.debug("Adding reverse proxy with config {}", revProxy);
        ServletHolder proxyHolder = new ServletHolder(ProxyServlet.Transparent.class);
        proxyHolder.setInitParameter("proxyTo", revProxy.getProxyTo());
        proxyHolder.setInitParameter("prefix", "/");
        server.addServlet(revProxy.getPath(), proxyHolder);
    }
}
 
Example #3
Source File: ZooKeeperStarter.java    From pulsar with Apache License 2.0 6 votes vote down vote up
protected static void start(String[] args, String defaultStatsPort) throws Exception {
    // Register basic JVM metrics
    DefaultExports.initialize();

    // Start Jetty to serve stats
    int port = Integer.parseInt(System.getProperties().getProperty("stats_server_port", defaultStatsPort));

    log.info("Starting ZK stats HTTP server at port {}", port);
    InetSocketAddress httpEndpoint = InetSocketAddress.createUnresolved("0.0.0.0", port);

    Server server = new Server(httpEndpoint);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    try {
        server.start();
    } catch (Exception e) {
        log.error("Failed to start HTTP server at port {}. Use \"-Dstats_server_port=1234\" to change port number",
                port, e);
        throw e;
    }

    // Start the regular ZooKeeper server
    QuorumPeerMain.main(args);
}
 
Example #4
Source File: JavaDropwizard.java    From java_examples with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
    // Increment the counter.
    counter.inc();

    // Hook the Dropwizard registry into the Prometheus registry
    // via the DropwizardExports collector.
    CollectorRegistry.defaultRegistry.register(new DropwizardExports(metrics));


    // Expose Prometheus metrics.
    Server server = new Server(1234);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    // Add metrics about CPU, JVM memory etc.
    DefaultExports.initialize();
    // Start the webserver.
    server.start();
    server.join();
}
 
Example #5
Source File: JavaSimple.java    From java_examples with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
    Server server = new Server(1234);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    // Expose our example servlet.
    context.addServlet(new ServletHolder(new ExampleServlet()), "/");
    // Expose Promtheus metrics.
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    // Add metrics about CPU, JVM memory etc.
    DefaultExports.initialize();


    // Start the webserver.
    server.start();
    server.join();
}
 
Example #6
Source File: PrometheusServer.java    From cineast with MIT License 5 votes vote down vote up
public static synchronized void initialize() {
  if (initalized) {
    LOGGER.info("Prometheus already initalized");
    return;
  }
  if (!Config.sharedConfig().getMonitoring().enablePrometheus) {
    LOGGER.info("Prometheus monitoring not enabled");
    return;
  }
  DefaultExports.initialize();
  Integer port = Config.sharedConfig().getMonitoring().prometheusPort;
  LOGGER.info("Initalizing Prometheus endpoint at port {}", port);
  server = Optional.of(new Server(port));
  ServletContextHandler context = new ServletContextHandler();
  context.setContextPath("/");
  server.get().setHandler(context);
  context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
  PrometheusExtractionTaskMonitor.init();
  ImportTaskMonitor.init();
  DatabaseHealthMonitor.init();
  RetrievalTaskMonitor.init();
  try {
    server.get().start();
  } catch (Exception e) {
    e.printStackTrace();
  }
  initalized = true;
}
 
Example #7
Source File: ExampleExporter.java    From client_java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  DefaultExports.initialize();
  Server server = new Server(1234);
  ServletContextHandler context = new ServletContextHandler();
  context.setContextPath("/");
  server.setHandler(context);
  context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
  server.start();
  server.join();
}
 
Example #8
Source File: PrometheusTelemetryManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean start(String name) {
    boolean success = false;
    TelemetryConfig config = telemetryConfigService.getConfig(name);
    PrometheusTelemetryConfig prometheusConfig = fromTelemetryConfig(config);

    if (prometheusConfig != null && !config.name().equals(PROMETHEUS_SCHEME) &&
            config.status() == ENABLED) {
        try {
            // TODO  Offer a 'Authentication'
            Server prometheusExporter = new Server(prometheusConfig.port());
            ServletContextHandler context = new ServletContextHandler();
            context.setContextPath("/");
            prometheusExporter.setHandler(context);
            context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");

            log.info("Prometheus server start");

            prometheusExporter.start();

            prometheusExporters.put(name, prometheusExporter);

            success = true;

        } catch (Exception ex) {
            log.warn("Failed to start prometheus server due to {}", ex);
        }
    }

    return success;
}
 
Example #9
Source File: WebServer.java    From cloudwatch_exporter with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println("Usage: WebServer <port> <yml configuration file>");
        System.exit(1);
    }

    configFilePath = args[1];
    CloudWatchCollector collector = null;
    FileReader reader = null;

    try {
      reader = new FileReader(configFilePath);
      collector = new CloudWatchCollector(new FileReader(configFilePath)).register();
    } finally {
      if (reader != null) {
        reader.close();
      }
    }

    ReloadSignalHandler.start(collector);

    int port = Integer.parseInt(args[0]);
    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    context.addServlet(new ServletHolder(new DynamicReloadServlet(collector)), "/-/reload");
    context.addServlet(new ServletHolder(new HealthServlet()), "/-/healthy");
    context.addServlet(new ServletHolder(new HealthServlet()), "/-/ready");
    context.addServlet(new ServletHolder(new HomePageServlet()), "/");
    server.start();
    server.join();
}
 
Example #10
Source File: PrometheusServlet.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Activate
public void activate(ComponentContext componentContext) throws Exception {
    if (componentContext.getProperties().get("alias") != null) {
        alias = componentContext.getProperties().get("alias").toString();
    }
    httpService.registerServlet(alias, new MetricsServlet(), null, null);
}
 
Example #11
Source File: WebServer.java    From cloudwatch_exporter with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println("Usage: WebServer <port> <yml configuration file>");
        System.exit(1);
    }

    configFilePath = args[1];
    CloudWatchCollector collector = null;
    FileReader reader = null;

    try {
      reader = new FileReader(configFilePath);
      collector = new CloudWatchCollector(new FileReader(configFilePath)).register();
    } finally {
      if (reader != null) {
        reader.close();
      }
    }

    ReloadSignalHandler.start(collector);

    int port = Integer.parseInt(args[0]);
    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    context.addServlet(new ServletHolder(new DynamicReloadServlet(collector)), "/-/reload");
    context.addServlet(new ServletHolder(new HealthServlet()), "/-/healthy");
    context.addServlet(new ServletHolder(new HealthServlet()), "/-/ready");
    context.addServlet(new ServletHolder(new HomePageServlet()), "/");
    server.start();
    server.join();
}
 
Example #12
Source File: PrometheusAutoConfiguration.java    From orders with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "prometheusMetricsServletRegistrationBean")
ServletRegistrationBean prometheusMetricsServletRegistrationBean(@Value("${prometheus.metrics" +
        ".path:/metrics}") String metricsPath) {
    DefaultExports.initialize();
    return new ServletRegistrationBean(new MetricsServlet(), metricsPath);
}
 
Example #13
Source File: MetricsConfiguration.java    From ehcache3-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) {

    if (jHipsterProperties.getMetrics().getPrometheus().isEnabled()) {
        String endpoint = jHipsterProperties.getMetrics().getPrometheus().getEndpoint();

        log.debug("Initializing prometheus metrics exporting via {}", endpoint);

        CollectorRegistry.defaultRegistry.register(new DropwizardExports(metricRegistry));
        servletContext
            .addServlet("prometheusMetrics", new MetricsServlet(CollectorRegistry.defaultRegistry))
            .addMapping(endpoint);
    }
}
 
Example #14
Source File: Kruize.java    From kruize with Apache License 2.0 5 votes vote down vote up
private static void addServlets(ServletContextHandler context)
{
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    context.addServlet(RecommendationsService.class, "/recommendations");
    context.addServlet(ListApplicationsService.class, "/listApplications");
    context.addServlet(HealthService.class, "/health");
}
 
Example #15
Source File: PrometheusAutoConfiguration.java    From shipping with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "prometheusMetricsServletRegistrationBean")
ServletRegistrationBean prometheusMetricsServletRegistrationBean(@Value("${prometheus.metrics" +
        ".path:/metrics}") String metricsPath) {
    DefaultExports.initialize();
    return new ServletRegistrationBean(new MetricsServlet(), metricsPath);
}
 
Example #16
Source File: MetricsContextListener.java    From javametrics with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
    // Uncomment the next line to enable the default hotspot events.
    // DefaultExports.initialize();

    metrics = new Metrics();
    ServletContext context = event.getServletContext();
    context.addServlet("Metrics", new MetricsServlet()).addMapping("");
}
 
Example #17
Source File: MetricsConfiguration.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) {

    if (jHipsterProperties.getMetrics().getPrometheus().isEnabled()) {
        String endpoint = jHipsterProperties.getMetrics().getPrometheus().getEndpoint();

        log.debug("Initializing prometheus metrics exporting via {}", endpoint);

        CollectorRegistry.defaultRegistry.register(new DropwizardExports(metricRegistry));
        servletContext
            .addServlet("prometheusMetrics", new MetricsServlet(CollectorRegistry.defaultRegistry))
            .addMapping(endpoint);
    }
}
 
Example #18
Source File: HealthCheckExporter.java    From hellokoding-courses with MIT License 5 votes vote down vote up
public void export() throws Exception {
    CollectorRegistry.defaultRegistry.register(this.healthChecksCollector);

    Server server = new Server(8080);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);

    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    DefaultExports.initialize();

    server.start();
    server.join();
}
 
Example #19
Source File: TaskApp.java    From osgi-best-practices with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Object> getSingletons() {
    return Set.of(
            taskResource,
            new MetricsServlet(registry),
            new OpenApiResource());
}
 
Example #20
Source File: Metrics.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a custom Prometheus Collector registry, registers
 * the dropwizard metrics with this registry, and attaches
 * it to a MetricsServlet, which is returned to the caller.
 */
public static Servlet createMetricsServlet() {
  CollectorRegistry registry = new CollectorRegistry();
  registry.register(new DropwizardExports(RegistryHolder.REGISTRY));
  return new MetricsServlet(registry);
}
 
Example #21
Source File: Application.java    From sqs-exporter with Apache License 2.0 4 votes vote down vote up
private void go() throws Exception {
	DefaultExports.initialize();
	new Sqs().register();

	Server server = new Server(9384);

	ServletHandler handler = new ServletHandler();
	server.setHandler(handler);
	handler.addServletWithMapping(IndexServlet.class, "/");
	handler.addServletWithMapping(MetricsServlet.class, "/metrics");
	handler.addFilterWithMapping(DisableMethodsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

	server.start();

	logger.info("Exporter has started.");
	startup.inc();
	
	HttpGenerator.setJettyVersion("");

	server.join();

}
 
Example #22
Source File: App.java    From modeldb with Apache License 2.0 4 votes vote down vote up
@Bean
public ServletRegistrationBean<MetricsServlet> servletRegistrationBean() {
  DefaultExports.initialize();
  return new ServletRegistrationBean<>(new MetricsServlet(), "/metrics");
}
 
Example #23
Source File: PrometheusServletConfiguration.java    From java-metrics with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnProperty(name="OPENTRACING_METRICS_EXPORTER_HTTP_PATH")
ServletRegistrationBean registerPrometheusExporterServlet() {
    return new ServletRegistrationBean(new MetricsServlet(collectorRegistry), metricsPath);
}
 
Example #24
Source File: InstrumentationConfig.java    From feast with Apache License 2.0 4 votes vote down vote up
@Bean
public ServletRegistrationBean servletRegistrationBean() {
  DefaultExports.initialize();
  return new ServletRegistrationBean(new MetricsServlet(), "/metrics");
}
 
Example #25
Source File: MonitoringConfig.java    From feast with Apache License 2.0 2 votes vote down vote up
/**
 * Add Prometheus exposition to an existing HTTP server using servlets.
 *
 * <p>https://github.com/prometheus/client_java/tree/b61dd232a504e20dad404a2bf3e2c0b8661c212a#http
 *
 * @return HTTP servlet for returning metrics data
 */
@Bean
public ServletRegistrationBean<HttpServlet> metricsServlet() {
  return new ServletRegistrationBean<>(new MetricsServlet(), PROMETHEUS_METRICS_PATH);
}