Search in sources :

Example 1 with StatisticsHandler

use of org.eclipse.jetty.server.handler.StatisticsHandler in project jetty.project by eclipse.

the class StatisticsServlet method init.

public void init() throws ServletException {
    ServletContext context = getServletContext();
    ContextHandler.Context scontext = (ContextHandler.Context) context;
    Server _server = scontext.getContextHandler().getServer();
    Handler handler = _server.getChildHandlerByClass(StatisticsHandler.class);
    if (handler != null) {
        _statsHandler = (StatisticsHandler) handler;
    } else {
        LOG.warn("Statistics Handler not installed!");
        return;
    }
    _memoryBean = ManagementFactory.getMemoryMXBean();
    _connectors = _server.getConnectors();
    if (getInitParameter("restrictToLocalhost") != null) {
        _restrictToLocalhost = "true".equals(getInitParameter("restrictToLocalhost"));
    }
}
Also used : ServletContext(javax.servlet.ServletContext) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Server(org.eclipse.jetty.server.Server) ServletContext(javax.servlet.ServletContext) Handler(org.eclipse.jetty.server.Handler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler)

Example 2 with StatisticsHandler

use of org.eclipse.jetty.server.handler.StatisticsHandler in project jetty.project by eclipse.

the class GracefulStopTest method testGracefulComplete.

/**
     * Test of standard graceful timeout mechanism when a block request does
     * complete. Note that even though the request completes after 100ms, the
     * stop always takes 1000ms
     * @throws Exception on test failure
     */
@Test
public void testGracefulComplete() throws Exception {
    assumeTrue(!OS.IS_WINDOWS);
    Server server = new Server();
    server.setStopTimeout(10000);
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(0);
    server.addConnector(connector);
    TestHandler handler = new TestHandler();
    StatisticsHandler stats = new StatisticsHandler();
    server.setHandler(stats);
    stats.setHandler(handler);
    server.start();
    final int port = connector.getLocalPort();
    try (final Socket client1 = new Socket("127.0.0.1", port);
        final Socket client2 = new Socket("127.0.0.1", port)) {
        client1.getOutputStream().write(("POST / HTTP/1.0\r\n" + "Host: localhost:" + port + "\r\n" + "Content-Type: plain/text\r\n" + "Content-Length: 10\r\n" + "\r\n" + "12345").getBytes());
        client1.getOutputStream().flush();
        handler.latch.await();
        new Thread() {

            @Override
            public void run() {
                long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                long end = now + 500;
                try {
                    Thread.sleep(100);
                    // Try creating a new connection
                    try {
                        new Socket("127.0.0.1", port);
                        throw new IllegalStateException();
                    } catch (ConnectException e) {
                    }
                    // Try another request on existing connection
                    client2.getOutputStream().write(("GET / HTTP/1.0\r\n" + "Host: localhost:" + port + "\r\n" + "\r\n").getBytes());
                    client2.getOutputStream().flush();
                    String response2 = IO.toString(client2.getInputStream());
                    assertThat(response2, containsString(" 503 "));
                    now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                    Thread.sleep(Math.max(1, end - now));
                    client1.getOutputStream().write("567890".getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        long start = System.nanoTime();
        server.stop();
        long stop = System.nanoTime();
        assertThat(TimeUnit.NANOSECONDS.toMillis(stop - start), greaterThan(490L));
        assertThat(TimeUnit.NANOSECONDS.toMillis(stop - start), lessThan(10000L));
        String response = IO.toString(client1.getInputStream());
        assertThat(handler.handling.get(), Matchers.is(false));
        assertThat(response, containsString(" 200 OK"));
        assertThat(response, containsString("read 10/10"));
        assertThat(stats.getRequests(), Matchers.is(2));
        assertThat(stats.getResponses5xx(), Matchers.is(1));
    }
}
Also used : Matchers.containsString(org.hamcrest.Matchers.containsString) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) EofException(org.eclipse.jetty.io.EofException) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) EOFException(java.io.EOFException) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) Socket(java.net.Socket) ConnectException(java.net.ConnectException) Test(org.junit.Test)

Example 3 with StatisticsHandler

use of org.eclipse.jetty.server.handler.StatisticsHandler in project jetty.project by eclipse.

the class ContinuationsTest method process.

private String process(String query, String content) throws Exception {
    Server server = new Server();
    server.setStopTimeout(20000);
    try {
        ServerConnector connector = new ServerConnector(server);
        server.addConnector(connector);
        if (log != null) {
            log.clear();
        }
        history.clear();
        StatisticsHandler stats = new StatisticsHandler();
        server.setHandler(stats);
        stats.setHandler(this.setupHandler);
        server.start();
        int port = connector.getLocalPort();
        StringBuilder request = new StringBuilder("GET /");
        if (query != null)
            request.append("?").append(query);
        request.append(" HTTP/1.1\r\n").append("Host: localhost\r\n").append("Connection: close\r\n");
        if (content == null) {
            request.append("\r\n");
        } else {
            request.append("Content-Length: ").append(content.length()).append("\r\n");
            request.append("\r\n").append(content);
        }
        try (Socket socket = new Socket("localhost", port)) {
            socket.setSoTimeout(10000);
            socket.getOutputStream().write(request.toString().getBytes(StandardCharsets.UTF_8));
            socket.getOutputStream().flush();
            return toString(socket.getInputStream());
        }
    } finally {
        if (log != null) {
            for (int i = 0; log.isEmpty() && i < 60; i++) {
                Thread.sleep(100);
            }
            assertThat("Log.size", log.size(), is(1));
            String entry = log.get(0);
            assertThat("Log entry", entry, startsWith("200 "));
            assertThat("Log entry", entry, endsWith(" /"));
        }
        server.stop();
    }
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Server(org.eclipse.jetty.server.Server) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) Socket(java.net.Socket)

Example 4 with StatisticsHandler

use of org.eclipse.jetty.server.handler.StatisticsHandler in project jetty.project by eclipse.

the class Runner method configure.

/**
     * 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":
                //skip
                ++i;
                break;
            case "--jar":
                //skip
                ++i;
                break;
            case "--classes":
                //skip
                ++i;
                break;
            case "--stats":
                _enableStats = true;
                _statsPropFile = args[++i];
                _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
                break;
            default:
                if (// log handlers not registered, server maybe not created, etc
                !runnerServerInitialized) {
                    if (// server not initialized yet
                    _server == null) {
                        // 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 ConnectionStatistics());
                    } else {
                        if (_enableStats) {
                            for (Connector connector : connectors) {
                                ((AbstractConnector) connector).addBean(new ConnectionStatistics());
                            }
                        }
                    }
                    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(Locale.ENGLISH).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);
                        String containerIncludeJarPattern = (String) handler.getAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN);
                        if (containerIncludeJarPattern == null)
                            containerIncludeJarPattern = __containerIncludeJarPattern;
                        else {
                            if (!containerIncludeJarPattern.contains(__containerIncludeJarPattern)) {
                                containerIncludeJarPattern = containerIncludeJarPattern + (StringUtil.isBlank(containerIncludeJarPattern) ? "" : "|") + __containerIncludeJarPattern;
                            }
                        }
                        handler.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerIncludeJarPattern);
                        //check the configurations, if not explicitly set up, then configure all of them
                        if (handler instanceof WebAppContext) {
                            WebAppContext wac = (WebAppContext) handler;
                            if (wac.getConfigurationClasses() == null || wac.getConfigurationClasses().length == 0)
                                wac.setConfigurationClasses(__plusConfigurationClasses);
                        }
                    } else {
                        // assume it is a WAR file
                        WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
                        webapp.setConfigurationClasses(__plusConfigurationClasses);
                        webapp.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, __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);
    }
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) AbstractConnector(org.eclipse.jetty.server.AbstractConnector) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) ShutdownMonitor(org.eclipse.jetty.server.ShutdownMonitor) Server(org.eclipse.jetty.server.Server) ConnectionStatistics(org.eclipse.jetty.io.ConnectionStatistics) Constraint(org.eclipse.jetty.util.security.Constraint) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ArrayList(java.util.ArrayList) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) RolloverFileOutputStream(org.eclipse.jetty.util.RolloverFileOutputStream) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) ServerConnector(org.eclipse.jetty.server.ServerConnector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) HashLoginService(org.eclipse.jetty.security.HashLoginService) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) NCSARequestLog(org.eclipse.jetty.server.NCSARequestLog) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) PrintStream(java.io.PrintStream) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) Resource(org.eclipse.jetty.util.resource.Resource) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) Constraint(org.eclipse.jetty.util.security.Constraint) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) StatisticsServlet(org.eclipse.jetty.servlet.StatisticsServlet) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) AbstractConnector(org.eclipse.jetty.server.AbstractConnector)

Example 5 with StatisticsHandler

use of org.eclipse.jetty.server.handler.StatisticsHandler in project jetty.project by eclipse.

the class OverlayServer method main.

public static void main(String[] args) throws Exception {
    // NamingUtil.__log.setDebugEnabled(true);
    String jetty_home = System.getProperty("jetty.home", "target/test-classes/home");
    System.setProperty("jetty.home", jetty_home);
    Server server = new Server();
    server.setAttribute("org.eclipse.jetty.webapp.configuration", new String[] { org.eclipse.jetty.webapp.WebInfConfiguration.class.getCanonicalName(), org.eclipse.jetty.webapp.WebXmlConfiguration.class.getCanonicalName(), org.eclipse.jetty.webapp.MetaInfConfiguration.class.getCanonicalName(), org.eclipse.jetty.webapp.FragmentConfiguration.class.getCanonicalName(), org.eclipse.jetty.plus.webapp.EnvConfiguration.class.getCanonicalName(), org.eclipse.jetty.plus.webapp.PlusConfiguration.class.getCanonicalName(), org.eclipse.jetty.webapp.JettyWebXmlConfiguration.class.getCanonicalName() });
    // Setup Connectors
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(8080);
    server.addConnector(connector);
    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);
    OverlayedAppProvider provider = new OverlayedAppProvider();
    provider.setNodeName("nodeA");
    provider.setScanDir(new File(jetty_home + "/overlays"));
    provider.setScanInterval(2);
    deployer.addAppProvider(provider);
    server.setStopAtShutdown(true);
    //server.setSendServerVersion(true);
    // Uncomment to work with JNDI examples
    // new org.eclipse.jetty.plus.jndi.Transaction(new com.atomikos.icatch.jta.UserTransactionImp());
    server.start();
    server.join();
}
Also used : Server(org.eclipse.jetty.server.Server) DeploymentManager(org.eclipse.jetty.deploy.DeploymentManager) OverlayedAppProvider(org.eclipse.jetty.overlays.OverlayedAppProvider) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) File(java.io.File)

Aggregations

StatisticsHandler (org.eclipse.jetty.server.handler.StatisticsHandler)24 Server (org.eclipse.jetty.server.Server)10 RequestLogHandler (org.eclipse.jetty.server.handler.RequestLogHandler)10 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)9 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)8 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)8 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)7 IOException (java.io.IOException)5 ServerConnector (org.eclipse.jetty.server.ServerConnector)5 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)4 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)4 Test (org.junit.Test)4 Socket (java.net.Socket)3 ConnectException (org.apache.kafka.connect.errors.ConnectException)3 Handler (org.eclipse.jetty.server.Handler)3 Slf4jRequestLog (org.eclipse.jetty.server.Slf4jRequestLog)3 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)3 ResourceConfig (org.glassfish.jersey.server.ResourceConfig)3 ServletContainer (org.glassfish.jersey.servlet.ServletContainer)3 Unirest (com.mashape.unirest.http.Unirest)2