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