Refactor FramingMechanismHandlerFactory
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / AbstractNetconfSessionNegotiator.java
1 /*
2  * Copyright (c) 2013 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 package org.opendaylight.netconf.nettyutil;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import io.netty.channel.Channel;
16 import io.netty.channel.ChannelHandler;
17 import io.netty.channel.ChannelHandlerContext;
18 import io.netty.channel.ChannelInboundHandlerAdapter;
19 import io.netty.handler.ssl.SslHandler;
20 import io.netty.util.Timeout;
21 import io.netty.util.Timer;
22 import io.netty.util.concurrent.Future;
23 import io.netty.util.concurrent.Promise;
24 import java.util.concurrent.TimeUnit;
25 import org.checkerframework.checker.index.qual.NonNegative;
26 import org.checkerframework.checker.lock.qual.GuardedBy;
27 import org.checkerframework.checker.lock.qual.Holding;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.netconf.api.CapabilityURN;
31 import org.opendaylight.netconf.api.NamespaceURN;
32 import org.opendaylight.netconf.api.NetconfDocumentedException;
33 import org.opendaylight.netconf.api.NetconfSessionListener;
34 import org.opendaylight.netconf.api.messages.HelloMessage;
35 import org.opendaylight.netconf.api.messages.NetconfMessage;
36 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
37 import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
38 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
39 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
40 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
41 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Document;
45 import org.w3c.dom.NodeList;
46
47 public abstract class AbstractNetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
48             L extends NetconfSessionListener<S>>
49             extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
50     /**
51      * Possible states for Finite State Machine.
52      */
53     protected enum State {
54         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
55     }
56
57     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
58     private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
59     private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
60     private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
61
62     /**
63      * Default upper bound on the size of an individual chunk. This value can be controlled through
64      * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
65      * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
66      */
67     @Beta
68     public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
69
70     static {
71         final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
72         if (propValue <= 0) {
73             LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
74             DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
75         } else {
76             DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
77         }
78         LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
79     }
80
81     private final @NonNull HelloMessage localHello;
82     protected final Channel channel;
83
84     private final @NonNegative int maximumIncomingChunkSize;
85     private final long connectionTimeoutMillis;
86     private final Promise<S> promise;
87     private final L sessionListener;
88     private final Timer timer;
89
90     @GuardedBy("this")
91     private Timeout timeoutTask;
92     @GuardedBy("this")
93     private State state = State.IDLE;
94
95     protected AbstractNetconfSessionNegotiator(final HelloMessage hello, final Promise<S> promise,
96                                                final Channel channel, final Timer timer, final L sessionListener,
97                                                final long connectionTimeoutMillis,
98                                                final @NonNegative int maximumIncomingChunkSize) {
99         localHello = requireNonNull(hello);
100         this.promise = requireNonNull(promise);
101         this.channel = requireNonNull(channel);
102         this.timer = timer;
103         this.sessionListener = sessionListener;
104         this.connectionTimeoutMillis = connectionTimeoutMillis;
105         this.maximumIncomingChunkSize = maximumIncomingChunkSize;
106         checkArgument(maximumIncomingChunkSize > 0, "Invalid maximum incoming chunk size %s", maximumIncomingChunkSize);
107     }
108
109     protected final @NonNull HelloMessage localHello() {
110         return localHello;
111     }
112
113     protected final void startNegotiation() {
114         if (ifNegotiatedAlready()) {
115             LOG.debug("Negotiation on channel {} already started", channel);
116         } else {
117             final var sslHandler = getSslHandler(channel);
118             if (sslHandler != null) {
119                 sslHandler.handshakeFuture().addListener(future -> {
120                     checkState(future.isSuccess(), "Ssl handshake was not successful");
121                     LOG.debug("Ssl handshake complete");
122                     start();
123                 });
124             } else {
125                 start();
126             }
127         }
128     }
129
130     protected final boolean ifNegotiatedAlready() {
131         // Indicates whether negotiation already started
132         return state() != State.IDLE;
133     }
134
135     private synchronized State state() {
136         return state;
137     }
138
139     private static @Nullable SslHandler getSslHandler(final Channel channel) {
140         return channel.pipeline().get(SslHandler.class);
141     }
142
143     private void start() {
144         LOG.debug("Sending negotiation proposal {} on channel {}", localHello, channel);
145
146         // Send the message out, but to not run listeners just yet, as we have some more state transitions to go through
147         final var helloFuture = channel.writeAndFlush(localHello);
148
149         // Quick check: if the future has already failed we call it quits before negotiation even started
150         final var helloCause = helloFuture.cause();
151         if (helloCause != null) {
152             LOG.warn("Failed to send negotiation proposal on channel {}", channel, helloCause);
153             failAndClose();
154             return;
155         }
156
157         // Catch any exceptions from this point on. Use a named class to ease debugging.
158         final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
159             @Override
160             public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
161                 LOG.warn("An exception occurred during negotiation with {} on channel {}",
162                         channel.remoteAddress(), channel, cause);
163                 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
164                 cancelTimeout();
165                 negotiationFailed(cause);
166                 changeState(State.FAILED);
167             }
168         }
169
170         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
171
172         // Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
173         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
174             new NetconfMessageToXMLEncoder());
175
176         synchronized (this) {
177             lockedChangeState(State.OPEN_WAIT);
178
179             // Service the timeout on channel's eventloop, so that we do not get state transition problems
180             timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
181                 connectionTimeoutMillis, TimeUnit.MILLISECONDS);
182         }
183
184         LOG.debug("Session negotiation started on channel {}", channel);
185
186         // State transition completed, now run any additional processing
187         helloFuture.addListener(this::onHelloWriteComplete);
188     }
189
190     private void onHelloWriteComplete(final Future<?> future) {
191         final var cause = future.cause();
192         if (cause != null) {
193             LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
194             negotiationFailed(cause);
195         } else {
196             LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
197         }
198     }
199
200     private synchronized void timeoutExpired() {
201         if (timeoutTask == null) {
202             // cancelTimeout() between expiry and execution on the loop
203             return;
204         }
205         timeoutTask = null;
206
207         if (state != State.ESTABLISHED) {
208             LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
209                 connectionTimeoutMillis, channel, state);
210
211             // Do not fail negotiation if promise is done or canceled
212             // It would result in setting result of the promise second time and that throws exception
213             if (!promise.isDone() && !promise.isCancelled()) {
214                 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
215                     connectionTimeoutMillis);
216                 failAndClose();
217             }
218         } else if (channel.isOpen()) {
219             channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
220         }
221     }
222
223     private void failAndClose() {
224         changeState(State.FAILED);
225         channel.close().addListener(this::onChannelClosed);
226     }
227
228     private void onChannelClosed(final Future<?> future) {
229         final var cause = future.cause();
230         if (cause != null) {
231             LOG.warn("Channel {} closed: fail", channel, cause);
232         } else {
233             LOG.debug("Channel {} closed: success", channel);
234         }
235     }
236
237     private synchronized void cancelTimeout() {
238         if (timeoutTask != null && !timeoutTask.cancel()) {
239             // Late-coming cancel: make sure the task does not actually run
240             timeoutTask = null;
241         }
242     }
243
244     protected final S getSessionForHelloMessage(final HelloMessage netconfMessage)
245             throws NetconfDocumentedException {
246         final Document doc = netconfMessage.getDocument();
247
248         if (shouldUseChunkFraming(doc)) {
249             insertChunkFramingToPipeline();
250         }
251
252         changeState(State.ESTABLISHED);
253         return getSession(sessionListener, channel, netconfMessage);
254     }
255
256     protected abstract S getSession(L sessionListener, Channel channel, HelloMessage message)
257         throws NetconfDocumentedException;
258
259     /**
260      * Insert chunk framing handlers into the pipeline.
261      */
262     private void insertChunkFramingToPipeline() {
263         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
264             new ChunkedFramingMechanismEncoder());
265         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
266             new NetconfChunkAggregator(maximumIncomingChunkSize));
267     }
268
269     private boolean shouldUseChunkFraming(final Document doc) {
270         return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
271     }
272
273     /**
274      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
275      *
276      * <p>
277      * Inbound hello message handler should be kept until negotiation is successful
278      * It caches any non-hello messages while negotiation is still in progress
279      */
280     protected final void replaceHelloMessageInboundHandler(final S session) {
281         ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
282                 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
283
284         checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
285                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
286         Iterable<NetconfMessage> netconfMessagesFromNegotiation =
287                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
288
289         // Process messages received during negotiation
290         // The hello message handler does not have to be synchronized,
291         // since it is always call from the same thread by netty.
292         // It means, we are now using the thread now
293         for (NetconfMessage message : netconfMessagesFromNegotiation) {
294             session.handleMessage(message);
295         }
296     }
297
298     private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
299                                                         final ChannelHandler decoder) {
300         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
301     }
302
303     private synchronized void changeState(final State newState) {
304         lockedChangeState(newState);
305     }
306
307     @Holding("this")
308     private void lockedChangeState(final State newState) {
309         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
310         checkState(isStateChangePermitted(state, newState),
311                 "Cannot change state from %s to %s for channel %s", state, newState, channel);
312         state = newState;
313     }
314
315     private static boolean containsBase11Capability(final Document doc) {
316         final NodeList nList = doc.getElementsByTagNameNS(NamespaceURN.BASE, XmlNetconfConstants.CAPABILITY);
317         for (int i = 0; i < nList.getLength(); i++) {
318             if (nList.item(i).getTextContent().contains(CapabilityURN.BASE_1_1)) {
319                 return true;
320             }
321         }
322         return false;
323     }
324
325     private static boolean isStateChangePermitted(final State state, final State newState) {
326         if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
327             return true;
328         }
329         if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
330             return true;
331         }
332         LOG.debug("Transition from {} to {} is not allowed", state, newState);
333         return false;
334     }
335
336     protected final void negotiationSuccessful(final S session) {
337         LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
338         channel.pipeline().replace(this, "session", session);
339         promise.setSuccess(session);
340     }
341
342     protected void negotiationFailed(final Throwable cause) {
343         LOG.debug("Negotiation on channel {} failed", channel, cause);
344         channel.close();
345         promise.setFailure(cause);
346     }
347
348     @Override
349     @SuppressWarnings("checkstyle:illegalCatch")
350     public final void channelActive(final ChannelHandlerContext ctx) {
351         LOG.debug("Starting session negotiation on channel {}", channel);
352         try {
353             startNegotiation();
354         } catch (final Exception e) {
355             LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
356             negotiationFailed(e);
357         }
358     }
359
360     @Override
361     @SuppressWarnings("checkstyle:illegalCatch")
362     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
363         if (state() == State.FAILED) {
364             // We have already failed -- do not process any more messages
365             return;
366         }
367
368         LOG.debug("Negotiation read invoked on channel {}", channel);
369         try {
370             handleMessage((HelloMessage) msg);
371         } catch (final Exception e) {
372             LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
373             negotiationFailed(e);
374         }
375     }
376
377     @Override
378     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
379         LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
380         negotiationFailed(cause);
381     }
382
383     protected abstract void handleMessage(HelloMessage msg) throws Exception;
384 }