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
package org.apache.mina.management;
import static org.jivesoftware.openfire.spi.ConnectionManagerImpl.EXECUTOR_FILTER_NAME;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.executor.OrderedThreadPoolExecutor;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
/**
* Collects statistics of an {@link org.apache.mina.common.IoService}. It's polling all the sessions of a given
* IoService. It's attaching a {@link org.apache.mina.management.IoSessionStat} object to all the sessions polled
* and filling the throughput values.
*
* Usage :
* <pre>
* IoService service = ...
* MINAStatCollector collector = new MINAStatCollector( service );
* collector.start();
* </pre>
*
* By default the {@link org.apache.mina.management.MINAStatCollector} is polling the sessions every 5 seconds. You can
* give a different polling time using a second constructor.<p>
*
* Note: This class is a spin-off from StatCollector present in
* https://svn.apache.org/repos/asf/mina/branches/1.1/core/src/main/java/org/apache/mina/management.
*
* @author The Apache Directory Project (mina-dev@directory.apache.org)
* @version $Rev: 477648 $, $Date: 2006-11-21 04:33:38 -0800 (Tue, 21 Nov 2006) $
*/
public class MINAStatCollector {
/**
* The session attribute key for {@link org.apache.mina.management.IoSessionStat}.
*/
public static final String KEY = MINAStatCollector.class.getName() + ".stat";
/**
* @noinspection StaticNonFinalField
*/
private static volatile int nextId = 0;
private final int id = nextId ++;
private final IoService service;
private Worker worker;
private int pollingInterval = 5000;
private Queue<IoSession> polledSessions;
// resume of session stats, for simplifying acces to the statistics
private AtomicLong totalProcessedSessions = new AtomicLong();
private AtomicLong totalMsgWritten = new AtomicLong();
private AtomicLong totalMsgRead = new AtomicLong();
private AtomicLong totalBytesWritten = new AtomicLong();
private AtomicLong totalBytesRead = new AtomicLong();
private AtomicLong totalScheduledWrites = new AtomicLong();
private AtomicLong totalQueuedEvents = new AtomicLong();
private final IoServiceListener serviceListener = new IoServiceListener()
{
public void sessionCreated( IoSession session )
{
addSession( session );
}
public void sessionDestroyed( IoSession session )
{
removeSession( session );
}
@Override
public void serviceActivated(IoService service) throws Exception {
}
@Override
public void serviceIdle(IoService service, IdleStatus idleStatus) throws Exception {
}
@Override
public void serviceDeactivated(IoService service) throws Exception {
}
@Override
public void sessionClosed(IoSession arg0) throws Exception {
}
};
/**
* Create a stat collector for the given service with a default polling time of 5 seconds.
* @param service the IoService to inspect
*/
public MINAStatCollector( IoService service )
{
this( service,5000 );
}
/**
* create a stat collector for the given given service
* @param service the IoService to inspect
* @param pollingInterval milliseconds
*/
public MINAStatCollector( IoService service, int pollingInterval )
{
this.service = service;
this.pollingInterval = pollingInterval;
}
/**
* Start collecting stats for the {@link org.apache.mina.common.IoSession} of the service.
* New sessions or destroyed will be automaticly added or removed.
*/
public void start()
{
synchronized (this)
{
if ( worker != null && worker.isAlive() )
throw new RuntimeException( "Stat collecting already started" );
// add all current sessions
polledSessions = new ConcurrentLinkedQueue<IoSession>();
Map<Long, IoSession> sessions = service.getManagedSessions();
if (sessions != null) {
for (IoSession ioSession : sessions.values()) {
addSession(ioSession);
}
}
// listen for new ones
service.addListener( serviceListener );
// start polling
worker = new Worker();
worker.start();
}
}
/**
* Stop collecting stats. all the {@link org.apache.mina.management.IoSessionStat} object will be removed of the
* polled session attachements.
*/
public void stop()
{
synchronized (this)
{
service.removeListener( serviceListener );
// stop worker
worker.stop = true;
worker.interrupt();
while( worker.isAlive() )
{
try
{
worker.join();
}
catch( InterruptedException e )
{
//ignore since this is shutdown time
}
}
for (IoSession session : polledSessions) {
session.removeAttribute(KEY);
}
polledSessions.clear();
}
}
/**
* is the stat collector started and polling the {@link org.apache.mina.common.IoSession} of the {@link org.apache.mina.common.IoService}
* @return true if started
*/
public boolean isRunning()
{
synchronized (this)
{
return worker != null && worker.stop != true;
}
}
private void addSession( IoSession session )
{
IoSessionStat sessionStats = new IoSessionStat();
sessionStats.lastPollingTime = System.currentTimeMillis();
session.setAttribute( KEY, sessionStats );
totalProcessedSessions.incrementAndGet();
polledSessions.add( session );
}
private void removeSession( IoSession session )
{
// remove the session from the list of polled sessions
polledSessions.remove( session );
// add the bytes processed between last polling and session closing
// prevent non seen byte with non-connected protocols like HTTP and datagrams
IoSessionStat sessStat = ( IoSessionStat ) session.getAttribute( KEY );
session.removeAttribute( KEY );
totalMsgWritten.addAndGet(session.getWrittenMessages() - sessStat.lastMessageWrite);
totalMsgRead.addAndGet(session.getReadMessages() - sessStat.lastMessageRead);
totalBytesWritten.addAndGet(session.getWrittenBytes() - sessStat.lastByteWrite);
totalBytesRead.addAndGet(session.getReadBytes() - sessStat.lastByteRead);
}
/**
* total number of sessions processed by the stat collector
* @return number of sessions
*/
public long getTotalProcessedSessions()
{
return totalProcessedSessions.longValue();
}
public long getBytesRead()
{
return totalBytesRead.get();
}
public long getBytesWritten()
{
return totalBytesWritten.get();
}
public long getMsgRead()
{
return totalMsgRead.get();
}
public long getMsgWritten()
{
return totalMsgWritten.get();
}
public long getScheduledWrites() {
return totalScheduledWrites.get();
}
public long getQueuedEvents() {
return totalQueuedEvents.get();
}
public long getSessionCount()
{
return polledSessions.size();
}
private class Worker extends Thread
{
boolean stop = false;
private Worker()
{
super( "StatCollectorWorker-"+id );
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run()
{
while ( !stop )
{
// wait polling time
try
{
Thread.sleep( pollingInterval );
}
catch ( InterruptedException e )
{
}
long tmpMsgWritten = 0l;
long tmpMsgRead = 0l;
long tmpBytesWritten = 0l;
long tmpBytesRead = 0l;
long tmpScheduledWrites = 0l;
long tmpQueuevedEvents = 0l;
for (IoSession session : polledSessions)
{
// upadating individual session statistics
IoSessionStat sessStat = ( IoSessionStat ) session.getAttribute( KEY );
long currentTimestamp = System.currentTimeMillis();
// Calculate delta
float pollDelta = (currentTimestamp - sessStat.lastPollingTime) / 1000f;
// Store last polling time of this session
sessStat.lastPollingTime = currentTimestamp;
long readBytes = session.getReadBytes();
long writtenBytes = session.getWrittenBytes();
long readMessages = session.getReadMessages();
long writtenMessages = session.getWrittenMessages();
sessStat.byteReadThroughput = (readBytes - sessStat.lastByteRead) / pollDelta;
sessStat.byteWrittenThroughput = (writtenBytes - sessStat.lastByteWrite) / pollDelta;
sessStat.messageReadThroughput = (readMessages - sessStat.lastMessageRead) / pollDelta;
sessStat.messageWrittenThroughput = (writtenMessages - sessStat.lastMessageWrite) / pollDelta;
tmpMsgWritten += (writtenMessages - sessStat.lastMessageWrite);
tmpMsgRead += (readMessages - sessStat.lastMessageRead);
tmpBytesWritten += (writtenBytes - sessStat.lastByteWrite);
tmpBytesRead += (readBytes - sessStat.lastByteRead);
tmpScheduledWrites += session.getScheduledWriteMessages();
ExecutorFilter executorFilter =
(ExecutorFilter) session.getFilterChain().get(EXECUTOR_FILTER_NAME);
if (executorFilter != null) {
Executor executor = executorFilter.getExecutor();
if (executor instanceof OrderedThreadPoolExecutor) {
tmpQueuevedEvents += ((OrderedThreadPoolExecutor) executor).getActiveCount();
}
}
sessStat.lastByteRead = readBytes;
sessStat.lastByteWrite = writtenBytes;
sessStat.lastMessageRead = readMessages;
sessStat.lastMessageWrite = writtenMessages;
}
totalMsgWritten.addAndGet(tmpMsgWritten);
totalMsgRead.addAndGet(tmpMsgRead);
totalBytesWritten.addAndGet(tmpBytesWritten);
totalBytesRead.addAndGet(tmpBytesRead);
totalScheduledWrites.set(tmpScheduledWrites);
totalQueuedEvents.set(tmpQueuevedEvents);
}
}
}
public class IoSessionStat {
long lastByteRead = -1;
long lastByteWrite = -1;
long lastMessageRead = -1;
long lastMessageWrite = -1;
float byteWrittenThroughput = 0;
float byteReadThroughput = 0;
float messageWrittenThroughput = 0;
float messageReadThroughput = 0;
// last time the session was polled
long lastPollingTime = System.currentTimeMillis();
/**
* Bytes read per second
* @return bytes per second
*/
public float getByteReadThroughput() {
return byteReadThroughput;
}
/**
* Bytes written per second
* @return bytes per second
*/
public float getByteWrittenThroughput() {
return byteWrittenThroughput;
}
/**
* Messages read per second
* @return messages per second
*/
public float getMessageReadThroughput() {
return messageReadThroughput;
}
/**
* Messages written per second
* @return messages per second
*/
public float getMessageWrittenThroughput() {
return messageWrittenThroughput;
}
/**
* used for the StatCollector, last polling value
*/
long getLastByteRead() {
return lastByteRead;
}
/**
* used for the StatCollector, last polling value
*/
long getLastByteWrite() {
return lastByteWrite;
}
/**
* used for the StatCollector, last polling value
*/
long getLastMessageRead() {
return lastMessageRead;
}
/**
* used for the StatCollector, last polling value
*/
long getLastMessageWrite() {
return lastMessageWrite;
}
}
}