1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.traffic;
17
18 import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
19 import static io.netty.util.internal.ObjectUtil.checkPositive;
20 import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
21
22 import io.netty.channel.Channel;
23 import io.netty.channel.ChannelId;
24 import io.netty.channel.ChannelHandler.Sharable;
25 import io.netty.channel.ChannelConfig;
26 import io.netty.channel.ChannelHandlerContext;
27 import io.netty.channel.ChannelPromise;
28 import io.netty.util.Attribute;
29 import io.netty.util.concurrent.EventExecutor;
30 import io.netty.util.internal.logging.InternalLogger;
31 import io.netty.util.internal.logging.InternalLoggerFactory;
32
33 import java.nio.channels.ClosedChannelException;
34 import java.util.AbstractCollection;
35 import java.util.ArrayDeque;
36 import java.util.Collection;
37 import java.util.Iterator;
38 import java.util.concurrent.ConcurrentHashMap;
39 import java.util.concurrent.ConcurrentMap;
40 import java.util.concurrent.ScheduledExecutorService;
41 import java.util.concurrent.TimeUnit;
42 import java.util.concurrent.atomic.AtomicLong;
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 @Sharable
92 public class GlobalChannelTrafficShapingHandler extends AbstractTrafficShapingHandler {
93 private static final InternalLogger logger =
94 InternalLoggerFactory.getInstance(GlobalChannelTrafficShapingHandler.class);
95
96
97
98 final ConcurrentMap<ChannelId, PerChannel> channelQueues = new ConcurrentHashMap<>();
99
100
101
102
103 private final AtomicLong queuesSize = new AtomicLong();
104
105
106
107
108 private final AtomicLong cumulativeWrittenBytes = new AtomicLong();
109
110
111
112
113 private final AtomicLong cumulativeReadBytes = new AtomicLong();
114
115
116
117
118
119 volatile long maxGlobalWriteSize = DEFAULT_MAX_SIZE * 100;
120
121
122
123
124 private volatile long writeChannelLimit;
125
126
127
128
129 private volatile long readChannelLimit;
130
131 private static final float DEFAULT_DEVIATION = 0.1F;
132 private static final float MAX_DEVIATION = 0.4F;
133 private static final float DEFAULT_SLOWDOWN = 0.4F;
134 private static final float DEFAULT_ACCELERATION = -0.1F;
135 private volatile float maxDeviation;
136 private volatile float accelerationFactor;
137 private volatile float slowDownFactor;
138 private volatile boolean readDeviationActive;
139 private volatile boolean writeDeviationActive;
140
141 static final class PerChannel {
142 ArrayDeque<ToSend> messagesQueue;
143 TrafficCounter channelTrafficCounter;
144 long queueSize;
145 long lastWriteTimestamp;
146 long lastReadTimestamp;
147 }
148
149
150
151
152 void createGlobalTrafficCounter(ScheduledExecutorService executor) {
153
154 setMaxDeviation(DEFAULT_DEVIATION, DEFAULT_SLOWDOWN, DEFAULT_ACCELERATION);
155 checkNotNullWithIAE(executor, "executor");
156 TrafficCounter tc = new GlobalChannelTrafficCounter(this, executor, "GlobalChannelTC", checkInterval);
157 setTrafficCounter(tc);
158 tc.start();
159 }
160
161 @Override
162 protected int userDefinedWritabilityIndex() {
163 return AbstractTrafficShapingHandler.GLOBALCHANNEL_DEFAULT_USER_DEFINED_WRITABILITY_INDEX;
164 }
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185 public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor,
186 long writeGlobalLimit, long readGlobalLimit,
187 long writeChannelLimit, long readChannelLimit,
188 long checkInterval, long maxTime) {
189 super(writeGlobalLimit, readGlobalLimit, checkInterval, maxTime);
190 createGlobalTrafficCounter(executor);
191 this.writeChannelLimit = writeChannelLimit;
192 this.readChannelLimit = readChannelLimit;
193 }
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212 public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor,
213 long writeGlobalLimit, long readGlobalLimit,
214 long writeChannelLimit, long readChannelLimit,
215 long checkInterval) {
216 super(writeGlobalLimit, readGlobalLimit, checkInterval);
217 this.writeChannelLimit = writeChannelLimit;
218 this.readChannelLimit = readChannelLimit;
219 createGlobalTrafficCounter(executor);
220 }
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236 public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor,
237 long writeGlobalLimit, long readGlobalLimit,
238 long writeChannelLimit, long readChannelLimit) {
239 super(writeGlobalLimit, readGlobalLimit);
240 this.writeChannelLimit = writeChannelLimit;
241 this.readChannelLimit = readChannelLimit;
242 createGlobalTrafficCounter(executor);
243 }
244
245
246
247
248
249
250
251
252
253
254 public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor, long checkInterval) {
255 super(checkInterval);
256 createGlobalTrafficCounter(executor);
257 }
258
259
260
261
262
263
264
265 public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor) {
266 createGlobalTrafficCounter(executor);
267 }
268
269
270
271
272 public float maxDeviation() {
273 return maxDeviation;
274 }
275
276
277
278
279 public float accelerationFactor() {
280 return accelerationFactor;
281 }
282
283
284
285
286 public float slowDownFactor() {
287 return slowDownFactor;
288 }
289
290
291
292
293
294
295
296
297
298
299
300
301 public void setMaxDeviation(float maxDeviation, float slowDownFactor, float accelerationFactor) {
302 if (maxDeviation > MAX_DEVIATION) {
303 throw new IllegalArgumentException("maxDeviation must be <= " + MAX_DEVIATION);
304 }
305 checkPositiveOrZero(slowDownFactor, "slowDownFactor");
306 if (accelerationFactor > 0) {
307 throw new IllegalArgumentException("accelerationFactor must be <= 0");
308 }
309 this.maxDeviation = maxDeviation;
310 this.accelerationFactor = 1 + accelerationFactor;
311 this.slowDownFactor = 1 + slowDownFactor;
312 }
313
314 private void computeDeviationCumulativeBytes() {
315
316 long maxWrittenBytes = 0;
317 long maxReadBytes = 0;
318 long minWrittenBytes = Long.MAX_VALUE;
319 long minReadBytes = Long.MAX_VALUE;
320 for (PerChannel perChannel : channelQueues.values()) {
321 long value = perChannel.channelTrafficCounter.cumulativeWrittenBytes();
322 if (maxWrittenBytes < value) {
323 maxWrittenBytes = value;
324 }
325 if (minWrittenBytes > value) {
326 minWrittenBytes = value;
327 }
328 value = perChannel.channelTrafficCounter.cumulativeReadBytes();
329 if (maxReadBytes < value) {
330 maxReadBytes = value;
331 }
332 if (minReadBytes > value) {
333 minReadBytes = value;
334 }
335 }
336 boolean multiple = channelQueues.size() > 1;
337 readDeviationActive = multiple && minReadBytes < maxReadBytes / 2;
338 writeDeviationActive = multiple && minWrittenBytes < maxWrittenBytes / 2;
339 cumulativeWrittenBytes.set(maxWrittenBytes);
340 cumulativeReadBytes.set(maxReadBytes);
341 }
342
343 @Override
344 protected void doAccounting(TrafficCounter counter) {
345 computeDeviationCumulativeBytes();
346 super.doAccounting(counter);
347 }
348
349 private long computeBalancedWait(float maxLocal, float maxGlobal, long wait) {
350 if (maxGlobal == 0) {
351
352 return wait;
353 }
354 float ratio = maxLocal / maxGlobal;
355
356 if (ratio > maxDeviation) {
357 if (ratio < 1 - maxDeviation) {
358 return wait;
359 } else {
360 ratio = slowDownFactor;
361 if (wait < MINIMAL_WAIT) {
362 wait = MINIMAL_WAIT;
363 }
364 }
365 } else {
366 ratio = accelerationFactor;
367 }
368 return (long) (wait * ratio);
369 }
370
371
372
373
374 public long getMaxGlobalWriteSize() {
375 return maxGlobalWriteSize;
376 }
377
378
379
380
381
382
383
384
385
386
387
388 public void setMaxGlobalWriteSize(long maxGlobalWriteSize) {
389 this.maxGlobalWriteSize = checkPositive(maxGlobalWriteSize, "maxGlobalWriteSize");
390 }
391
392
393
394
395 public long queuesSize() {
396 return queuesSize.get();
397 }
398
399
400
401
402
403 public void configureChannel(long newWriteLimit, long newReadLimit) {
404 writeChannelLimit = newWriteLimit;
405 readChannelLimit = newReadLimit;
406 long now = TrafficCounter.milliSecondFromNano();
407 for (PerChannel perChannel : channelQueues.values()) {
408 perChannel.channelTrafficCounter.resetAccounting(now);
409 }
410 }
411
412
413
414
415 public long getWriteChannelLimit() {
416 return writeChannelLimit;
417 }
418
419
420
421
422 public void setWriteChannelLimit(long writeLimit) {
423 writeChannelLimit = writeLimit;
424 long now = TrafficCounter.milliSecondFromNano();
425 for (PerChannel perChannel : channelQueues.values()) {
426 perChannel.channelTrafficCounter.resetAccounting(now);
427 }
428 }
429
430
431
432
433 public long getReadChannelLimit() {
434 return readChannelLimit;
435 }
436
437
438
439
440 public void setReadChannelLimit(long readLimit) {
441 readChannelLimit = readLimit;
442 long now = TrafficCounter.milliSecondFromNano();
443 for (PerChannel perChannel : channelQueues.values()) {
444 perChannel.channelTrafficCounter.resetAccounting(now);
445 }
446 }
447
448
449
450
451 public final void release() {
452 trafficCounter.stop();
453 }
454
455 private PerChannel getOrSetPerChannel(ChannelHandlerContext ctx) {
456
457 Channel channel = ctx.channel();
458 ChannelId key = channel.id();
459 PerChannel perChannel = channelQueues.get(key);
460 if (perChannel == null) {
461 perChannel = new PerChannel();
462 perChannel.messagesQueue = new ArrayDeque<ToSend>();
463
464 perChannel.channelTrafficCounter = new TrafficCounter(this, null, "ChannelTC" +
465 ctx.channel().id().asShortText(), checkInterval);
466 perChannel.queueSize = 0L;
467 perChannel.lastReadTimestamp = TrafficCounter.milliSecondFromNano();
468 perChannel.lastWriteTimestamp = perChannel.lastReadTimestamp;
469 channelQueues.put(key, perChannel);
470 }
471 return perChannel;
472 }
473
474 @Override
475 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
476 getOrSetPerChannel(ctx);
477 trafficCounter.resetCumulativeTime();
478 super.handlerAdded(ctx);
479 }
480
481 @Override
482 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
483 trafficCounter.resetCumulativeTime();
484 Channel channel = ctx.channel();
485 ChannelId key = channel.id();
486 PerChannel perChannel = channelQueues.remove(key);
487 if (perChannel != null) {
488
489 synchronized (perChannel) {
490 if (channel.isActive()) {
491 for (ToSend toSend : perChannel.messagesQueue) {
492 long size = calculateSize(toSend.toSend);
493 trafficCounter.bytesRealWriteFlowControl(size);
494 perChannel.channelTrafficCounter.bytesRealWriteFlowControl(size);
495 perChannel.queueSize -= size;
496 queuesSize.addAndGet(-size);
497 ctx.write(toSend.toSend, toSend.promise);
498 }
499 } else if (!perChannel.messagesQueue.isEmpty()) {
500 queuesSize.addAndGet(-perChannel.queueSize);
501 ClosedChannelException cause = new ClosedChannelException();
502 for (ToSend toSend : perChannel.messagesQueue) {
503 releaseAndFailQueuedWrite(toSend.toSend, toSend.promise, cause);
504 }
505 perChannel.queueSize = 0;
506 }
507 perChannel.messagesQueue.clear();
508 }
509 }
510 releaseWriteSuspended(ctx);
511 releaseReadSuspended(ctx);
512 super.handlerRemoved(ctx);
513 }
514
515 @Override
516 public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
517 long size = calculateSize(msg);
518 long now = TrafficCounter.milliSecondFromNano();
519 if (size > 0) {
520
521 long waitGlobal = trafficCounter.readTimeToWait(size, getReadLimit(), maxTime, now);
522 ChannelId key = ctx.channel().id();
523 PerChannel perChannel = channelQueues.get(key);
524 long wait = 0;
525 if (perChannel != null) {
526 wait = perChannel.channelTrafficCounter.readTimeToWait(size, readChannelLimit, maxTime, now);
527 if (readDeviationActive) {
528
529 long maxLocalRead;
530 maxLocalRead = perChannel.channelTrafficCounter.cumulativeReadBytes();
531 long maxGlobalRead = cumulativeReadBytes.get();
532 if (maxLocalRead <= 0) {
533 maxLocalRead = 0;
534 }
535 if (maxGlobalRead < maxLocalRead) {
536 maxGlobalRead = maxLocalRead;
537 }
538 wait = computeBalancedWait(maxLocalRead, maxGlobalRead, wait);
539 }
540 }
541 if (wait < waitGlobal) {
542 wait = waitGlobal;
543 }
544 wait = checkWaitReadTime(ctx, wait, now);
545 if (wait >= MINIMAL_WAIT) {
546
547
548 Channel channel = ctx.channel();
549 ChannelConfig config = channel.config();
550 if (logger.isDebugEnabled()) {
551 logger.debug("Read Suspend: " + wait + ':' + config.isAutoRead() + ':'
552 + isHandlerActive(ctx));
553 }
554 if (config.isAutoRead() && isHandlerActive(ctx)) {
555 config.setAutoRead(false);
556 channel.attr(READ_SUSPENDED).set(true);
557
558
559 Attribute<Runnable> attr = channel.attr(REOPEN_TASK);
560 Runnable reopenTask = attr.get();
561 if (reopenTask == null) {
562 reopenTask = new ReopenReadTimerTask(ctx);
563 attr.set(reopenTask);
564 }
565 ctx.executor().schedule(reopenTask, wait, TimeUnit.MILLISECONDS);
566 if (logger.isDebugEnabled()) {
567 logger.debug("Suspend final status => " + config.isAutoRead() + ':'
568 + isHandlerActive(ctx) + " will reopened at: " + wait);
569 }
570 }
571 }
572 }
573 informReadOperation(ctx, now);
574 ctx.fireChannelRead(msg);
575 }
576
577 @Override
578 protected long checkWaitReadTime(final ChannelHandlerContext ctx, long wait, final long now) {
579 ChannelId key = ctx.channel().id();
580 PerChannel perChannel = channelQueues.get(key);
581 if (perChannel != null) {
582 if (wait > maxTime && now + wait - perChannel.lastReadTimestamp > maxTime) {
583 wait = maxTime;
584 }
585 }
586 return wait;
587 }
588
589 @Override
590 protected void informReadOperation(final ChannelHandlerContext ctx, final long now) {
591 ChannelId key = ctx.channel().id();
592 PerChannel perChannel = channelQueues.get(key);
593 if (perChannel != null) {
594 perChannel.lastReadTimestamp = now;
595 }
596 }
597
598 private static final class ToSend {
599 final long relativeTimeAction;
600 final Object toSend;
601 final ChannelPromise promise;
602 final long size;
603
604 private ToSend(final long delay, final Object toSend, final long size, final ChannelPromise promise) {
605 relativeTimeAction = delay;
606 this.toSend = toSend;
607 this.size = size;
608 this.promise = promise;
609 }
610 }
611
612 protected long maximumCumulativeWrittenBytes() {
613 return cumulativeWrittenBytes.get();
614 }
615
616 protected long maximumCumulativeReadBytes() {
617 return cumulativeReadBytes.get();
618 }
619
620
621
622
623
624 public Collection<TrafficCounter> channelTrafficCounters() {
625 return new AbstractCollection<TrafficCounter>() {
626 @Override
627 public Iterator<TrafficCounter> iterator() {
628 return new Iterator<TrafficCounter>() {
629 final Iterator<PerChannel> iter = channelQueues.values().iterator();
630 @Override
631 public boolean hasNext() {
632 return iter.hasNext();
633 }
634 @Override
635 public TrafficCounter next() {
636 return iter.next().channelTrafficCounter;
637 }
638 @Override
639 public void remove() {
640 throw new UnsupportedOperationException();
641 }
642 };
643 }
644 @Override
645 public int size() {
646 return channelQueues.size();
647 }
648 };
649 }
650
651 @Override
652 public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
653 throws Exception {
654 long size = calculateSize(msg);
655 long now = TrafficCounter.milliSecondFromNano();
656 if (size > 0) {
657
658 long waitGlobal = trafficCounter.writeTimeToWait(size, getWriteLimit(), maxTime, now);
659 ChannelId key = ctx.channel().id();
660 PerChannel perChannel = channelQueues.get(key);
661 long wait = 0;
662 if (perChannel != null) {
663 wait = perChannel.channelTrafficCounter.writeTimeToWait(size, writeChannelLimit, maxTime, now);
664 if (writeDeviationActive) {
665
666 long maxLocalWrite;
667 maxLocalWrite = perChannel.channelTrafficCounter.cumulativeWrittenBytes();
668 long maxGlobalWrite = cumulativeWrittenBytes.get();
669 if (maxLocalWrite <= 0) {
670 maxLocalWrite = 0;
671 }
672 if (maxGlobalWrite < maxLocalWrite) {
673 maxGlobalWrite = maxLocalWrite;
674 }
675 wait = computeBalancedWait(maxLocalWrite, maxGlobalWrite, wait);
676 }
677 }
678 if (wait < waitGlobal) {
679 wait = waitGlobal;
680 }
681 if (wait >= MINIMAL_WAIT) {
682 if (logger.isDebugEnabled()) {
683 logger.debug("Write suspend: " + wait + ':' + ctx.channel().config().isAutoRead() + ':'
684 + isHandlerActive(ctx));
685 }
686 submitWrite(ctx, msg, size, wait, now, promise);
687 return;
688 }
689 }
690
691 submitWrite(ctx, msg, size, 0, now, promise);
692 }
693
694 @Override
695 protected void submitWrite(final ChannelHandlerContext ctx, final Object msg,
696 final long size, final long writedelay, final long now,
697 final ChannelPromise promise) {
698 Channel channel = ctx.channel();
699 ChannelId key = channel.id();
700 PerChannel perChannel = channelQueues.get(key);
701 if (perChannel == null) {
702
703
704 perChannel = getOrSetPerChannel(ctx);
705 }
706 final ToSend newToSend;
707 long delay = writedelay;
708 boolean globalSizeExceeded = false;
709
710 synchronized (perChannel) {
711 if (writedelay == 0 && perChannel.messagesQueue.isEmpty()) {
712 trafficCounter.bytesRealWriteFlowControl(size);
713 perChannel.channelTrafficCounter.bytesRealWriteFlowControl(size);
714 ctx.write(msg, promise);
715 perChannel.lastWriteTimestamp = now;
716 return;
717 }
718 if (delay > maxTime && now + delay - perChannel.lastWriteTimestamp > maxTime) {
719 delay = maxTime;
720 }
721 newToSend = new ToSend(delay + now, msg, size, promise);
722 perChannel.messagesQueue.addLast(newToSend);
723 perChannel.queueSize += size;
724 queuesSize.addAndGet(size);
725 checkWriteSuspend(ctx, delay, perChannel.queueSize);
726 if (queuesSize.get() > maxGlobalWriteSize) {
727 globalSizeExceeded = true;
728 }
729 }
730 if (globalSizeExceeded) {
731 setUserDefinedWritability(ctx, false);
732 }
733 final long futureNow = newToSend.relativeTimeAction;
734 final PerChannel forSchedule = perChannel;
735 ctx.executor().schedule(new Runnable() {
736 @Override
737 public void run() {
738 sendAllValid(ctx, forSchedule, futureNow);
739 }
740 }, delay, TimeUnit.MILLISECONDS);
741 }
742
743 private void sendAllValid(final ChannelHandlerContext ctx, final PerChannel perChannel, final long now) {
744
745 synchronized (perChannel) {
746 ToSend newToSend = perChannel.messagesQueue.pollFirst();
747 for (; newToSend != null; newToSend = perChannel.messagesQueue.pollFirst()) {
748 if (newToSend.relativeTimeAction <= now) {
749 long size = newToSend.size;
750 trafficCounter.bytesRealWriteFlowControl(size);
751 perChannel.channelTrafficCounter.bytesRealWriteFlowControl(size);
752 perChannel.queueSize -= size;
753 queuesSize.addAndGet(-size);
754 ctx.write(newToSend.toSend, newToSend.promise);
755 perChannel.lastWriteTimestamp = now;
756 } else {
757 perChannel.messagesQueue.addFirst(newToSend);
758 break;
759 }
760 }
761 if (perChannel.messagesQueue.isEmpty()) {
762 releaseWriteSuspended(ctx);
763 }
764 }
765 ctx.flush();
766 }
767
768 @Override
769 public String toString() {
770 return new StringBuilder(340).append(super.toString())
771 .append(" Write Channel Limit: ").append(writeChannelLimit)
772 .append(" Read Channel Limit: ").append(readChannelLimit).toString();
773 }
774 }