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.ChannelFuture;
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.GenericFutureListener;
23 import io.netty.util.concurrent.Promise;
24 import java.util.Optional;
25 import java.util.concurrent.TimeUnit;
26 import org.checkerframework.checker.index.qual.NonNegative;
27 import org.checkerframework.checker.lock.qual.GuardedBy;
28 import org.opendaylight.netconf.api.NetconfDocumentedException;
29 import org.opendaylight.netconf.api.NetconfMessage;
30 import org.opendaylight.netconf.api.NetconfSessionListener;
31 import org.opendaylight.netconf.api.NetconfSessionPreferences;
32 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
33 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
34 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
35 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
36 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
37 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
38 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
39 import org.opendaylight.netconf.util.messages.FramingMechanism;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.w3c.dom.Document;
43 import org.w3c.dom.NodeList;
45 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences,
46 S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
47 extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
49 * Possible states for Finite State Machine.
51 protected enum State {
52 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
55 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
56 private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
57 private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
58 private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
61 * Default upper bound on the size of an individual chunk. This value can be controlled through
62 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
63 * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
66 public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
69 final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
71 LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
72 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
74 DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
76 LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
79 protected final P sessionPreferences;
80 protected final Channel channel;
82 private final long connectionTimeoutMillis;
83 private final Promise<S> promise;
84 private final L sessionListener;
85 private final Timer timer;
87 private Timeout timeoutTask;
90 private State state = State.IDLE;
92 protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
93 final Channel channel, final Timer timer,
94 final L sessionListener, final long connectionTimeoutMillis) {
95 this.channel = requireNonNull(channel);
96 this.promise = requireNonNull(promise);
97 this.sessionPreferences = sessionPreferences;
99 this.sessionListener = sessionListener;
100 this.connectionTimeoutMillis = connectionTimeoutMillis;
103 protected final void startNegotiation() {
104 if (ifNegotiatedAlready()) {
105 LOG.debug("Negotiation on channel {} already started", channel);
107 final Optional<SslHandler> sslHandler = getSslHandler(channel);
108 if (sslHandler.isPresent()) {
109 sslHandler.get().handshakeFuture().addListener(future -> {
110 checkState(future.isSuccess(), "Ssl handshake was not successful");
111 LOG.debug("Ssl handshake complete");
120 protected final synchronized boolean ifNegotiatedAlready() {
121 // Indicates whether negotiation already started
122 return this.state != State.IDLE;
125 private static Optional<SslHandler> getSslHandler(final Channel channel) {
126 return Optional.ofNullable(channel.pipeline().get(SslHandler.class));
129 public P getSessionPreferences() {
130 return sessionPreferences;
133 private void start() {
134 final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
135 LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);
137 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
139 sendMessage(helloMessage);
141 replaceHelloMessageOutboundHandler();
142 changeState(State.OPEN_WAIT);
144 timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
147 private synchronized void timeoutExpired(final Timeout timeout) {
148 if (state != State.ESTABLISHED) {
149 LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
152 // Do not fail negotiation if promise is done or canceled
153 // It would result in setting result of the promise second time and that throws exception
154 if (!promise.isDone() && !promise.isCancelled()) {
155 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
156 connectionTimeoutMillis);
157 changeState(State.FAILED);
159 channel.close().addListener((GenericFutureListener<ChannelFuture>) future -> {
160 if (future.isSuccess()) {
161 LOG.debug("Channel {} closed: success", future.channel());
163 LOG.warn("Channel {} closed: fail", future.channel());
167 } else if (channel.isOpen()) {
168 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
172 private void cancelTimeout() {
173 if (timeoutTask != null) {
174 timeoutTask.cancel();
178 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
179 throws NetconfDocumentedException {
180 final Document doc = netconfMessage.getDocument();
182 if (shouldUseChunkFraming(doc)) {
183 insertChunkFramingToPipeline();
186 changeState(State.ESTABLISHED);
187 return getSession(sessionListener, channel, netconfMessage);
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(DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE));
200 private boolean shouldUseChunkFraming(final Document doc) {
201 return containsBase11Capability(doc)
202 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
206 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
209 * Inbound hello message handler should be kept until negotiation is successful
210 * It caches any non-hello messages while negotiation is still in progress
212 protected final void replaceHelloMessageInboundHandler(final S session) {
213 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
214 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
216 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
217 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
218 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
219 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
221 // Process messages received during negotiation
222 // The hello message handler does not have to be synchronized,
223 // since it is always call from the same thread by netty.
224 // It means, we are now using the thread now
225 for (NetconfMessage message : netconfMessagesFromNegotiation) {
226 session.handleMessage(message);
231 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
233 private void replaceHelloMessageOutboundHandler() {
234 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
235 new NetconfMessageToXMLEncoder());
238 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
239 final ChannelHandler decoder) {
240 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
243 @SuppressWarnings("checkstyle:hiddenField")
244 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
245 throws NetconfDocumentedException;
247 private synchronized void changeState(final State newState) {
248 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
249 checkState(isStateChangePermitted(state, newState),
250 "Cannot change state from %s to %s for channel %s", state, newState, channel);
251 this.state = newState;
254 private static boolean containsBase11Capability(final Document doc) {
255 final NodeList nList = doc.getElementsByTagNameNS(
256 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
257 XmlNetconfConstants.CAPABILITY);
258 for (int i = 0; i < nList.getLength(); i++) {
259 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
266 private static boolean isStateChangePermitted(final State state, final State newState) {
267 if (state == State.IDLE && newState == State.OPEN_WAIT) {
270 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
273 if (state == State.OPEN_WAIT && newState == State.FAILED) {
276 LOG.debug("Transition from {} to {} is not allowed", state, newState);
281 * Handler to catch exceptions in pipeline during negotiation.
283 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
285 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
286 LOG.warn("An exception occurred during negotiation with {} on channel {}",
287 channel.remoteAddress(), channel, cause);
288 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
290 negotiationFailed(cause);
291 changeState(State.FAILED);
295 protected final void negotiationSuccessful(final S session) {
296 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
297 channel.pipeline().replace(this, "session", session);
298 promise.setSuccess(session);
301 protected void negotiationFailed(final Throwable cause) {
302 LOG.debug("Negotiation on channel {} failed", channel, cause);
304 promise.setFailure(cause);
308 * Send a message to peer and fail negotiation if it does not reach
311 * @param msg Message which should be sent.
313 protected final void sendMessage(final NetconfMessage msg) {
314 this.channel.writeAndFlush(msg).addListener(f -> {
315 if (!f.isSuccess()) {
316 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
317 negotiationFailed(f.cause());
319 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
325 @SuppressWarnings("checkstyle:illegalCatch")
326 public final void channelActive(final ChannelHandlerContext ctx) {
327 LOG.debug("Starting session negotiation on channel {}", channel);
330 } catch (final Exception e) {
331 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
332 negotiationFailed(e);
337 @SuppressWarnings("checkstyle:illegalCatch")
338 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
339 LOG.debug("Negotiation read invoked on channel {}", channel);
341 handleMessage((NetconfHelloMessage) msg);
342 } catch (final Exception e) {
343 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
344 negotiationFailed(e);
349 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
350 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
351 negotiationFailed(cause);
354 protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;