use of org.eclipse.jetty.io.ConnectionStatistics 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);
}
}
use of org.eclipse.jetty.io.ConnectionStatistics in project jetty.project by eclipse.
the class StatisticsServlet method sendTextResponse.
private void sendTextResponse(HttpServletResponse response) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(_statsHandler.toStatsHTML());
sb.append("<h2>Connections:</h2>\n");
for (Connector connector : _connectors) {
sb.append("<h3>").append(connector.getClass().getName()).append("@").append(connector.hashCode()).append("</h3>");
sb.append("Protocols:");
for (String protocol : connector.getProtocols()) sb.append(protocol).append(" ");
sb.append(" <br />\n");
ConnectionStatistics connectionStats = null;
if (connector instanceof Container)
connectionStats = ((Container) connector).getBean(ConnectionStatistics.class);
if (connectionStats != null) {
sb.append("Total connections: ").append(connectionStats.getConnectionsTotal()).append("<br />\n");
sb.append("Current connections open: ").append(connectionStats.getConnections()).append("<br />\n");
sb.append("Max concurrent connections open: ").append(connectionStats.getConnectionsMax()).append("<br />\n");
sb.append("Mean connection duration: ").append(connectionStats.getConnectionDurationMean()).append("<br />\n");
sb.append("Max connection duration: ").append(connectionStats.getConnectionDurationMax()).append("<br />\n");
sb.append("Connection duration standard deviation: ").append(connectionStats.getConnectionDurationStdDev()).append("<br />\n");
sb.append("Total bytes received: ").append(connectionStats.getReceivedBytes()).append("<br />\n");
sb.append("Total bytes sent: ").append(connectionStats.getSentBytes()).append("<br />\n");
sb.append("Total messages received: ").append(connectionStats.getReceivedMessages()).append("<br />\n");
sb.append("Total messages sent: ").append(connectionStats.getSentMessages()).append("<br />\n");
} else {
ConnectorStatistics connectorStats = null;
if (connector instanceof AbstractConnector)
connectorStats = ((AbstractConnector) connector).getBean(ConnectorStatistics.class);
if (connectorStats != null) {
sb.append("Statistics gathering started ").append(connectorStats.getStartedMillis()).append("ms ago").append("<br />\n");
sb.append("Total connections: ").append(connectorStats.getConnections()).append("<br />\n");
sb.append("Current connections open: ").append(connectorStats.getConnectionsOpen()).append("<br />\n");
sb.append("Max concurrent connections open: ").append(connectorStats.getConnectionsOpenMax()).append("<br />\n");
sb.append("Mean connection duration: ").append(connectorStats.getConnectionDurationMean()).append("<br />\n");
sb.append("Max connection duration: ").append(connectorStats.getConnectionDurationMax()).append("<br />\n");
sb.append("Connection duration standard deviation: ").append(connectorStats.getConnectionDurationStdDev()).append("<br />\n");
sb.append("Total messages in: ").append(connectorStats.getMessagesIn()).append("<br />\n");
sb.append("Total messages out: ").append(connectorStats.getMessagesOut()).append("<br />\n");
} else {
sb.append("Statistics gathering off.\n");
}
}
}
sb.append("<h2>Memory:</h2>\n");
sb.append("Heap memory usage: ").append(_memoryBean.getHeapMemoryUsage().getUsed()).append(" bytes").append("<br />\n");
sb.append("Non-heap memory usage: ").append(_memoryBean.getNonHeapMemoryUsage().getUsed()).append(" bytes").append("<br />\n");
response.setContentType("text/html");
PrintWriter pout = response.getWriter();
pout.write(sb.toString());
}
use of org.eclipse.jetty.io.ConnectionStatistics in project jetty.project by eclipse.
the class StatisticsHandlerTest method init.
@Before
public void init() throws Exception {
_server = new Server();
_connector = new LocalConnector(_server);
_statistics = new ConnectionStatistics();
_connector.addBean(_statistics);
_server.addConnector(_connector);
_latchHandler = new LatchHandler();
_statsHandler = new StatisticsHandler();
_server.setHandler(_latchHandler);
_latchHandler.setHandler(_statsHandler);
}
use of org.eclipse.jetty.io.ConnectionStatistics in project jetty.project by eclipse.
the class ConnectionStatisticsTest method testConnectionStatistics.
@Test
public void testConnectionStatistics() throws Exception {
Assume.assumeThat(transport, Matchers.isOneOf(Transport.H2C, Transport.H2));
start(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
baseRequest.setHandled(true);
IO.copy(request.getInputStream(), response.getOutputStream());
}
});
ConnectionStatistics serverStats = new ConnectionStatistics();
connector.addBean(serverStats);
serverStats.start();
ConnectionStatistics clientStats = new ConnectionStatistics();
client.addBean(clientStats);
clientStats.start();
byte[] content = new byte[3072];
long contentLength = content.length;
ContentResponse response = client.newRequest(newURI()).content(new BytesContentProvider(content)).timeout(5, TimeUnit.SECONDS).send();
Assert.assertThat(response.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
// The bytes have already arrived, but give time to
// the server to finish to run the response logic.
Thread.sleep(1000);
// Close all connections.
stop();
// Give some time to process the stop event.
Thread.sleep(1000);
Assert.assertThat(serverStats.getConnectionsMax(), Matchers.greaterThan(0L));
Assert.assertThat(serverStats.getReceivedBytes(), Matchers.greaterThan(contentLength));
Assert.assertThat(serverStats.getSentBytes(), Matchers.greaterThan(contentLength));
Assert.assertThat(serverStats.getReceivedMessages(), Matchers.greaterThan(0L));
Assert.assertThat(serverStats.getSentMessages(), Matchers.greaterThan(0L));
Assert.assertThat(clientStats.getConnectionsMax(), Matchers.greaterThan(0L));
Assert.assertThat(clientStats.getReceivedBytes(), Matchers.greaterThan(contentLength));
Assert.assertThat(clientStats.getSentBytes(), Matchers.greaterThan(contentLength));
Assert.assertThat(clientStats.getReceivedMessages(), Matchers.greaterThan(0L));
Assert.assertThat(clientStats.getSentMessages(), Matchers.greaterThan(0L));
}
use of org.eclipse.jetty.io.ConnectionStatistics in project jetty.project by eclipse.
the class StatisticsServlet method sendXmlResponse.
private void sendXmlResponse(HttpServletResponse response) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("<statistics>\n");
sb.append(" <requests>\n");
sb.append(" <statsOnMs>").append(_statsHandler.getStatsOnMs()).append("</statsOnMs>\n");
sb.append(" <requests>").append(_statsHandler.getRequests()).append("</requests>\n");
sb.append(" <requestsActive>").append(_statsHandler.getRequestsActive()).append("</requestsActive>\n");
sb.append(" <requestsActiveMax>").append(_statsHandler.getRequestsActiveMax()).append("</requestsActiveMax>\n");
sb.append(" <requestsTimeTotal>").append(_statsHandler.getRequestTimeTotal()).append("</requestsTimeTotal>\n");
sb.append(" <requestsTimeMean>").append(_statsHandler.getRequestTimeMean()).append("</requestsTimeMean>\n");
sb.append(" <requestsTimeMax>").append(_statsHandler.getRequestTimeMax()).append("</requestsTimeMax>\n");
sb.append(" <requestsTimeStdDev>").append(_statsHandler.getRequestTimeStdDev()).append("</requestsTimeStdDev>\n");
sb.append(" <dispatched>").append(_statsHandler.getDispatched()).append("</dispatched>\n");
sb.append(" <dispatchedActive>").append(_statsHandler.getDispatchedActive()).append("</dispatchedActive>\n");
sb.append(" <dispatchedActiveMax>").append(_statsHandler.getDispatchedActiveMax()).append("</dispatchedActiveMax>\n");
sb.append(" <dispatchedTimeTotalMs>").append(_statsHandler.getDispatchedTimeTotal()).append("</dispatchedTimeTotalMs>\n");
sb.append(" <dispatchedTimeMeanMs>").append(_statsHandler.getDispatchedTimeMean()).append("</dispatchedTimeMeanMs>\n");
sb.append(" <dispatchedTimeMaxMs>").append(_statsHandler.getDispatchedTimeMax()).append("</dispatchedTimeMaxMs>\n");
sb.append(" <dispatchedTimeStdDevMs>").append(_statsHandler.getDispatchedTimeStdDev()).append("</dispatchedTimeStdDevMs>\n");
sb.append(" <asyncRequests>").append(_statsHandler.getAsyncRequests()).append("</asyncRequests>\n");
sb.append(" <requestsSuspended>").append(_statsHandler.getAsyncRequestsWaiting()).append("</requestsSuspended>\n");
sb.append(" <requestsSuspendedMax>").append(_statsHandler.getAsyncRequestsWaitingMax()).append("</requestsSuspendedMax>\n");
sb.append(" <requestsResumed>").append(_statsHandler.getAsyncDispatches()).append("</requestsResumed>\n");
sb.append(" <requestsExpired>").append(_statsHandler.getExpires()).append("</requestsExpired>\n");
sb.append(" </requests>\n");
sb.append(" <responses>\n");
sb.append(" <responses1xx>").append(_statsHandler.getResponses1xx()).append("</responses1xx>\n");
sb.append(" <responses2xx>").append(_statsHandler.getResponses2xx()).append("</responses2xx>\n");
sb.append(" <responses3xx>").append(_statsHandler.getResponses3xx()).append("</responses3xx>\n");
sb.append(" <responses4xx>").append(_statsHandler.getResponses4xx()).append("</responses4xx>\n");
sb.append(" <responses5xx>").append(_statsHandler.getResponses5xx()).append("</responses5xx>\n");
sb.append(" <responsesBytesTotal>").append(_statsHandler.getResponsesBytesTotal()).append("</responsesBytesTotal>\n");
sb.append(" </responses>\n");
sb.append(" <connections>\n");
for (Connector connector : _connectors) {
sb.append(" <connector>\n");
sb.append(" <name>").append(connector.getClass().getName()).append("@").append(connector.hashCode()).append("</name>\n");
sb.append(" <protocols>\n");
for (String protocol : connector.getProtocols()) sb.append(" <protocol>").append(protocol).append("</protocol>\n");
sb.append(" </protocols>\n");
ConnectionStatistics connectionStats = null;
if (connector instanceof AbstractConnector)
connectionStats = ((AbstractConnector) connector).getBean(ConnectionStatistics.class);
if (connectionStats != null) {
sb.append(" <statsOn>true</statsOn>\n");
sb.append(" <connections>").append(connectionStats.getConnectionsTotal()).append("</connections>\n");
sb.append(" <connectionsOpen>").append(connectionStats.getConnections()).append("</connectionsOpen>\n");
sb.append(" <connectionsOpenMax>").append(connectionStats.getConnectionsMax()).append("</connectionsOpenMax>\n");
sb.append(" <connectionsDurationMean>").append(connectionStats.getConnectionDurationMean()).append("</connectionsDurationMean>\n");
sb.append(" <connectionsDurationMax>").append(connectionStats.getConnectionDurationMax()).append("</connectionsDurationMax>\n");
sb.append(" <connectionsDurationStdDev>").append(connectionStats.getConnectionDurationStdDev()).append("</connectionsDurationStdDev>\n");
sb.append(" <bytesIn>").append(connectionStats.getReceivedBytes()).append("</bytesIn>\n");
sb.append(" <bytesOut>").append(connectionStats.getSentBytes()).append("</connectorStats>\n");
sb.append(" <messagesIn>").append(connectionStats.getReceivedMessages()).append("</messagesIn>\n");
sb.append(" <messagesOut>").append(connectionStats.getSentMessages()).append("</messagesOut>\n");
} else {
ConnectorStatistics connectorStats = null;
if (connector instanceof AbstractConnector)
connectorStats = ((AbstractConnector) connector).getBean(ConnectorStatistics.class);
if (connectorStats != null) {
sb.append(" <statsOn>true</statsOn>\n");
sb.append(" <connections>").append(connectorStats.getConnections()).append("</connections>\n");
sb.append(" <connectionsOpen>").append(connectorStats.getConnectionsOpen()).append("</connectionsOpen>\n");
sb.append(" <connectionsOpenMax>").append(connectorStats.getConnectionsOpenMax()).append("</connectionsOpenMax>\n");
sb.append(" <connectionsDurationMean>").append(connectorStats.getConnectionDurationMean()).append("</connectionsDurationMean>\n");
sb.append(" <connectionsDurationMax>").append(connectorStats.getConnectionDurationMax()).append("</connectionsDurationMax>\n");
sb.append(" <connectionsDurationStdDev>").append(connectorStats.getConnectionDurationStdDev()).append("</connectionsDurationStdDev>\n");
sb.append(" <messagesIn>").append(connectorStats.getMessagesIn()).append("</messagesIn>\n");
sb.append(" <messagesOut>").append(connectorStats.getMessagesIn()).append("</messagesOut>\n");
sb.append(" <elapsedMs>").append(connectorStats.getStartedMillis()).append("</elapsedMs>\n");
} else {
sb.append(" <statsOn>false</statsOn>\n");
}
}
sb.append(" </connector>\n");
}
sb.append(" </connections>\n");
sb.append(" <memory>\n");
sb.append(" <heapMemoryUsage>").append(_memoryBean.getHeapMemoryUsage().getUsed()).append("</heapMemoryUsage>\n");
sb.append(" <nonHeapMemoryUsage>").append(_memoryBean.getNonHeapMemoryUsage().getUsed()).append("</nonHeapMemoryUsage>\n");
sb.append(" </memory>\n");
sb.append("</statistics>\n");
response.setContentType("text/xml");
PrintWriter pout = response.getWriter();
pout.write(sb.toString());
}
Aggregations