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
8 package org.opendaylight.netconf.nettyutil;
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
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.concurrent.Promise;
21 import java.util.Optional;
22 import java.util.concurrent.TimeUnit;
23 import org.checkerframework.checker.lock.qual.GuardedBy;
24 import org.opendaylight.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.netconf.api.NetconfMessage;
26 import org.opendaylight.netconf.api.NetconfSessionListener;
27 import org.opendaylight.netconf.api.NetconfSessionPreferences;
28 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
29 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
30 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
31 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
32 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
33 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
34 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
35 import org.opendaylight.netconf.util.messages.FramingMechanism;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.NodeList;
41 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences,
42 S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
43 extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
45 * Possible states for Finite State Machine.
47 protected enum State {
48 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
51 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
52 private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
54 protected final P sessionPreferences;
55 protected final Channel channel;
57 private final long connectionTimeoutMillis;
58 private final Promise<S> promise;
59 private final L sessionListener;
60 private final Timer timer;
62 private Timeout timeoutTask;
65 private State state = State.IDLE;
67 protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
68 final Channel channel, final Timer timer,
69 final L sessionListener, final long connectionTimeoutMillis) {
70 this.channel = requireNonNull(channel);
71 this.promise = requireNonNull(promise);
72 this.sessionPreferences = sessionPreferences;
74 this.sessionListener = sessionListener;
75 this.connectionTimeoutMillis = connectionTimeoutMillis;
78 protected final void startNegotiation() {
79 if (ifNegotiatedAlready()) {
80 LOG.debug("Negotiation on channel {} already started", channel);
82 final Optional<SslHandler> sslHandler = getSslHandler(channel);
83 if (sslHandler.isPresent()) {
84 sslHandler.get().handshakeFuture().addListener(future -> {
85 checkState(future.isSuccess(), "Ssl handshake was not successful");
86 LOG.debug("Ssl handshake complete");
95 protected final synchronized boolean ifNegotiatedAlready() {
96 // Indicates whether negotiation already started
97 return this.state != State.IDLE;
100 private static Optional<SslHandler> getSslHandler(final Channel channel) {
101 return Optional.ofNullable(channel.pipeline().get(SslHandler.class));
104 public final P getSessionPreferences() {
105 return sessionPreferences;
108 private void start() {
109 final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
110 LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);
112 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
114 sendMessage(helloMessage);
116 replaceHelloMessageOutboundHandler();
117 changeState(State.OPEN_WAIT);
119 timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
122 private synchronized void timeoutExpired(final Timeout timeout) {
123 if (state != State.ESTABLISHED) {
124 LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
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 (!promise.isDone() && !promise.isCancelled()) {
130 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
131 connectionTimeoutMillis);
132 changeState(State.FAILED);
134 channel.close().addListener(future -> {
135 if (future.isSuccess()) {
136 LOG.debug("Channel {} closed: success", channel);
138 LOG.warn("Channel {} closed: fail", channel);
142 } else if (channel.isOpen()) {
143 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
147 private void cancelTimeout() {
148 if (timeoutTask != null) {
149 timeoutTask.cancel();
153 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
154 throws NetconfDocumentedException {
155 final Document doc = netconfMessage.getDocument();
157 if (shouldUseChunkFraming(doc)) {
158 insertChunkFramingToPipeline();
161 changeState(State.ESTABLISHED);
162 return getSession(sessionListener, channel, netconfMessage);
165 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
166 throws NetconfDocumentedException;
169 * Insert chunk framing handlers into the pipeline.
171 private void insertChunkFramingToPipeline() {
172 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
173 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
174 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
175 new NetconfChunkAggregator());
178 private boolean shouldUseChunkFraming(final Document doc) {
179 return containsBase11Capability(doc)
180 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
184 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
187 * Inbound hello message handler should be kept until negotiation is successful
188 * It caches any non-hello messages while negotiation is still in progress
190 protected final void replaceHelloMessageInboundHandler(final S session) {
191 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
192 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
194 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
195 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
196 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
197 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
199 // Process messages received during negotiation
200 // The hello message handler does not have to be synchronized,
201 // since it is always call from the same thread by netty.
202 // It means, we are now using the thread now
203 for (NetconfMessage message : netconfMessagesFromNegotiation) {
204 session.handleMessage(message);
209 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
211 private void replaceHelloMessageOutboundHandler() {
212 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
213 new NetconfMessageToXMLEncoder());
216 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
217 final ChannelHandler decoder) {
218 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
221 private synchronized void changeState(final State newState) {
222 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
223 checkState(isStateChangePermitted(state, newState),
224 "Cannot change state from %s to %s for channel %s", state, newState, channel);
225 this.state = newState;
228 private static boolean containsBase11Capability(final Document doc) {
229 final NodeList nList = doc.getElementsByTagNameNS(
230 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
231 XmlNetconfConstants.CAPABILITY);
232 for (int i = 0; i < nList.getLength(); i++) {
233 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
240 private static boolean isStateChangePermitted(final State state, final State newState) {
241 if (state == State.IDLE && newState == State.OPEN_WAIT) {
244 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
247 if (state == State.OPEN_WAIT && newState == State.FAILED) {
250 LOG.debug("Transition from {} to {} is not allowed", state, newState);
255 * Handler to catch exceptions in pipeline during negotiation.
257 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
259 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
260 LOG.warn("An exception occurred during negotiation with {} on channel {}",
261 channel.remoteAddress(), channel, cause);
262 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
264 negotiationFailed(cause);
265 changeState(State.FAILED);
269 protected final void negotiationSuccessful(final S session) {
270 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
271 channel.pipeline().replace(this, "session", session);
272 promise.setSuccess(session);
275 protected void negotiationFailed(final Throwable cause) {
276 LOG.debug("Negotiation on channel {} failed", channel, cause);
278 promise.setFailure(cause);
282 * Send a message to peer and fail negotiation if it does not reach
285 * @param msg Message which should be sent.
287 protected final void sendMessage(final NetconfMessage msg) {
288 this.channel.writeAndFlush(msg).addListener(f -> {
289 if (!f.isSuccess()) {
290 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
291 negotiationFailed(f.cause());
293 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
299 @SuppressWarnings("checkstyle:illegalCatch")
300 public final void channelActive(final ChannelHandlerContext ctx) {
301 LOG.debug("Starting session negotiation on channel {}", channel);
304 } catch (final Exception e) {
305 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
306 negotiationFailed(e);
311 @SuppressWarnings("checkstyle:illegalCatch")
312 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
313 LOG.debug("Negotiation read invoked on channel {}", channel);
315 handleMessage((NetconfHelloMessage) msg);
316 } catch (final Exception e) {
317 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
318 negotiationFailed(e);
323 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
324 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
325 negotiationFailed(cause);
328 protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;