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.concurrent.Future;
22 import io.netty.util.concurrent.Promise;
23 import java.util.concurrent.TimeUnit;
24 import org.checkerframework.checker.index.qual.NonNegative;
25 import org.checkerframework.checker.lock.qual.GuardedBy;
26 import org.checkerframework.checker.lock.qual.Holding;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.netconf.api.CapabilityURN;
30 import org.opendaylight.netconf.api.NamespaceURN;
31 import org.opendaylight.netconf.api.NetconfDocumentedException;
32 import org.opendaylight.netconf.api.NetconfSessionListener;
33 import org.opendaylight.netconf.api.messages.HelloMessage;
34 import org.opendaylight.netconf.api.messages.NetconfMessage;
35 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
36 import org.opendaylight.netconf.common.NetconfTimer;
37 import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
38 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
39 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
40 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
41 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Document;
45 import org.w3c.dom.NodeList;
48 * A negotiator of a NETCONF session. It is responsible for message handling while the exact session parameters are not
49 * known. Once the session parameters are finalized, the negotiator replaces itself in the channel pipeline with the
52 * @param <S> Session type
53 * @param <L> Session listener type
55 public abstract class NetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
56 L extends NetconfSessionListener<S>> extends ChannelInboundHandlerAdapter {
58 * Possible states for Finite State Machine.
60 protected enum State {
61 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
64 private static final Logger LOG = LoggerFactory.getLogger(NetconfSessionNegotiator.class);
65 private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
66 private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
67 private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
70 * Default upper bound on the size of an individual chunk. This value can be controlled through
71 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
72 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
75 public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
78 final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
80 LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
81 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
83 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
85 LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
88 private final @NonNull HelloMessage localHello;
89 protected final Channel channel;
91 private final @NonNegative int maximumIncomingChunkSize;
92 private final long connectionTimeoutMillis;
93 private final Promise<S> promise;
94 private final L sessionListener;
95 private final NetconfTimer timer;
98 private Timeout timeoutTask;
100 private State state = State.IDLE;
102 protected NetconfSessionNegotiator(final HelloMessage hello, final Promise<S> promise, final Channel channel,
103 final NetconfTimer timer, final L sessionListener, final long connectionTimeoutMillis,
104 final @NonNegative int maximumIncomingChunkSize) {
105 localHello = requireNonNull(hello);
106 this.promise = requireNonNull(promise);
107 this.channel = requireNonNull(channel);
108 this.timer = requireNonNull(timer);
109 this.sessionListener = sessionListener;
110 this.connectionTimeoutMillis = connectionTimeoutMillis;
111 this.maximumIncomingChunkSize = maximumIncomingChunkSize;
112 checkArgument(maximumIncomingChunkSize > 0, "Invalid maximum incoming chunk size %s", maximumIncomingChunkSize);
115 protected final @NonNull HelloMessage localHello() {
119 protected final void startNegotiation() {
120 if (ifNegotiatedAlready()) {
121 LOG.debug("Negotiation on channel {} already started", channel);
123 final var sslHandler = getSslHandler(channel);
124 if (sslHandler != null) {
125 sslHandler.handshakeFuture().addListener(future -> {
126 checkState(future.isSuccess(), "Ssl handshake was not successful");
127 LOG.debug("Ssl handshake complete");
136 protected final boolean ifNegotiatedAlready() {
137 // Indicates whether negotiation already started
138 return state() != State.IDLE;
141 private synchronized State state() {
145 private static @Nullable SslHandler getSslHandler(final Channel channel) {
146 return channel.pipeline().get(SslHandler.class);
149 private void start() {
150 LOG.debug("Sending negotiation proposal {} on channel {}", localHello, channel);
152 // Send the message out, but to not run listeners just yet, as we have some more state transitions to go through
153 final var helloFuture = channel.writeAndFlush(localHello);
155 // Quick check: if the future has already failed we call it quits before negotiation even started
156 final var helloCause = helloFuture.cause();
157 if (helloCause != null) {
158 LOG.warn("Failed to send negotiation proposal on channel {}", channel, helloCause);
163 // Catch any exceptions from this point on. Use a named class to ease debugging.
164 final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
166 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
167 LOG.warn("An exception occurred during negotiation with {} on channel {}",
168 channel.remoteAddress(), channel, cause);
169 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
171 negotiationFailed(cause);
172 changeState(State.FAILED);
176 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
178 // Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
179 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
180 new NetconfMessageToXMLEncoder());
182 synchronized (this) {
183 lockedChangeState(State.OPEN_WAIT);
185 // Service the timeout on channel's eventloop, so that we do not get state transition problems
186 timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
187 connectionTimeoutMillis, TimeUnit.MILLISECONDS);
190 LOG.debug("Session negotiation started on channel {}", channel);
192 // State transition completed, now run any additional processing
193 helloFuture.addListener(this::onHelloWriteComplete);
196 private void onHelloWriteComplete(final Future<?> future) {
197 final var cause = future.cause();
199 LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
200 negotiationFailed(cause);
202 LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
206 private synchronized void timeoutExpired() {
207 if (timeoutTask == null) {
208 // cancelTimeout() between expiry and execution on the loop
213 if (state != State.ESTABLISHED) {
214 LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
215 connectionTimeoutMillis, channel, state);
217 // Do not fail negotiation if promise is done or canceled
218 // It would result in setting result of the promise second time and that throws exception
219 if (!promise.isDone() && !promise.isCancelled()) {
220 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
221 connectionTimeoutMillis);
224 } else if (channel.isOpen()) {
225 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
229 private void failAndClose() {
230 changeState(State.FAILED);
231 channel.close().addListener(this::onChannelClosed);
234 private void onChannelClosed(final Future<?> future) {
235 final var cause = future.cause();
237 LOG.warn("Channel {} closed: fail", channel, cause);
239 LOG.debug("Channel {} closed: success", channel);
243 private synchronized void cancelTimeout() {
244 if (timeoutTask != null && !timeoutTask.cancel()) {
245 // Late-coming cancel: make sure the task does not actually run
250 protected final S getSessionForHelloMessage(final HelloMessage netconfMessage)
251 throws NetconfDocumentedException {
252 final Document doc = netconfMessage.getDocument();
254 if (shouldUseChunkFraming(doc)) {
255 insertChunkFramingToPipeline();
258 changeState(State.ESTABLISHED);
259 return getSession(sessionListener, channel, netconfMessage);
262 protected abstract S getSession(L sessionListener, Channel channel, HelloMessage message)
263 throws NetconfDocumentedException;
266 * Insert chunk framing handlers into the pipeline.
268 private void insertChunkFramingToPipeline() {
269 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
270 new ChunkedFramingMechanismEncoder());
271 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
272 new NetconfChunkAggregator(maximumIncomingChunkSize));
275 private boolean shouldUseChunkFraming(final Document doc) {
276 return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
280 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
283 * Inbound hello message handler should be kept until negotiation is successful
284 * It caches any non-hello messages while negotiation is still in progress
286 protected final void replaceHelloMessageInboundHandler(final S session) {
287 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
288 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
290 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
291 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
292 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
293 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
295 // Process messages received during negotiation
296 // The hello message handler does not have to be synchronized,
297 // since it is always call from the same thread by netty.
298 // It means, we are now using the thread now
299 for (NetconfMessage message : netconfMessagesFromNegotiation) {
300 session.handleMessage(message);
304 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
305 final ChannelHandler decoder) {
306 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
309 private synchronized void changeState(final State newState) {
310 lockedChangeState(newState);
314 private void lockedChangeState(final State newState) {
315 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
316 checkState(isStateChangePermitted(state, newState),
317 "Cannot change state from %s to %s for channel %s", state, newState, channel);
321 private static boolean containsBase11Capability(final Document doc) {
322 final NodeList nList = doc.getElementsByTagNameNS(NamespaceURN.BASE, XmlNetconfConstants.CAPABILITY);
323 for (int i = 0; i < nList.getLength(); i++) {
324 if (nList.item(i).getTextContent().contains(CapabilityURN.BASE_1_1)) {
331 private static boolean isStateChangePermitted(final State state, final State newState) {
332 if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
335 if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
338 LOG.debug("Transition from {} to {} is not allowed", state, newState);
342 protected final void negotiationSuccessful(final S session) {
343 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
344 channel.pipeline().replace(this, "session", session);
345 promise.setSuccess(session);
348 protected void negotiationFailed(final Throwable cause) {
349 LOG.debug("Negotiation on channel {} failed", channel, cause);
351 promise.setFailure(cause);
355 @SuppressWarnings("checkstyle:illegalCatch")
356 public final void channelActive(final ChannelHandlerContext ctx) {
357 LOG.debug("Starting session negotiation on channel {}", channel);
360 } catch (final Exception e) {
361 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
362 negotiationFailed(e);
367 @SuppressWarnings("checkstyle:illegalCatch")
368 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
369 if (state() == State.FAILED) {
370 // We have already failed -- do not process any more messages
374 LOG.debug("Negotiation read invoked on channel {}", channel);
376 handleMessage((HelloMessage) msg);
377 } catch (final Exception e) {
378 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
379 negotiationFailed(e);
384 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
385 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
386 negotiationFailed(cause);
389 protected abstract void handleMessage(HelloMessage msg) throws Exception;