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