protected Handler addStatsHandler(Handler handler) {
   // Graceful shutdown is implemented via the statistics handler,
   // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=420142
   final StatisticsHandler statisticsHandler = new StatisticsHandler();
   statisticsHandler.setHandler(handler);
   return statisticsHandler;
 }
Example #2
0
  /**
   * Configure a jetty instance and deploy the webapps presented as args
   *
   * @param args the command line arguments
   * @throws Exception if unable to configure
   */
  public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
      if ("--lib".equals(args[i])) {
        try (Resource lib = Resource.newResource(args[++i])) {
          if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib);
          _classpath.addJars(lib);
        }
      } else if ("--jar".equals(args[i])) {
        try (Resource jar = Resource.newResource(args[++i])) {
          if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar);
          _classpath.addPath(jar);
        }
      } else if ("--classes".equals(args[i])) {
        try (Resource classes = Resource.newResource(args[++i])) {
          if (!classes.exists() || !classes.isDirectory())
            usage("No such classes directory " + classes);
          _classpath.addPath(classes);
        }
      } else if (args[i].startsWith("--")) i++;
    }

    initClassLoader();

    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);

    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;

    boolean runnerServerInitialized = false;

    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--port":
          port = Integer.parseInt(args[++i]);
          break;
        case "--host":
          host = args[++i];
          break;
        case "--stop-port":
          stopPort = Integer.parseInt(args[++i]);
          break;
        case "--stop-key":
          stopKey = args[++i];
          break;
        case "--log":
          _logFile = args[++i];
          break;
        case "--out":
          String outFile = args[++i];
          PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
          LOG.info("Redirecting stderr/stdout to " + outFile);
          System.setErr(out);
          System.setOut(out);
          break;
        case "--path":
          contextPath = args[++i];
          contextPathSet = true;
          break;
        case "--config":
          if (_configFiles == null) _configFiles = new ArrayList<>();
          _configFiles.add(args[++i]);
          break;
        case "--lib":
          ++i; // skip

          break;
        case "--jar":
          ++i; // skip

          break;
        case "--classes":
          ++i; // skip

          break;
        case "--stats":
          _enableStats = true;
          _statsPropFile = args[++i];
          _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
          break;
        default:
          // process contexts

          if (!runnerServerInitialized) // log handlers not registered, server maybe not created,
                                        // etc
          {
            if (_server == null) // server not initialized yet
            {
              // build the server
              _server = new Server();
            }

            // apply jetty config files if there are any
            if (_configFiles != null) {
              for (String cfg : _configFiles) {
                try (Resource resource = Resource.newResource(cfg)) {
                  XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                  xmlConfiguration.configure(_server);
                }
              }
            }

            // check that everything got configured, and if not, make the handlers
            HandlerCollection handlers =
                (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
            if (handlers == null) {
              handlers = new HandlerCollection();
              _server.setHandler(handlers);
            }

            // check if contexts already configured
            _contexts =
                (ContextHandlerCollection)
                    handlers.getChildHandlerByClass(ContextHandlerCollection.class);
            if (_contexts == null) {
              _contexts = new ContextHandlerCollection();
              prependHandler(_contexts, handlers);
            }

            if (_enableStats) {
              // if no stats handler already configured
              if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                StatisticsHandler statsHandler = new StatisticsHandler();

                Handler oldHandler = _server.getHandler();
                statsHandler.setHandler(oldHandler);
                _server.setHandler(statsHandler);

                ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                statsContext.setSessionHandler(new SessionHandler());
                if (_statsPropFile != null) {
                  HashLoginService loginService =
                      new HashLoginService("StatsRealm", _statsPropFile);
                  Constraint constraint = new Constraint();
                  constraint.setName("Admin Only");
                  constraint.setRoles(new String[] {"admin"});
                  constraint.setAuthenticate(true);

                  ConstraintMapping cm = new ConstraintMapping();
                  cm.setConstraint(constraint);
                  cm.setPathSpec("/*");

                  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                  securityHandler.setLoginService(loginService);
                  securityHandler.setConstraintMappings(Collections.singletonList(cm));
                  securityHandler.setAuthenticator(new BasicAuthenticator());
                  statsContext.setSecurityHandler(securityHandler);
                }
              }
            }

            // ensure a DefaultHandler is present
            if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
              handlers.addHandler(new DefaultHandler());
            }

            // ensure a log handler is present
            _logHandler =
                (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
            if (_logHandler == null) {
              _logHandler = new RequestLogHandler();
              handlers.addHandler(_logHandler);
            }

            // check a connector is configured to listen on
            Connector[] connectors = _server.getConnectors();
            if (connectors == null || connectors.length == 0) {
              ServerConnector connector = new ServerConnector(_server);
              connector.setPort(port);
              if (host != null) connector.setHost(host);
              _server.addConnector(connector);
              if (_enableStats) connector.addBean(new ConnectorStatistics());
            } else {
              if (_enableStats) {
                for (Connector connector : connectors) {
                  ((AbstractConnector) connector).addBean(new ConnectorStatistics());
                }
              }
            }

            runnerServerInitialized = true;
          }

          // Create a context
          try (Resource ctx = Resource.newResource(args[i])) {
            if (!ctx.exists()) usage("Context '" + ctx + "' does not exist");

            if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath;

            // Configure the context
            if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) {
              // It is a context config file
              XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
              xmlConfiguration.getIdMap().put("Server", _server);
              ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
              if (contextPathSet) handler.setContextPath(contextPath);
              _contexts.addHandler(handler);
              handler.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            } else {
              // assume it is a WAR file
              WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
              webapp.setConfigurationClasses(__plusConfigurationClasses);
              webapp.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            }
          }
          // reset
          contextPathSet = false;
          contextPath = __defaultContextPath;
          break;
      }
    }

    if (_server == null) usage("No Contexts defined");
    _server.setStopAtShutdown(true);

    switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
      case 1:
        usage("Must specify --stop-key when --stop-port is specified");
        break;

      case 2:
        usage("Must specify --stop-port when --stop-key is specified");
        break;

      case 3:
        ShutdownMonitor monitor = ShutdownMonitor.getInstance();
        monitor.setPort(stopPort);
        monitor.setKey(stopKey);
        monitor.setExitVm(true);
        break;
    }

    if (_logFile != null) {
      NCSARequestLog requestLog = new NCSARequestLog(_logFile);
      requestLog.setExtended(false);
      _logHandler.setRequestLog(requestLog);
    }
  }
Example #3
0
  public static void main(String[] args) throws Exception {
    String jetty_home =
        System.getProperty("jetty.home", "../../jetty-distribution/target/distribution");
    System.setProperty("jetty.home", jetty_home);

    // Setup Threadpool
    QueuedThreadPool threadPool = new QueuedThreadPool(512);

    Server server = new Server(threadPool);
    server.manage(threadPool);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);

    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);

    // Common HTTP configuration
    HttpConfiguration config = new HttpConfiguration();
    config.setSecurePort(8443);
    config.addCustomizer(new ForwardedRequestCustomizer());
    config.addCustomizer(new SecureRequestCustomizer());
    config.setSendServerVersion(true);

    // Http Connector
    HttpConnectionFactory http = new HttpConnectionFactory(config);
    ServerConnector httpConnector = new ServerConnector(server, http);
    httpConnector.setPort(8080);
    httpConnector.setIdleTimeout(10000);
    server.addConnector(httpConnector);

    // SSL configurations
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore");
    sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
    sslContextFactory.setTrustStorePath(jetty_home + "/etc/keystore");
    sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setExcludeCipherSuites(
        "SSL_RSA_WITH_DES_CBC_SHA",
        "SSL_DHE_RSA_WITH_DES_CBC_SHA",
        "SSL_DHE_DSS_WITH_DES_CBC_SHA",
        "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
        "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
        "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
        "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");

    // Spdy Connector
    SPDYServerConnectionFactory.checkNPNAvailable();

    PushStrategy push = new ReferrerPushStrategy();
    HTTPSPDYServerConnectionFactory spdy2 = new HTTPSPDYServerConnectionFactory(2, config, push);
    spdy2.setInputBufferSize(8192);
    spdy2.setInitialWindowSize(32768);

    HTTPSPDYServerConnectionFactory spdy3 = new HTTPSPDYServerConnectionFactory(3, config, push);
    spdy2.setInputBufferSize(8192);

    NPNServerConnectionFactory npn =
        new NPNServerConnectionFactory(
            spdy3.getProtocol(), spdy2.getProtocol(), http.getProtocol());
    npn.setDefaultProtocol(http.getProtocol());
    npn.setInputBufferSize(1024);

    SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, npn.getProtocol());

    ServerConnector spdyConnector = new ServerConnector(server, ssl, npn, spdy3, spdy2, http);
    spdyConnector.setPort(8443);

    server.addConnector(spdyConnector);

    // Setup handlers
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    RequestLogHandler requestLogHandler = new RequestLogHandler();

    handlers.setHandlers(new Handler[] {contexts, new DefaultHandler(), requestLogHandler});

    StatisticsHandler stats = new StatisticsHandler();
    stats.setHandler(handlers);

    server.setHandler(stats);

    // Setup deployers
    DeploymentManager deployer = new DeploymentManager();
    deployer.setContexts(contexts);
    server.addBean(deployer);

    WebAppProvider webapp_provider = new WebAppProvider();
    webapp_provider.setMonitoredDirName(jetty_home + "/webapps");
    webapp_provider.setParentLoaderPriority(false);
    webapp_provider.setExtractWars(true);
    webapp_provider.setScanInterval(2);
    webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml");
    deployer.addAppProvider(webapp_provider);

    HashLoginService login = new HashLoginService();
    login.setName("Test Realm");
    login.setConfig(jetty_home + "/etc/realm.properties");
    server.addBean(login);

    NCSARequestLog requestLog = new AsyncNCSARequestLog();
    requestLog.setFilename(jetty_home + "/logs/jetty-yyyy_mm_dd.log");
    requestLog.setExtended(false);
    requestLogHandler.setRequestLog(requestLog);

    server.setStopAtShutdown(true);

    server.start();
    server.dumpStdErr();
    server.join();
  }
Example #4
0
  @SuppressWarnings({"deprecation"})
  public HttpServer(
      HttpServerInfo httpServerInfo,
      NodeInfo nodeInfo,
      HttpServerConfig config,
      Servlet theServlet,
      Map<String, String> parameters,
      Set<Filter> filters,
      Set<HttpResourceBinding> resources,
      Servlet theAdminServlet,
      Map<String, String> adminParameters,
      Set<Filter> adminFilters,
      MBeanServer mbeanServer,
      LoginService loginService,
      TraceTokenManager tokenManager,
      RequestStats stats,
      EventClient eventClient)
      throws IOException {
    Preconditions.checkNotNull(httpServerInfo, "httpServerInfo is null");
    Preconditions.checkNotNull(nodeInfo, "nodeInfo is null");
    Preconditions.checkNotNull(config, "config is null");
    Preconditions.checkNotNull(theServlet, "theServlet is null");

    QueuedThreadPool threadPool = new QueuedThreadPool(config.getMaxThreads());
    threadPool.setMinThreads(config.getMinThreads());
    threadPool.setIdleTimeout(Ints.checkedCast(config.getThreadMaxIdleTime().toMillis()));
    threadPool.setName("http-worker");
    server = new Server(threadPool);

    if (config.isShowStackTrace()) {
      server.addBean(new ErrorHandler());
    }

    if (mbeanServer != null) {
      // export jmx mbeans if a server was provided
      MBeanContainer mbeanContainer = new MBeanContainer(mbeanServer);
      server.addBean(mbeanContainer);
    }

    // set up HTTP connector
    if (config.isHttpEnabled()) {
      HttpConfiguration httpConfiguration = new HttpConfiguration();
      httpConfiguration.setSendServerVersion(false);
      httpConfiguration.setSendXPoweredBy(false);
      if (config.getMaxRequestHeaderSize() != null) {
        httpConfiguration.setRequestHeaderSize(
            Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes()));
      }

      // if https is enabled, set the CONFIDENTIAL and INTEGRAL redirection information
      if (config.isHttpsEnabled()) {
        httpConfiguration.setSecureScheme("https");
        httpConfiguration.setSecurePort(httpServerInfo.getHttpsUri().getPort());
      }

      Integer acceptors = config.getHttpAcceptorThreads();
      Integer selectors = config.getHttpSelectorThreads();
      httpConnector =
          new ServerConnector(
              server,
              null,
              null,
              null,
              acceptors == null ? -1 : acceptors,
              selectors == null ? -1 : selectors,
              new HttpConnectionFactory(httpConfiguration));
      httpConnector.setName("http");
      httpConnector.setPort(httpServerInfo.getHttpUri().getPort());
      httpConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis());
      httpConnector.setHost(nodeInfo.getBindIp().getHostAddress());
      httpConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize());

      server.addConnector(httpConnector);
    } else {
      httpConnector = null;
    }

    // set up NIO-based HTTPS connector
    if (config.isHttpsEnabled()) {
      HttpConfiguration httpsConfiguration = new HttpConfiguration();
      httpsConfiguration.setSendServerVersion(false);
      httpsConfiguration.setSendXPoweredBy(false);
      if (config.getMaxRequestHeaderSize() != null) {
        httpsConfiguration.setRequestHeaderSize(
            Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes()));
      }
      httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

      SslContextFactory sslContextFactory = new SslContextFactory(config.getKeystorePath());
      sslContextFactory.setKeyStorePassword(config.getKeystorePassword());
      SslConnectionFactory sslConnectionFactory =
          new SslConnectionFactory(sslContextFactory, "http/1.1");

      Integer acceptors = config.getHttpsAcceptorThreads();
      Integer selectors = config.getHttpsSelectorThreads();
      httpsConnector =
          new ServerConnector(
              server,
              null,
              null,
              null,
              acceptors == null ? -1 : acceptors,
              selectors == null ? -1 : selectors,
              sslConnectionFactory,
              new HttpConnectionFactory(httpsConfiguration));
      httpsConnector.setName("https");
      httpsConnector.setPort(httpServerInfo.getHttpsUri().getPort());
      httpsConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis());
      httpsConnector.setHost(nodeInfo.getBindIp().getHostAddress());
      httpsConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize());

      server.addConnector(httpsConnector);
    } else {
      httpsConnector = null;
    }

    // set up NIO-based Admin connector
    if (theAdminServlet != null && config.isAdminEnabled()) {
      HttpConfiguration adminConfiguration = new HttpConfiguration();
      adminConfiguration.setSendServerVersion(false);
      adminConfiguration.setSendXPoweredBy(false);
      if (config.getMaxRequestHeaderSize() != null) {
        adminConfiguration.setRequestHeaderSize(
            Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes()));
      }

      QueuedThreadPool adminThreadPool = new QueuedThreadPool(config.getAdminMaxThreads());
      adminThreadPool.setName("http-admin-worker");
      adminThreadPool.setMinThreads(config.getAdminMinThreads());
      adminThreadPool.setIdleTimeout(Ints.checkedCast(config.getThreadMaxIdleTime().toMillis()));

      if (config.isHttpsEnabled()) {
        adminConfiguration.addCustomizer(new SecureRequestCustomizer());

        SslContextFactory sslContextFactory = new SslContextFactory(config.getKeystorePath());
        sslContextFactory.setKeyStorePassword(config.getKeystorePassword());
        SslConnectionFactory sslConnectionFactory =
            new SslConnectionFactory(sslContextFactory, "http/1.1");
        adminConnector =
            new ServerConnector(
                server,
                adminThreadPool,
                null,
                null,
                0,
                -1,
                sslConnectionFactory,
                new HttpConnectionFactory(adminConfiguration));
      } else {
        adminConnector =
            new ServerConnector(
                server,
                adminThreadPool,
                null,
                null,
                0,
                -1,
                new HttpConnectionFactory(adminConfiguration));
      }

      adminConnector.setName("admin");
      adminConnector.setPort(httpServerInfo.getAdminUri().getPort());
      adminConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis());
      adminConnector.setHost(nodeInfo.getBindIp().getHostAddress());
      adminConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize());

      server.addConnector(adminConnector);
    } else {
      adminConnector = null;
    }

    /**
     * structure is:
     *
     * <p>server |--- statistics handler |--- context handler | |--- trace token filter | |--- gzip
     * response filter | |--- gzip request filter | |--- security handler | |--- user provided
     * filters | |--- the servlet (normally GuiceContainer) | |--- resource handlers |--- log
     * handler |-- admin context handler \ --- the admin servlet
     */
    HandlerCollection handlers = new HandlerCollection();

    for (HttpResourceBinding resource : resources) {
      handlers.addHandler(
          new ClassPathResourceHandler(
              resource.getBaseUri(),
              resource.getClassPathResourceBase(),
              resource.getWelcomeFiles()));
    }

    handlers.addHandler(
        createServletContext(
            theServlet, parameters, filters, tokenManager, loginService, "http", "https"));
    if (config.isLogEnabled()) {
      handlers.addHandler(createLogHandler(config, tokenManager, eventClient));
    }

    RequestLogHandler statsRecorder = new RequestLogHandler();
    statsRecorder.setRequestLog(new StatsRecordingHandler(stats));
    handlers.addHandler(statsRecorder);

    // add handlers to Jetty
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);

    HandlerList rootHandlers = new HandlerList();
    if (theAdminServlet != null && config.isAdminEnabled()) {
      rootHandlers.addHandler(
          createServletContext(
              theAdminServlet, adminParameters, adminFilters, tokenManager, loginService, "admin"));
    }
    rootHandlers.addHandler(statsHandler);
    server.setHandler(rootHandlers);
  }