@Override
  public void run() {

    try {
      // Set GAE SystemProperties
      setSystemProperties();

      // Create the server, connector and associated instances
      QueuedThreadPool threadpool = new QueuedThreadPool();
      server = new Server(threadpool);
      HttpConfiguration httpConfig = new HttpConfiguration();
      ServerConnector connector =
          new ServerConnector(server, new HttpConnectionFactory(httpConfig));
      connector.setPort(port);
      server.addConnector(connector);

      MappedByteBufferPool bufferpool = new MappedByteBufferPool();

      // Basic jetty.xml handler setup
      HandlerCollection handlers = new HandlerCollection();
      ContextHandlerCollection contexts =
          new ContextHandlerCollection(); // TODO is a context handler collection needed for a
                                          // single context?
      handlers.setHandlers(new Handler[] {contexts, new DefaultHandler()});
      server.setHandler(handlers);

      // Configuration as done by gae.mod/gae.ini
      httpConfig.setOutputAggregationSize(32768);

      threadpool.setMinThreads(10);
      threadpool.setMaxThreads(500);
      threadpool.setIdleTimeout(60000);

      httpConfig.setOutputBufferSize(32768);
      httpConfig.setRequestHeaderSize(8192);
      httpConfig.setResponseHeaderSize(8192);
      httpConfig.setSendServerVersion(true);
      httpConfig.setSendDateHeader(false);
      httpConfig.setDelayDispatchUntilContent(false);

      // Setup Server as done by gae.xml
      server.addBean(bufferpool);

      httpConfig.setHeaderCacheSize(512);

      RequestLogHandler requestLogHandler = new RequestLogHandler();
      handlers.addHandler(requestLogHandler);
      File logs = File.createTempFile("logs", "logs");
      logs.delete();
      logs.mkdirs();
      NCSARequestLog requestLog =
          new NCSARequestLog(logs.getCanonicalPath() + "/request.yyyy_mm_dd.log");
      requestLogHandler.setRequestLog(requestLog);
      requestLog.setRetainDays(2);
      requestLog.setAppend(true);
      requestLog.setExtended(true);
      requestLog.setLogTimeZone("GMT");
      requestLog.setLogLatency(true);
      requestLog.setPreferProxiedForAddress(true);

      // Ugly hack to delete possible previous run lock file
      new File("target/log.0.lck").delete();
      new File("target/log.0.1.lck").delete();

      // configuration from root.xml
      VmRuntimeWebAppContext context = new VmRuntimeWebAppContext();
      context.setContextPath("/");

      // find the sibling testwebapp target
      File currentDir = new File("").getAbsoluteFile();
      File webAppLocation = new File(currentDir, "target/webapps/testwebapp");
      context.setResourceBase(webAppLocation.getAbsolutePath());
      context.init("WEB-INF/appengine-web.xml");
      context.setParentLoaderPriority(true); // true in tests for easier mocking

      // Hack to find the webdefault.xml
      File webDefault = new File(currentDir.getParentFile(), "docker/etc/webdefault.xml");
      context.setDefaultsDescriptor(webDefault.getAbsolutePath());

      contexts.addHandler(context);

      // start and join
      server.start();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      started.countDown();
    }

    try {
      if (Log.getLogger(Server.class).isDebugEnabled()) server.dumpStdErr();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
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();
  }