Merge "Bump to odlparent 3.1.0 and yangtools 2.0.3"
[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
9 package org.opendaylight.netconf.nettyutil;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import io.netty.channel.Channel;
14 import io.netty.channel.ChannelFuture;
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.TimerTask;
22 import io.netty.util.concurrent.Future;
23 import io.netty.util.concurrent.GenericFutureListener;
24 import io.netty.util.concurrent.Promise;
25 import java.util.concurrent.TimeUnit;
26 import org.opendaylight.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.netconf.api.NetconfMessage;
28 import org.opendaylight.netconf.api.NetconfSessionListener;
29 import org.opendaylight.netconf.api.NetconfSessionPreferences;
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.opendaylight.protocol.framework.AbstractSessionNegotiator;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.w3c.dom.Document;
42 import org.w3c.dom.NodeList;
43
44 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences,
45         S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
46     extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
47
48     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
49
50     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
51
52     protected final P sessionPreferences;
53
54     private final L sessionListener;
55     private Timeout timeout;
56
57     /**
58      * Possible states for Finite State Machine.
59      */
60     protected enum State {
61         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
62     }
63
64     private State state = State.IDLE;
65     private final Promise<S> promise;
66     private final Timer timer;
67     private final long connectionTimeoutMillis;
68
69     protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
70                                                final Channel channel, final Timer timer,
71                                                final L sessionListener, final long connectionTimeoutMillis) {
72         super(promise, channel);
73         this.sessionPreferences = sessionPreferences;
74         this.promise = promise;
75         this.timer = timer;
76         this.sessionListener = sessionListener;
77         this.connectionTimeoutMillis = connectionTimeoutMillis;
78     }
79
80     @Override
81     protected final void startNegotiation() {
82         if (ifNegotiatedAlready()) {
83             LOG.debug("Negotiation on channel {} already started", channel);
84         } else {
85             final Optional<SslHandler> sslHandler = getSslHandler(channel);
86             if (sslHandler.isPresent()) {
87                 Future<Channel> future = sslHandler.get().handshakeFuture();
88                 future.addListener(new GenericFutureListener<Future<? super Channel>>() {
89                     @Override
90                     public void operationComplete(final Future<? super Channel> future) {
91                         Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
92                         LOG.debug("Ssl handshake complete");
93                         start();
94                     }
95                 });
96             } else {
97                 start();
98             }
99         }
100     }
101
102     protected final boolean ifNegotiatedAlready() {
103         // Indicates whether negotiation already started
104         return this.state != State.IDLE;
105     }
106
107     private static Optional<SslHandler> getSslHandler(final Channel channel) {
108         final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
109         return sslHandler == null ? Optional.<SslHandler>absent() : Optional.of(sslHandler);
110     }
111
112     public P getSessionPreferences() {
113         return sessionPreferences;
114     }
115
116     private void start() {
117         final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
118         LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);
119
120         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
121
122         sendMessage(helloMessage);
123
124         replaceHelloMessageOutboundHandler();
125         changeState(State.OPEN_WAIT);
126
127         timeout = this.timer.newTimeout(new TimerTask() {
128             @Override
129             @SuppressWarnings("checkstyle:hiddenField")
130             public void run(final Timeout timeout) {
131                 synchronized (this) {
132                     if (state != State.ESTABLISHED) {
133
134                         LOG.debug("Connection timeout after {}, session is in state {}", timeout, state);
135
136                         // Do not fail negotiation if promise is done or canceled
137                         // It would result in setting result of the promise second time and that throws exception
138                         if (!isPromiseFinished()) {
139                             LOG.warn("Netconf session was not established after {}", connectionTimeoutMillis);
140                             changeState(State.FAILED);
141
142                             channel.close().addListener(new GenericFutureListener<ChannelFuture>() {
143                                 @Override
144                                 public void operationComplete(final ChannelFuture future) throws Exception {
145                                     if (future.isSuccess()) {
146                                         LOG.debug("Channel {} closed: success", future.channel());
147                                     } else {
148                                         LOG.warn("Channel {} closed: fail", future.channel());
149                                     }
150                                 }
151                             });
152                         }
153                     } else if (channel.isOpen()) {
154                         channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
155                     }
156                 }
157             }
158
159             private boolean isPromiseFinished() {
160                 return promise.isDone() || promise.isCancelled();
161             }
162
163         }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
164     }
165
166     private void cancelTimeout() {
167         if (timeout != null) {
168             timeout.cancel();
169         }
170     }
171
172     protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
173             throws NetconfDocumentedException {
174         Preconditions.checkNotNull(netconfMessage, "netconfMessage");
175
176         final Document doc = netconfMessage.getDocument();
177
178         if (shouldUseChunkFraming(doc)) {
179             insertChunkFramingToPipeline();
180         }
181
182         changeState(State.ESTABLISHED);
183         return getSession(sessionListener, channel, netconfMessage);
184     }
185
186     /**
187      * Insert chunk framing handlers into the pipeline.
188      */
189     private void insertChunkFramingToPipeline() {
190         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
191                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
192         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
193                 new NetconfChunkAggregator());
194     }
195
196     private boolean shouldUseChunkFraming(final Document doc) {
197         return containsBase11Capability(doc)
198                 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
199     }
200
201     /**
202      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
203      *
204      * <p>
205      * Inbound hello message handler should be kept until negotiation is successful
206      * It caches any non-hello messages while negotiation is still in progress
207      */
208     protected final void replaceHelloMessageInboundHandler(final S session) {
209         ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
210                 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
211
212         Preconditions.checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
213                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
214         Iterable<NetconfMessage> netconfMessagesFromNegotiation =
215                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
216
217         // Process messages received during negotiation
218         // The hello message handler does not have to be synchronized,
219         // since it is always call from the same thread by netty.
220         // It means, we are now using the thread now
221         for (NetconfMessage message : netconfMessagesFromNegotiation) {
222             session.handleMessage(message);
223         }
224     }
225
226     /**
227      * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
228      */
229     private void replaceHelloMessageOutboundHandler() {
230         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
231                 new NetconfMessageToXMLEncoder());
232     }
233
234     private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
235                                                         final ChannelHandler decoder) {
236         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
237     }
238
239     @SuppressWarnings("checkstyle:hiddenField")
240     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
241             throws NetconfDocumentedException;
242
243     private synchronized void changeState(final State newState) {
244         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
245         Preconditions.checkState(isStateChangePermitted(state, newState),
246                 "Cannot change state from %s to %s for chanel %s", state, newState, channel);
247         this.state = newState;
248     }
249
250     private static boolean containsBase11Capability(final Document doc) {
251         final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
252         for (int i = 0; i < nList.getLength(); i++) {
253             if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
254                 return true;
255             }
256         }
257         return false;
258     }
259
260     private static boolean isStateChangePermitted(final State state, final State newState) {
261         if (state == State.IDLE && newState == State.OPEN_WAIT) {
262             return true;
263         }
264         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
265             return true;
266         }
267         if (state == State.OPEN_WAIT && newState == State.FAILED) {
268             return true;
269         }
270         LOG.debug("Transition from {} to {} is not allowed", state, newState);
271         return false;
272     }
273
274     /**
275      * Handler to catch exceptions in pipeline during negotiation.
276      */
277     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
278         @Override
279         public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
280             LOG.warn("An exception occurred during negotiation with {}", channel.remoteAddress(), cause);
281             cancelTimeout();
282             negotiationFailed(cause);
283             changeState(State.FAILED);
284         }
285     }
286 }