Merge (Abstract)NetconfSessionNegotiator 08/108608/7
authorRobert Varga <robert.varga@pantheon.tech>
Mon, 23 Oct 2023 22:37:29 +0000 (00:37 +0200)
committerRobert Varga <nite@hq.sk>
Tue, 24 Oct 2023 13:59:17 +0000 (13:59 +0000)
All NetconfSessionNegotiator are based on
AbstractNetconfSessionNegotiator, hence we can ditch the intermediate
interface to improve clarity.

JIRA: NETCONF-590
Change-Id: I952a2d0f03b8ff3d2dda3e6b382a93e9ba38168c
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java [deleted file]
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/NetconfSessionNegotiator.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/TestSessionNegotiator.java
protocol/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiator.java
protocol/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiatorFactory.java
protocol/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfClientConfigurationBuilder.java
protocol/netconf-server/src/main/java/org/opendaylight/netconf/server/NetconfServerSessionNegotiator.java
protocol/netconf-server/src/main/java/org/opendaylight/netconf/server/NetconfServerSessionNegotiatorFactory.java
protocol/netconf-server/src/main/java/org/opendaylight/netconf/server/NetconfServerSessionNegotiatorFactoryBuilder.java

diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java
deleted file mode 100644 (file)
index a5d65a3..0000000
+++ /dev/null
@@ -1,384 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.netconf.nettyutil;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkState;
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.annotations.Beta;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.handler.ssl.SslHandler;
-import io.netty.util.Timeout;
-import io.netty.util.Timer;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.Promise;
-import java.util.concurrent.TimeUnit;
-import org.checkerframework.checker.index.qual.NonNegative;
-import org.checkerframework.checker.lock.qual.GuardedBy;
-import org.checkerframework.checker.lock.qual.Holding;
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
-import org.opendaylight.netconf.api.CapabilityURN;
-import org.opendaylight.netconf.api.NamespaceURN;
-import org.opendaylight.netconf.api.NetconfDocumentedException;
-import org.opendaylight.netconf.api.NetconfSessionListener;
-import org.opendaylight.netconf.api.messages.HelloMessage;
-import org.opendaylight.netconf.api.messages.NetconfMessage;
-import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
-import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
-import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
-import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
-import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.NodeList;
-
-public abstract class AbstractNetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
-            L extends NetconfSessionListener<S>>
-            extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
-    /**
-     * Possible states for Finite State Machine.
-     */
-    protected enum State {
-        IDLE, OPEN_WAIT, FAILED, ESTABLISHED
-    }
-
-    private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
-    private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
-    private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
-    private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
-
-    /**
-     * Default upper bound on the size of an individual chunk. This value can be controlled through
-     * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
-     * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
-     */
-    @Beta
-    public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
-
-    static {
-        final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
-        if (propValue <= 0) {
-            LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
-            DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
-        } else {
-            DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
-        }
-        LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
-    }
-
-    private final @NonNull HelloMessage localHello;
-    protected final Channel channel;
-
-    private final @NonNegative int maximumIncomingChunkSize;
-    private final long connectionTimeoutMillis;
-    private final Promise<S> promise;
-    private final L sessionListener;
-    private final Timer timer;
-
-    @GuardedBy("this")
-    private Timeout timeoutTask;
-    @GuardedBy("this")
-    private State state = State.IDLE;
-
-    protected AbstractNetconfSessionNegotiator(final HelloMessage hello, final Promise<S> promise,
-                                               final Channel channel, final Timer timer, final L sessionListener,
-                                               final long connectionTimeoutMillis,
-                                               final @NonNegative int maximumIncomingChunkSize) {
-        localHello = requireNonNull(hello);
-        this.promise = requireNonNull(promise);
-        this.channel = requireNonNull(channel);
-        this.timer = timer;
-        this.sessionListener = sessionListener;
-        this.connectionTimeoutMillis = connectionTimeoutMillis;
-        this.maximumIncomingChunkSize = maximumIncomingChunkSize;
-        checkArgument(maximumIncomingChunkSize > 0, "Invalid maximum incoming chunk size %s", maximumIncomingChunkSize);
-    }
-
-    protected final @NonNull HelloMessage localHello() {
-        return localHello;
-    }
-
-    protected final void startNegotiation() {
-        if (ifNegotiatedAlready()) {
-            LOG.debug("Negotiation on channel {} already started", channel);
-        } else {
-            final var sslHandler = getSslHandler(channel);
-            if (sslHandler != null) {
-                sslHandler.handshakeFuture().addListener(future -> {
-                    checkState(future.isSuccess(), "Ssl handshake was not successful");
-                    LOG.debug("Ssl handshake complete");
-                    start();
-                });
-            } else {
-                start();
-            }
-        }
-    }
-
-    protected final boolean ifNegotiatedAlready() {
-        // Indicates whether negotiation already started
-        return state() != State.IDLE;
-    }
-
-    private synchronized State state() {
-        return state;
-    }
-
-    private static @Nullable SslHandler getSslHandler(final Channel channel) {
-        return channel.pipeline().get(SslHandler.class);
-    }
-
-    private void start() {
-        LOG.debug("Sending negotiation proposal {} on channel {}", localHello, channel);
-
-        // Send the message out, but to not run listeners just yet, as we have some more state transitions to go through
-        final var helloFuture = channel.writeAndFlush(localHello);
-
-        // Quick check: if the future has already failed we call it quits before negotiation even started
-        final var helloCause = helloFuture.cause();
-        if (helloCause != null) {
-            LOG.warn("Failed to send negotiation proposal on channel {}", channel, helloCause);
-            failAndClose();
-            return;
-        }
-
-        // Catch any exceptions from this point on. Use a named class to ease debugging.
-        final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
-            @Override
-            public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
-                LOG.warn("An exception occurred during negotiation with {} on channel {}",
-                        channel.remoteAddress(), channel, cause);
-                // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
-                cancelTimeout();
-                negotiationFailed(cause);
-                changeState(State.FAILED);
-            }
-        }
-
-        channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
-
-        // Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
-        replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
-            new NetconfMessageToXMLEncoder());
-
-        synchronized (this) {
-            lockedChangeState(State.OPEN_WAIT);
-
-            // Service the timeout on channel's eventloop, so that we do not get state transition problems
-            timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
-                connectionTimeoutMillis, TimeUnit.MILLISECONDS);
-        }
-
-        LOG.debug("Session negotiation started on channel {}", channel);
-
-        // State transition completed, now run any additional processing
-        helloFuture.addListener(this::onHelloWriteComplete);
-    }
-
-    private void onHelloWriteComplete(final Future<?> future) {
-        final var cause = future.cause();
-        if (cause != null) {
-            LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
-            negotiationFailed(cause);
-        } else {
-            LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
-        }
-    }
-
-    private synchronized void timeoutExpired() {
-        if (timeoutTask == null) {
-            // cancelTimeout() between expiry and execution on the loop
-            return;
-        }
-        timeoutTask = null;
-
-        if (state != State.ESTABLISHED) {
-            LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
-                connectionTimeoutMillis, channel, state);
-
-            // Do not fail negotiation if promise is done or canceled
-            // It would result in setting result of the promise second time and that throws exception
-            if (!promise.isDone() && !promise.isCancelled()) {
-                LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
-                    connectionTimeoutMillis);
-                failAndClose();
-            }
-        } else if (channel.isOpen()) {
-            channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
-        }
-    }
-
-    private void failAndClose() {
-        changeState(State.FAILED);
-        channel.close().addListener(this::onChannelClosed);
-    }
-
-    private void onChannelClosed(final Future<?> future) {
-        final var cause = future.cause();
-        if (cause != null) {
-            LOG.warn("Channel {} closed: fail", channel, cause);
-        } else {
-            LOG.debug("Channel {} closed: success", channel);
-        }
-    }
-
-    private synchronized void cancelTimeout() {
-        if (timeoutTask != null && !timeoutTask.cancel()) {
-            // Late-coming cancel: make sure the task does not actually run
-            timeoutTask = null;
-        }
-    }
-
-    protected final S getSessionForHelloMessage(final HelloMessage netconfMessage)
-            throws NetconfDocumentedException {
-        final Document doc = netconfMessage.getDocument();
-
-        if (shouldUseChunkFraming(doc)) {
-            insertChunkFramingToPipeline();
-        }
-
-        changeState(State.ESTABLISHED);
-        return getSession(sessionListener, channel, netconfMessage);
-    }
-
-    protected abstract S getSession(L sessionListener, Channel channel, HelloMessage message)
-        throws NetconfDocumentedException;
-
-    /**
-     * Insert chunk framing handlers into the pipeline.
-     */
-    private void insertChunkFramingToPipeline() {
-        replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
-            new ChunkedFramingMechanismEncoder());
-        replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
-            new NetconfChunkAggregator(maximumIncomingChunkSize));
-    }
-
-    private boolean shouldUseChunkFraming(final Document doc) {
-        return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
-    }
-
-    /**
-     * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
-     *
-     * <p>
-     * Inbound hello message handler should be kept until negotiation is successful
-     * It caches any non-hello messages while negotiation is still in progress
-     */
-    protected final void replaceHelloMessageInboundHandler(final S session) {
-        ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
-                AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
-
-        checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
-                "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
-        Iterable<NetconfMessage> netconfMessagesFromNegotiation =
-                ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
-
-        // Process messages received during negotiation
-        // The hello message handler does not have to be synchronized,
-        // since it is always call from the same thread by netty.
-        // It means, we are now using the thread now
-        for (NetconfMessage message : netconfMessagesFromNegotiation) {
-            session.handleMessage(message);
-        }
-    }
-
-    private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
-                                                        final ChannelHandler decoder) {
-        return channel.pipeline().replace(handlerKey, handlerKey, decoder);
-    }
-
-    private synchronized void changeState(final State newState) {
-        lockedChangeState(newState);
-    }
-
-    @Holding("this")
-    private void lockedChangeState(final State newState) {
-        LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
-        checkState(isStateChangePermitted(state, newState),
-                "Cannot change state from %s to %s for channel %s", state, newState, channel);
-        state = newState;
-    }
-
-    private static boolean containsBase11Capability(final Document doc) {
-        final NodeList nList = doc.getElementsByTagNameNS(NamespaceURN.BASE, XmlNetconfConstants.CAPABILITY);
-        for (int i = 0; i < nList.getLength(); i++) {
-            if (nList.item(i).getTextContent().contains(CapabilityURN.BASE_1_1)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    private static boolean isStateChangePermitted(final State state, final State newState) {
-        if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
-            return true;
-        }
-        if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
-            return true;
-        }
-        LOG.debug("Transition from {} to {} is not allowed", state, newState);
-        return false;
-    }
-
-    protected final void negotiationSuccessful(final S session) {
-        LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
-        channel.pipeline().replace(this, "session", session);
-        promise.setSuccess(session);
-    }
-
-    protected void negotiationFailed(final Throwable cause) {
-        LOG.debug("Negotiation on channel {} failed", channel, cause);
-        channel.close();
-        promise.setFailure(cause);
-    }
-
-    @Override
-    @SuppressWarnings("checkstyle:illegalCatch")
-    public final void channelActive(final ChannelHandlerContext ctx) {
-        LOG.debug("Starting session negotiation on channel {}", channel);
-        try {
-            startNegotiation();
-        } catch (final Exception e) {
-            LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
-            negotiationFailed(e);
-        }
-    }
-
-    @Override
-    @SuppressWarnings("checkstyle:illegalCatch")
-    public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
-        if (state() == State.FAILED) {
-            // We have already failed -- do not process any more messages
-            return;
-        }
-
-        LOG.debug("Negotiation read invoked on channel {}", channel);
-        try {
-            handleMessage((HelloMessage) msg);
-        } catch (final Exception e) {
-            LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
-            negotiationFailed(e);
-        }
-    }
-
-    @Override
-    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
-        LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
-        negotiationFailed(cause);
-    }
-
-    protected abstract void handleMessage(HelloMessage msg) throws Exception;
-}
index 38978ced3d5cd65af5bfb143961931aea9908c12..7e2e1fff31b451c79833b3d3115f0fac0d5a60cc 100644 (file)
  */
 package org.opendaylight.netconf.nettyutil;
 
-import io.netty.channel.ChannelInboundHandler;
-import org.opendaylight.netconf.api.NetconfSession;
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import com.google.common.annotations.Beta;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.handler.ssl.SslHandler;
+import io.netty.util.Timeout;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.Promise;
+import java.util.concurrent.TimeUnit;
+import org.checkerframework.checker.index.qual.NonNegative;
+import org.checkerframework.checker.lock.qual.GuardedBy;
+import org.checkerframework.checker.lock.qual.Holding;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.netconf.api.CapabilityURN;
+import org.opendaylight.netconf.api.NamespaceURN;
+import org.opendaylight.netconf.api.NetconfDocumentedException;
+import org.opendaylight.netconf.api.NetconfSessionListener;
+import org.opendaylight.netconf.api.messages.HelloMessage;
+import org.opendaylight.netconf.api.messages.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
+import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
+import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
+import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
+import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
 
 /**
- * Session negotiator concepts. A negotiator is responsible for message
- * handling while the exact session parameters are not known. Once the
- * session parameters are finalized, the negotiator replaces itself in
- * the channel pipeline with the session.
+ * A negotiator of a NETCONF session. It is responsible for message handling while the exact session parameters are not
+ * known. Once the session parameters are finalized, the negotiator replaces itself in the channel pipeline with the
+ * session.
  *
- * @param <T> Protocol session type.
+ * @param <S> Session type
+ * @param <L> Session listener type
  */
-@Deprecated
-public interface NetconfSessionNegotiator<T extends NetconfSession> extends ChannelInboundHandler {
+public abstract class NetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
+            L extends NetconfSessionListener<S>> extends ChannelInboundHandlerAdapter {
+    /**
+     * Possible states for Finite State Machine.
+     */
+    protected enum State {
+        IDLE, OPEN_WAIT, FAILED, ESTABLISHED
+    }
+
+    private static final Logger LOG = LoggerFactory.getLogger(NetconfSessionNegotiator.class);
+    private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
+    private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
+    private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
+
+    /**
+     * Default upper bound on the size of an individual chunk. This value can be controlled through
+     * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
+     * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
+     */
+    @Beta
+    public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
+
+    static {
+        final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
+        if (propValue <= 0) {
+            LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
+            DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
+        } else {
+            DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
+        }
+        LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
+    }
+
+    private final @NonNull HelloMessage localHello;
+    protected final Channel channel;
+
+    private final @NonNegative int maximumIncomingChunkSize;
+    private final long connectionTimeoutMillis;
+    private final Promise<S> promise;
+    private final L sessionListener;
+    private final Timer timer;
+
+    @GuardedBy("this")
+    private Timeout timeoutTask;
+    @GuardedBy("this")
+    private State state = State.IDLE;
+
+    protected NetconfSessionNegotiator(final HelloMessage hello, final Promise<S> promise, final Channel channel,
+            final Timer timer, final L sessionListener, final long connectionTimeoutMillis,
+            final @NonNegative int maximumIncomingChunkSize) {
+        localHello = requireNonNull(hello);
+        this.promise = requireNonNull(promise);
+        this.channel = requireNonNull(channel);
+        this.timer = timer;
+        this.sessionListener = sessionListener;
+        this.connectionTimeoutMillis = connectionTimeoutMillis;
+        this.maximumIncomingChunkSize = maximumIncomingChunkSize;
+        checkArgument(maximumIncomingChunkSize > 0, "Invalid maximum incoming chunk size %s", maximumIncomingChunkSize);
+    }
+
+    protected final @NonNull HelloMessage localHello() {
+        return localHello;
+    }
+
+    protected final void startNegotiation() {
+        if (ifNegotiatedAlready()) {
+            LOG.debug("Negotiation on channel {} already started", channel);
+        } else {
+            final var sslHandler = getSslHandler(channel);
+            if (sslHandler != null) {
+                sslHandler.handshakeFuture().addListener(future -> {
+                    checkState(future.isSuccess(), "Ssl handshake was not successful");
+                    LOG.debug("Ssl handshake complete");
+                    start();
+                });
+            } else {
+                start();
+            }
+        }
+    }
+
+    protected final boolean ifNegotiatedAlready() {
+        // Indicates whether negotiation already started
+        return state() != State.IDLE;
+    }
+
+    private synchronized State state() {
+        return state;
+    }
+
+    private static @Nullable SslHandler getSslHandler(final Channel channel) {
+        return channel.pipeline().get(SslHandler.class);
+    }
+
+    private void start() {
+        LOG.debug("Sending negotiation proposal {} on channel {}", localHello, channel);
+
+        // Send the message out, but to not run listeners just yet, as we have some more state transitions to go through
+        final var helloFuture = channel.writeAndFlush(localHello);
+
+        // Quick check: if the future has already failed we call it quits before negotiation even started
+        final var helloCause = helloFuture.cause();
+        if (helloCause != null) {
+            LOG.warn("Failed to send negotiation proposal on channel {}", channel, helloCause);
+            failAndClose();
+            return;
+        }
+
+        // Catch any exceptions from this point on. Use a named class to ease debugging.
+        final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
+            @Override
+            public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
+                LOG.warn("An exception occurred during negotiation with {} on channel {}",
+                        channel.remoteAddress(), channel, cause);
+                // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
+                cancelTimeout();
+                negotiationFailed(cause);
+                changeState(State.FAILED);
+            }
+        }
+
+        channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
+
+        // Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
+        replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
+            new NetconfMessageToXMLEncoder());
+
+        synchronized (this) {
+            lockedChangeState(State.OPEN_WAIT);
+
+            // Service the timeout on channel's eventloop, so that we do not get state transition problems
+            timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
+                connectionTimeoutMillis, TimeUnit.MILLISECONDS);
+        }
+
+        LOG.debug("Session negotiation started on channel {}", channel);
+
+        // State transition completed, now run any additional processing
+        helloFuture.addListener(this::onHelloWriteComplete);
+    }
+
+    private void onHelloWriteComplete(final Future<?> future) {
+        final var cause = future.cause();
+        if (cause != null) {
+            LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
+            negotiationFailed(cause);
+        } else {
+            LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
+        }
+    }
+
+    private synchronized void timeoutExpired() {
+        if (timeoutTask == null) {
+            // cancelTimeout() between expiry and execution on the loop
+            return;
+        }
+        timeoutTask = null;
+
+        if (state != State.ESTABLISHED) {
+            LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
+                connectionTimeoutMillis, channel, state);
+
+            // Do not fail negotiation if promise is done or canceled
+            // It would result in setting result of the promise second time and that throws exception
+            if (!promise.isDone() && !promise.isCancelled()) {
+                LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
+                    connectionTimeoutMillis);
+                failAndClose();
+            }
+        } else if (channel.isOpen()) {
+            channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
+        }
+    }
+
+    private void failAndClose() {
+        changeState(State.FAILED);
+        channel.close().addListener(this::onChannelClosed);
+    }
+
+    private void onChannelClosed(final Future<?> future) {
+        final var cause = future.cause();
+        if (cause != null) {
+            LOG.warn("Channel {} closed: fail", channel, cause);
+        } else {
+            LOG.debug("Channel {} closed: success", channel);
+        }
+    }
+
+    private synchronized void cancelTimeout() {
+        if (timeoutTask != null && !timeoutTask.cancel()) {
+            // Late-coming cancel: make sure the task does not actually run
+            timeoutTask = null;
+        }
+    }
+
+    protected final S getSessionForHelloMessage(final HelloMessage netconfMessage)
+            throws NetconfDocumentedException {
+        final Document doc = netconfMessage.getDocument();
+
+        if (shouldUseChunkFraming(doc)) {
+            insertChunkFramingToPipeline();
+        }
+
+        changeState(State.ESTABLISHED);
+        return getSession(sessionListener, channel, netconfMessage);
+    }
+
+    protected abstract S getSession(L sessionListener, Channel channel, HelloMessage message)
+        throws NetconfDocumentedException;
+
+    /**
+     * Insert chunk framing handlers into the pipeline.
+     */
+    private void insertChunkFramingToPipeline() {
+        replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
+            new ChunkedFramingMechanismEncoder());
+        replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
+            new NetconfChunkAggregator(maximumIncomingChunkSize));
+    }
+
+    private boolean shouldUseChunkFraming(final Document doc) {
+        return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
+    }
+
+    /**
+     * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
+     *
+     * <p>
+     * Inbound hello message handler should be kept until negotiation is successful
+     * It caches any non-hello messages while negotiation is still in progress
+     */
+    protected final void replaceHelloMessageInboundHandler(final S session) {
+        ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
+                AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
+
+        checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
+                "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
+        Iterable<NetconfMessage> netconfMessagesFromNegotiation =
+                ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
+
+        // Process messages received during negotiation
+        // The hello message handler does not have to be synchronized,
+        // since it is always call from the same thread by netty.
+        // It means, we are now using the thread now
+        for (NetconfMessage message : netconfMessagesFromNegotiation) {
+            session.handleMessage(message);
+        }
+    }
+
+    private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
+                                                        final ChannelHandler decoder) {
+        return channel.pipeline().replace(handlerKey, handlerKey, decoder);
+    }
+
+    private synchronized void changeState(final State newState) {
+        lockedChangeState(newState);
+    }
+
+    @Holding("this")
+    private void lockedChangeState(final State newState) {
+        LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
+        checkState(isStateChangePermitted(state, newState),
+                "Cannot change state from %s to %s for channel %s", state, newState, channel);
+        state = newState;
+    }
+
+    private static boolean containsBase11Capability(final Document doc) {
+        final NodeList nList = doc.getElementsByTagNameNS(NamespaceURN.BASE, XmlNetconfConstants.CAPABILITY);
+        for (int i = 0; i < nList.getLength(); i++) {
+            if (nList.item(i).getTextContent().contains(CapabilityURN.BASE_1_1)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static boolean isStateChangePermitted(final State state, final State newState) {
+        if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
+            return true;
+        }
+        if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
+            return true;
+        }
+        LOG.debug("Transition from {} to {} is not allowed", state, newState);
+        return false;
+    }
+
+    protected final void negotiationSuccessful(final S session) {
+        LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
+        channel.pipeline().replace(this, "session", session);
+        promise.setSuccess(session);
+    }
+
+    protected void negotiationFailed(final Throwable cause) {
+        LOG.debug("Negotiation on channel {} failed", channel, cause);
+        channel.close();
+        promise.setFailure(cause);
+    }
+
+    @Override
+    @SuppressWarnings("checkstyle:illegalCatch")
+    public final void channelActive(final ChannelHandlerContext ctx) {
+        LOG.debug("Starting session negotiation on channel {}", channel);
+        try {
+            startNegotiation();
+        } catch (final Exception e) {
+            LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
+            negotiationFailed(e);
+        }
+    }
+
+    @Override
+    @SuppressWarnings("checkstyle:illegalCatch")
+    public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
+        if (state() == State.FAILED) {
+            // We have already failed -- do not process any more messages
+            return;
+        }
+
+        LOG.debug("Negotiation read invoked on channel {}", channel);
+        try {
+            handleMessage((HelloMessage) msg);
+        } catch (final Exception e) {
+            LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
+            negotiationFailed(e);
+        }
+    }
+
+    @Override
+    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
+        LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
+        negotiationFailed(cause);
+    }
 
+    protected abstract void handleMessage(HelloMessage msg) throws Exception;
 }
index 6db94a60c3a5922f48046921791137d2c69f80f6..d7bcb1525ebf589ccecbf395d76fb25e6a6991c5 100644 (file)
@@ -16,7 +16,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.re
 import org.opendaylight.yangtools.yang.common.Uint32;
 
 final class TestSessionNegotiator
-        extends AbstractNetconfSessionNegotiator<TestingNetconfSession, NetconfSessionListener<TestingNetconfSession>> {
+        extends NetconfSessionNegotiator<TestingNetconfSession, NetconfSessionListener<TestingNetconfSession>> {
     TestSessionNegotiator(final HelloMessage hello, final Promise<TestingNetconfSession> promise,
             final Channel channel, final Timer timer,
             final NetconfSessionListener<TestingNetconfSession> sessionListener, final long connectionTimeoutMillis) {
index f4d3ad822b587fe9e58d595828d6a325b9bd06c9..beb9282ba97a5aab0e208548cf14c6d3c870d1e7 100644 (file)
@@ -30,7 +30,7 @@ import org.opendaylight.netconf.api.messages.RpcMessage;
 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.netconf.api.xml.XmlUtil;
 import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
-import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
+import org.opendaylight.netconf.nettyutil.NetconfSessionNegotiator;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.SessionIdType;
 import org.opendaylight.yangtools.yang.common.Uint32;
 import org.slf4j.Logger;
@@ -41,7 +41,7 @@ import org.w3c.dom.NodeList;
 
 // Non-final for mocking
 class NetconfClientSessionNegotiator
-        extends AbstractNetconfSessionNegotiator<NetconfClientSession, NetconfClientSessionListener> {
+        extends NetconfSessionNegotiator<NetconfClientSession, NetconfClientSessionListener> {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
 
     private static final XPathExpression SESSION_ID_X_PATH = XMLNetconfUtil
index e476f27b484cc760aa45237e38bbdd99f46ec95b..d49d3a2684e72fbfc09033c7a4eda7e49f9d1141 100644 (file)
@@ -20,7 +20,7 @@ import org.opendaylight.netconf.api.CapabilityURN;
 import org.opendaylight.netconf.api.NetconfSessionListenerFactory;
 import org.opendaylight.netconf.api.messages.HelloMessage;
 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
-import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
+import org.opendaylight.netconf.nettyutil.NetconfSessionNegotiator;
 import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
 import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessageProvider;
 import org.opendaylight.netconf.shaded.exificient.core.CodingMode;
@@ -101,7 +101,7 @@ public final class NetconfClientSessionNegotiatorFactory {
                                                  final long connectionTimeoutMillis, final EXIParameters exiOptions,
                                                  final Set<String> capabilities) {
         this(timer, additionalHeader, connectionTimeoutMillis, exiOptions, capabilities,
-            AbstractNetconfSessionNegotiator.DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
+            NetconfSessionNegotiator.DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
     }
 
     public NetconfClientSessionNegotiatorFactory(final Timer timer,
index 1f2db96082710489e634086cdf15b24d6facc87e..ce368e7cdf33ab3d42b479190e26a6526e40168d 100644 (file)
@@ -15,7 +15,7 @@ import org.checkerframework.checker.index.qual.NonNegative;
 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
 import org.opendaylight.netconf.client.NetconfClientSessionListener;
 import org.opendaylight.netconf.client.SslHandlerFactory;
-import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
+import org.opendaylight.netconf.nettyutil.NetconfSessionNegotiator;
 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
 import org.opendaylight.netconf.nettyutil.handler.ssh.client.NetconfSshClient;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
@@ -42,7 +42,7 @@ public class NetconfClientConfigurationBuilder {
     private NetconfSshClient sshClient;
     private List<Uri> odlHelloCapabilities;
     private @NonNegative int maximumIncomingChunkSize =
-        AbstractNetconfSessionNegotiator.DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
+        NetconfSessionNegotiator.DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
     private String name;
     private TcpClientGrouping tcpParameters;
     private TlsClientGrouping tlsParameters;
index 6b1302488550672d074dd1e81bd26ae6ac2ef9e4..01cb0e6a9f5fc0c76f062fc3ac117ff30de4846d 100644 (file)
@@ -22,13 +22,13 @@ import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.netconf.api.NetconfDocumentedException;
 import org.opendaylight.netconf.api.messages.HelloMessage;
 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
-import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
+import org.opendaylight.netconf.nettyutil.NetconfSessionNegotiator;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.SessionIdType;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public final class NetconfServerSessionNegotiator
-        extends AbstractNetconfSessionNegotiator<NetconfServerSession, NetconfServerSessionListener> {
+        extends NetconfSessionNegotiator<NetconfServerSession, NetconfServerSessionListener> {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiator.class);
     private static final String UNKNOWN = "unknown";
 
index 4d4ce617787481a5e7b04dfb011348b2cdfd0c45..b8391fb86e1bb917306692a23fa674a0630b5d6d 100644 (file)
@@ -19,7 +19,7 @@ import java.util.Set;
 import org.checkerframework.checker.index.qual.NonNegative;
 import org.opendaylight.netconf.api.CapabilityURN;
 import org.opendaylight.netconf.api.messages.HelloMessage;
-import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
+import org.opendaylight.netconf.nettyutil.NetconfSessionNegotiator;
 import org.opendaylight.netconf.server.api.SessionIdProvider;
 import org.opendaylight.netconf.server.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.netconf.server.api.operations.NetconfOperationService;
@@ -58,7 +58,7 @@ public class NetconfServerSessionNegotiatorFactory {
             final long connectionTimeoutMillis,  final NetconfMonitoringService monitoringService,
             final Set<String> baseCapabilities) {
         this(timer, netconfOperationProvider, idProvider, connectionTimeoutMillis, monitoringService, baseCapabilities,
-            AbstractNetconfSessionNegotiator.DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
+            NetconfSessionNegotiator.DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
     }
 
     protected NetconfServerSessionNegotiatorFactory(final Timer timer,
index 66d3f4bd77001ae6e998f03bb8ebe3d1357356e2..52c527187a70e43199f488861212f251c5c4e28c 100644 (file)
@@ -13,7 +13,7 @@ import static java.util.Objects.requireNonNull;
 import io.netty.util.Timer;
 import java.util.Set;
 import org.checkerframework.checker.index.qual.NonNegative;
-import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
+import org.opendaylight.netconf.nettyutil.NetconfSessionNegotiator;
 import org.opendaylight.netconf.server.api.SessionIdProvider;
 import org.opendaylight.netconf.server.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.netconf.server.api.operations.NetconfOperationServiceFactory;
@@ -25,8 +25,7 @@ public class NetconfServerSessionNegotiatorFactoryBuilder {
     private long connectionTimeoutMillis;
     private NetconfMonitoringService monitoringService;
     private Set<String> baseCapabilities;
-    private @NonNegative int maximumIncomingChunkSize =
-        AbstractNetconfSessionNegotiator.DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
+    private @NonNegative int maximumIncomingChunkSize = NetconfSessionNegotiator.DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
 
     public NetconfServerSessionNegotiatorFactoryBuilder() {
     }