BUG-848 Fix netconf communication while using CHUNK encoding
[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 com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import io.netty.channel.Channel;
14 import io.netty.channel.ChannelHandler;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.channel.ChannelInboundHandlerAdapter;
17 import io.netty.handler.ssl.SslHandler;
18 import io.netty.util.Timeout;
19 import io.netty.util.Timer;
20 import io.netty.util.TimerTask;
21 import io.netty.util.concurrent.Future;
22 import io.netty.util.concurrent.GenericFutureListener;
23 import io.netty.util.concurrent.Promise;
24 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
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.NetconfXMLToHelloMessageDecoder;
32 import org.opendaylight.controller.netconf.util.handler.NetconfXMLToMessageDecoder;
33 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
34 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
35 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
36 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.w3c.dom.Document;
40 import org.w3c.dom.NodeList;
41
42 import java.util.concurrent.TimeUnit;
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 Timer timer;
65     private final long connectionTimeoutMillis;
66
67     // TODO shrink constructor
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 final 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) {
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
95     private static Optional<SslHandler> getSslHandler(Channel channel) {
96         final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
97         return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
98     }
99
100     public P getSessionPreferences() {
101         return sessionPreferences;
102     }
103
104     private void start() {
105         final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
106         logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
107
108         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
109
110         timeout = this.timer.newTimeout(new TimerTask() {
111             @Override
112             public void run(final Timeout timeout) {
113                 synchronized (this) {
114                     if (state != State.ESTABLISHED) {
115                         logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
116                         final IllegalStateException cause = new IllegalStateException(
117                                 "Session was not established after " + timeout);
118                         negotiationFailed(cause);
119                         changeState(State.FAILED);
120                     } else if(channel.isOpen()) {
121                         channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
122                     }
123                 }
124             }
125         }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
126
127         // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
128         sendMessage((NetconfHelloMessage)helloMessage);
129
130         replaceHelloMessageOutboundHandler();
131         changeState(State.OPEN_WAIT);
132     }
133
134     private void cancelTimeout() {
135         if(timeout!=null) {
136             timeout.cancel();
137         }
138     }
139
140     protected final S getSessionForHelloMessage(NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
141         Preconditions.checkNotNull(netconfMessage, "netconfMessage");
142
143         final Document doc = netconfMessage.getDocument();
144
145         if (shouldUseChunkFraming(doc)) {
146             insertChunkFramingToPipeline();
147         }
148
149         changeState(State.ESTABLISHED);
150         return getSession(sessionListener, channel, netconfMessage);
151     }
152
153     /**
154      * Insert chunk framing handlers into the pipeline
155      */
156     private void insertChunkFramingToPipeline() {
157         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
158                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
159         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
160                 new NetconfChunkAggregator());
161     }
162
163     private boolean shouldUseChunkFraming(Document doc) {
164         return containsBase11Capability(doc)
165                 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
166     }
167
168     /**
169      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
170      *
171      * Inbound hello message handler should be kept until negotiation is successful
172      * It caches any non-hello messages while negotiation is still in progress
173      */
174     protected final void replaceHelloMessageInboundHandler(final S session) {
175         ChannelHandler helloMessageHandler = replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
176
177         Preconditions.checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
178                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
179         Iterable<NetconfMessage> netconfMessagesFromNegotiation =
180                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
181
182         // Process messages received during negotiation
183         // The hello message handler does not have to be synchronized, since it is always call from the same thread by netty
184         // It means, we are now using the thread now
185         for (NetconfMessage message : netconfMessagesFromNegotiation) {
186             session.handleMessage(message);
187         }
188     }
189
190     /**
191      * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
192      */
193     private void replaceHelloMessageOutboundHandler() {
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) throws NetconfDocumentedException;
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         }
224         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
225             return true;
226         }
227         if (state == State.OPEN_WAIT && newState == State.FAILED) {
228             return true;
229         }
230         logger.debug("Transition from {} to {} is not allowed", state, newState);
231         return false;
232     }
233
234     /**
235      * Handler to catch exceptions in pipeline during negotiation
236      */
237     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
238         @Override
239         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
240             logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
241             cancelTimeout();
242             negotiationFailed(cause);
243             changeState(State.FAILED);
244         }
245     }
246 }