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