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.util;
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.NetconfDocumentedException;
25 import org.opendaylight.controller.netconf.api.NetconfMessage;
26 import org.opendaylight.controller.netconf.api.NetconfSessionListener;
27 import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
28 import org.opendaylight.controller.netconf.util.handler.FramingMechanismHandlerFactory;
29 import org.opendaylight.controller.netconf.util.handler.NetconfChunkAggregator;
30 import org.opendaylight.controller.netconf.util.handler.NetconfMessageToXMLEncoder;
31 import org.opendaylight.controller.netconf.util.handler.NetconfXMLToHelloMessageDecoder;
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;
42 import java.util.concurrent.TimeUnit;
44 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
45 extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
47 private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
49 public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
51 protected final P sessionPreferences;
53 private final L sessionListener;
54 private Timeout timeout;
57 * Possible states for Finite State Machine
59 protected enum State {
60 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
63 private State state = State.IDLE;
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;
73 this.sessionListener = sessionListener;
74 this.connectionTimeoutMillis = connectionTimeoutMillis;
78 protected final void startNegotiation() {
79 final Optional<SslHandler> sslHandler = getSslHandler(channel);
80 if (sslHandler.isPresent()) {
81 Future<Channel> future = sslHandler.get().handshakeFuture();
82 future.addListener(new GenericFutureListener<Future<? super Channel>>() {
84 public void operationComplete(Future<? super Channel> future) {
85 Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
86 logger.debug("Ssl handshake complete");
95 private static Optional<SslHandler> getSslHandler(Channel channel) {
96 final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
97 return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
100 public P getSessionPreferences() {
101 return sessionPreferences;
104 private void start() {
105 final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
106 logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
108 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
110 timeout = this.timer.newTimeout(new TimerTask() {
112 public void run(final Timeout timeout) {
113 synchronized (this) {
114 if (state != State.ESTABLISHED) {
115 logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
116 final IllegalStateException cause = new IllegalStateException(
117 "Session was not established after " + timeout);
118 negotiationFailed(cause);
119 changeState(State.FAILED);
120 } else if(channel.isOpen()) {
121 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
125 }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
127 // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
128 sendMessage((NetconfHelloMessage)helloMessage);
130 replaceHelloMessageOutboundHandler();
131 changeState(State.OPEN_WAIT);
134 private void cancelTimeout() {
140 protected final S getSessionForHelloMessage(NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
141 Preconditions.checkNotNull(netconfMessage, "netconfMessage");
143 final Document doc = netconfMessage.getDocument();
145 if (shouldUseChunkFraming(doc)) {
146 insertChunkFramingToPipeline();
149 changeState(State.ESTABLISHED);
150 return getSession(sessionListener, channel, netconfMessage);
154 * Insert chunk framing handlers into the pipeline
156 private void insertChunkFramingToPipeline() {
157 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
158 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
159 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
160 new NetconfChunkAggregator());
163 private boolean shouldUseChunkFraming(Document doc) {
164 return containsBase11Capability(doc)
165 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
169 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
171 * Inbound hello message handler should be kept until negotiation is successful
172 * It caches any non-hello messages while negotiation is still in progress
174 protected final void replaceHelloMessageInboundHandler(final S session) {
175 ChannelHandler helloMessageHandler = replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
177 Preconditions.checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
178 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
179 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
180 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
182 // Process messages received during negotiation
183 // The hello message handler does not have to be synchronized, since it is always call from the same thread by netty
184 // It means, we are now using the thread now
185 for (NetconfMessage message : netconfMessagesFromNegotiation) {
186 session.handleMessage(message);
191 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
193 private void replaceHelloMessageOutboundHandler() {
194 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new NetconfMessageToXMLEncoder());
197 private static ChannelHandler replaceChannelHandler(Channel channel, String handlerKey, ChannelHandler decoder) {
198 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
201 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message) throws NetconfDocumentedException;
203 private synchronized void changeState(final State newState) {
204 logger.debug("Changing state from : {} to : {}", state, newState);
205 Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
207 this.state = newState;
210 private boolean containsBase11Capability(final Document doc) {
211 final NodeList nList = doc.getElementsByTagName("capability");
212 for (int i = 0; i < nList.getLength(); i++) {
213 if (nList.item(i).getTextContent().contains("base:1.1")) {
220 private static boolean isStateChangePermitted(State state, State newState) {
221 if (state == State.IDLE && newState == State.OPEN_WAIT) {
224 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
227 if (state == State.OPEN_WAIT && newState == State.FAILED) {
230 logger.debug("Transition from {} to {} is not allowed", state, newState);
235 * Handler to catch exceptions in pipeline during negotiation
237 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
239 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
240 logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
242 negotiationFailed(cause);
243 changeState(State.FAILED);