1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.traffic;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelPromise;
22 import io.netty.channel.ChannelHandler.Sharable;
23 import io.netty.util.concurrent.EventExecutor;
24 import io.netty.util.internal.PlatformDependent;
25
26 import java.util.ArrayDeque;
27 import java.util.concurrent.ConcurrentMap;
28 import java.util.concurrent.ScheduledExecutorService;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.atomic.AtomicLong;
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 @Sharable
78 public class GlobalTrafficShapingHandler extends AbstractTrafficShapingHandler {
79
80
81
82 private final ConcurrentMap<Integer, PerChannel> channelQueues = PlatformDependent.newConcurrentHashMap();
83
84
85
86
87 private final AtomicLong queuesSize = new AtomicLong();
88
89
90
91
92
93 long maxGlobalWriteSize = DEFAULT_MAX_SIZE * 100;
94
95 private static final class PerChannel {
96 ArrayDeque<ToSend> messagesQueue;
97 long queueSize;
98 long lastWriteTimestamp;
99 long lastReadTimestamp;
100 }
101
102
103
104
105 void createGlobalTrafficCounter(ScheduledExecutorService executor) {
106 if (executor == null) {
107 throw new NullPointerException("executor");
108 }
109 TrafficCounter tc = new TrafficCounter(this, executor, "GlobalTC", checkInterval);
110 setTrafficCounter(tc);
111 tc.start();
112 }
113
114 @Override
115 protected int userDefinedWritabilityIndex() {
116 return AbstractTrafficShapingHandler.GLOBAL_DEFAULT_USER_DEFINED_WRITABILITY_INDEX;
117 }
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 public GlobalTrafficShapingHandler(ScheduledExecutorService executor, long writeLimit, long readLimit,
135 long checkInterval, long maxTime) {
136 super(writeLimit, readLimit, checkInterval, maxTime);
137 createGlobalTrafficCounter(executor);
138 }
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154 public GlobalTrafficShapingHandler(ScheduledExecutorService executor, long writeLimit,
155 long readLimit, long checkInterval) {
156 super(writeLimit, readLimit, checkInterval);
157 createGlobalTrafficCounter(executor);
158 }
159
160
161
162
163
164
165
166
167
168
169
170
171 public GlobalTrafficShapingHandler(ScheduledExecutorService executor, long writeLimit,
172 long readLimit) {
173 super(writeLimit, readLimit);
174 createGlobalTrafficCounter(executor);
175 }
176
177
178
179
180
181
182
183
184
185
186
187 public GlobalTrafficShapingHandler(ScheduledExecutorService executor, long checkInterval) {
188 super(checkInterval);
189 createGlobalTrafficCounter(executor);
190 }
191
192
193
194
195
196
197
198
199 public GlobalTrafficShapingHandler(EventExecutor executor) {
200 createGlobalTrafficCounter(executor);
201 }
202
203
204
205
206 public long getMaxGlobalWriteSize() {
207 return maxGlobalWriteSize;
208 }
209
210
211
212
213
214
215
216
217
218
219
220
221 public void setMaxGlobalWriteSize(long maxGlobalWriteSize) {
222 this.maxGlobalWriteSize = maxGlobalWriteSize;
223 }
224
225
226
227
228 public long queuesSize() {
229 return queuesSize.get();
230 }
231
232
233
234
235 public final void release() {
236 trafficCounter.stop();
237 }
238
239 private PerChannel getOrSetPerChannel(ChannelHandlerContext ctx) {
240
241 Channel channel = ctx.channel();
242 Integer key = channel.hashCode();
243 PerChannel perChannel = channelQueues.get(key);
244 if (perChannel == null) {
245 perChannel = new PerChannel();
246 perChannel.messagesQueue = new ArrayDeque<ToSend>();
247 perChannel.queueSize = 0L;
248 perChannel.lastReadTimestamp = TrafficCounter.milliSecondFromNano();
249 perChannel.lastWriteTimestamp = perChannel.lastReadTimestamp;
250 channelQueues.put(key, perChannel);
251 }
252 return perChannel;
253 }
254
255 @Override
256 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
257 getOrSetPerChannel(ctx);
258 super.handlerAdded(ctx);
259 }
260
261 @Override
262 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
263 Channel channel = ctx.channel();
264 Integer key = channel.hashCode();
265 PerChannel perChannel = channelQueues.remove(key);
266 if (perChannel != null) {
267
268 synchronized (perChannel) {
269 if (channel.isActive()) {
270 for (ToSend toSend : perChannel.messagesQueue) {
271 long size = calculateSize(toSend.toSend);
272 trafficCounter.bytesRealWriteFlowControl(size);
273 perChannel.queueSize -= size;
274 queuesSize.addAndGet(-size);
275 ctx.write(toSend.toSend, toSend.promise);
276 }
277 } else {
278 queuesSize.addAndGet(-perChannel.queueSize);
279 for (ToSend toSend : perChannel.messagesQueue) {
280 if (toSend.toSend instanceof ByteBuf) {
281 ((ByteBuf) toSend.toSend).release();
282 }
283 }
284 }
285 perChannel.messagesQueue.clear();
286 }
287 }
288 releaseWriteSuspended(ctx);
289 releaseReadSuspended(ctx);
290 super.handlerRemoved(ctx);
291 }
292
293 @Override
294 long checkWaitReadTime(final ChannelHandlerContext ctx, long wait, final long now) {
295 Integer key = ctx.channel().hashCode();
296 PerChannel perChannel = channelQueues.get(key);
297 if (perChannel != null) {
298 if (wait > maxTime && now + wait - perChannel.lastReadTimestamp > maxTime) {
299 wait = maxTime;
300 }
301 }
302 return wait;
303 }
304
305 @Override
306 void informReadOperation(final ChannelHandlerContext ctx, final long now) {
307 Integer key = ctx.channel().hashCode();
308 PerChannel perChannel = channelQueues.get(key);
309 if (perChannel != null) {
310 perChannel.lastReadTimestamp = now;
311 }
312 }
313
314 private static final class ToSend {
315 final long relativeTimeAction;
316 final Object toSend;
317 final long size;
318 final ChannelPromise promise;
319
320 private ToSend(final long delay, final Object toSend, final long size, final ChannelPromise promise) {
321 relativeTimeAction = delay;
322 this.toSend = toSend;
323 this.size = size;
324 this.promise = promise;
325 }
326 }
327
328 @Override
329 void submitWrite(final ChannelHandlerContext ctx, final Object msg,
330 final long size, final long writedelay, final long now,
331 final ChannelPromise promise) {
332 Channel channel = ctx.channel();
333 Integer key = channel.hashCode();
334 PerChannel perChannel = channelQueues.get(key);
335 if (perChannel == null) {
336
337
338 perChannel = getOrSetPerChannel(ctx);
339 }
340 final ToSend newToSend;
341 long delay = writedelay;
342 boolean globalSizeExceeded = false;
343
344 synchronized (perChannel) {
345 if (writedelay == 0 && perChannel.messagesQueue.isEmpty()) {
346 trafficCounter.bytesRealWriteFlowControl(size);
347 ctx.write(msg, promise);
348 perChannel.lastWriteTimestamp = now;
349 return;
350 }
351 if (delay > maxTime && now + delay - perChannel.lastWriteTimestamp > maxTime) {
352 delay = maxTime;
353 }
354 newToSend = new ToSend(delay + now, msg, size, promise);
355 perChannel.messagesQueue.addLast(newToSend);
356 perChannel.queueSize += size;
357 queuesSize.addAndGet(size);
358 checkWriteSuspend(ctx, delay, perChannel.queueSize);
359 if (queuesSize.get() > maxGlobalWriteSize) {
360 globalSizeExceeded = true;
361 }
362 }
363 if (globalSizeExceeded) {
364 setUserDefinedWritability(ctx, false);
365 }
366 final long futureNow = newToSend.relativeTimeAction;
367 final PerChannel forSchedule = perChannel;
368 ctx.executor().schedule(new Runnable() {
369 @Override
370 public void run() {
371 sendAllValid(ctx, forSchedule, futureNow);
372 }
373 }, delay, TimeUnit.MILLISECONDS);
374 }
375
376 private void sendAllValid(final ChannelHandlerContext ctx, final PerChannel perChannel, final long now) {
377
378 synchronized (perChannel) {
379 ToSend newToSend = perChannel.messagesQueue.pollFirst();
380 for (; newToSend != null; newToSend = perChannel.messagesQueue.pollFirst()) {
381 if (newToSend.relativeTimeAction <= now) {
382 long size = newToSend.size;
383 trafficCounter.bytesRealWriteFlowControl(size);
384 perChannel.queueSize -= size;
385 queuesSize.addAndGet(-size);
386 ctx.write(newToSend.toSend, newToSend.promise);
387 perChannel.lastWriteTimestamp = now;
388 } else {
389 perChannel.messagesQueue.addFirst(newToSend);
390 break;
391 }
392 }
393 if (perChannel.messagesQueue.isEmpty()) {
394 releaseWriteSuspended(ctx);
395 }
396 }
397 ctx.flush();
398 }
399 }