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 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
166 replaceHelloMessageOutboundHandler();
168 synchronized (this) {
169 lockedChangeState(State.OPEN_WAIT);
171 // Service the timeout on channel's eventloop, so that we do not get state transition problems
172 timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
173 connectionTimeoutMillis, TimeUnit.MILLISECONDS);
176 LOG.debug("Session negotiation started on channel {}", channel);
178 // State transition completed, now run any additional processing
179 helloFuture.addListener(this::onHelloWriteComplete);
182 private void onHelloWriteComplete(final Future<?> future) {
183 final var cause = future.cause();
185 LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
186 negotiationFailed(cause);
188 LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
192 private synchronized void timeoutExpired() {
193 if (timeoutTask == null) {
194 // cancelTimeout() between expiry and execution on the loop
199 if (state != State.ESTABLISHED) {
200 LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
201 connectionTimeoutMillis, channel, state);
203 // Do not fail negotiation if promise is done or canceled
204 // It would result in setting result of the promise second time and that throws exception
205 if (!promise.isDone() && !promise.isCancelled()) {
206 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
207 connectionTimeoutMillis);
210 } else if (channel.isOpen()) {
211 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
215 private void failAndClose() {
216 changeState(State.FAILED);
217 channel.close().addListener(this::onChannelClosed);
220 private void onChannelClosed(final Future<?> future) {
221 final var cause = future.cause();
223 LOG.warn("Channel {} closed: fail", channel, cause);
225 LOG.debug("Channel {} closed: success", channel);
229 private synchronized void cancelTimeout() {
230 if (timeoutTask != null && !timeoutTask.cancel()) {
231 // Late-coming cancel: make sure the task does not actually run
236 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
237 throws NetconfDocumentedException {
238 final Document doc = netconfMessage.getDocument();
240 if (shouldUseChunkFraming(doc)) {
241 insertChunkFramingToPipeline();
244 changeState(State.ESTABLISHED);
245 return getSession(sessionListener, channel, netconfMessage);
248 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
249 throws NetconfDocumentedException;
252 * Insert chunk framing handlers into the pipeline.
254 private void insertChunkFramingToPipeline() {
255 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
256 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
257 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
258 new NetconfChunkAggregator(maximumIncomingChunkSize));
261 private boolean shouldUseChunkFraming(final Document doc) {
262 return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
266 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
269 * Inbound hello message handler should be kept until negotiation is successful
270 * It caches any non-hello messages while negotiation is still in progress
272 protected final void replaceHelloMessageInboundHandler(final S session) {
273 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
274 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
276 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
277 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
278 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
279 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
281 // Process messages received during negotiation
282 // The hello message handler does not have to be synchronized,
283 // since it is always call from the same thread by netty.
284 // It means, we are now using the thread now
285 for (NetconfMessage message : netconfMessagesFromNegotiation) {
286 session.handleMessage(message);
291 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
293 private void replaceHelloMessageOutboundHandler() {
294 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
295 new NetconfMessageToXMLEncoder());
298 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
299 final ChannelHandler decoder) {
300 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
303 private synchronized void changeState(final State newState) {
304 lockedChangeState(newState);
308 private void lockedChangeState(final State newState) {
309 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
310 checkState(isStateChangePermitted(state, newState),
311 "Cannot change state from %s to %s for channel %s", state, newState, channel);
312 this.state = newState;
315 private static boolean containsBase11Capability(final Document doc) {
316 final NodeList nList = doc.getElementsByTagNameNS(
317 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
318 XmlNetconfConstants.CAPABILITY);
319 for (int i = 0; i < nList.getLength(); i++) {
320 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
327 private static boolean isStateChangePermitted(final State state, final State newState) {
328 if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
331 if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
334 LOG.debug("Transition from {} to {} is not allowed", state, newState);
339 * Handler to catch exceptions in pipeline during negotiation.
341 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
343 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
344 LOG.warn("An exception occurred during negotiation with {} on channel {}",
345 channel.remoteAddress(), channel, cause);
346 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
348 negotiationFailed(cause);
349 changeState(State.FAILED);
353 protected final void negotiationSuccessful(final S session) {
354 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
355 channel.pipeline().replace(this, "session", session);
356 promise.setSuccess(session);
359 protected void negotiationFailed(final Throwable cause) {
360 LOG.debug("Negotiation on channel {} failed", channel, cause);
362 promise.setFailure(cause);
366 @SuppressWarnings("checkstyle:illegalCatch")
367 public final void channelActive(final ChannelHandlerContext ctx) {
368 LOG.debug("Starting session negotiation on channel {}", channel);
371 } catch (final Exception e) {
372 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
373 negotiationFailed(e);
378 @SuppressWarnings("checkstyle:illegalCatch")
379 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
380 if (state() == State.FAILED) {
381 // We have already failed -- do not process any more messages
385 LOG.debug("Negotiation read invoked on channel {}", channel);
387 handleMessage((NetconfHelloMessage) msg);
388 } catch (final Exception e) {
389 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
390 negotiationFailed(e);
395 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
396 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
397 negotiationFailed(cause);
400 protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;