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 final 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);
166 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
167 throws NetconfDocumentedException;
170 * Insert chunk framing handlers into the pipeline.
172 private void insertChunkFramingToPipeline() {
173 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
174 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
175 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
176 new NetconfChunkAggregator());
179 private boolean shouldUseChunkFraming(final Document doc) {
180 return containsBase11Capability(doc)
181 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
185 * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
188 * Inbound hello message handler should be kept until negotiation is successful
189 * It caches any non-hello messages while negotiation is still in progress
191 protected final void replaceHelloMessageInboundHandler(final S session) {
192 ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
193 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
195 checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
196 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
197 Iterable<NetconfMessage> netconfMessagesFromNegotiation =
198 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
200 // Process messages received during negotiation
201 // The hello message handler does not have to be synchronized,
202 // since it is always call from the same thread by netty.
203 // It means, we are now using the thread now
204 for (NetconfMessage message : netconfMessagesFromNegotiation) {
205 session.handleMessage(message);
210 * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
212 private void replaceHelloMessageOutboundHandler() {
213 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
214 new NetconfMessageToXMLEncoder());
217 private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
218 final ChannelHandler decoder) {
219 return channel.pipeline().replace(handlerKey, handlerKey, decoder);
222 private synchronized void changeState(final State newState) {
223 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
224 checkState(isStateChangePermitted(state, newState),
225 "Cannot change state from %s to %s for channel %s", state, newState, channel);
226 this.state = newState;
229 private static boolean containsBase11Capability(final Document doc) {
230 final NodeList nList = doc.getElementsByTagNameNS(
231 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
232 XmlNetconfConstants.CAPABILITY);
233 for (int i = 0; i < nList.getLength(); i++) {
234 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
241 private static boolean isStateChangePermitted(final State state, final State newState) {
242 if (state == State.IDLE && newState == State.OPEN_WAIT) {
245 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
248 if (state == State.OPEN_WAIT && newState == State.FAILED) {
251 LOG.debug("Transition from {} to {} is not allowed", state, newState);
256 * Handler to catch exceptions in pipeline during negotiation.
258 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
260 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
261 LOG.warn("An exception occurred during negotiation with {} on channel {}",
262 channel.remoteAddress(), channel, cause);
263 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
265 negotiationFailed(cause);
266 changeState(State.FAILED);
270 protected final void negotiationSuccessful(final S session) {
271 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
272 channel.pipeline().replace(this, "session", session);
273 promise.setSuccess(session);
276 protected void negotiationFailed(final Throwable cause) {
277 LOG.debug("Negotiation on channel {} failed", channel, cause);
279 promise.setFailure(cause);
283 * Send a message to peer and fail negotiation if it does not reach
286 * @param msg Message which should be sent.
288 protected final void sendMessage(final NetconfMessage msg) {
289 this.channel.writeAndFlush(msg).addListener(f -> {
290 if (!f.isSuccess()) {
291 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
292 negotiationFailed(f.cause());
294 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
300 @SuppressWarnings("checkstyle:illegalCatch")
301 public final void channelActive(final ChannelHandlerContext ctx) {
302 LOG.debug("Starting session negotiation on channel {}", channel);
305 } catch (final Exception e) {
306 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
307 negotiationFailed(e);
312 @SuppressWarnings("checkstyle:illegalCatch")
313 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
314 LOG.debug("Negotiation read invoked on channel {}", channel);
316 handleMessage((NetconfHelloMessage) msg);
317 } catch (final Exception e) {
318 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
319 negotiationFailed(e);
324 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
325 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
326 negotiationFailed(cause);
329 protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;