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 io.netty.channel.Channel;
14 import io.netty.channel.ChannelHandler;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.channel.ChannelInboundHandlerAdapter;
17 import io.netty.handler.ssl.SslHandler;
18 import io.netty.util.Timeout;
19 import io.netty.util.Timer;
20 import io.netty.util.concurrent.Promise;
21 import java.util.Optional;
22 import java.util.concurrent.TimeUnit;
23 import org.checkerframework.checker.lock.qual.GuardedBy;
24 import org.opendaylight.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.netconf.api.NetconfMessage;
26 import org.opendaylight.netconf.api.NetconfSessionListener;
27 import org.opendaylight.netconf.api.NetconfSessionPreferences;
28 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
29 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
30 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
31 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
32 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
33 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
34 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
35 import org.opendaylight.netconf.util.messages.FramingMechanism;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.NodeList;
41 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences,
42 S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
43 extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
45 * Possible states for Finite State Machine.
47 protected enum State {
48 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
51 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
53 public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
55 protected final P sessionPreferences;
56 protected final Channel channel;
58 private final long connectionTimeoutMillis;
59 private final Promise<S> promise;
60 private final L sessionListener;
61 private final Timer timer;
63 private Timeout timeoutTask;
66 private State state = State.IDLE;
68 protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
69 final Channel channel, final Timer timer,
70 final L sessionListener, final long connectionTimeoutMillis) {
71 this.channel = requireNonNull(channel);
72 this.promise = requireNonNull(promise);
73 this.sessionPreferences = sessionPreferences;
75 this.sessionListener = sessionListener;
76 this.connectionTimeoutMillis = connectionTimeoutMillis;
79 protected final void startNegotiation() {
80 if (ifNegotiatedAlready()) {
81 LOG.debug("Negotiation on channel {} already started", channel);
83 final Optional<SslHandler> sslHandler = getSslHandler(channel);
84 if (sslHandler.isPresent()) {
85 sslHandler.get().handshakeFuture().addListener(future -> {
86 checkState(future.isSuccess(), "Ssl handshake was not successful");
87 LOG.debug("Ssl handshake complete");
96 protected final synchronized boolean ifNegotiatedAlready() {
97 // Indicates whether negotiation already started
98 return this.state != State.IDLE;
101 private static Optional<SslHandler> getSslHandler(final Channel channel) {
102 return Optional.ofNullable(channel.pipeline().get(SslHandler.class));
105 public P getSessionPreferences() {
106 return sessionPreferences;
109 private void start() {
110 final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
111 LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);
113 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
115 sendMessage(helloMessage);
117 replaceHelloMessageOutboundHandler();
118 changeState(State.OPEN_WAIT);
120 timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
123 private synchronized void timeoutExpired(final Timeout timeout) {
124 if (state != State.ESTABLISHED) {
125 LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
128 // Do not fail negotiation if promise is done or canceled
129 // It would result in setting result of the promise second time and that throws exception
130 if (!promise.isDone() && !promise.isCancelled()) {
131 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
132 connectionTimeoutMillis);
133 changeState(State.FAILED);
135 channel.close().addListener(future -> {
136 if (future.isSuccess()) {
137 LOG.debug("Channel {} closed: success", channel);
139 LOG.warn("Channel {} closed: fail", channel);
143 } else if (channel.isOpen()) {
144 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
148 private void cancelTimeout() {
149 if (timeoutTask != null) {
150 timeoutTask.cancel();
154 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
155 throws NetconfDocumentedException {
156 final Document doc = netconfMessage.getDocument();
158 if (shouldUseChunkFraming(doc)) {
159 insertChunkFramingToPipeline();
162 changeState(State.ESTABLISHED);
163 return getSession(sessionListener, channel, netconfMessage);
167 * Insert chunk framing handlers into the pipeline.
169 private void insertChunkFramingToPipeline() {
170 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
171 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
172 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
173 new NetconfChunkAggregator());
176 private boolean shouldUseChunkFraming(final Document doc) {
177 return containsBase11Capability(doc)
178 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
182 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
185 * Inbound hello message handler should be kept until negotiation is successful
186 * It caches any non-hello messages while negotiation is still in progress
188 protected final void replaceHelloMessageInboundHandler(final S session) {
189 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
190 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
192 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
193 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
194 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
195 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
197 // Process messages received during negotiation
198 // The hello message handler does not have to be synchronized,
199 // since it is always call from the same thread by netty.
200 // It means, we are now using the thread now
201 for (NetconfMessage message : netconfMessagesFromNegotiation) {
202 session.handleMessage(message);
207 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
209 private void replaceHelloMessageOutboundHandler() {
210 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
211 new NetconfMessageToXMLEncoder());
214 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
215 final ChannelHandler decoder) {
216 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
219 @SuppressWarnings("checkstyle:hiddenField")
220 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
221 throws NetconfDocumentedException;
223 private synchronized void changeState(final State newState) {
224 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
225 checkState(isStateChangePermitted(state, newState),
226 "Cannot change state from %s to %s for channel %s", state, newState, channel);
227 this.state = newState;
230 private static boolean containsBase11Capability(final Document doc) {
231 final NodeList nList = doc.getElementsByTagNameNS(
232 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
233 XmlNetconfConstants.CAPABILITY);
234 for (int i = 0; i < nList.getLength(); i++) {
235 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
242 private static boolean isStateChangePermitted(final State state, final State newState) {
243 if (state == State.IDLE && newState == State.OPEN_WAIT) {
246 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
249 if (state == State.OPEN_WAIT && newState == State.FAILED) {
252 LOG.debug("Transition from {} to {} is not allowed", state, newState);
257 * Handler to catch exceptions in pipeline during negotiation.
259 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
261 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
262 LOG.warn("An exception occurred during negotiation with {} on channel {}",
263 channel.remoteAddress(), channel, cause);
264 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
266 negotiationFailed(cause);
267 changeState(State.FAILED);
271 protected final void negotiationSuccessful(final S session) {
272 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
273 channel.pipeline().replace(this, "session", session);
274 promise.setSuccess(session);
277 protected void negotiationFailed(final Throwable cause) {
278 LOG.debug("Negotiation on channel {} failed", channel, cause);
280 promise.setFailure(cause);
284 * Send a message to peer and fail negotiation if it does not reach
287 * @param msg Message which should be sent.
289 protected final void sendMessage(final NetconfMessage msg) {
290 this.channel.writeAndFlush(msg).addListener(f -> {
291 if (!f.isSuccess()) {
292 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
293 negotiationFailed(f.cause());
295 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
301 @SuppressWarnings("checkstyle:illegalCatch")
302 public final void channelActive(final ChannelHandlerContext ctx) {
303 LOG.debug("Starting session negotiation on channel {}", channel);
306 } catch (final Exception e) {
307 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
308 negotiationFailed(e);
313 @SuppressWarnings("checkstyle:illegalCatch")
314 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
315 LOG.debug("Negotiation read invoked on channel {}", channel);
317 handleMessage((NetconfHelloMessage) msg);
318 } catch (final Exception e) {
319 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
320 negotiationFailed(e);
325 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
326 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
327 negotiationFailed(cause);
330 protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;