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.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.netconf.api.NetconfDocumentedException;
26 import org.opendaylight.netconf.api.NetconfMessage;
27 import org.opendaylight.netconf.api.NetconfSessionListener;
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<S extends AbstractNetconfSession<S, L>,
42 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);
52 private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
54 private final @NonNull NetconfHelloMessage localHello;
55 protected final Channel channel;
57 private final long connectionTimeoutMillis;
58 private final Promise<S> promise;
59 private final L sessionListener;
60 private final Timer timer;
62 private Timeout timeoutTask;
65 private State state = State.IDLE;
67 protected AbstractNetconfSessionNegotiator(final NetconfHelloMessage hello, final Promise<S> promise,
68 final Channel channel, final Timer timer,
69 final L sessionListener, final long connectionTimeoutMillis) {
70 this.localHello = requireNonNull(hello);
71 this.promise = requireNonNull(promise);
72 this.channel = requireNonNull(channel);
74 this.sessionListener = sessionListener;
75 this.connectionTimeoutMillis = connectionTimeoutMillis;
78 protected final @NonNull NetconfHelloMessage localHello() {
82 protected final void startNegotiation() {
83 if (ifNegotiatedAlready()) {
84 LOG.debug("Negotiation on channel {} already started", channel);
86 final Optional<SslHandler> sslHandler = getSslHandler(channel);
87 if (sslHandler.isPresent()) {
88 sslHandler.get().handshakeFuture().addListener(future -> {
89 checkState(future.isSuccess(), "Ssl handshake was not successful");
90 LOG.debug("Ssl handshake complete");
99 protected final synchronized boolean ifNegotiatedAlready() {
100 // Indicates whether negotiation already started
101 return this.state != State.IDLE;
104 private static Optional<SslHandler> getSslHandler(final Channel channel) {
105 return Optional.ofNullable(channel.pipeline().get(SslHandler.class));
108 private void start() {
109 LOG.debug("Session negotiation started with hello message {} on channel {}", localHello, channel);
111 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
113 sendMessage(localHello);
115 replaceHelloMessageOutboundHandler();
116 changeState(State.OPEN_WAIT);
118 timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
121 private synchronized void timeoutExpired(final Timeout timeout) {
122 if (state != State.ESTABLISHED) {
123 LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
126 // Do not fail negotiation if promise is done or canceled
127 // It would result in setting result of the promise second time and that throws exception
128 if (!promise.isDone() && !promise.isCancelled()) {
129 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
130 connectionTimeoutMillis);
131 changeState(State.FAILED);
133 channel.close().addListener(future -> {
134 if (future.isSuccess()) {
135 LOG.debug("Channel {} closed: success", channel);
137 LOG.warn("Channel {} closed: fail", channel);
141 } else if (channel.isOpen()) {
142 channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
146 private void cancelTimeout() {
147 if (timeoutTask != null) {
148 timeoutTask.cancel();
152 protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
153 throws NetconfDocumentedException {
154 final Document doc = netconfMessage.getDocument();
156 if (shouldUseChunkFraming(doc)) {
157 insertChunkFramingToPipeline();
160 changeState(State.ESTABLISHED);
161 return getSession(sessionListener, channel, netconfMessage);
164 protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
165 throws NetconfDocumentedException;
168 * Insert chunk framing handlers into the pipeline.
170 private void insertChunkFramingToPipeline() {
171 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
172 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
173 replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
174 new NetconfChunkAggregator());
177 private boolean shouldUseChunkFraming(final Document doc) {
178 return containsBase11Capability(doc) && containsBase11Capability(localHello.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 private synchronized void changeState(final State newState) {
220 LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
221 checkState(isStateChangePermitted(state, newState),
222 "Cannot change state from %s to %s for channel %s", state, newState, channel);
223 this.state = newState;
226 private static boolean containsBase11Capability(final Document doc) {
227 final NodeList nList = doc.getElementsByTagNameNS(
228 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
229 XmlNetconfConstants.CAPABILITY);
230 for (int i = 0; i < nList.getLength(); i++) {
231 if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
238 private static boolean isStateChangePermitted(final State state, final State newState) {
239 if (state == State.IDLE && newState == State.OPEN_WAIT) {
242 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
245 if (state == State.OPEN_WAIT && newState == State.FAILED) {
248 LOG.debug("Transition from {} to {} is not allowed", state, newState);
253 * Handler to catch exceptions in pipeline during negotiation.
255 private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
257 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
258 LOG.warn("An exception occurred during negotiation with {} on channel {}",
259 channel.remoteAddress(), channel, cause);
260 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
262 negotiationFailed(cause);
263 changeState(State.FAILED);
267 protected final void negotiationSuccessful(final S session) {
268 LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
269 channel.pipeline().replace(this, "session", session);
270 promise.setSuccess(session);
273 protected void negotiationFailed(final Throwable cause) {
274 LOG.debug("Negotiation on channel {} failed", channel, cause);
276 promise.setFailure(cause);
280 * Send a message to peer and fail negotiation if it does not reach
283 * @param msg Message which should be sent.
285 protected final void sendMessage(final NetconfMessage msg) {
286 this.channel.writeAndFlush(msg).addListener(f -> {
287 if (!f.isSuccess()) {
288 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
289 negotiationFailed(f.cause());
291 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
297 @SuppressWarnings("checkstyle:illegalCatch")
298 public final void channelActive(final ChannelHandlerContext ctx) {
299 LOG.debug("Starting session negotiation on channel {}", channel);
302 } catch (final Exception e) {
303 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
304 negotiationFailed(e);
309 @SuppressWarnings("checkstyle:illegalCatch")
310 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
311 LOG.debug("Negotiation read invoked on channel {}", channel);
313 handleMessage((NetconfHelloMessage) msg);
314 } catch (final Exception e) {
315 LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
316 negotiationFailed(e);
321 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
322 LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
323 negotiationFailed(cause);
326 protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;