Search in sources :

Example 81 with QueuedThreadPool

use of org.eclipse.jetty.util.thread.QueuedThreadPool in project jetty.project by eclipse.

the class JettyRunForkedMojo method startJetty.

@Override
public void startJetty() throws MojoExecutionException {
    try {
        printSystemProperties();
        //do NOT apply the jettyXml configuration - as the jvmArgs may be needed for it to work 
        if (server == null)
            server = new Server();
        //ensure handler structure enabled
        ServerSupport.configureHandlers(server, null);
        ServerSupport.configureDefaultConfigurationClasses(server);
        //ensure config of the webapp based on settings in plugin
        configureWebApplication();
        //copy the base resource as configured by the plugin
        originalBaseResource = webApp.getBaseResource();
        //get the original persistance setting
        originalPersistTemp = webApp.isPersistTempDirectory();
        //set the webapp up to do very little other than generate the quickstart-web.xml
        webApp.setCopyWebDir(false);
        webApp.setCopyWebInf(false);
        webApp.setGenerateQuickStart(true);
        if (webApp.getQuickStartWebDescriptor() == null) {
            if (forkWebXml == null)
                forkWebXml = new File(target, "fork-web.xml");
            if (!forkWebXml.getParentFile().exists())
                forkWebXml.getParentFile().mkdirs();
            if (!forkWebXml.exists())
                forkWebXml.createNewFile();
            webApp.setQuickStartWebDescriptor(Resource.newResource(forkWebXml));
        }
        //add webapp to our fake server instance
        ServerSupport.addWebApplication(server, webApp);
        //if our server has a thread pool associated we can do annotation scanning multithreaded,
        //otherwise scanning will be single threaded
        QueuedThreadPool tpool = server.getBean(QueuedThreadPool.class);
        if (tpool != null)
            tpool.start();
        else
            webApp.setAttribute(AnnotationConfiguration.MULTI_THREADED, Boolean.FALSE.toString());
        //leave everything unpacked for the forked process to use
        webApp.setPersistTempDirectory(true);
        //just enough to generate the quickstart           
        webApp.start();
        //save config of the webapp BEFORE we stop
        File props = prepareConfiguration();
        webApp.stop();
        if (tpool != null)
            tpool.stop();
        List<String> cmd = new ArrayList<String>();
        cmd.add(getJavaBin());
        if (jvmArgs != null) {
            String[] args = jvmArgs.split(" ");
            for (int i = 0; args != null && i < args.length; i++) {
                if (args[i] != null && !"".equals(args[i]))
                    cmd.add(args[i].trim());
            }
        }
        String classPath = getContainerClassPath();
        if (classPath != null && classPath.length() > 0) {
            cmd.add("-cp");
            cmd.add(classPath);
        }
        cmd.add(Starter.class.getCanonicalName());
        if (stopPort > 0 && stopKey != null) {
            cmd.add("--stop-port");
            cmd.add(Integer.toString(stopPort));
            cmd.add("--stop-key");
            cmd.add(stopKey);
        }
        if (jettyXml != null) {
            cmd.add("--jetty-xml");
            cmd.add(jettyXml);
        }
        if (contextXml != null) {
            cmd.add("--context-xml");
            cmd.add(contextXml);
        }
        cmd.add("--props");
        cmd.add(props.getAbsolutePath());
        String token = createToken();
        cmd.add("--token");
        cmd.add(token);
        ProcessBuilder builder = new ProcessBuilder(cmd);
        builder.directory(project.getBasedir());
        if (PluginLog.getLog().isDebugEnabled())
            PluginLog.getLog().debug(Arrays.toString(cmd.toArray()));
        PluginLog.getLog().info("Forked process starting");
        //set up extra environment vars if there are any
        if (!env.isEmpty()) {
            builder.environment().putAll(env);
        }
        if (waitForChild) {
            forkedProcess = builder.start();
            startPump("STDOUT", forkedProcess.getInputStream());
            startPump("STDERR", forkedProcess.getErrorStream());
            int exitcode = forkedProcess.waitFor();
            PluginLog.getLog().info("Forked execution exit: " + exitcode);
        } else {
            //merge stderr and stdout from child
            builder.redirectErrorStream(true);
            forkedProcess = builder.start();
            //child indicates it has finished starting by printing on stdout the token passed to it
            try {
                String line = "";
                try (InputStream is = forkedProcess.getInputStream();
                    LineNumberReader reader = new LineNumberReader(new InputStreamReader(is))) {
                    //max lines we'll read trying to get token
                    int attempts = maxStartupLines;
                    while (attempts > 0 && line != null) {
                        --attempts;
                        line = reader.readLine();
                        if (line != null && line.startsWith(token))
                            break;
                    }
                }
                if (line != null && line.trim().equals(token))
                    PluginLog.getLog().info("Forked process started.");
                else {
                    String err = (line == null ? "" : (line.startsWith(token) ? line.substring(token.length()) : line));
                    PluginLog.getLog().info("Forked process startup errors" + (!"".equals(err) ? ", received: " + err : ""));
                }
            } catch (Exception e) {
                throw new MojoExecutionException("Problem determining if forked process is ready: " + e.getMessage());
            }
        }
    } catch (InterruptedException ex) {
        if (forkedProcess != null && waitForChild)
            forkedProcess.destroy();
        throw new MojoExecutionException("Failed to start Jetty within time limit");
    } catch (Exception ex) {
        if (forkedProcess != null && waitForChild)
            forkedProcess.destroy();
        throw new MojoExecutionException("Failed to create Jetty process", ex);
    }
}
Also used : Server(org.eclipse.jetty.server.Server) InputStreamReader(java.io.InputStreamReader) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) LineNumberReader(java.io.LineNumberReader) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) File(java.io.File)

Example 82 with QueuedThreadPool

use of org.eclipse.jetty.util.thread.QueuedThreadPool in project jetty.project by eclipse.

the class SessionTrackingTest method startServer.

@Before
public void startServer() throws Exception {
    QueuedThreadPool serverThreads = new QueuedThreadPool();
    serverThreads.setName("server");
    server = new Server(serverThreads);
    ServerConnector serverConnector = new ServerConnector(server);
    serverConnector.setPort(0);
    server.addConnector(serverConnector);
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    servletContextHandler.setContextPath("/");
    server.setHandler(servletContextHandler);
    serverContainer = WebSocketServerContainerInitializer.configureContext(servletContextHandler);
    serverContainer.addEndpoint(EchoSocket.class);
    wsServerFactory = serverContainer.getWebSocketServerFactory();
    server.start();
    serverURI = new URI("ws://localhost:" + serverConnector.getLocalPort());
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Server(org.eclipse.jetty.server.Server) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) URI(java.net.URI) Before(org.junit.Before)

Example 83 with QueuedThreadPool

use of org.eclipse.jetty.util.thread.QueuedThreadPool in project jetty.project by eclipse.

the class SessionTrackingTest method testAddRemoveSessions.

@Test
public void testAddRemoveSessions() throws Exception {
    // Create Client
    ClientContainer clientContainer = new ClientContainer();
    QueuedThreadPool clientThreads = new QueuedThreadPool();
    clientThreads.setName("client");
    clientContainer.getClient().setExecutor(clientThreads);
    try {
        CountDownLatch openedLatch = new CountDownLatch(2);
        CountDownLatch closedLatch = new CountDownLatch(2);
        wsServerFactory.addSessionListener(new WebSocketSession.Listener() {

            @Override
            public void onOpened(WebSocketSession session) {
                openedLatch.countDown();
            }

            @Override
            public void onClosed(WebSocketSession session) {
                closedLatch.countDown();
            }
        });
        clientContainer.start();
        // Establish connections
        ClientSocket cli1 = new ClientSocket();
        clientContainer.connectToServer(cli1, serverURI.resolve("/test"));
        cli1.waitForOpen(1, TimeUnit.SECONDS);
        // Establish new connection
        ClientSocket cli2 = new ClientSocket();
        clientContainer.connectToServer(cli2, serverURI.resolve("/test"));
        cli2.waitForOpen(1, TimeUnit.SECONDS);
        openedLatch.await(5, TimeUnit.SECONDS);
        assertServerOpenConnectionCount(2);
        // Establish close both connections
        cli1.session.close();
        cli2.session.close();
        cli1.waitForClose(1, TimeUnit.SECONDS);
        cli2.waitForClose(1, TimeUnit.SECONDS);
        closedLatch.await(5, TimeUnit.SECONDS);
        assertServerOpenConnectionCount(0);
    } finally {
        clientContainer.stop();
    }
}
Also used : QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ClientContainer(org.eclipse.jetty.websocket.jsr356.ClientContainer) CountDownLatch(java.util.concurrent.CountDownLatch) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Test(org.junit.Test)

Example 84 with QueuedThreadPool

use of org.eclipse.jetty.util.thread.QueuedThreadPool in project jetty.project by eclipse.

the class TestServer method main.

public static void main(String[] args) throws Exception {
    ((StdErrLog) Log.getLog()).setSource(false);
    String jetty_root = "../../..";
    // Setup Threadpool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(100);
    // Setup server
    Server server = new Server(threadPool);
    server.manage(threadPool);
    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);
    server.addBean(Log.getLog());
    // Common HTTP configuration
    HttpConfiguration config = new HttpConfiguration();
    config.setSecurePort(8443);
    config.addCustomizer(new ForwardedRequestCustomizer());
    config.addCustomizer(new SecureRequestCustomizer());
    config.setSendDateHeader(true);
    config.setSendServerVersion(true);
    // Http Connector
    HttpConnectionFactory http = new HttpConnectionFactory(config);
    ServerConnector httpConnector = new ServerConnector(server, http);
    httpConnector.setPort(8080);
    httpConnector.setIdleTimeout(30000);
    server.addConnector(httpConnector);
    // Handlers
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    // Add restart handler to test the ability to save sessions and restart
    RestartHandler restart = new RestartHandler();
    restart.setHandler(handlers);
    server.setHandler(restart);
    // Setup context
    HashLoginService login = new HashLoginService();
    login.setName("Test Realm");
    login.setConfig(jetty_root + "/tests/test-webapps/test-jetty-webapp/src/main/config/demo-base/etc/realm.properties");
    server.addBean(login);
    File log = File.createTempFile("jetty-yyyy_mm_dd", "log");
    NCSARequestLog requestLog = new NCSARequestLog(log.toString());
    requestLog.setExtended(false);
    requestLogHandler.setRequestLog(requestLog);
    server.setStopAtShutdown(true);
    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/test");
    webapp.setParentLoaderPriority(true);
    webapp.setResourceBase("./src/main/webapp");
    webapp.setAttribute("testAttribute", "testValue");
    File sessiondir = File.createTempFile("sessions", null);
    if (sessiondir.exists())
        sessiondir.delete();
    sessiondir.mkdir();
    sessiondir.deleteOnExit();
    DefaultSessionCache ss = new DefaultSessionCache(webapp.getSessionHandler());
    FileSessionDataStore sds = new FileSessionDataStore();
    ss.setSessionDataStore(sds);
    sds.setStoreDir(sessiondir);
    webapp.getSessionHandler().setSessionCache(ss);
    contexts.addHandler(webapp);
    ContextHandler srcroot = new ContextHandler();
    srcroot.setResourceBase(".");
    srcroot.setHandler(new ResourceHandler());
    srcroot.setContextPath("/src");
    contexts.addHandler(srcroot);
    server.start();
    server.join();
}
Also used : DefaultSessionCache(org.eclipse.jetty.server.session.DefaultSessionCache) StdErrLog(org.eclipse.jetty.util.log.StdErrLog) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) HashLoginService(org.eclipse.jetty.security.HashLoginService) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) NCSARequestLog(org.eclipse.jetty.server.NCSARequestLog) MBeanContainer(org.eclipse.jetty.jmx.MBeanContainer) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) FileSessionDataStore(org.eclipse.jetty.server.session.FileSessionDataStore) File(java.io.File)

Example 85 with QueuedThreadPool

use of org.eclipse.jetty.util.thread.QueuedThreadPool in project jetty.project by eclipse.

the class TestTransparentProxyServer method main.

public static void main(String[] args) throws Exception {
    ((StdErrLog) Log.getLog()).setSource(false);
    String jetty_root = "../../..";
    // Setup Threadpool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(100);
    // Setup server
    Server server = new Server(threadPool);
    server.manage(threadPool);
    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);
    server.addBean(Log.getLog());
    // Common HTTP configuration
    HttpConfiguration config = new HttpConfiguration();
    config.setSecurePort(8443);
    config.addCustomizer(new ForwardedRequestCustomizer());
    config.setSendDateHeader(true);
    config.setSendServerVersion(true);
    // Http Connector
    HttpConnectionFactory http = new HttpConnectionFactory(config);
    ServerConnector httpConnector = new ServerConnector(server, http);
    httpConnector.setPort(8080);
    httpConnector.setIdleTimeout(30000);
    server.addConnector(httpConnector);
    // SSL configurations
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(jetty_root + "/jetty-server/src/main/config/etc/keystore");
    sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
    sslContextFactory.setTrustStorePath(jetty_root + "/jetty-server/src/main/config/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");
    sslContextFactory.setCipherComparator(new HTTP2Cipher.CipherComparator());
    // HTTPS Configuration
    HttpConfiguration https_config = new HttpConfiguration(config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    // HTTP2 factory
    HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(https_config);
    ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
    alpn.setDefaultProtocol(h2.getProtocol());
    // SSL Factory
    SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol());
    // HTTP2 Connector
    ServerConnector http2Connector = new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(https_config));
    http2Connector.setPort(8443);
    http2Connector.setIdleTimeout(15000);
    server.addConnector(http2Connector);
    // Handlers
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    handlers.setHandlers(new Handler[] { contexts, new DefaultHandler() });
    server.setHandler(handlers);
    // Setup proxy webapp
    WebAppContext webapp = new WebAppContext();
    webapp.setResourceBase("src/main/webapp");
    contexts.addHandler(webapp);
    // start server
    server.setStopAtShutdown(true);
    server.start();
    server.join();
}
Also used : StdErrLog(org.eclipse.jetty.util.log.StdErrLog) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ALPNServerConnectionFactory(org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HTTP2Cipher(org.eclipse.jetty.http2.HTTP2Cipher) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) MBeanContainer(org.eclipse.jetty.jmx.MBeanContainer) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection)

Aggregations

QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)126 Server (org.eclipse.jetty.server.Server)65 ServerConnector (org.eclipse.jetty.server.ServerConnector)51 Test (org.junit.Test)30 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)26 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)23 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)22 HttpClient (org.eclipse.jetty.client.HttpClient)18 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)18 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)18 IOException (java.io.IOException)17 SslConnectionFactory (org.eclipse.jetty.server.SslConnectionFactory)11 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)11 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)10 File (java.io.File)9 CountDownLatch (java.util.concurrent.CountDownLatch)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 InputStream (java.io.InputStream)8 HttpServletResponse (javax.servlet.http.HttpServletResponse)8 SecureRequestCustomizer (org.eclipse.jetty.server.SecureRequestCustomizer)8