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.GenericFutureListener;
23 import io.netty.util.concurrent.Promise;
24 import java.util.concurrent.TimeUnit;
25 import org.opendaylight.netconf.api.NetconfDocumentedException;
26 import org.opendaylight.netconf.api.NetconfMessage;
27 import org.opendaylight.netconf.api.NetconfSessionListener;
28 import org.opendaylight.netconf.api.NetconfSessionPreferences;
29 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
30 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
31 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
32 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
33 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
34 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
35 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
36 import org.opendaylight.netconf.util.messages.FramingMechanism;
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,
44 S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
45 extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
47 private static final Logger LOG = 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 Promise<S> promise;
65 private final Timer timer;
66 private final long connectionTimeoutMillis;
68 protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
69 final Channel channel, final Timer timer,
70 final L sessionListener, final long connectionTimeoutMillis) {
71 super(promise, channel);
72 this.sessionPreferences = sessionPreferences;
73 this.promise = promise;
75 this.sessionListener = sessionListener;
76 this.connectionTimeoutMillis = connectionTimeoutMillis;
80 protected final void startNegotiation() {
81 if (ifNegotiatedAlready()) {
82 LOG.debug("Negotiation on channel {} already started", channel);
84 final Optional<SslHandler> sslHandler = getSslHandler(channel);
85 if (sslHandler.isPresent()) {
86 sslHandler.get().handshakeFuture().addListener(future -> {
87 Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
88 LOG.debug("Ssl handshake complete");
97 protected final synchronized boolean ifNegotiatedAlready() {
98 // Indicates whether negotiation already started
99 return this.state != State.IDLE;
102 private static Optional<SslHandler> getSslHandler(final Channel channel) {
103 final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
104 return sslHandler == null ? Optional.absent() : Optional.of(sslHandler);
107 public P getSessionPreferences() {
108 return sessionPreferences;
111 private void start() {
112 final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
113 LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);
115 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
117 sendMessage(helloMessage);
119 replaceHelloMessageOutboundHandler();
120 changeState(State.OPEN_WAIT);
122 timeout = this.timer.newTimeout(new TimerTask() {
124 @SuppressWarnings("checkstyle:hiddenField")
125 public void run(final Timeout timeout) {
126 synchronized (this) {
127 if (state != State.ESTABLISHED) {
129 LOG.debug("Connection timeout after {}, session is in state {}", timeout, state);
131 // Do not fail negotiation if promise is done or canceled
132 // It would result in setting result of the promise second time and that throws exception
133 if (!isPromiseFinished()) {
134 LOG.warn("Netconf session was not established after {}", connectionTimeoutMillis);
135 changeState(State.FAILED);
137 channel.close().addListener((GenericFutureListener<ChannelFuture>) future -> {
138 if (future.isSuccess()) {
139 LOG.debug("Channel {} closed: success", future.channel());
141 LOG.warn("Channel {} closed: fail", future.channel());
145 } else if (channel.isOpen()) {
146 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
151 private boolean isPromiseFinished() {
152 return promise.isDone() || promise.isCancelled();
155 }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
158 private void cancelTimeout() {
159 if (timeout != null) {
164 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
165 throws NetconfDocumentedException {
166 Preconditions.checkNotNull(netconfMessage, "netconfMessage");
168 final Document doc = netconfMessage.getDocument();
170 if (shouldUseChunkFraming(doc)) {
171 insertChunkFramingToPipeline();
174 changeState(State.ESTABLISHED);
175 return getSession(sessionListener, channel, netconfMessage);
179 * Insert chunk framing handlers into the pipeline.
181 private void insertChunkFramingToPipeline() {
182 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
183 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
184 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
185 new NetconfChunkAggregator());
188 private boolean shouldUseChunkFraming(final Document doc) {
189 return containsBase11Capability(doc)
190 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
194 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
197 * Inbound hello message handler should be kept until negotiation is successful
198 * It caches any non-hello messages while negotiation is still in progress
200 protected final void replaceHelloMessageInboundHandler(final S session) {
201 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
202 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
204 Preconditions.checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
205 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
206 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
207 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
209 // Process messages received during negotiation
210 // The hello message handler does not have to be synchronized,
211 // since it is always call from the same thread by netty.
212 // It means, we are now using the thread now
213 for (NetconfMessage message : netconfMessagesFromNegotiation) {
214 session.handleMessage(message);
219 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
221 private void replaceHelloMessageOutboundHandler() {
222 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
223 new NetconfMessageToXMLEncoder());
226 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
227 final ChannelHandler decoder) {
228 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
231 @SuppressWarnings("checkstyle:hiddenField")
232 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
233 throws NetconfDocumentedException;
235 private synchronized void changeState(final State newState) {
236 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
237 Preconditions.checkState(isStateChangePermitted(state, newState),
238 "Cannot change state from %s to %s for chanel %s", state, newState, channel);
239 this.state = newState;
242 private static boolean containsBase11Capability(final Document doc) {
243 final NodeList nList = doc.getElementsByTagNameNS(
244 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
245 XmlNetconfConstants.CAPABILITY);
246 for (int i = 0; i < nList.getLength(); i++) {
247 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
254 private static boolean isStateChangePermitted(final State state, final State newState) {
255 if (state == State.IDLE && newState == State.OPEN_WAIT) {
258 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
261 if (state == State.OPEN_WAIT && newState == State.FAILED) {
264 LOG.debug("Transition from {} to {} is not allowed", state, newState);
269 * Handler to catch exceptions in pipeline during negotiation.
271 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
273 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
274 LOG.warn("An exception occurred during negotiation with {}", channel.remoteAddress(), cause);
276 negotiationFailed(cause);
277 changeState(State.FAILED);