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.NetconfXMLToMessageDecoder;
32 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
33 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
34 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
35 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.NodeList;
41 import java.util.concurrent.TimeUnit;
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 Timer timer;
64 private final long connectionTimeoutMillis;
66 // TODO shrink constructor
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;
72 this.sessionListener = sessionListener;
73 this.connectionTimeoutMillis = connectionTimeoutMillis;
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>>() {
83 public void operationComplete(Future<? super Channel> future) {
84 Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
85 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 public P getSessionPreferences() {
100 return sessionPreferences;
103 private void start() {
104 final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
105 logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
107 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
109 timeout = this.timer.newTimeout(new TimerTask() {
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);
124 }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
126 // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
127 sendMessage((NetconfHelloMessage)helloMessage);
128 changeState(State.OPEN_WAIT);
130 private void cancelTimeout() {
137 protected void handleMessage(NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
138 S session = getSessionForHelloMessage(netconfMessage) ;
139 negotiationSuccessful(session);
142 protected final S getSessionForHelloMessage(NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
143 Preconditions.checkNotNull(netconfMessage, "netconfMessage");
145 final Document doc = netconfMessage.getDocument();
147 replaceHelloMessageHandlers();
149 if (shouldUseChunkFraming(doc)) {
150 insertChunkFramingToPipeline();
153 changeState(State.ESTABLISHED);
154 return getSession(sessionListener, channel, netconfMessage);
158 * Insert chunk framing handlers into the pipeline
160 protected void insertChunkFramingToPipeline() {
161 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
162 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
163 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
164 new NetconfChunkAggregator());
167 protected boolean shouldUseChunkFraming(Document doc) {
168 return containsBase11Capability(doc)
169 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
173 * Remove special handlers for hello message. Insert regular netconf xml message (en|de)coders.
175 protected void replaceHelloMessageHandlers() {
176 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
177 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new NetconfMessageToXMLEncoder());
180 private static ChannelHandler replaceChannelHandler(Channel channel, String handlerKey, ChannelHandler decoder) {
181 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
184 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message) throws NetconfDocumentedException;
186 protected synchronized void changeState(final State newState) {
187 logger.debug("Changing state from : {} to : {}", state, newState);
188 Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
190 this.state = newState;
193 private boolean containsBase11Capability(final Document doc) {
194 final NodeList nList = doc.getElementsByTagName("capability");
195 for (int i = 0; i < nList.getLength(); i++) {
196 if (nList.item(i).getTextContent().contains("base:1.1")) {
203 private static boolean isStateChangePermitted(State state, State newState) {
204 if (state == State.IDLE && newState == State.OPEN_WAIT) {
207 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
210 if (state == State.OPEN_WAIT && newState == State.FAILED) {
213 logger.debug("Transition from {} to {} is not allowed", state, newState);
218 * Handler to catch exceptions in pipeline during negotiation
220 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
222 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
223 logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
225 negotiationFailed(cause);
226 changeState(State.FAILED);