724b45bc08d867f6702ae75a11aece291fefd484
[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.NetconfMessage;
25 import org.opendaylight.controller.netconf.api.NetconfSessionListener;
26 import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
27 import org.opendaylight.controller.netconf.util.handler.FramingMechanismHandlerFactory;
28 import org.opendaylight.controller.netconf.util.handler.NetconfChunkAggregator;
29 import org.opendaylight.controller.netconf.util.handler.NetconfMessageToXMLEncoder;
30 import org.opendaylight.controller.netconf.util.handler.NetconfXMLToMessageDecoder;
31 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
32 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
33 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
34 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.w3c.dom.Document;
38 import org.w3c.dom.NodeList;
39
40 import java.util.concurrent.TimeUnit;
41
42 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
43 extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
44
45     private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
46
47     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
48
49     protected final P sessionPreferences;
50
51     private final L sessionListener;
52     private Timeout timeout;
53
54     /**
55      * Possible states for Finite State Machine
56      */
57     protected enum State {
58         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
59     }
60
61     private State state = State.IDLE;
62     private final Timer timer;
63     private final long connectionTimeoutMillis;
64
65     // TODO shrink constructor
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) {
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
93     private static Optional<SslHandler> getSslHandler(Channel channel) {
94         final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
95         return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
96     }
97
98     public P getSessionPreferences() {
99         return sessionPreferences;
100     }
101
102     private void start() {
103         final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
104         logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
105
106         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
107
108         timeout = this.timer.newTimeout(new TimerTask() {
109             @Override
110             public void run(final Timeout timeout) {
111                 synchronized (this) {
112                     if (state != State.ESTABLISHED) {
113                         logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
114                         final IllegalStateException cause = new IllegalStateException(
115                                 "Session was not established after " + timeout);
116                         negotiationFailed(cause);
117                         changeState(State.FAILED);
118                     } else if(channel.isOpen()) {
119                         channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
120                     }
121                 }
122             }
123         }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
124
125         // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
126         sendMessage((NetconfHelloMessage)helloMessage);
127         changeState(State.OPEN_WAIT);
128     }
129     private void cancelTimeout() {
130         if(timeout!=null) {
131             timeout.cancel();
132         }
133     }
134
135     @Override
136     protected void handleMessage(NetconfHelloMessage netconfMessage) {
137         S session = getSessionForHelloMessage(netconfMessage);
138         negotiationSuccessful(session);
139     }
140
141     protected final S getSessionForHelloMessage(NetconfHelloMessage netconfMessage) {
142         Preconditions.checkNotNull(netconfMessage, "netconfMessage");
143
144         final Document doc = netconfMessage.getDocument();
145
146         replaceHelloMessageHandlers();
147
148         if (shouldUseChunkFraming(doc)) {
149             insertChunkFramingToPipeline();
150         }
151
152         changeState(State.ESTABLISHED);
153         return getSession(sessionListener, channel, netconfMessage);
154     }
155
156     /**
157      * Insert chunk framing handlers into the pipeline
158      */
159     protected void insertChunkFramingToPipeline() {
160         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
161                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
162         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
163                 new NetconfChunkAggregator());
164     }
165
166     protected boolean shouldUseChunkFraming(Document doc) {
167         return containsBase11Capability(doc)
168                 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
169     }
170
171     /**
172      * Remove special handlers for hello message. Insert regular netconf xml message (en|de)coders.
173      */
174     protected void replaceHelloMessageHandlers() {
175         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
176         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new NetconfMessageToXMLEncoder());
177     }
178
179     private static ChannelHandler replaceChannelHandler(Channel channel, String handlerKey, ChannelHandler decoder) {
180         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
181     }
182
183     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message);
184
185     protected synchronized void changeState(final State newState) {
186         logger.debug("Changing state from : {} to : {}", state, newState);
187         Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
188                 newState);
189         this.state = newState;
190     }
191
192     private boolean containsBase11Capability(final Document doc) {
193         final NodeList nList = doc.getElementsByTagName("capability");
194         for (int i = 0; i < nList.getLength(); i++) {
195             if (nList.item(i).getTextContent().contains("base:1.1")) {
196                 return true;
197             }
198         }
199         return false;
200     }
201
202     private static boolean isStateChangePermitted(State state, State newState) {
203         if (state == State.IDLE && newState == State.OPEN_WAIT) {
204             return true;
205         }
206         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
207             return true;
208         }
209         if (state == State.OPEN_WAIT && newState == State.FAILED) {
210             return true;
211         }
212         logger.debug("Transition from {} to {} is not allowed", state, newState);
213         return false;
214     }
215
216     /**
217      * Handler to catch exceptions in pipeline during negotiation
218      */
219     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
220         @Override
221         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
222             logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
223             cancelTimeout();
224             negotiationFailed(cause);
225             changeState(State.FAILED);
226         }
227     }
228 }