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