/
StatisticsHandler.java
626 lines (556 loc) · 20.6 KB
/
StatisticsHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.handler;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.AsyncContextEvent;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpChannelState;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.component.Graceful;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.statistic.CounterStatistic;
import org.eclipse.jetty.util.statistic.SampleStatistic;
@ManagedObject("Request Statistics Gathering")
public class StatisticsHandler extends HandlerWrapper implements Graceful
{
private static final Logger LOG = Log.getLogger(StatisticsHandler.class);
private final AtomicLong _statsStartedAt = new AtomicLong();
private final CounterStatistic _requestStats = new CounterStatistic();
private final SampleStatistic _requestTimeStats = new SampleStatistic();
private final CounterStatistic _dispatchedStats = new CounterStatistic();
private final SampleStatistic _dispatchedTimeStats = new SampleStatistic();
private final CounterStatistic _asyncWaitStats = new CounterStatistic();
private final LongAdder _asyncDispatches = new LongAdder();
private final LongAdder _expires = new LongAdder();
private final LongAdder _errors = new LongAdder();
private final LongAdder _responses1xx = new LongAdder();
private final LongAdder _responses2xx = new LongAdder();
private final LongAdder _responses3xx = new LongAdder();
private final LongAdder _responses4xx = new LongAdder();
private final LongAdder _responses5xx = new LongAdder();
private final LongAdder _responsesTotalBytes = new LongAdder();
private boolean _gracefulShutdownWaitsForRequests = true;
private final Graceful.Shutdown _shutdown = new Graceful.Shutdown()
{
@Override
protected FutureCallback newShutdownCallback()
{
return new FutureCallback(_requestStats.getCurrent() == 0);
}
};
private final AsyncListener _onCompletion = new AsyncListener()
{
@Override
public void onStartAsync(AsyncEvent event)
{
event.getAsyncContext().addListener(this);
}
@Override
public void onTimeout(AsyncEvent event)
{
_expires.increment();
}
@Override
public void onError(AsyncEvent event)
{
_errors.increment();
}
@Override
public void onComplete(AsyncEvent event)
{
HttpChannelState state = ((AsyncContextEvent)event).getHttpChannelState();
Request request = state.getBaseRequest();
final long elapsed = System.currentTimeMillis() - request.getTimeStamp();
long numRequests = _requestStats.decrement();
_requestTimeStats.record(elapsed);
updateResponse(request);
_asyncWaitStats.decrement();
if (numRequests == 0 && _gracefulShutdownWaitsForRequests)
{
FutureCallback shutdown = _shutdown.get();
if (shutdown != null)
shutdown.succeeded();
}
}
};
/**
* Resets the current request statistics.
*/
@ManagedOperation(value = "resets statistics", impact = "ACTION")
public void statsReset()
{
_statsStartedAt.set(System.currentTimeMillis());
_requestStats.reset();
_requestTimeStats.reset();
_dispatchedStats.reset();
_dispatchedTimeStats.reset();
_asyncWaitStats.reset();
_asyncDispatches.reset();
_expires.reset();
_responses1xx.reset();
_responses2xx.reset();
_responses3xx.reset();
_responses4xx.reset();
_responses5xx.reset();
_responsesTotalBytes.reset();
}
@Override
public void handle(String path, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
Handler handler = getHandler();
if (handler == null || !isStarted() || isShutdown())
{
if (!baseRequest.getResponse().isCommitted())
response.sendError(HttpStatus.SERVICE_UNAVAILABLE_503);
return;
}
_dispatchedStats.increment();
final long start;
HttpChannelState state = baseRequest.getHttpChannelState();
if (state.isInitial())
{
// new request
_requestStats.increment();
start = baseRequest.getTimeStamp();
}
else
{
// resumed request
start = System.currentTimeMillis();
_asyncDispatches.increment();
}
try
{
handler.handle(path, baseRequest, request, response);
}
finally
{
final long now = System.currentTimeMillis();
final long dispatched = now - start;
long numRequests = -1;
long numDispatches = _dispatchedStats.decrement();
_dispatchedTimeStats.record(dispatched);
if (state.isInitial())
{
if (state.isAsyncStarted())
{
state.addListener(_onCompletion);
_asyncWaitStats.increment();
}
else
{
numRequests = _requestStats.decrement();
_requestTimeStats.record(dispatched);
updateResponse(baseRequest);
}
}
FutureCallback shutdown = _shutdown.get();
if (shutdown != null)
{
response.flushBuffer();
if (_gracefulShutdownWaitsForRequests ? (numRequests == 0) : (numDispatches == 0))
shutdown.succeeded();
}
}
}
protected void updateResponse(Request request)
{
Response response = request.getResponse();
if (request.isHandled())
{
switch (response.getStatus() / 100)
{
case 1:
_responses1xx.increment();
break;
case 2:
_responses2xx.increment();
break;
case 3:
_responses3xx.increment();
break;
case 4:
_responses4xx.increment();
break;
case 5:
_responses5xx.increment();
break;
default:
break;
}
}
else
// will fall through to not found handler
_responses4xx.increment();
_responsesTotalBytes.add(response.getContentCount());
}
@Override
protected void doStart() throws Exception
{
if (getHandler() == null)
throw new IllegalStateException("StatisticsHandler has no Wrapped Handler");
_shutdown.cancel();
super.doStart();
statsReset();
}
@Override
protected void doStop() throws Exception
{
_shutdown.cancel();
super.doStop();
}
/**
* Set whether the graceful shutdown should wait for all requests to complete including
* async requests which are not currently dispatched, or whether it should only wait for all the
* actively dispatched requests to complete.
* @param gracefulShutdownWaitsForRequests true to wait for async requests on graceful shutdown.
*/
public void setGracefulShutdownWaitsForRequests(boolean gracefulShutdownWaitsForRequests)
{
_gracefulShutdownWaitsForRequests = gracefulShutdownWaitsForRequests;
}
/**
* @return whether the graceful shutdown will wait for all requests to complete including
* async requests which are not currently dispatched, or whether it will only wait for all the
* actively dispatched requests to complete.
* @see #getAsyncDispatches()
*/
@ManagedAttribute("if graceful shutdown will wait for all requests")
public boolean getGracefulShutdownWaitsForRequests()
{
return _gracefulShutdownWaitsForRequests;
}
/**
* @return the number of requests handled by this handler
* since {@link #statsReset()} was last called, excluding
* active requests
* @see #getAsyncDispatches()
*/
@ManagedAttribute("number of requests")
public int getRequests()
{
return (int)_requestStats.getTotal();
}
/**
* @return the number of requests currently active.
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("number of requests currently active")
public int getRequestsActive()
{
return (int)_requestStats.getCurrent();
}
/**
* @return the maximum number of active requests
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("maximum number of active requests")
public int getRequestsActiveMax()
{
return (int)_requestStats.getMax();
}
/**
* @return the maximum time (in milliseconds) of request handling
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("maximum time spend handling requests (in ms)")
public long getRequestTimeMax()
{
return _requestTimeStats.getMax();
}
/**
* @return the total time (in milliseconds) of requests handling
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("total time spend in all request handling (in ms)")
public long getRequestTimeTotal()
{
return _requestTimeStats.getTotal();
}
/**
* @return the mean time (in milliseconds) of request handling
* since {@link #statsReset()} was last called.
* @see #getRequestTimeTotal()
* @see #getRequests()
*/
@ManagedAttribute("mean time spent handling requests (in ms)")
public double getRequestTimeMean()
{
return _requestTimeStats.getMean();
}
/**
* @return the standard deviation of time (in milliseconds) of request handling
* since {@link #statsReset()} was last called.
* @see #getRequestTimeTotal()
* @see #getRequests()
*/
@ManagedAttribute("standard deviation for request handling (in ms)")
public double getRequestTimeStdDev()
{
return _requestTimeStats.getStdDev();
}
/**
* @return the number of dispatches seen by this handler
* since {@link #statsReset()} was last called, excluding
* active dispatches
*/
@ManagedAttribute("number of dispatches")
public int getDispatched()
{
return (int)_dispatchedStats.getTotal();
}
/**
* @return the number of dispatches currently in this handler
* since {@link #statsReset()} was last called, including
* resumed requests
*/
@ManagedAttribute("number of dispatches currently active")
public int getDispatchedActive()
{
return (int)_dispatchedStats.getCurrent();
}
/**
* @return the max number of dispatches currently in this handler
* since {@link #statsReset()} was last called, including
* resumed requests
*/
@ManagedAttribute("maximum number of active dispatches being handled")
public int getDispatchedActiveMax()
{
return (int)_dispatchedStats.getMax();
}
/**
* @return the maximum time (in milliseconds) of request dispatch
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("maximum time spend in dispatch handling")
public long getDispatchedTimeMax()
{
return _dispatchedTimeStats.getMax();
}
/**
* @return the total time (in milliseconds) of requests handling
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("total time spent in dispatch handling (in ms)")
public long getDispatchedTimeTotal()
{
return _dispatchedTimeStats.getTotal();
}
/**
* @return the mean time (in milliseconds) of request handling
* since {@link #statsReset()} was last called.
* @see #getRequestTimeTotal()
* @see #getRequests()
*/
@ManagedAttribute("mean time spent in dispatch handling (in ms)")
public double getDispatchedTimeMean()
{
return _dispatchedTimeStats.getMean();
}
/**
* @return the standard deviation of time (in milliseconds) of request handling
* since {@link #statsReset()} was last called.
* @see #getRequestTimeTotal()
* @see #getRequests()
*/
@ManagedAttribute("standard deviation for dispatch handling (in ms)")
public double getDispatchedTimeStdDev()
{
return _dispatchedTimeStats.getStdDev();
}
/**
* @return the number of requests handled by this handler
* since {@link #statsReset()} was last called, including
* resumed requests
* @see #getAsyncDispatches()
*/
@ManagedAttribute("total number of async requests")
public int getAsyncRequests()
{
return (int)_asyncWaitStats.getTotal();
}
/**
* @return the number of requests currently suspended.
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("currently waiting async requests")
public int getAsyncRequestsWaiting()
{
return (int)_asyncWaitStats.getCurrent();
}
/**
* @return the maximum number of current suspended requests
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("maximum number of waiting async requests")
public int getAsyncRequestsWaitingMax()
{
return (int)_asyncWaitStats.getMax();
}
/**
* @return the number of requests that have been asynchronously dispatched
*/
@ManagedAttribute("number of requested that have been asynchronously dispatched")
public int getAsyncDispatches()
{
return _asyncDispatches.intValue();
}
/**
* @return the number of requests that expired while suspended.
* @see #getAsyncDispatches()
*/
@ManagedAttribute("number of async requests requests that have expired")
public int getExpires()
{
return _expires.intValue();
}
/**
* @return the number of async errors that occurred.
* @see #getAsyncDispatches()
*/
@ManagedAttribute("number of async errors that occurred")
public int getErrors()
{
return _errors.intValue();
}
/**
* @return the number of responses with a 1xx status returned by this context
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("number of requests with 1xx response status")
public int getResponses1xx()
{
return _responses1xx.intValue();
}
/**
* @return the number of responses with a 2xx status returned by this context
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("number of requests with 2xx response status")
public int getResponses2xx()
{
return _responses2xx.intValue();
}
/**
* @return the number of responses with a 3xx status returned by this context
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("number of requests with 3xx response status")
public int getResponses3xx()
{
return _responses3xx.intValue();
}
/**
* @return the number of responses with a 4xx status returned by this context
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("number of requests with 4xx response status")
public int getResponses4xx()
{
return _responses4xx.intValue();
}
/**
* @return the number of responses with a 5xx status returned by this context
* since {@link #statsReset()} was last called.
*/
@ManagedAttribute("number of requests with 5xx response status")
public int getResponses5xx()
{
return _responses5xx.intValue();
}
/**
* @return the milliseconds since the statistics were started with {@link #statsReset()}.
*/
@ManagedAttribute("time in milliseconds stats have been collected for")
public long getStatsOnMs()
{
return System.currentTimeMillis() - _statsStartedAt.get();
}
/**
* @return the total bytes of content sent in responses
*/
@ManagedAttribute("total number of bytes across all responses")
public long getResponsesBytesTotal()
{
return _responsesTotalBytes.longValue();
}
public String toStatsHTML()
{
StringBuilder sb = new StringBuilder();
sb.append("<h1>Statistics:</h1>\n");
sb.append("Statistics gathering started ").append(getStatsOnMs()).append("ms ago").append("<br />\n");
sb.append("<h2>Requests:</h2>\n");
sb.append("Total requests: ").append(getRequests()).append("<br />\n");
sb.append("Active requests: ").append(getRequestsActive()).append("<br />\n");
sb.append("Max active requests: ").append(getRequestsActiveMax()).append("<br />\n");
sb.append("Total requests time: ").append(getRequestTimeTotal()).append("<br />\n");
sb.append("Mean request time: ").append(getRequestTimeMean()).append("<br />\n");
sb.append("Max request time: ").append(getRequestTimeMax()).append("<br />\n");
sb.append("Request time standard deviation: ").append(getRequestTimeStdDev()).append("<br />\n");
sb.append("<h2>Dispatches:</h2>\n");
sb.append("Total dispatched: ").append(getDispatched()).append("<br />\n");
sb.append("Active dispatched: ").append(getDispatchedActive()).append("<br />\n");
sb.append("Max active dispatched: ").append(getDispatchedActiveMax()).append("<br />\n");
sb.append("Total dispatched time: ").append(getDispatchedTimeTotal()).append("<br />\n");
sb.append("Mean dispatched time: ").append(getDispatchedTimeMean()).append("<br />\n");
sb.append("Max dispatched time: ").append(getDispatchedTimeMax()).append("<br />\n");
sb.append("Dispatched time standard deviation: ").append(getDispatchedTimeStdDev()).append("<br />\n");
sb.append("Total requests suspended: ").append(getAsyncRequests()).append("<br />\n");
sb.append("Total requests expired: ").append(getExpires()).append("<br />\n");
sb.append("Total requests resumed: ").append(getAsyncDispatches()).append("<br />\n");
sb.append("<h2>Responses:</h2>\n");
sb.append("1xx responses: ").append(getResponses1xx()).append("<br />\n");
sb.append("2xx responses: ").append(getResponses2xx()).append("<br />\n");
sb.append("3xx responses: ").append(getResponses3xx()).append("<br />\n");
sb.append("4xx responses: ").append(getResponses4xx()).append("<br />\n");
sb.append("5xx responses: ").append(getResponses5xx()).append("<br />\n");
sb.append("Bytes sent total: ").append(getResponsesBytesTotal()).append("<br />\n");
return sb.toString();
}
@Override
public Future<Void> shutdown()
{
return _shutdown.shutdown();
}
@Override
public boolean isShutdown()
{
return _shutdown.isShutdown();
}
@Override
public String toString()
{
return String.format("%s@%x{%s,r=%d,d=%d}", getClass().getSimpleName(), hashCode(), getState(), _requestStats.getCurrent(), _dispatchedStats.getCurrent());
}
}