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.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.Beta;
15 import io.netty.channel.Channel;
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.Future;
23 import io.netty.util.concurrent.Promise;
24 import java.util.concurrent.TimeUnit;
25 import org.checkerframework.checker.index.qual.NonNegative;
26 import org.checkerframework.checker.lock.qual.GuardedBy;
27 import org.checkerframework.checker.lock.qual.Holding;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.netconf.api.CapabilityURN;
31 import org.opendaylight.netconf.api.NamespaceURN;
32 import org.opendaylight.netconf.api.NetconfDocumentedException;
33 import org.opendaylight.netconf.api.NetconfMessage;
34 import org.opendaylight.netconf.api.NetconfSessionListener;
35 import org.opendaylight.netconf.api.messages.FramingMechanism;
36 import org.opendaylight.netconf.api.messages.HelloMessage;
37 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
38 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
39 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
40 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
41 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
42 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.NodeList;
48 public abstract class AbstractNetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
49 L extends NetconfSessionListener<S>>
50 extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
52 * Possible states for Finite State Machine.
54 protected enum State {
55 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
58 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
59 private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
60 private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
61 private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
64 * Default upper bound on the size of an individual chunk. This value can be controlled through
65 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
66 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
69 public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
72 final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
74 LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
75 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
77 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
79 LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
82 private final @NonNull HelloMessage localHello;
83 protected final Channel channel;
85 private final @NonNegative int maximumIncomingChunkSize;
86 private final long connectionTimeoutMillis;
87 private final Promise<S> promise;
88 private final L sessionListener;
89 private final Timer timer;
92 private Timeout timeoutTask;
94 private State state = State.IDLE;
96 protected AbstractNetconfSessionNegotiator(final HelloMessage hello, final Promise<S> promise,
97 final Channel channel, final Timer timer, final L sessionListener,
98 final long connectionTimeoutMillis,
99 final @NonNegative int maximumIncomingChunkSize) {
100 localHello = requireNonNull(hello);
101 this.promise = requireNonNull(promise);
102 this.channel = requireNonNull(channel);
104 this.sessionListener = sessionListener;
105 this.connectionTimeoutMillis = connectionTimeoutMillis;
106 this.maximumIncomingChunkSize = maximumIncomingChunkSize;
107 checkArgument(maximumIncomingChunkSize > 0, "Invalid maximum incoming chunk size %s", maximumIncomingChunkSize);
110 @Deprecated(since = "4.0.1", forRemoval = true)
111 protected AbstractNetconfSessionNegotiator(final HelloMessage hello, final Promise<S> promise,
112 final Channel channel, final Timer timer,
113 final L sessionListener, final long connectionTimeoutMillis) {
114 this(hello, promise, channel, timer, sessionListener, connectionTimeoutMillis,
115 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
118 protected final @NonNull HelloMessage localHello() {
122 protected final void startNegotiation() {
123 if (ifNegotiatedAlready()) {
124 LOG.debug("Negotiation on channel {} already started", channel);
126 final var sslHandler = getSslHandler(channel);
127 if (sslHandler != null) {
128 sslHandler.handshakeFuture().addListener(future -> {
129 checkState(future.isSuccess(), "Ssl handshake was not successful");
130 LOG.debug("Ssl handshake complete");
139 protected final boolean ifNegotiatedAlready() {
140 // Indicates whether negotiation already started
141 return state() != State.IDLE;
144 private synchronized State state() {
148 private static @Nullable SslHandler getSslHandler(final Channel channel) {
149 return channel.pipeline().get(SslHandler.class);
152 private void start() {
153 LOG.debug("Sending negotiation proposal {} on channel {}", localHello, channel);
155 // Send the message out, but to not run listeners just yet, as we have some more state transitions to go through
156 final var helloFuture = channel.writeAndFlush(localHello);
158 // Quick check: if the future has already failed we call it quits before negotiation even started
159 final var helloCause = helloFuture.cause();
160 if (helloCause != null) {
161 LOG.warn("Failed to send negotiation proposal on channel {}", channel, helloCause);
166 // Catch any exceptions from this point on. Use a named class to ease debugging.
167 final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
169 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
170 LOG.warn("An exception occurred during negotiation with {} on channel {}",
171 channel.remoteAddress(), channel, cause);
172 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
174 negotiationFailed(cause);
175 changeState(State.FAILED);
179 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
181 // Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
182 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
183 new NetconfMessageToXMLEncoder());
185 synchronized (this) {
186 lockedChangeState(State.OPEN_WAIT);
188 // Service the timeout on channel's eventloop, so that we do not get state transition problems
189 timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
190 connectionTimeoutMillis, TimeUnit.MILLISECONDS);
193 LOG.debug("Session negotiation started on channel {}", channel);
195 // State transition completed, now run any additional processing
196 helloFuture.addListener(this::onHelloWriteComplete);
199 private void onHelloWriteComplete(final Future<?> future) {
200 final var cause = future.cause();
202 LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
203 negotiationFailed(cause);
205 LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
209 private synchronized void timeoutExpired() {
210 if (timeoutTask == null) {
211 // cancelTimeout() between expiry and execution on the loop
216 if (state != State.ESTABLISHED) {
217 LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
218 connectionTimeoutMillis, channel, state);
220 // Do not fail negotiation if promise is done or canceled
221 // It would result in setting result of the promise second time and that throws exception
222 if (!promise.isDone() && !promise.isCancelled()) {
223 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
224 connectionTimeoutMillis);
227 } else if (channel.isOpen()) {
228 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
232 private void failAndClose() {
233 changeState(State.FAILED);
234 channel.close().addListener(this::onChannelClosed);
237 private void onChannelClosed(final Future<?> future) {
238 final var cause = future.cause();
240 LOG.warn("Channel {} closed: fail", channel, cause);
242 LOG.debug("Channel {} closed: success", channel);
246 private synchronized void cancelTimeout() {
247 if (timeoutTask != null && !timeoutTask.cancel()) {
248 // Late-coming cancel: make sure the task does not actually run
253 protected final S getSessionForHelloMessage(final HelloMessage netconfMessage)
254 throws NetconfDocumentedException {
255 final Document doc = netconfMessage.getDocument();
257 if (shouldUseChunkFraming(doc)) {
258 insertChunkFramingToPipeline();
261 changeState(State.ESTABLISHED);
262 return getSession(sessionListener, channel, netconfMessage);
265 protected abstract S getSession(L sessionListener, Channel channel, HelloMessage message)
266 throws NetconfDocumentedException;
269 * Insert chunk framing handlers into the pipeline.
271 private void insertChunkFramingToPipeline() {
272 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
273 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
274 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
275 new NetconfChunkAggregator(maximumIncomingChunkSize));
278 private boolean shouldUseChunkFraming(final Document doc) {
279 return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
283 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
286 * Inbound hello message handler should be kept until negotiation is successful
287 * It caches any non-hello messages while negotiation is still in progress
289 protected final void replaceHelloMessageInboundHandler(final S session) {
290 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
291 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
293 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
294 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
295 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
296 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
298 // Process messages received during negotiation
299 // The hello message handler does not have to be synchronized,
300 // since it is always call from the same thread by netty.
301 // It means, we are now using the thread now
302 for (NetconfMessage message : netconfMessagesFromNegotiation) {
303 session.handleMessage(message);
307 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
308 final ChannelHandler decoder) {
309 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
312 private synchronized void changeState(final State newState) {
313 lockedChangeState(newState);
317 private void lockedChangeState(final State newState) {
318 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
319 checkState(isStateChangePermitted(state, newState),
320 "Cannot change state from %s to %s for channel %s", state, newState, channel);
324 private static boolean containsBase11Capability(final Document doc) {
325 final NodeList nList = doc.getElementsByTagNameNS(NamespaceURN.BASE, XmlNetconfConstants.CAPABILITY);
326 for (int i = 0; i < nList.getLength(); i++) {
327 if (nList.item(i).getTextContent().contains(CapabilityURN.BASE_1_1)) {
334 private static boolean isStateChangePermitted(final State state, final State newState) {
335 if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
338 if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
341 LOG.debug("Transition from {} to {} is not allowed", state, newState);
345 protected final void negotiationSuccessful(final S session) {
346 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
347 channel.pipeline().replace(this, "session", session);
348 promise.setSuccess(session);
351 protected void negotiationFailed(final Throwable cause) {
352 LOG.debug("Negotiation on channel {} failed", channel, cause);
354 promise.setFailure(cause);
358 @SuppressWarnings("checkstyle:illegalCatch")
359 public final void channelActive(final ChannelHandlerContext ctx) {
360 LOG.debug("Starting session negotiation on channel {}", channel);
363 } catch (final Exception e) {
364 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
365 negotiationFailed(e);
370 @SuppressWarnings("checkstyle:illegalCatch")
371 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
372 if (state() == State.FAILED) {
373 // We have already failed -- do not process any more messages
377 LOG.debug("Negotiation read invoked on channel {}", channel);
379 handleMessage((HelloMessage) msg);
380 } catch (final Exception e) {
381 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
382 negotiationFailed(e);
387 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
388 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
389 negotiationFailed(cause);
392 protected abstract void handleMessage(HelloMessage msg) throws Exception;