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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.channel.ChannelHandler;
17 import io.netty.channel.ChannelHandlerContext;
18 import io.netty.channel.ChannelInboundHandlerAdapter;
19 import io.netty.handler.ssl.SslHandler;
20 import io.netty.util.Timeout;
21 import io.netty.util.Timer;
22 import io.netty.util.concurrent.GenericFutureListener;
23 import io.netty.util.concurrent.Promise;
24 import java.util.concurrent.TimeUnit;
25 import org.checkerframework.checker.lock.qual.GuardedBy;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.netconf.api.NetconfMessage;
29 import org.opendaylight.netconf.api.NetconfSessionListener;
30 import org.opendaylight.netconf.api.NetconfSessionPreferences;
31 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
32 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
33 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
34 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
35 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
36 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
37 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
38 import org.opendaylight.netconf.util.messages.FramingMechanism;
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 ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
48 * Possible states for Finite State Machine.
50 protected enum State {
51 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
54 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
56 public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
58 protected final P sessionPreferences;
59 protected final Channel channel;
61 private final long connectionTimeoutMillis;
62 private final Promise<S> promise;
63 private final L sessionListener;
64 private final Timer timer;
66 private Timeout timeoutTask;
69 private State state = State.IDLE;
71 protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
72 final Channel channel, final Timer timer,
73 final L sessionListener, final long connectionTimeoutMillis) {
74 this.channel = requireNonNull(channel);
75 this.promise = requireNonNull(promise);
76 this.sessionPreferences = sessionPreferences;
78 this.sessionListener = sessionListener;
79 this.connectionTimeoutMillis = connectionTimeoutMillis;
82 protected final void startNegotiation() {
83 if (ifNegotiatedAlready()) {
84 LOG.debug("Negotiation on channel {} already started", channel);
86 final var sslHandler = getSslHandler(channel);
87 if (sslHandler != null) {
88 sslHandler.handshakeFuture().addListener(future -> {
89 checkState(future.isSuccess(), "Ssl handshake was not successful");
90 LOG.debug("Ssl handshake complete");
99 protected final synchronized boolean ifNegotiatedAlready() {
100 // Indicates whether negotiation already started
101 return this.state != State.IDLE;
104 private static @Nullable SslHandler getSslHandler(final Channel channel) {
105 return channel.pipeline().get(SslHandler.class);
108 public P getSessionPreferences() {
109 return sessionPreferences;
112 private void start() {
113 final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
114 LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);
116 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
118 sendMessage(helloMessage);
120 replaceHelloMessageOutboundHandler();
121 changeState(State.OPEN_WAIT);
123 timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
126 private synchronized void timeoutExpired(final Timeout timeout) {
127 if (state != State.ESTABLISHED) {
128 LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
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 (!promise.isDone() && !promise.isCancelled()) {
134 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
135 connectionTimeoutMillis);
136 changeState(State.FAILED);
138 channel.close().addListener((GenericFutureListener<ChannelFuture>) future -> {
139 if (future.isSuccess()) {
140 LOG.debug("Channel {} closed: success", future.channel());
142 LOG.warn("Channel {} closed: fail", future.channel());
146 } else if (channel.isOpen()) {
147 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
151 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
152 justification = "https://github.com/spotbugs/spotbugs/issues/811")
153 private void cancelTimeout() {
154 if (timeoutTask != null) {
155 timeoutTask.cancel();
159 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
160 throws NetconfDocumentedException {
161 final Document doc = netconfMessage.getDocument();
163 if (shouldUseChunkFraming(doc)) {
164 insertChunkFramingToPipeline();
167 changeState(State.ESTABLISHED);
168 return getSession(sessionListener, channel, netconfMessage);
172 * Insert chunk framing handlers into the pipeline.
174 private void insertChunkFramingToPipeline() {
175 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
176 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
177 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
178 new NetconfChunkAggregator());
181 private boolean shouldUseChunkFraming(final Document doc) {
182 return containsBase11Capability(doc)
183 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
187 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
190 * Inbound hello message handler should be kept until negotiation is successful
191 * It caches any non-hello messages while negotiation is still in progress
193 protected final void replaceHelloMessageInboundHandler(final S session) {
194 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
195 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
197 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
198 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
199 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
200 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
202 // Process messages received during negotiation
203 // The hello message handler does not have to be synchronized,
204 // since it is always call from the same thread by netty.
205 // It means, we are now using the thread now
206 for (NetconfMessage message : netconfMessagesFromNegotiation) {
207 session.handleMessage(message);
212 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
214 private void replaceHelloMessageOutboundHandler() {
215 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
216 new NetconfMessageToXMLEncoder());
219 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
220 final ChannelHandler decoder) {
221 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
224 @SuppressWarnings("checkstyle:hiddenField")
225 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
226 throws NetconfDocumentedException;
228 private synchronized void changeState(final State newState) {
229 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
230 checkState(isStateChangePermitted(state, newState),
231 "Cannot change state from %s to %s for channel %s", state, newState, channel);
232 this.state = newState;
235 private static boolean containsBase11Capability(final Document doc) {
236 final NodeList nList = doc.getElementsByTagNameNS(
237 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
238 XmlNetconfConstants.CAPABILITY);
239 for (int i = 0; i < nList.getLength(); i++) {
240 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
247 private static boolean isStateChangePermitted(final State state, final State newState) {
248 if (state == State.IDLE && newState == State.OPEN_WAIT) {
251 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
254 if (state == State.OPEN_WAIT && newState == State.FAILED) {
257 LOG.debug("Transition from {} to {} is not allowed", state, newState);
262 * Handler to catch exceptions in pipeline during negotiation.
264 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
266 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
267 LOG.warn("An exception occurred during negotiation with {} on channel {}",
268 channel.remoteAddress(), channel, cause);
269 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
271 negotiationFailed(cause);
272 changeState(State.FAILED);
276 protected final void negotiationSuccessful(final S session) {
277 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
278 channel.pipeline().replace(this, "session", session);
279 promise.setSuccess(session);
282 protected void negotiationFailed(final Throwable cause) {
283 LOG.debug("Negotiation on channel {} failed", channel, cause);
285 promise.setFailure(cause);
289 * Send a message to peer and fail negotiation if it does not reach
292 * @param msg Message which should be sent.
294 protected final void sendMessage(final NetconfMessage msg) {
295 this.channel.writeAndFlush(msg).addListener(f -> {
296 if (!f.isSuccess()) {
297 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
298 negotiationFailed(f.cause());
300 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
306 @SuppressWarnings("checkstyle:illegalCatch")
307 public final void channelActive(final ChannelHandlerContext ctx) {
308 LOG.debug("Starting session negotiation on channel {}", channel);
311 } catch (final Exception e) {
312 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
313 negotiationFailed(e);
318 @SuppressWarnings("checkstyle:illegalCatch")
319 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
320 LOG.debug("Negotiation read invoked on channel {}", channel);
322 handleMessage((NetconfHelloMessage) msg);
323 } catch (final Exception e) {
324 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
325 negotiationFailed(e);
330 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
331 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
332 negotiationFailed(cause);
335 protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;