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.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.ChannelFuture;
15 import io.netty.channel.ChannelHandler;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.channel.ChannelInboundHandlerAdapter;
18 import io.netty.handler.ssl.SslHandler;
19 import io.netty.util.Timeout;
20 import io.netty.util.Timer;
21 import io.netty.util.TimerTask;
22 import io.netty.util.concurrent.Future;
23 import io.netty.util.concurrent.GenericFutureListener;
24 import io.netty.util.concurrent.Promise;
25 import java.util.concurrent.TimeUnit;
26 import org.opendaylight.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.netconf.api.NetconfMessage;
28 import org.opendaylight.netconf.api.NetconfSessionListener;
29 import org.opendaylight.netconf.api.NetconfSessionPreferences;
30 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
31 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
32 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
33 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
34 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
35 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
36 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
37 import org.opendaylight.netconf.util.messages.FramingMechanism;
38 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.w3c.dom.Document;
42 import org.w3c.dom.NodeList;
44 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences,
45 S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
46 extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
48 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
50 public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
52 protected final P sessionPreferences;
54 private final L sessionListener;
55 private Timeout timeout;
58 * Possible states for Finite State Machine.
60 protected enum State {
61 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
64 private State state = State.IDLE;
65 private final Promise<S> promise;
66 private final Timer timer;
67 private final long connectionTimeoutMillis;
69 protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
70 final Channel channel, final Timer timer,
71 final L sessionListener, final long connectionTimeoutMillis) {
72 super(promise, channel);
73 this.sessionPreferences = sessionPreferences;
74 this.promise = promise;
76 this.sessionListener = sessionListener;
77 this.connectionTimeoutMillis = connectionTimeoutMillis;
81 protected final void startNegotiation() {
82 final Optional<SslHandler> sslHandler = getSslHandler(channel);
83 if (sslHandler.isPresent()) {
84 Future<Channel> future = sslHandler.get().handshakeFuture();
85 future.addListener(new GenericFutureListener<Future<? super Channel>>() {
87 public void operationComplete(final Future<? super Channel> future) {
88 Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
89 LOG.debug("Ssl handshake complete");
98 private static Optional<SslHandler> getSslHandler(final Channel channel) {
99 final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
100 return sslHandler == null ? Optional.<SslHandler>absent() : Optional.of(sslHandler);
103 public P getSessionPreferences() {
104 return sessionPreferences;
107 private void start() {
108 final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
109 LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);
111 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
113 sendMessage(helloMessage);
115 replaceHelloMessageOutboundHandler();
116 changeState(State.OPEN_WAIT);
118 timeout = this.timer.newTimeout(new TimerTask() {
120 @SuppressWarnings("checkstyle:hiddenField")
121 public void run(final Timeout timeout) {
122 synchronized (this) {
123 if (state != State.ESTABLISHED) {
125 LOG.debug("Connection timeout after {}, session is in state {}", timeout, state);
127 // Do not fail negotiation if promise is done or canceled
128 // It would result in setting result of the promise second time and that throws exception
129 if (!isPromiseFinished()) {
130 LOG.warn("Netconf session was not established after {}", connectionTimeoutMillis);
131 changeState(State.FAILED);
133 channel.close().addListener(new GenericFutureListener<ChannelFuture>() {
135 public void operationComplete(final ChannelFuture future) throws Exception {
136 if (future.isSuccess()) {
137 LOG.debug("Channel {} closed: success", future.channel());
139 LOG.warn("Channel {} closed: fail", future.channel());
144 } else if (channel.isOpen()) {
145 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
150 private boolean isPromiseFinished() {
151 return promise.isDone() || promise.isCancelled();
154 }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
157 private void cancelTimeout() {
158 if (timeout != null) {
163 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
164 throws NetconfDocumentedException {
165 Preconditions.checkNotNull(netconfMessage, "netconfMessage");
167 final Document doc = netconfMessage.getDocument();
169 if (shouldUseChunkFraming(doc)) {
170 insertChunkFramingToPipeline();
173 changeState(State.ESTABLISHED);
174 return getSession(sessionListener, channel, netconfMessage);
178 * Insert chunk framing handlers into the pipeline.
180 private void insertChunkFramingToPipeline() {
181 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
182 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
183 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
184 new NetconfChunkAggregator());
187 private boolean shouldUseChunkFraming(final Document doc) {
188 return containsBase11Capability(doc)
189 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
193 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
196 * Inbound hello message handler should be kept until negotiation is successful
197 * It caches any non-hello messages while negotiation is still in progress
199 protected final void replaceHelloMessageInboundHandler(final S session) {
200 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
201 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
203 Preconditions.checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
204 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
205 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
206 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
208 // Process messages received during negotiation
209 // The hello message handler does not have to be synchronized,
210 // since it is always call from the same thread by netty.
211 // It means, we are now using the thread now
212 for (NetconfMessage message : netconfMessagesFromNegotiation) {
213 session.handleMessage(message);
218 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
220 private void replaceHelloMessageOutboundHandler() {
221 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
222 new NetconfMessageToXMLEncoder());
225 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
226 final ChannelHandler decoder) {
227 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
230 @SuppressWarnings("checkstyle:hiddenField")
231 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
232 throws NetconfDocumentedException;
234 private synchronized void changeState(final State newState) {
235 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
236 Preconditions.checkState(isStateChangePermitted(state, newState),
237 "Cannot change state from %s to %s for chanel %s", state, newState, channel);
238 this.state = newState;
241 private static boolean containsBase11Capability(final Document doc) {
242 final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
243 for (int i = 0; i < nList.getLength(); i++) {
244 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
251 private static boolean isStateChangePermitted(final State state, final State newState) {
252 if (state == State.IDLE && newState == State.OPEN_WAIT) {
255 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
258 if (state == State.OPEN_WAIT && newState == State.FAILED) {
261 LOG.debug("Transition from {} to {} is not allowed", state, newState);
266 * Handler to catch exceptions in pipeline during negotiation.
268 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
270 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
271 LOG.warn("An exception occurred during negotiation with {}", channel.remoteAddress(), cause);
273 negotiationFailed(cause);
274 changeState(State.FAILED);