EnhancedMessageTypeKey add hash(), ChannelOutboundQueue change address to final and...
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / connection / ChannelOutboundQueue.java
1 /*
2  * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowjava.protocol.impl.connection;
10
11 import io.netty.channel.Channel;
12 import io.netty.channel.ChannelFuture;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.ChannelInboundHandlerAdapter;
15 import io.netty.util.concurrent.EventExecutor;
16 import io.netty.util.concurrent.Future;
17 import io.netty.util.concurrent.GenericFutureListener;
18
19 import java.net.InetSocketAddress;
20 import java.util.Queue;
21 import java.util.concurrent.LinkedBlockingQueue;
22 import java.util.concurrent.RejectedExecutionException;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import com.google.common.base.Preconditions;
30
31 /**
32  * Channel handler which bypasses wraps on top of normal Netty pipeline, allowing
33  * writes to be enqueued from any thread, it then schedules a task pipeline task,
34  * which shuffles messages from the queue into the pipeline.
35  *
36  * Note this is an *Inbound* handler, as it reacts to channel writability changing,
37  * which in the Netty vocabulary is an inbound event. This has already changed in
38  * the Netty 5.0.0 API, where Handlers are unified.
39  */
40 final class ChannelOutboundQueue extends ChannelInboundHandlerAdapter {
41     public interface MessageHolder<T> {
42         /**
43          * Take ownership of the encapsulated listener. Guaranteed to
44          * be called at most once.
45          *
46          * @return listener encapsulated in the holder, may be null
47          * @throws IllegalStateException if the listener is no longer
48          *         available (for example because it has already been
49          *         taken).
50          */
51         GenericFutureListener<Future<Void>> takeListener();
52
53         /**
54          * Take ownership of the encapsulated message. Guaranteed to be
55          * called at most once.
56          *
57          * @return message encapsulated in the holder, may not be null
58          * @throws IllegalStateException if the message is no longer
59          *         available (for example because it has already been
60          *         taken).
61          */
62         T takeMessage();
63     }
64
65     /**
66      * This is the default upper bound we place on the flush task running
67      * a single iteration. We relinquish control after about this amount
68      * of time.
69      */
70     private static final long DEFAULT_WORKTIME_MICROS = TimeUnit.MILLISECONDS.toMicros(100);
71
72     /**
73      * We re-check the time spent flushing every this many messages. We do this because
74      * checking after each message may prove to be CPU-intensive. Set to Integer.MAX_VALUE
75      * or similar to disable the feature.
76      */
77     private static final int WORKTIME_RECHECK_MSGS = 64;
78     private static final Logger LOG = LoggerFactory.getLogger(ChannelOutboundQueue.class);
79
80     // Passed to executor to request triggering of flush
81     private final Runnable flushRunnable = new Runnable() {
82         @Override
83         public void run() {
84             ChannelOutboundQueue.this.flush();
85         }
86     };
87
88     /*
89      * Instead of using an AtomicBoolean object, we use these two. It saves us
90      * from allocating an extra object.
91      */
92     private static final AtomicIntegerFieldUpdater<ChannelOutboundQueue> FLUSH_SCHEDULED_UPDATER =
93             AtomicIntegerFieldUpdater.newUpdater(ChannelOutboundQueue.class, "flushScheduled");
94     private volatile int flushScheduled = 0;
95
96     private final Queue<MessageHolder<?>> queue;
97     private final long maxWorkTime;
98     private final Channel channel;
99     private final InetSocketAddress address;
100
101     public ChannelOutboundQueue(final Channel channel, final int queueDepth, final InetSocketAddress address) {
102         Preconditions.checkArgument(queueDepth > 0, "Queue depth has to be positive");
103
104         /*
105          * This looks like a good trade-off for throughput. Alternative is
106          * to use an ArrayBlockingQueue -- but that uses a single lock to
107          * synchronize both producers and consumers, potentially leading
108          * to less throughput.
109          */
110         this.queue = new LinkedBlockingQueue<>(queueDepth);
111         this.channel = Preconditions.checkNotNull(channel);
112         this.maxWorkTime = TimeUnit.MICROSECONDS.toNanos(DEFAULT_WORKTIME_MICROS);
113         this.address = address;
114     }
115
116     /**
117      * Enqueue a message holder for transmission. Is a thread-safe entry point
118      * for the channel. If the cannot be placed on the queue, this
119      *
120      * @param holder MessageHolder which should be enqueue
121      * @return Success indicator, true if the enqueue operation succeeded,
122      *         false if the queue is full.
123      */
124     public boolean enqueue(final MessageHolder<?> holder) {
125         LOG.trace("Enqueuing message {}", holder);
126         if (queue.offer(holder)) {
127             LOG.trace("Message enqueued");
128             conditionalFlush();
129             return true;
130         }
131
132         LOG.trace("Message queue is full");
133         return false;
134     }
135
136     private void scheduleFlush(final EventExecutor executor) {
137         if (FLUSH_SCHEDULED_UPDATER.compareAndSet(this, 0, 1)) {
138             LOG.trace("Scheduling flush task");
139             executor.execute(flushRunnable);
140         } else {
141             LOG.trace("Flush task is already present");
142         }
143     }
144
145     /**
146      * Schedule a queue flush if it is not empty and the channel is found
147      * to be writable.
148      */
149     private void conditionalFlush() {
150         if (queue.isEmpty()) {
151             LOG.trace("Queue is empty, not flush needed");
152             return;
153         }
154         if (!channel.isWritable()) {
155             LOG.trace("Channel {} is not writable, not issuing a flush", channel);
156             return;
157         }
158
159         scheduleFlush(channel.pipeline().lastContext().executor());
160     }
161
162     /*
163      * The synchronized keyword should be unnecessary, really, but it enforces
164      * queue order should something go terribly wrong. It should be completely
165      * uncontended.
166      */
167     private synchronized void flush() {
168         final long start = System.nanoTime();
169         final long deadline = start + maxWorkTime;
170
171         LOG.debug("Dequeuing messages to channel {}", channel);
172
173         long messages = 0;
174         for (;; ++messages) {
175             if (!channel.isWritable()) {
176                 LOG.trace("Channel is no longer writable");
177                 break;
178             }
179
180             final MessageHolder<?> h = queue.poll();
181             if (h == null) {
182                 LOG.trace("The queue is completely drained");
183                 break;
184             }
185
186             final GenericFutureListener<Future<Void>> l = h.takeListener();
187             
188             final ChannelFuture p;
189             if (address == null) {
190                 p = channel.write(new MessageListenerWrapper(h.takeMessage(), l));
191             } else {
192                 p = channel.write(new UdpMessageListenerWrapper(h.takeMessage(), l, address));
193             }
194             if (l != null) {
195                 p.addListener(l);
196             }
197
198             /*
199              * Check every WORKTIME_RECHECK_MSGS for exceeded time.
200              *
201              * XXX: given we already measure our flushing throughput, we
202              *      should be able to perform dynamic adjustments here.
203              *      is that additional complexity needed, though?
204              */
205             if ((messages % WORKTIME_RECHECK_MSGS) == 0) {
206                 if (System.nanoTime() >= deadline) {
207                     LOG.trace("Exceeded allotted work time {}us",
208                             TimeUnit.NANOSECONDS.toMicros(maxWorkTime));
209                     break;
210                 }
211             }
212         }
213
214         if (messages > 0) {
215             LOG.debug("Flushing {} message(s) to channel {}", messages, channel);
216             channel.flush();
217         }
218
219         final long stop = System.nanoTime();
220         LOG.debug("Flushed {} messages in {}us to channel {}",
221                 messages, TimeUnit.NANOSECONDS.toMicros(stop - start), channel);
222
223         /*
224          * We are almost ready to terminate. This is a bit tricky, because
225          * we do not want to have a race window where a message would be
226          * stuck on the queue without a flush being scheduled.
227          *
228          * So we mark ourselves as not running and then re-check if a
229          * flush out is needed. That will re-synchronized with other threads
230          * such that only one flush is scheduled at any given time.
231          */
232         if (!FLUSH_SCHEDULED_UPDATER.compareAndSet(this, 1, 0)) {
233             LOG.warn("Channel {} queue {} flusher found unscheduled", channel, queue);
234         }
235
236         conditionalFlush();
237     }
238
239     private void conditionalFlush(final ChannelHandlerContext ctx) {
240         Preconditions.checkState(ctx.channel() == channel, "Inconsistent channel %s with context %s", channel, ctx);
241         conditionalFlush();
242     }
243
244     @Override
245     public void channelActive(final ChannelHandlerContext ctx) throws Exception {
246         super.channelActive(ctx);
247         conditionalFlush(ctx);
248     }
249
250     @Override
251     public void channelWritabilityChanged(final ChannelHandlerContext ctx) throws Exception {
252         super.channelWritabilityChanged(ctx);
253         conditionalFlush(ctx);
254     }
255
256     @Override
257     public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
258         super.channelInactive(ctx);
259
260         long entries = 0;
261         LOG.debug("Channel shutdown, flushing queue...");
262         final Future<Void> result = ctx.newFailedFuture(new RejectedExecutionException("Channel disconnected"));
263         while (true) {
264             final MessageHolder<?> e = queue.poll();
265             if (e == null) {
266                 break;
267             }
268
269             e.takeListener().operationComplete(result);
270             entries++;
271         }
272
273         LOG.debug("Flushed {} queue entries", entries);
274     }
275
276     @Override
277     public String toString() {
278         return String.format("Channel %s queue [%s messages flushing=%s]", channel, queue.size(), flushScheduled);
279     }
280 }