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.NetconfDocumentedException;
31 import org.opendaylight.netconf.api.NetconfMessage;
32 import org.opendaylight.netconf.api.NetconfSessionListener;
33 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
34 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
35 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
36 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
37 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
38 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
39 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
40 import org.opendaylight.netconf.util.messages.FramingMechanism;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
44 import org.w3c.dom.NodeList;
46 public abstract class AbstractNetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
47 L extends NetconfSessionListener<S>>
48 extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
50 * Possible states for Finite State Machine.
52 protected enum State {
53 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
56 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
57 private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
58 private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
59 private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
62 * Default upper bound on the size of an individual chunk. This value can be controlled through
63 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
64 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
67 public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
70 final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
72 LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
73 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
75 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
77 LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
80 private final @NonNull NetconfHelloMessage localHello;
81 protected final Channel channel;
83 private final @NonNegative int maximumIncomingChunkSize;
84 private final long connectionTimeoutMillis;
85 private final Promise<S> promise;
86 private final L sessionListener;
87 private final Timer timer;
90 private Timeout timeoutTask;
92 private State state = State.IDLE;
94 protected AbstractNetconfSessionNegotiator(final NetconfHelloMessage hello, final Promise<S> promise,
95 final Channel channel, final Timer timer, final L sessionListener,
96 final long connectionTimeoutMillis,
97 final @NonNegative int maximumIncomingChunkSize) {
98 this.localHello = requireNonNull(hello);
99 this.promise = requireNonNull(promise);
100 this.channel = requireNonNull(channel);
102 this.sessionListener = sessionListener;
103 this.connectionTimeoutMillis = connectionTimeoutMillis;
104 this.maximumIncomingChunkSize = maximumIncomingChunkSize;
105 checkArgument(maximumIncomingChunkSize > 0, "Invalid maximum incoming chunk size %s", maximumIncomingChunkSize);
108 @Deprecated(since = "4.0.1", forRemoval = true)
109 protected AbstractNetconfSessionNegotiator(final NetconfHelloMessage hello, final Promise<S> promise,
110 final Channel channel, final Timer timer,
111 final L sessionListener, final long connectionTimeoutMillis) {
112 this(hello, promise, channel, timer, sessionListener, connectionTimeoutMillis,
113 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
116 protected final @NonNull NetconfHelloMessage localHello() {
120 protected final void startNegotiation() {
121 if (ifNegotiatedAlready()) {
122 LOG.debug("Negotiation on channel {} already started", channel);
124 final var sslHandler = getSslHandler(channel);
125 if (sslHandler != null) {
126 sslHandler.handshakeFuture().addListener(future -> {
127 checkState(future.isSuccess(), "Ssl handshake was not successful");
128 LOG.debug("Ssl handshake complete");
137 protected final boolean ifNegotiatedAlready() {
138 // Indicates whether negotiation already started
139 return state() != State.IDLE;
142 private synchronized State state() {
146 private static @Nullable SslHandler getSslHandler(final Channel channel) {
147 return channel.pipeline().get(SslHandler.class);
150 private void start() {
151 LOG.debug("Sending negotiation proposal {} on channel {}", localHello, channel);
153 // Send the message out, but to not run listeners just yet, as we have some more state transitions to go through
154 final var helloFuture = channel.writeAndFlush(localHello);
156 // Quick check: if the future has already failed we call it quits before negotiation even started
157 final var helloCause = helloFuture.cause();
158 if (helloCause != null) {
159 LOG.warn("Failed to send negotiation proposal on channel {}", channel, helloCause);
164 // Catch any exceptions from this point on. Use a named class to ease debugging.
165 final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
167 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
168 LOG.warn("An exception occurred during negotiation with {} on channel {}",
169 channel.remoteAddress(), channel, cause);
170 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
172 negotiationFailed(cause);
173 changeState(State.FAILED);
177 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
179 // Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
180 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
181 new NetconfMessageToXMLEncoder());
183 synchronized (this) {
184 lockedChangeState(State.OPEN_WAIT);
186 // Service the timeout on channel's eventloop, so that we do not get state transition problems
187 timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
188 connectionTimeoutMillis, TimeUnit.MILLISECONDS);
191 LOG.debug("Session negotiation started on channel {}", channel);
193 // State transition completed, now run any additional processing
194 helloFuture.addListener(this::onHelloWriteComplete);
197 private void onHelloWriteComplete(final Future<?> future) {
198 final var cause = future.cause();
200 LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
201 negotiationFailed(cause);
203 LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
207 private synchronized void timeoutExpired() {
208 if (timeoutTask == null) {
209 // cancelTimeout() between expiry and execution on the loop
214 if (state != State.ESTABLISHED) {
215 LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
216 connectionTimeoutMillis, channel, state);
218 // Do not fail negotiation if promise is done or canceled
219 // It would result in setting result of the promise second time and that throws exception
220 if (!promise.isDone() && !promise.isCancelled()) {
221 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
222 connectionTimeoutMillis);
225 } else if (channel.isOpen()) {
226 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
230 private void failAndClose() {
231 changeState(State.FAILED);
232 channel.close().addListener(this::onChannelClosed);
235 private void onChannelClosed(final Future<?> future) {
236 final var cause = future.cause();
238 LOG.warn("Channel {} closed: fail", channel, cause);
240 LOG.debug("Channel {} closed: success", channel);
244 private synchronized void cancelTimeout() {
245 if (timeoutTask != null && !timeoutTask.cancel()) {
246 // Late-coming cancel: make sure the task does not actually run
251 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
252 throws NetconfDocumentedException {
253 final Document doc = netconfMessage.getDocument();
255 if (shouldUseChunkFraming(doc)) {
256 insertChunkFramingToPipeline();
259 changeState(State.ESTABLISHED);
260 return getSession(sessionListener, channel, netconfMessage);
263 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
264 throws NetconfDocumentedException;
267 * Insert chunk framing handlers into the pipeline.
269 private void insertChunkFramingToPipeline() {
270 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
271 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
272 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
273 new NetconfChunkAggregator(maximumIncomingChunkSize));
276 private boolean shouldUseChunkFraming(final Document doc) {
277 return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
281 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
284 * Inbound hello message handler should be kept until negotiation is successful
285 * It caches any non-hello messages while negotiation is still in progress
287 protected final void replaceHelloMessageInboundHandler(final S session) {
288 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
289 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
291 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
292 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
293 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
294 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
296 // Process messages received during negotiation
297 // The hello message handler does not have to be synchronized,
298 // since it is always call from the same thread by netty.
299 // It means, we are now using the thread now
300 for (NetconfMessage message : netconfMessagesFromNegotiation) {
301 session.handleMessage(message);
305 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
306 final ChannelHandler decoder) {
307 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
310 private synchronized void changeState(final State newState) {
311 lockedChangeState(newState);
315 private void lockedChangeState(final State newState) {
316 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
317 checkState(isStateChangePermitted(state, newState),
318 "Cannot change state from %s to %s for channel %s", state, newState, channel);
319 this.state = newState;
322 private static boolean containsBase11Capability(final Document doc) {
323 final NodeList nList = doc.getElementsByTagNameNS(
324 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
325 XmlNetconfConstants.CAPABILITY);
326 for (int i = 0; i < nList.getLength(); i++) {
327 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_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((NetconfHelloMessage) 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(NetconfHelloMessage msg) throws Exception;