2 // ========================================================================
3 // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.server.handler;
21 import java.io.IOException;
22 import java.util.concurrent.Future;
23 import java.util.concurrent.TimeoutException;
24 import java.util.concurrent.atomic.AtomicInteger;
25 import java.util.concurrent.atomic.AtomicLong;
26 import java.util.concurrent.atomic.AtomicReference;
28 import javax.servlet.AsyncEvent;
29 import javax.servlet.AsyncListener;
30 import javax.servlet.ServletException;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
34 import org.eclipse.jetty.server.AsyncContextEvent;
35 import org.eclipse.jetty.server.HttpChannelState;
36 import org.eclipse.jetty.server.Request;
37 import org.eclipse.jetty.server.Response;
38 import org.eclipse.jetty.util.FutureCallback;
39 import org.eclipse.jetty.util.annotation.ManagedAttribute;
40 import org.eclipse.jetty.util.annotation.ManagedObject;
41 import org.eclipse.jetty.util.annotation.ManagedOperation;
42 import org.eclipse.jetty.util.component.Graceful;
43 import org.eclipse.jetty.util.statistic.CounterStatistic;
44 import org.eclipse.jetty.util.statistic.SampleStatistic;
46 @ManagedObject("Request Statistics Gathering")
47 public class StatisticsHandler extends HandlerWrapper implements Graceful
49 private final AtomicLong _statsStartedAt = new AtomicLong();
51 private final CounterStatistic _requestStats = new CounterStatistic();
52 private final SampleStatistic _requestTimeStats = new SampleStatistic();
53 private final CounterStatistic _dispatchedStats = new CounterStatistic();
54 private final SampleStatistic _dispatchedTimeStats = new SampleStatistic();
55 private final CounterStatistic _asyncWaitStats = new CounterStatistic();
57 private final AtomicInteger _asyncDispatches = new AtomicInteger();
58 private final AtomicInteger _expires = new AtomicInteger();
60 private final AtomicInteger _responses1xx = new AtomicInteger();
61 private final AtomicInteger _responses2xx = new AtomicInteger();
62 private final AtomicInteger _responses3xx = new AtomicInteger();
63 private final AtomicInteger _responses4xx = new AtomicInteger();
64 private final AtomicInteger _responses5xx = new AtomicInteger();
65 private final AtomicLong _responsesTotalBytes = new AtomicLong();
67 private final AtomicReference<FutureCallback> _shutdown=new AtomicReference<>();
69 private final AsyncListener _onCompletion = new AsyncListener()
72 public void onTimeout(AsyncEvent event) throws IOException
74 _expires.incrementAndGet();
78 public void onStartAsync(AsyncEvent event) throws IOException
80 event.getAsyncContext().addListener(this);
84 public void onError(AsyncEvent event) throws IOException
89 public void onComplete(AsyncEvent event) throws IOException
91 HttpChannelState state = ((AsyncContextEvent)event).getHttpChannelState();
93 Request request = state.getBaseRequest();
94 final long elapsed = System.currentTimeMillis()-request.getTimeStamp();
96 long d=_requestStats.decrement();
97 _requestTimeStats.set(elapsed);
99 updateResponse(request);
101 _asyncWaitStats.decrement();
103 // If we have no more dispatches, should we signal shutdown?
106 FutureCallback shutdown = _shutdown.get();
108 shutdown.succeeded();
114 * Resets the current request statistics.
116 @ManagedOperation(value="resets statistics", impact="ACTION")
117 public void statsReset()
119 _statsStartedAt.set(System.currentTimeMillis());
121 _requestStats.reset();
122 _requestTimeStats.reset();
123 _dispatchedStats.reset();
124 _dispatchedTimeStats.reset();
125 _asyncWaitStats.reset();
127 _asyncDispatches.set(0);
129 _responses1xx.set(0);
130 _responses2xx.set(0);
131 _responses3xx.set(0);
132 _responses4xx.set(0);
133 _responses5xx.set(0);
134 _responsesTotalBytes.set(0L);
138 public void handle(String path, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException
140 _dispatchedStats.increment();
143 HttpChannelState state = request.getHttpChannelState();
144 if (state.isInitial())
147 _requestStats.increment();
148 start = request.getTimeStamp();
153 start = System.currentTimeMillis();
154 _asyncDispatches.incrementAndGet();
159 super.handle(path, request, httpRequest, httpResponse);
163 final long now = System.currentTimeMillis();
164 final long dispatched=now-start;
166 _dispatchedStats.decrement();
167 _dispatchedTimeStats.set(dispatched);
169 if (state.isSuspended())
171 if (state.isInitial())
173 state.addListener(_onCompletion);
174 _asyncWaitStats.increment();
177 else if (state.isInitial())
179 long d=_requestStats.decrement();
180 _requestTimeStats.set(dispatched);
181 updateResponse(request);
183 // If we have no more dispatches, should we signal shutdown?
184 FutureCallback shutdown = _shutdown.get();
187 httpResponse.flushBuffer();
189 shutdown.succeeded();
192 // else onCompletion will handle it.
196 private void updateResponse(Request request)
198 Response response = request.getResponse();
199 switch (response.getStatus() / 100)
202 if (request.isHandled())
203 _responses2xx.incrementAndGet();
205 _responses4xx.incrementAndGet();
208 _responses1xx.incrementAndGet();
211 _responses2xx.incrementAndGet();
214 _responses3xx.incrementAndGet();
217 _responses4xx.incrementAndGet();
220 _responses5xx.incrementAndGet();
225 _responsesTotalBytes.addAndGet(response.getContentCount());
229 protected void doStart() throws Exception
238 protected void doStop() throws Exception
241 FutureCallback shutdown = _shutdown.get();
242 if (shutdown!=null && !shutdown.isDone())
243 shutdown.failed(new TimeoutException());
247 * @return the number of requests handled by this handler
248 * since {@link #statsReset()} was last called, excluding
250 * @see #getAsyncDispatches()
252 @ManagedAttribute("number of requests")
253 public int getRequests()
255 return (int)_requestStats.getTotal();
259 * @return the number of requests currently active.
260 * since {@link #statsReset()} was last called.
262 @ManagedAttribute("number of requests currently active")
263 public int getRequestsActive()
265 return (int)_requestStats.getCurrent();
269 * @return the maximum number of active requests
270 * since {@link #statsReset()} was last called.
272 @ManagedAttribute("maximum number of active requests")
273 public int getRequestsActiveMax()
275 return (int)_requestStats.getMax();
279 * @return the maximum time (in milliseconds) of request handling
280 * since {@link #statsReset()} was last called.
282 @ManagedAttribute("maximum time spend handling requests (in ms)")
283 public long getRequestTimeMax()
285 return _requestTimeStats.getMax();
289 * @return the total time (in milliseconds) of requests handling
290 * since {@link #statsReset()} was last called.
292 @ManagedAttribute("total time spend in all request handling (in ms)")
293 public long getRequestTimeTotal()
295 return _requestTimeStats.getTotal();
299 * @return the mean time (in milliseconds) of request handling
300 * since {@link #statsReset()} was last called.
301 * @see #getRequestTimeTotal()
302 * @see #getRequests()
304 @ManagedAttribute("mean time spent handling requests (in ms)")
305 public double getRequestTimeMean()
307 return _requestTimeStats.getMean();
311 * @return the standard deviation of time (in milliseconds) of request handling
312 * since {@link #statsReset()} was last called.
313 * @see #getRequestTimeTotal()
314 * @see #getRequests()
316 @ManagedAttribute("standard deviation for request handling (in ms)")
317 public double getRequestTimeStdDev()
319 return _requestTimeStats.getStdDev();
323 * @return the number of dispatches seen by this handler
324 * since {@link #statsReset()} was last called, excluding
327 @ManagedAttribute("number of dispatches")
328 public int getDispatched()
330 return (int)_dispatchedStats.getTotal();
334 * @return the number of dispatches currently in this handler
335 * since {@link #statsReset()} was last called, including
338 @ManagedAttribute("number of dispatches currently active")
339 public int getDispatchedActive()
341 return (int)_dispatchedStats.getCurrent();
345 * @return the max number of dispatches currently in this handler
346 * since {@link #statsReset()} was last called, including
349 @ManagedAttribute("maximum number of active dispatches being handled")
350 public int getDispatchedActiveMax()
352 return (int)_dispatchedStats.getMax();
356 * @return the maximum time (in milliseconds) of request dispatch
357 * since {@link #statsReset()} was last called.
359 @ManagedAttribute("maximum time spend in dispatch handling")
360 public long getDispatchedTimeMax()
362 return _dispatchedTimeStats.getMax();
366 * @return the total time (in milliseconds) of requests handling
367 * since {@link #statsReset()} was last called.
369 @ManagedAttribute("total time spent in dispatch handling (in ms)")
370 public long getDispatchedTimeTotal()
372 return _dispatchedTimeStats.getTotal();
376 * @return the mean time (in milliseconds) of request handling
377 * since {@link #statsReset()} was last called.
378 * @see #getRequestTimeTotal()
379 * @see #getRequests()
381 @ManagedAttribute("mean time spent in dispatch handling (in ms)")
382 public double getDispatchedTimeMean()
384 return _dispatchedTimeStats.getMean();
388 * @return the standard deviation of time (in milliseconds) of request handling
389 * since {@link #statsReset()} was last called.
390 * @see #getRequestTimeTotal()
391 * @see #getRequests()
393 @ManagedAttribute("standard deviation for dispatch handling (in ms)")
394 public double getDispatchedTimeStdDev()
396 return _dispatchedTimeStats.getStdDev();
400 * @return the number of requests handled by this handler
401 * since {@link #statsReset()} was last called, including
403 * @see #getAsyncDispatches()
405 @ManagedAttribute("total number of async requests")
406 public int getAsyncRequests()
408 return (int)_asyncWaitStats.getTotal();
412 * @return the number of requests currently suspended.
413 * since {@link #statsReset()} was last called.
415 @ManagedAttribute("currently waiting async requests")
416 public int getAsyncRequestsWaiting()
418 return (int)_asyncWaitStats.getCurrent();
422 * @return the maximum number of current suspended requests
423 * since {@link #statsReset()} was last called.
425 @ManagedAttribute("maximum number of waiting async requests")
426 public int getAsyncRequestsWaitingMax()
428 return (int)_asyncWaitStats.getMax();
432 * @return the number of requests that have been asynchronously dispatched
434 @ManagedAttribute("number of requested that have been asynchronously dispatched")
435 public int getAsyncDispatches()
437 return _asyncDispatches.get();
441 * @return the number of requests that expired while suspended.
442 * @see #getAsyncDispatches()
444 @ManagedAttribute("number of async requests requests that have expired")
445 public int getExpires()
447 return _expires.get();
451 * @return the number of responses with a 1xx status returned by this context
452 * since {@link #statsReset()} was last called.
454 @ManagedAttribute("number of requests with 1xx response status")
455 public int getResponses1xx()
457 return _responses1xx.get();
461 * @return the number of responses with a 2xx status returned by this context
462 * since {@link #statsReset()} was last called.
464 @ManagedAttribute("number of requests with 2xx response status")
465 public int getResponses2xx()
467 return _responses2xx.get();
471 * @return the number of responses with a 3xx status returned by this context
472 * since {@link #statsReset()} was last called.
474 @ManagedAttribute("number of requests with 3xx response status")
475 public int getResponses3xx()
477 return _responses3xx.get();
481 * @return the number of responses with a 4xx status returned by this context
482 * since {@link #statsReset()} was last called.
484 @ManagedAttribute("number of requests with 4xx response status")
485 public int getResponses4xx()
487 return _responses4xx.get();
491 * @return the number of responses with a 5xx status returned by this context
492 * since {@link #statsReset()} was last called.
494 @ManagedAttribute("number of requests with 5xx response status")
495 public int getResponses5xx()
497 return _responses5xx.get();
501 * @return the milliseconds since the statistics were started with {@link #statsReset()}.
503 @ManagedAttribute("time in milliseconds stats have been collected for")
504 public long getStatsOnMs()
506 return System.currentTimeMillis() - _statsStartedAt.get();
510 * @return the total bytes of content sent in responses
512 @ManagedAttribute("total number of bytes across all responses")
513 public long getResponsesBytesTotal()
515 return _responsesTotalBytes.get();
518 public String toStatsHTML()
520 StringBuilder sb = new StringBuilder();
522 sb.append("<h1>Statistics:</h1>\n");
523 sb.append("Statistics gathering started ").append(getStatsOnMs()).append("ms ago").append("<br />\n");
525 sb.append("<h2>Requests:</h2>\n");
526 sb.append("Total requests: ").append(getRequests()).append("<br />\n");
527 sb.append("Active requests: ").append(getRequestsActive()).append("<br />\n");
528 sb.append("Max active requests: ").append(getRequestsActiveMax()).append("<br />\n");
529 sb.append("Total requests time: ").append(getRequestTimeTotal()).append("<br />\n");
530 sb.append("Mean request time: ").append(getRequestTimeMean()).append("<br />\n");
531 sb.append("Max request time: ").append(getRequestTimeMax()).append("<br />\n");
532 sb.append("Request time standard deviation: ").append(getRequestTimeStdDev()).append("<br />\n");
535 sb.append("<h2>Dispatches:</h2>\n");
536 sb.append("Total dispatched: ").append(getDispatched()).append("<br />\n");
537 sb.append("Active dispatched: ").append(getDispatchedActive()).append("<br />\n");
538 sb.append("Max active dispatched: ").append(getDispatchedActiveMax()).append("<br />\n");
539 sb.append("Total dispatched time: ").append(getDispatchedTimeTotal()).append("<br />\n");
540 sb.append("Mean dispatched time: ").append(getDispatchedTimeMean()).append("<br />\n");
541 sb.append("Max dispatched time: ").append(getDispatchedTimeMax()).append("<br />\n");
542 sb.append("Dispatched time standard deviation: ").append(getDispatchedTimeStdDev()).append("<br />\n");
545 sb.append("Total requests suspended: ").append(getAsyncRequests()).append("<br />\n");
546 sb.append("Total requests expired: ").append(getExpires()).append("<br />\n");
547 sb.append("Total requests resumed: ").append(getAsyncDispatches()).append("<br />\n");
549 sb.append("<h2>Responses:</h2>\n");
550 sb.append("1xx responses: ").append(getResponses1xx()).append("<br />\n");
551 sb.append("2xx responses: ").append(getResponses2xx()).append("<br />\n");
552 sb.append("3xx responses: ").append(getResponses3xx()).append("<br />\n");
553 sb.append("4xx responses: ").append(getResponses4xx()).append("<br />\n");
554 sb.append("5xx responses: ").append(getResponses5xx()).append("<br />\n");
555 sb.append("Bytes sent total: ").append(getResponsesBytesTotal()).append("<br />\n");
557 return sb.toString();
562 public Future<Void> shutdown()
564 FutureCallback shutdown=new FutureCallback(false);
565 _shutdown.compareAndSet(null,shutdown);
566 shutdown=_shutdown.get();
567 if (_dispatchedStats.getCurrent()==0)
568 shutdown.succeeded();