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