Make use of new sendMessage method in AbstractNegotiator
[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 io.netty.channel.ChannelInboundHandlerAdapter;
25 import org.opendaylight.controller.netconf.api.AbstractNetconfSession;
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.util.handler.FramingMechanismHandlerFactory;
30 import org.opendaylight.controller.netconf.util.handler.NetconfChunkAggregator;
31 import org.opendaylight.controller.netconf.util.handler.NetconfMessageToXMLEncoder;
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 com.google.common.base.Optional;
43 import com.google.common.base.Preconditions;
44
45 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
46 extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
47
48     private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
49     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
50
51     private final P sessionPreferences;
52
53     private final L sessionListener;
54     private Timeout timeout;
55
56     /**
57      * Possible states for Finite State Machine
58      */
59     private 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     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 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         changeState(State.OPEN_WAIT);
129     }
130
131     private void cancelTimeout() {
132         if(timeout!=null) {
133             timeout.cancel();
134         }
135     }
136
137     @Override
138     protected void handleMessage(NetconfHelloMessage netconfMessage) {
139         Preconditions.checkNotNull(netconfMessage != null, "netconfMessage");
140
141         final Document doc = netconfMessage.getDocument();
142
143         replaceHelloMessageHandlers();
144
145         if (shouldUseChunkFraming(doc)) {
146             insertChunkFramingToPipeline();
147         }
148
149         changeState(State.ESTABLISHED);
150         S session = getSession(sessionListener, channel, netconfMessage);
151
152         negotiationSuccessful(session);
153     }
154
155     /**
156      * Insert chunk framing handlers into the pipeline
157      */
158     private void insertChunkFramingToPipeline() {
159         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
160                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
161         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
162                 new NetconfChunkAggregator());
163     }
164
165     private boolean shouldUseChunkFraming(Document doc) {
166         return containsBase11Capability(doc)
167                 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
168     }
169
170     /**
171      * Remove special handlers for hello message. Insert regular netconf xml message (en|de)coders.
172      */
173     private void replaceHelloMessageHandlers() {
174         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
175         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new NetconfMessageToXMLEncoder());
176     }
177
178     private static ChannelHandler replaceChannelHandler(Channel channel, String handlerKey, ChannelHandler decoder) {
179         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
180     }
181
182     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message);
183
184     private synchronized void changeState(final State newState) {
185         logger.debug("Changing state from : {} to : {}", state, newState);
186         Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
187                 newState);
188         this.state = newState;
189     }
190
191     private boolean containsBase11Capability(final Document doc) {
192         final NodeList nList = doc.getElementsByTagName("capability");
193         for (int i = 0; i < nList.getLength(); i++) {
194             if (nList.item(i).getTextContent().contains("base:1.1")) {
195                 return true;
196             }
197         }
198         return false;
199     }
200
201     private static boolean isStateChangePermitted(State state, State newState) {
202         if (state == State.IDLE && newState == State.OPEN_WAIT) {
203             return true;
204         }
205         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
206             return true;
207         }
208         if (state == State.OPEN_WAIT && newState == State.FAILED) {
209             return true;
210         }
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
221         @Override
222         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
223             logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
224             cancelTimeout();
225             negotiationFailed(cause);
226             changeState(State.FAILED);
227         }
228     }
229 }