2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.nettyutil;
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;
43 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
44 extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
46 private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
48 public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
50 protected final P sessionPreferences;
52 private final L sessionListener;
53 private Timeout timeout;
56 * Possible states for Finite State Machine
58 protected enum State {
59 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
62 private State state = State.IDLE;
63 private final Promise<S> promise;
64 private final Timer timer;
65 private final long connectionTimeoutMillis;
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.promise = promise;
74 this.sessionListener = sessionListener;
75 this.connectionTimeoutMillis = connectionTimeoutMillis;
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>>() {
85 public void operationComplete(Future<? super Channel> future) {
86 Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
87 logger.debug("Ssl handshake complete");
96 private static Optional<SslHandler> getSslHandler(Channel channel) {
97 final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
98 return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
101 public P getSessionPreferences() {
102 return sessionPreferences;
105 private void start() {
106 final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
107 logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
109 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
111 // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
112 sendMessage((NetconfHelloMessage)helloMessage);
114 replaceHelloMessageOutboundHandler();
115 changeState(State.OPEN_WAIT);
117 timeout = this.timer.newTimeout(new TimerTask() {
119 public void run(final Timeout timeout) {
120 synchronized (this) {
121 if (state != State.ESTABLISHED) {
123 logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
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 // FIXME BUG-1365 calling "negotiation failed" closes the channel, but the channel does not get closed if data is still being transferred
129 // Loopback connection initiation might
130 negotiationFailed(new IllegalStateException("Session was not established after " + timeout));
133 changeState(State.FAILED);
134 } else if(channel.isOpen()) {
135 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
140 private boolean isPromiseFinished() {
141 return promise.isDone() || promise.isCancelled();
144 }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
147 private void cancelTimeout() {
153 protected final S getSessionForHelloMessage(NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
154 Preconditions.checkNotNull(netconfMessage, "netconfMessage");
156 final Document doc = netconfMessage.getDocument();
158 if (shouldUseChunkFraming(doc)) {
159 insertChunkFramingToPipeline();
162 changeState(State.ESTABLISHED);
163 return getSession(sessionListener, channel, netconfMessage);
167 * Insert chunk framing handlers into the pipeline
169 private void insertChunkFramingToPipeline() {
170 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
171 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
172 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
173 new NetconfChunkAggregator());
176 private boolean shouldUseChunkFraming(Document doc) {
177 return containsBase11Capability(doc)
178 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
182 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
184 * Inbound hello message handler should be kept until negotiation is successful
185 * It caches any non-hello messages while negotiation is still in progress
187 protected final void replaceHelloMessageInboundHandler(final S session) {
188 ChannelHandler helloMessageHandler = replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
190 Preconditions.checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
191 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
192 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
193 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
195 // Process messages received during negotiation
196 // The hello message handler does not have to be synchronized, since it is always call from the same thread by netty
197 // It means, we are now using the thread now
198 for (NetconfMessage message : netconfMessagesFromNegotiation) {
199 session.handleMessage(message);
204 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
206 private void replaceHelloMessageOutboundHandler() {
207 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new NetconfMessageToXMLEncoder());
210 private static ChannelHandler replaceChannelHandler(Channel channel, String handlerKey, ChannelHandler decoder) {
211 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
214 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message) throws NetconfDocumentedException;
216 private synchronized void changeState(final State newState) {
217 logger.debug("Changing state from : {} to : {}", state, newState);
218 Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
220 this.state = newState;
223 private boolean containsBase11Capability(final Document doc) {
224 final NodeList nList = doc.getElementsByTagName("capability");
225 for (int i = 0; i < nList.getLength(); i++) {
226 if (nList.item(i).getTextContent().contains("base:1.1")) {
233 private static boolean isStateChangePermitted(State state, State newState) {
234 if (state == State.IDLE && newState == State.OPEN_WAIT) {
237 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
240 if (state == State.OPEN_WAIT && newState == State.FAILED) {
243 logger.debug("Transition from {} to {} is not allowed", state, newState);
248 * Handler to catch exceptions in pipeline during negotiation
250 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
252 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
253 logger.warn("An exception occurred during negotiation with {}", channel.remoteAddress(), cause);
255 negotiationFailed(cause);
256 changeState(State.FAILED);