com.codahale.metrics.jetty9.InstrumentedHandler Java Examples

The following examples show how to use com.codahale.metrics.jetty9.InstrumentedHandler. 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: Poseidon.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private Handler getPoseidonHandler() {
    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/");
    servletContextHandler.addServlet(new ServletHolder(getPoseidonServlet()), "/*");
    servletContextHandler.addServlet(new ServletHolder(rotationCheckServlet), "/_poseidon/rotation");
    servletContextHandler.addServlet(new ServletHolder(backInRotationServlet), "/_poseidon/bir");
    servletContextHandler.addServlet(new ServletHolder(outOfRotationServlet), "/_poseidon/oor");

    configuration.registerServlets().forEach(servlet -> servletContextHandler.addServlet(servlet.getRight(), servlet.getLeft()));

    addFilters(servletContextHandler);

    InstrumentedHandler instrumentedHandler = new InstrumentedHandler(Metrics.getRegistry());
    instrumentedHandler.setHandler(servletContextHandler);
    return instrumentedHandler;
}
 
Example #2
Source File: ApiServer.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
ApiServer(SchedulerConfig schedulerConfig, Collection<Object> resources) {
  this.port = schedulerConfig.getApiServerPort();
  this.server = JettyHttpContainerFactory.createServer(
      UriBuilder.fromUri("http://0.0.0.0/").port(this.port).build(),
      new ResourceConfig(MultiPartFeature.class).registerInstances(new HashSet<>(resources)),
      false /* don't start yet. wait for start() call below. */);
  this.startTimeout = schedulerConfig.getApiServerInitTimeout();

  ServletContextHandler context = new ServletContextHandler();

  // Serve metrics registry content at these paths:
  Metrics.configureMetricsEndpoints(
      context,
      "/v1/metrics",
      "/v1/metrics/prometheus");
  // Serve resources at their declared paths relative to root:
  context
      .addServlet(
          new ServletHolder(
              new ServletContainer(
                  new ResourceConfig(MultiPartFeature.class)
                      .registerInstances(new HashSet<>(resources))
              )
          ),
          "/*");

  // Passthru handler: Collect basic metrics on queries, and store those metrics in the registry
  // TODO(nickbp): reimplement InstrumentedHandler with better/more granular metrics
  // (e.g. resource being queried)
  final InstrumentedHandler instrumentedHandler = new InstrumentedHandler(Metrics.getRegistry());
  instrumentedHandler.setHandler(context);

  server.setHandler(instrumentedHandler);
}
 
Example #3
Source File: ContainerModule.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Jetty server instance for the Flux API endpoint.
 * @param port where the service is available.
 * @return Jetty Server instance
 */
@Named("APIJettyServer")
@Provides
@Singleton
Server getAPIJettyServer(@Named("Api.service.port") int port,
						 @Named("APIResourceConfig")ResourceConfig resourceConfig,
						 @Named("Api.service.acceptors") int acceptorThreads,
						 @Named("Api.service.selectors") int selectorThreads,
						 @Named("Api.service.workers") int maxWorkerThreads,
						 ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
	JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
	provider.setMapper(objectMapper);
	resourceConfig.register(provider);
	QueuedThreadPool threadPool = new QueuedThreadPool();
	threadPool.setMaxThreads(maxWorkerThreads);
	Server server = new Server(threadPool);
	ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
	http.setPort(port);
	server.addConnector(http);
	ServletContextHandler context = new ServletContextHandler(server, "/*");
	ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
	context.addServlet(servlet, "/*");

	final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
	handler.setHandler(context);
	server.setHandler(handler);

	server.setStopAtShutdown(true);
	return server;
}
 
Example #4
Source File: ExecutionContainerModule.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Jetty server instance for the Flux Execution API endpoint.
 * @return Jetty Server instance
 */
@Named("ExecutionAPIJettyServer")
@Provides
@Singleton
Server getExecutionAPIJettyServer(@Named("Execution.Node.Api.service.port") int port,
                         @Named("ExecutionAPIResourceConfig")ResourceConfig resourceConfig,
                         @Named("Execution.Node.Api.service.acceptors") int acceptorThreads,
                         @Named("Execution.Node.Api.service.selectors") int selectorThreads,
                         @Named("Execution.Node.Api.service.workers") int maxWorkerThreads,
                         ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    provider.setMapper(objectMapper);
    resourceConfig.register(provider);
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxWorkerThreads);
    Server server = new Server(threadPool);
    ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
    http.setPort(port);
    server.addConnector(http);
    ServletContextHandler context = new ServletContextHandler(server, "/*");
    ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
    context.addServlet(servlet, "/*");

    final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
    handler.setHandler(context);
    server.setHandler(handler);

    server.setStopAtShutdown(true);
    return server;
}
 
Example #5
Source File: EsigateServer.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * Create and start server.
 * 
 * @throws Exception
 *             when server cannot be started.
 */
public static void start() throws Exception {
    MetricRegistry registry = new MetricRegistry();

    QueuedThreadPool threadPool = new InstrumentedQueuedThreadPool(registry);
    threadPool.setName("esigate");
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);

    srv = new Server(threadPool);
    srv.setStopAtShutdown(true);
    srv.setStopTimeout(5000);

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setOutputBufferSize(outputBufferSize);
    httpConfig.setSendServerVersion(false);
    Timer processTime = registry.timer("processTime");

    try (ServerConnector connector =
            new InstrumentedServerConnector("main", EsigateServer.port, srv, registry,
                    new InstrumentedConnectionFactory(new HttpConnectionFactory(httpConfig), processTime));
            ServerConnector controlConnector = new ServerConnector(srv)) {

        // Main connector
        connector.setIdleTimeout(EsigateServer.idleTimeout);
        connector.setSoLingerTime(-1);
        connector.setName("main");
        connector.setAcceptQueueSize(200);

        // Control connector
        controlConnector.setHost("127.0.0.1");
        controlConnector.setPort(EsigateServer.controlPort);
        controlConnector.setName("control");

        srv.setConnectors(new Connector[] {connector, controlConnector});
        // War
        ProtectionDomain protectionDomain = EsigateServer.class.getProtectionDomain();
        String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();
        String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent();

        File workDir = resetTempDirectory(currentDir);

        WebAppContext context = new WebAppContext(warFile, EsigateServer.contextPath);
        context.setServer(srv);
        context.setTempDirectory(workDir);
        if (StringUtils.isNoneEmpty(sessionCookieName)) {
            context.getSessionHandler().getSessionCookieConfig().setName(sessionCookieName);
        }
        // Add extra classpath (allows to add extensions).
        if (EsigateServer.extraClasspath != null) {
            context.setExtraClasspath(EsigateServer.extraClasspath);
        }

        // Add the handlers
        HandlerCollection handlers = new HandlerList();
        // control handler must be the first one.
        // Work in progress, currently disabled.
        handlers.addHandler(new ControlHandler(registry));
        InstrumentedHandler ih = new InstrumentedHandler(registry);
        ih.setName("main");
        ih.setHandler(context);
        handlers.addHandler(ih);

        srv.setHandler(handlers);
        srv.start();
        srv.join();

    }

}
 
Example #6
Source File: Main.java    From billow with Apache License 2.0 4 votes vote down vote up
private Main(Config config) throws Exception {
    log.info("Startup...");

    try {
        System.out.println(Resources.toString(getResource("banner.txt"), Charsets.UTF_8));
    } catch (IllegalArgumentException | IOException e) {
        log.debug("No banner.txt", e);
    }

    final MetricRegistry metricRegistry = new MetricRegistry();
    final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();

    log.info("Creating database");

    final Config awsConfig = config.getConfig("aws");
    final Long refreshRate = awsConfig.getDuration("refreshRate", TimeUnit.MILLISECONDS);

    final AWSDatabaseHolder dbHolder = new AWSDatabaseHolder(awsConfig);

    final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    scheduler.getContext().put(AWSDatabaseHolderRefreshJob.DB_KEY, dbHolder);
    scheduler.start();

    final SimpleTrigger trigger = newTrigger().
            withIdentity(AWSDatabaseHolderRefreshJob.NAME).
            startNow().
            withSchedule(simpleSchedule().withIntervalInMilliseconds(refreshRate).repeatForever()).
            build();

    final JobDetail jobDetail = newJob(AWSDatabaseHolderRefreshJob.class).
            withIdentity(AWSDatabaseHolderRefreshJob.NAME).
            build();

    scheduler.scheduleJob(jobDetail, trigger);

    log.info("Creating age health check");
    healthCheckRegistry.register("DB", new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return dbHolder.healthy();
        }
    });

    log.info("Creating HTTP servers");
    final Server mainServer = new Server(config.getInt("mainPort"));
    final Server adminServer = new Server(config.getInt("adminPort"));

    configureConnectors(mainServer);
    configureConnectors(adminServer);

    log.info("Creating HTTP handlers");
    final Handler mainHandler = new Handler(metricRegistry, dbHolder, refreshRate);
    final InstrumentedHandler instrumentedHandler =
            new InstrumentedHandler(metricRegistry);
    instrumentedHandler.setHandler(mainHandler);

    mainServer.setHandler(instrumentedHandler);

    final ServletContextHandler adminHandler = new ServletContextHandler();
    adminHandler.addServlet(new ServletHolder(new AdminServlet()), "/*");

    final ServletContext adminContext = adminHandler.getServletContext();
    adminContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
    adminContext.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry);
    adminServer.setHandler(adminHandler);

    log.info("Starting HTTP servers");

    adminServer.start();
    mainServer.start();

    log.info("Joining...");

    mainServer.join();
    adminServer.join();

    log.info("Shutting down scheduler...");

    scheduler.shutdown();

    log.info("We're done!");
}