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.checkState;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelHandler;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.channel.ChannelInboundHandlerAdapter;
18 import io.netty.handler.ssl.SslHandler;
19 import io.netty.util.Timeout;
20 import io.netty.util.Timer;
21 import io.netty.util.concurrent.Promise;
22 import java.util.Optional;
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.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.netconf.api.NetconfMessage;
29 import org.opendaylight.netconf.api.NetconfSessionListener;
30 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
31 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
32 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
33 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
34 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
35 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
36 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
37 import org.opendaylight.netconf.util.messages.FramingMechanism;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.w3c.dom.Document;
41 import org.w3c.dom.NodeList;
43 public abstract class AbstractNetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
44 L extends NetconfSessionListener<S>>
45 extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
47 * Possible states for Finite State Machine.
49 protected enum State {
50 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
53 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
54 private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
55 private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
56 private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
59 * Default upper bound on the size of an individual chunk. This value can be controlled through
60 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
61 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
64 public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
67 final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
69 LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
70 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
72 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
74 LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
77 private final @NonNull NetconfHelloMessage localHello;
78 protected final Channel channel;
80 private final long connectionTimeoutMillis;
81 private final Promise<S> promise;
82 private final L sessionListener;
83 private final Timer timer;
85 private Timeout timeoutTask;
88 private State state = State.IDLE;
90 protected AbstractNetconfSessionNegotiator(final NetconfHelloMessage hello, final Promise<S> promise,
91 final Channel channel, final Timer timer,
92 final L sessionListener, final long connectionTimeoutMillis) {
93 this.localHello = requireNonNull(hello);
94 this.promise = requireNonNull(promise);
95 this.channel = requireNonNull(channel);
97 this.sessionListener = sessionListener;
98 this.connectionTimeoutMillis = connectionTimeoutMillis;
101 protected final @NonNull NetconfHelloMessage localHello() {
105 protected final void startNegotiation() {
106 if (ifNegotiatedAlready()) {
107 LOG.debug("Negotiation on channel {} already started", channel);
109 final Optional<SslHandler> sslHandler = getSslHandler(channel);
110 if (sslHandler.isPresent()) {
111 sslHandler.get().handshakeFuture().addListener(future -> {
112 checkState(future.isSuccess(), "Ssl handshake was not successful");
113 LOG.debug("Ssl handshake complete");
122 protected final synchronized boolean ifNegotiatedAlready() {
123 // Indicates whether negotiation already started
124 return this.state != State.IDLE;
127 private static Optional<SslHandler> getSslHandler(final Channel channel) {
128 return Optional.ofNullable(channel.pipeline().get(SslHandler.class));
131 private void start() {
132 LOG.debug("Session negotiation started with hello message {} on channel {}", localHello, channel);
134 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
136 sendMessage(localHello);
138 replaceHelloMessageOutboundHandler();
139 changeState(State.OPEN_WAIT);
141 timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
144 private synchronized void timeoutExpired(final Timeout timeout) {
145 if (state != State.ESTABLISHED) {
146 LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
149 // Do not fail negotiation if promise is done or canceled
150 // It would result in setting result of the promise second time and that throws exception
151 if (!promise.isDone() && !promise.isCancelled()) {
152 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
153 connectionTimeoutMillis);
154 changeState(State.FAILED);
156 channel.close().addListener(future -> {
157 if (future.isSuccess()) {
158 LOG.debug("Channel {} closed: success", channel);
160 LOG.warn("Channel {} closed: fail", channel);
164 } else if (channel.isOpen()) {
165 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
169 private void cancelTimeout() {
170 if (timeoutTask != null) {
171 timeoutTask.cancel();
175 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
176 throws NetconfDocumentedException {
177 final Document doc = netconfMessage.getDocument();
179 if (shouldUseChunkFraming(doc)) {
180 insertChunkFramingToPipeline();
183 changeState(State.ESTABLISHED);
184 return getSession(sessionListener, channel, netconfMessage);
187 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
188 throws NetconfDocumentedException;
191 * Insert chunk framing handlers into the pipeline.
193 private void insertChunkFramingToPipeline() {
194 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
195 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
196 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
197 new NetconfChunkAggregator());
200 private boolean shouldUseChunkFraming(final Document doc) {
201 return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
205 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
208 * Inbound hello message handler should be kept until negotiation is successful
209 * It caches any non-hello messages while negotiation is still in progress
211 protected final void replaceHelloMessageInboundHandler(final S session) {
212 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
213 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
215 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
216 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
217 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
218 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
220 // Process messages received during negotiation
221 // The hello message handler does not have to be synchronized,
222 // since it is always call from the same thread by netty.
223 // It means, we are now using the thread now
224 for (NetconfMessage message : netconfMessagesFromNegotiation) {
225 session.handleMessage(message);
230 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
232 private void replaceHelloMessageOutboundHandler() {
233 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
234 new NetconfMessageToXMLEncoder());
237 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
238 final ChannelHandler decoder) {
239 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
242 private synchronized void changeState(final State newState) {
243 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
244 checkState(isStateChangePermitted(state, newState),
245 "Cannot change state from %s to %s for channel %s", state, newState, channel);
246 this.state = newState;
249 private static boolean containsBase11Capability(final Document doc) {
250 final NodeList nList = doc.getElementsByTagNameNS(
251 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
252 XmlNetconfConstants.CAPABILITY);
253 for (int i = 0; i < nList.getLength(); i++) {
254 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
261 private static boolean isStateChangePermitted(final State state, final State newState) {
262 if (state == State.IDLE && newState == State.OPEN_WAIT) {
265 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
268 if (state == State.OPEN_WAIT && newState == State.FAILED) {
271 LOG.debug("Transition from {} to {} is not allowed", state, newState);
276 * Handler to catch exceptions in pipeline during negotiation.
278 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
280 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
281 LOG.warn("An exception occurred during negotiation with {} on channel {}",
282 channel.remoteAddress(), channel, cause);
283 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
285 negotiationFailed(cause);
286 changeState(State.FAILED);
290 protected final void negotiationSuccessful(final S session) {
291 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
292 channel.pipeline().replace(this, "session", session);
293 promise.setSuccess(session);
296 protected void negotiationFailed(final Throwable cause) {
297 LOG.debug("Negotiation on channel {} failed", channel, cause);
299 promise.setFailure(cause);
303 * Send a message to peer and fail negotiation if it does not reach
306 * @param msg Message which should be sent.
308 protected final void sendMessage(final NetconfMessage msg) {
309 this.channel.writeAndFlush(msg).addListener(f -> {
310 if (!f.isSuccess()) {
311 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
312 negotiationFailed(f.cause());
314 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
320 @SuppressWarnings("checkstyle:illegalCatch")
321 public final void channelActive(final ChannelHandlerContext ctx) {
322 LOG.debug("Starting session negotiation on channel {}", channel);
325 } catch (final Exception e) {
326 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
327 negotiationFailed(e);
332 @SuppressWarnings("checkstyle:illegalCatch")
333 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
334 LOG.debug("Negotiation read invoked on channel {}", channel);
336 handleMessage((NetconfHelloMessage) msg);
337 } catch (final Exception e) {
338 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
339 negotiationFailed(e);
344 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
345 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
346 negotiationFailed(cause);
349 protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;