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 java.util.concurrent.TimeUnit;
13 import org.opendaylight.controller.netconf.api.AbstractNetconfSession;
14 import org.opendaylight.controller.netconf.api.NetconfMessage;
15 import org.opendaylight.controller.netconf.api.NetconfSessionListener;
16 import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
17 import org.opendaylight.controller.netconf.util.handler.FramingMechanismHandlerFactory;
18 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
19 import org.opendaylight.controller.netconf.util.handler.NetconfMessageAggregator;
20 import org.opendaylight.controller.netconf.util.handler.NetconfMessageChunkDecoder;
21 import org.opendaylight.controller.netconf.util.handler.NetconfMessageToXMLEncoder;
22 import org.opendaylight.controller.netconf.util.handler.NetconfXMLToMessageDecoder;
23 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
24 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
25 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import org.w3c.dom.Document;
29 import org.w3c.dom.NodeList;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
34 import io.netty.channel.Channel;
35 import io.netty.channel.ChannelHandler;
36 import io.netty.channel.ChannelHandlerContext;
37 import io.netty.handler.ssl.SslHandler;
38 import io.netty.util.Timeout;
39 import io.netty.util.Timer;
40 import io.netty.util.TimerTask;
41 import io.netty.util.concurrent.Future;
42 import io.netty.util.concurrent.GenericFutureListener;
43 import io.netty.util.concurrent.Promise;
45 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
46 extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
48 private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
49 public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
50 public static final String CHUNK_DECODER_CHANNEL_HANDLER_KEY = "chunkDecoder";
52 protected final P sessionPreferences;
54 private final L sessionListener;
55 private Timeout timeout;
58 * Possible states for Finite State Machine
61 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
64 private State state = State.IDLE;
65 private final Timer timer;
66 private final long connectionTimeoutMillis;
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 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) throws Exception {
85 Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
86 logger.debug("Ssl handshake complete");
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);
99 private void start() {
100 final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
101 logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
103 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ChannelHandler() {
105 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
109 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
113 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
114 logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
116 negotiationFailed(cause);
117 changeState(State.FAILED);
121 timeout = this.timer.newTimeout(new TimerTask() {
123 public void run(final Timeout timeout) throws Exception {
124 synchronized (this) {
125 if (state != State.ESTABLISHED) {
126 logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
127 final IllegalStateException cause = new IllegalStateException(
128 "Session was not established after " + timeout);
129 negotiationFailed(cause);
130 changeState(State.FAILED);
131 } else if(channel.isOpen()) {
132 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
136 }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
138 sendMessage(helloMessage);
139 changeState(State.OPEN_WAIT);
142 private void cancelTimeout() {
147 private void sendMessage(NetconfMessage message) {
148 this.channel.writeAndFlush(message);
152 protected void handleMessage(NetconfHelloMessage netconfMessage) {
153 final Document doc = netconfMessage.getDocument();
155 // Only Hello message should arrive during negotiation
156 if (netconfMessage instanceof NetconfHelloMessage) {
158 replaceHelloMessageHandlers();
160 if (shouldUseChunkFraming(doc)) {
161 insertChunkFramingToPipeline();
164 changeState(State.ESTABLISHED);
165 S session = getSession(sessionListener, channel, (NetconfHelloMessage)netconfMessage);
167 negotiationSuccessful(session);
169 final IllegalStateException cause = new IllegalStateException(
170 "Received message was not hello as expected, but was " + XmlUtil.toString(doc));
171 logger.warn("Negotiation of netconf session failed", cause);
172 negotiationFailed(cause);
177 * Insert chunk framing handlers into the pipeline
179 private void insertChunkFramingToPipeline() {
180 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
181 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
182 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
183 new NetconfMessageAggregator(FramingMechanism.CHUNK));
184 channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
185 CHUNK_DECODER_CHANNEL_HANDLER_KEY, new NetconfMessageChunkDecoder());
188 private boolean shouldUseChunkFraming(Document doc) {
189 return containsBase11Capability(doc)
190 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
194 * Remove special handlers for hello message. Insert regular netconf xml message (en|de)coders.
196 private void replaceHelloMessageHandlers() {
197 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
198 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new NetconfMessageToXMLEncoder());
201 private static ChannelHandler replaceChannelHandler(Channel channel, String handlerKey, ChannelHandler decoder) {
202 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
205 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message);
207 private synchronized void changeState(final State newState) {
208 logger.debug("Changing state from : {} to : {}", state, newState);
209 Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
211 this.state = newState;
214 private boolean containsBase11Capability(final Document doc) {
215 final NodeList nList = doc.getElementsByTagName("capability");
216 for (int i = 0; i < nList.getLength(); i++) {
217 if (nList.item(i).getTextContent().contains("base:1.1")) {
224 private static boolean isStateChangePermitted(State state, State newState) {
225 if (state == State.IDLE && newState == State.OPEN_WAIT)
227 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED)
229 if (state == State.OPEN_WAIT && newState == State.FAILED)
232 logger.debug("Transition from {} to {} is not allowed", state, newState);