Use String(byte[], Charset)
[openflowplugin.git] / openflowjava / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / connection / AbstractOutboundQueueManager.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.core.connection;
10
11 import com.google.common.base.Preconditions;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.channel.ChannelInboundHandlerAdapter;
14 import io.netty.util.concurrent.Future;
15 import io.netty.util.concurrent.GenericFutureListener;
16 import java.math.BigInteger;
17 import java.net.InetSocketAddress;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.atomic.AtomicBoolean;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInputBuilder;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 /**
30  * Class capsulate basic processing for stacking requests for netty channel
31  * and provide functionality for pairing request/response device message communication.
32  */
33 abstract class AbstractOutboundQueueManager<T extends OutboundQueueHandler, O extends AbstractStackedOutboundQueue>
34         extends ChannelInboundHandlerAdapter
35         implements AutoCloseable {
36
37     private static final Logger LOG = LoggerFactory.getLogger(AbstractOutboundQueueManager.class);
38
39     private enum PipelineState {
40         /**
41          * Netty thread is potentially idle, no assumptions
42          * can be made about its state.
43          */
44         IDLE,
45         /**
46          * Netty thread is currently reading, once the read completes,
47          * if will flush the queue in the {@link #WRITING} state.
48          */
49         READING,
50         /**
51          * Netty thread is currently performing a flush on the queue.
52          * It will then transition to {@link #IDLE} state.
53          */
54         WRITING,
55     }
56
57     /**
58      * Default low write watermark. Channel will become writable when number of outstanding
59      * bytes dips below this value.
60      */
61     private static final int DEFAULT_LOW_WATERMARK = 128 * 1024;
62
63     /**
64      * Default write high watermark. Channel will become un-writable when number of
65      * outstanding bytes hits this value.
66      */
67     private static final int DEFAULT_HIGH_WATERMARK = DEFAULT_LOW_WATERMARK * 2;
68
69     private final AtomicBoolean flushScheduled = new AtomicBoolean();
70     protected final ConnectionAdapterImpl parent;
71     protected final InetSocketAddress address;
72     protected final O currentQueue;
73     private final T handler;
74
75     // Accessed concurrently
76     private volatile PipelineState state = PipelineState.IDLE;
77
78     // Updated from netty only
79     private boolean alreadyReading;
80     protected boolean shuttingDown;
81
82     // Passed to executor to request triggering of flush
83     protected final Runnable flushRunnable = this::flush;
84
85     AbstractOutboundQueueManager(final ConnectionAdapterImpl parent, final InetSocketAddress address, final T handler) {
86         this.parent = Preconditions.checkNotNull(parent);
87         this.handler = Preconditions.checkNotNull(handler);
88         this.address = address;
89         /* Note: don't wish to use reflection here */
90         currentQueue = initializeStackedOutboudnqueue();
91         LOG.debug("Queue manager instantiated with queue {}", currentQueue);
92
93         handler.onConnectionQueueChanged(currentQueue);
94     }
95
96     /**
97      * Method has to initialize some child of {@link AbstractStackedOutboundQueue}.
98      *
99      * @return correct implementation of StacketOutboundqueue
100      */
101     protected abstract O initializeStackedOutboudnqueue();
102
103     @Override
104     public void close() {
105         handler.onConnectionQueueChanged(null);
106     }
107
108     @Override
109     public String toString() {
110         return String.format("Channel %s queue [flushing=%s]", parent.getChannel(), flushScheduled.get());
111     }
112
113     @Override
114     public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
115         /*
116          * Tune channel write buffering. We increase the writability window
117          * to ensure we can flush an entire queue segment in one go. We definitely
118          * want to keep the difference above 64k, as that will ensure we use jam-packed
119          * TCP packets. UDP will fragment as appropriate.
120          */
121         ctx.channel().config().setWriteBufferHighWaterMark(DEFAULT_HIGH_WATERMARK);
122         ctx.channel().config().setWriteBufferLowWaterMark(DEFAULT_LOW_WATERMARK);
123
124         super.handlerAdded(ctx);
125     }
126
127     @Override
128     public void channelActive(final ChannelHandlerContext ctx) throws Exception {
129         super.channelActive(ctx);
130         conditionalFlush();
131     }
132
133     @Override
134     public void channelReadComplete(final ChannelHandlerContext ctx) throws Exception {
135         super.channelReadComplete(ctx);
136
137         // Run flush regardless of writability. This is not strictly required, as
138         // there may be a scheduled flush. Instead of canceling it, which is expensive,
139         // we'll steal its work. Note that more work may accumulate in the time window
140         // between now and when the task will run, so it may not be a no-op after all.
141         //
142         // The reason for this is to fill the output buffer before we go into selection
143         // phase. This will make sure the pipe is full (in which case our next wake up
144         // will be the queue becoming writable).
145         writeAndFlush();
146         alreadyReading = false;
147     }
148
149     @Override
150     public void channelWritabilityChanged(final ChannelHandlerContext ctx) throws Exception {
151         super.channelWritabilityChanged(ctx);
152
153         // The channel is writable again. There may be a flush task on the way, but let's
154         // steal its work, potentially decreasing latency. Since there is a window between
155         // now and when it will run, it may still pick up some more work to do.
156         LOG.debug("Channel {} writability changed, invoking flush", parent.getChannel());
157         writeAndFlush();
158     }
159
160     @Override
161     public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
162         // First of all, delegates disconnect event notification into ConnectionAdapter -> OF Plugin -> queue.close()
163         // -> queueHandler.onConnectionQueueChanged(null). The last call causes that no more entries are enqueued
164         // in the queue.
165         super.channelInactive(ctx);
166
167         LOG.debug("Channel {} initiating shutdown...", ctx.channel());
168
169         // Then we start queue shutdown, start counting written messages (so that we don't keep sending messages
170         // indefinitely) and failing not completed entries.
171         shuttingDown = true;
172         final long entries = currentQueue.startShutdown();
173         LOG.debug("Cleared {} queue entries from channel {}", entries, ctx.channel());
174
175         // Finally, we schedule flush task that will take care of unflushed entries. We also cover the case,
176         // when there is more than shutdownOffset messages enqueued in unflushed segments
177         // (AbstractStackedOutboundQueue#finishShutdown()).
178         scheduleFlush();
179     }
180
181     @Override
182     public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
183         // Netty does not provide a 'start reading' callback, so this is our first
184         // (and repeated) chance to detect reading. Since this callback can be invoked
185         // multiple times, we keep a boolean we check. That prevents a volatile write
186         // on repeated invocations. It will be cleared in channelReadComplete().
187         if (!alreadyReading) {
188             alreadyReading = true;
189             state = PipelineState.READING;
190         }
191         super.channelRead(ctx, msg);
192     }
193
194     /**
195      * Invoked whenever a message comes in from the switch. Runs matching
196      * on all active queues in an attempt to complete a previous request.
197      *
198      * @param message Potential response message
199      * @return True if the message matched a previous request, false otherwise.
200      */
201     boolean onMessage(final OfHeader message) {
202         LOG.trace("Attempting to pair message {} to a request", message);
203
204         return currentQueue.pairRequest(message);
205     }
206
207     T getHandler() {
208         return handler;
209     }
210
211     void ensureFlushing() {
212         // If the channel is not writable, there's no point in waking up,
213         // once we become writable, we will run a full flush
214         if (!parent.getChannel().isWritable()) {
215             return;
216         }
217
218         // We are currently reading something, just a quick sync to ensure we will in fact
219         // flush state.
220         final PipelineState localState = state;
221         LOG.debug("Synchronize on pipeline state {}", localState);
222         switch (localState) {
223             case READING:
224                 // Netty thread is currently reading, it will flush the pipeline once it
225                 // finishes reading. This is a no-op situation.
226                 break;
227             case WRITING:
228             case IDLE:
229             default:
230                 // We cannot rely on the change being flushed, schedule a request
231                 scheduleFlush();
232         }
233     }
234
235     /**
236      * Method immediately response on Echo message.
237      *
238      * @param message incoming Echo message from device
239      * @param datapathId the dpnId of the node
240      */
241     void onEchoRequest(final EchoRequestMessage message, BigInteger datapathId) {
242         LOG.debug("echo request received: {} for the DPN {}", message.getXid(), datapathId);
243         final EchoReplyInput reply = new EchoReplyInputBuilder().setData(message.getData())
244                 .setVersion(message.getVersion()).setXid(message.getXid()).build();
245         parent.getChannel().writeAndFlush(makeMessageListenerWrapper(reply));
246     }
247
248     /**
249      * Wraps outgoing message and includes listener attached to this message
250      * which is send to OFEncoder for serialization. Correct wrapper is
251      * selected by communication pipeline.
252      */
253     void writeMessage(final OfHeader message, final long now) {
254         final Object wrapper = makeMessageListenerWrapper(message);
255         parent.getChannel().write(wrapper);
256     }
257
258     /**
259      * Wraps outgoing message and includes listener attached to this message
260      * which is send to OFEncoder for serialization. Correct wrapper is
261      * selected by communication pipeline.
262      */
263     protected Object makeMessageListenerWrapper(@NonNull final OfHeader msg) {
264         Preconditions.checkArgument(msg != null);
265
266         if (address == null) {
267             return new MessageListenerWrapper(msg, LOG_ENCODER_LISTENER);
268         }
269         return new UdpMessageListenerWrapper(msg, LOG_ENCODER_LISTENER, address);
270     }
271
272     /* NPE are coming from {@link OFEncoder#encode} from catch block and we don't wish to lost it */
273     private static final GenericFutureListener<Future<Void>> LOG_ENCODER_LISTENER = future -> {
274         if (future.cause() != null) {
275             LOG.warn("Message encoding fail !", future.cause());
276         }
277     };
278
279     /**
280      * Perform a single flush operation. We keep it here so we do not generate
281      * syntetic accessors for private fields. Otherwise it could be moved into {@link #flushRunnable}.
282      */
283     protected void flush() {
284         // If the channel is gone, just flush whatever is not completed
285         if (!shuttingDown) {
286             LOG.trace("Dequeuing messages to channel {}", parent.getChannel());
287             writeAndFlush();
288             rescheduleFlush();
289         } else {
290             close();
291             if (currentQueue.finishShutdown(parent.getChannel())) {
292                 LOG.debug("Channel {} shutdown complete", parent.getChannel());
293             } else {
294                 LOG.trace("Channel {} current queue not completely flushed yet", parent.getChannel());
295                 rescheduleFlush();
296             }
297         }
298     }
299
300     private void scheduleFlush() {
301         if (flushScheduled.compareAndSet(false, true)) {
302             LOG.trace("Scheduling flush task on channel {}", parent.getChannel());
303             parent.getChannel().eventLoop().execute(flushRunnable);
304         } else {
305             LOG.trace("Flush task is already present on channel {}", parent.getChannel());
306         }
307     }
308
309     private void writeAndFlush() {
310         state = PipelineState.WRITING;
311
312         final long start = System.nanoTime();
313
314         final int entries = currentQueue.writeEntries(parent.getChannel(), start);
315         if (entries > 0) {
316             LOG.trace("Flushing channel {}", parent.getChannel());
317             parent.getChannel().flush();
318         }
319
320         if (LOG.isDebugEnabled()) {
321             final long stop = System.nanoTime();
322             LOG.debug("Flushed {} messages to channel {} in {}us", entries, parent.getChannel(),
323                     TimeUnit.NANOSECONDS.toMicros(stop - start));
324         }
325
326         state = PipelineState.IDLE;
327     }
328
329     private void rescheduleFlush() {
330         /*
331          * We are almost ready to terminate. This is a bit tricky, because
332          * we do not want to have a race window where a message would be
333          * stuck on the queue without a flush being scheduled.
334          * So we mark ourselves as not running and then re-check if a
335          * flush out is needed. That will re-synchronized with other threads
336          * such that only one flush is scheduled at any given time.
337          */
338         if (!flushScheduled.compareAndSet(true, false)) {
339             LOG.warn("Channel {} queue {} flusher found unscheduled", parent.getChannel(), this);
340         }
341
342         conditionalFlush();
343     }
344
345     /**
346      * Schedule a queue flush if it is not empty and the channel is found
347      * to be writable. May only be called from Netty context.
348      */
349     private void conditionalFlush() {
350         if (currentQueue.needsFlush()) {
351             if (shuttingDown || parent.getChannel().isWritable()) {
352                 scheduleFlush();
353             } else {
354                 LOG.debug("Channel {} is not I/O ready, not scheduling a flush", parent.getChannel());
355             }
356         } else {
357             LOG.trace("Queue is empty, no flush needed");
358         }
359     }
360 }