Merge "CHange log level from warn to debug in ProtocolSessionPromise when connection...
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / 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.util;
10
11 import java.util.concurrent.TimeUnit;
12
13 import org.opendaylight.controller.netconf.api.AbstractNetconfSession;
14 import org.opendaylight.controller.netconf.api.NetconfMessage;
15 import org.opendaylight.controller.netconf.api.NetconfSessionListener;
16 import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
17 import org.opendaylight.controller.netconf.util.handler.FramingMechanismHandlerFactory;
18 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
19 import org.opendaylight.controller.netconf.util.handler.NetconfMessageAggregator;
20 import org.opendaylight.controller.netconf.util.handler.NetconfMessageChunkDecoder;
21 import org.opendaylight.controller.netconf.util.handler.NetconfMessageToXMLEncoder;
22 import org.opendaylight.controller.netconf.util.handler.NetconfXMLToMessageDecoder;
23 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
24 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
25 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import org.w3c.dom.Document;
29 import org.w3c.dom.NodeList;
30
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
33
34 import io.netty.channel.Channel;
35 import io.netty.channel.ChannelHandler;
36 import io.netty.channel.ChannelHandlerContext;
37 import io.netty.handler.ssl.SslHandler;
38 import io.netty.util.Timeout;
39 import io.netty.util.Timer;
40 import io.netty.util.TimerTask;
41 import io.netty.util.concurrent.Future;
42 import io.netty.util.concurrent.GenericFutureListener;
43 import io.netty.util.concurrent.Promise;
44
45 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
46 extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
47
48     private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
49     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
50     public static final String CHUNK_DECODER_CHANNEL_HANDLER_KEY = "chunkDecoder";
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     private enum State {
61         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
62     }
63
64     private State state = State.IDLE;
65     private final Timer timer;
66     private final long connectionTimeoutMillis;
67
68     protected AbstractNetconfSessionNegotiator(P sessionPreferences, Promise<S> promise, Channel channel, Timer timer,
69             L sessionListener, long connectionTimeoutMillis) {
70         super(promise, channel);
71         this.sessionPreferences = sessionPreferences;
72         this.timer = timer;
73         this.sessionListener = sessionListener;
74         this.connectionTimeoutMillis = connectionTimeoutMillis;
75     }
76
77     @Override
78     protected void startNegotiation() {
79         final Optional<SslHandler> sslHandler = getSslHandler(channel);
80         if (sslHandler.isPresent()) {
81             Future<Channel> future = sslHandler.get().handshakeFuture();
82             future.addListener(new GenericFutureListener<Future<? super Channel>>() {
83                 @Override
84                 public void operationComplete(Future<? super Channel> future) throws Exception {
85                     Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
86                     logger.debug("Ssl handshake complete");
87                     start();
88                 }
89             });
90         } else
91             start();
92     }
93
94     private static Optional<SslHandler> getSslHandler(Channel channel) {
95         final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
96         return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
97     }
98
99     private void start() {
100         final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
101         logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
102
103         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ChannelHandler() {
104             @Override
105             public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
106             }
107
108             @Override
109             public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
110             }
111
112             @Override
113             public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
114                 logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
115                 cancelTimeout();
116                 negotiationFailed(cause);
117                 changeState(State.FAILED);
118             }
119         });
120
121         timeout = this.timer.newTimeout(new TimerTask() {
122             @Override
123             public void run(final Timeout timeout) throws Exception {
124                 synchronized (this) {
125                     if (state != State.ESTABLISHED) {
126                         logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
127                         final IllegalStateException cause = new IllegalStateException(
128                                 "Session was not established after " + timeout);
129                         negotiationFailed(cause);
130                         changeState(State.FAILED);
131                     } else if(channel.isOpen()) {
132                         channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
133                     }
134                 }
135             }
136         }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
137
138         sendMessage(helloMessage);
139         changeState(State.OPEN_WAIT);
140     }
141
142     private void cancelTimeout() {
143         if(timeout!=null)
144             timeout.cancel();
145     }
146
147     private void sendMessage(NetconfMessage message) {
148         this.channel.writeAndFlush(message);
149     }
150
151     @Override
152     protected void handleMessage(NetconfHelloMessage netconfMessage) {
153         final Document doc = netconfMessage.getDocument();
154
155         // Only Hello message should arrive during negotiation
156         if (netconfMessage instanceof NetconfHelloMessage) {
157
158             replaceHelloMessageHandlers();
159
160             if (shouldUseChunkFraming(doc)) {
161                 insertChunkFramingToPipeline();
162             }
163
164             changeState(State.ESTABLISHED);
165             S session = getSession(sessionListener, channel, (NetconfHelloMessage)netconfMessage);
166
167             negotiationSuccessful(session);
168         } else {
169             final IllegalStateException cause = new IllegalStateException(
170                     "Received message was not hello as expected, but was " + XmlUtil.toString(doc));
171             logger.warn("Negotiation of netconf session failed", cause);
172             negotiationFailed(cause);
173         }
174     }
175
176     /**
177      * Insert chunk framing handlers into the pipeline
178      */
179     private void insertChunkFramingToPipeline() {
180         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
181                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
182         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
183                 new NetconfMessageAggregator(FramingMechanism.CHUNK));
184         channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
185                 CHUNK_DECODER_CHANNEL_HANDLER_KEY, new NetconfMessageChunkDecoder());
186     }
187
188     private boolean shouldUseChunkFraming(Document doc) {
189         return containsBase11Capability(doc)
190                 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
191     }
192
193     /**
194      * Remove special handlers for hello message. Insert regular netconf xml message (en|de)coders.
195      */
196     private void replaceHelloMessageHandlers() {
197         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
198         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new NetconfMessageToXMLEncoder());
199     }
200
201     private static ChannelHandler replaceChannelHandler(Channel channel, String handlerKey, ChannelHandler decoder) {
202         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
203     }
204
205     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message);
206
207     private synchronized void changeState(final State newState) {
208         logger.debug("Changing state from : {} to : {}", state, newState);
209         Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
210                 newState);
211         this.state = newState;
212     }
213
214     private boolean containsBase11Capability(final Document doc) {
215         final NodeList nList = doc.getElementsByTagName("capability");
216         for (int i = 0; i < nList.getLength(); i++) {
217             if (nList.item(i).getTextContent().contains("base:1.1")) {
218                 return true;
219             }
220         }
221         return false;
222     }
223
224     private static boolean isStateChangePermitted(State state, State newState) {
225         if (state == State.IDLE && newState == State.OPEN_WAIT)
226             return true;
227         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED)
228             return true;
229         if (state == State.OPEN_WAIT && newState == State.FAILED)
230             return true;
231
232         logger.debug("Transition from {} to {} is not allowed", state, newState);
233         return false;
234     }
235 }