9c713f1b5c3c5f50feaa542b9a06b3d57b390f0d
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / AbstractNetconfSessionNegotiator.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.nettyutil;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
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.concurrent.TimeUnit;
25 import org.checkerframework.checker.lock.qual.GuardedBy;
26 import org.eclipse.jdt.annotation.Nullable;
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.NetconfSessionPreferences;
31 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
32 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
33 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
34 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
35 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
36 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
37 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
38 import org.opendaylight.netconf.util.messages.FramingMechanism;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.w3c.dom.Document;
42 import org.w3c.dom.NodeList;
43
44 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences,
45         S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
46             extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
47     /**
48      * Possible states for Finite State Machine.
49      */
50     protected enum State {
51         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
52     }
53
54     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
55
56     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
57
58     protected final P sessionPreferences;
59     protected final Channel channel;
60
61     private final long connectionTimeoutMillis;
62     private final Promise<S> promise;
63     private final L sessionListener;
64     private final Timer timer;
65
66     private Timeout timeoutTask;
67
68     @GuardedBy("this")
69     private State state = State.IDLE;
70
71     protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
72                                                final Channel channel, final Timer timer,
73                                                final L sessionListener, final long connectionTimeoutMillis) {
74         this.channel = requireNonNull(channel);
75         this.promise = requireNonNull(promise);
76         this.sessionPreferences = sessionPreferences;
77         this.timer = timer;
78         this.sessionListener = sessionListener;
79         this.connectionTimeoutMillis = connectionTimeoutMillis;
80     }
81
82     protected final void startNegotiation() {
83         if (ifNegotiatedAlready()) {
84             LOG.debug("Negotiation on channel {} already started", channel);
85         } else {
86             final var sslHandler = getSslHandler(channel);
87             if (sslHandler != null) {
88                 sslHandler.handshakeFuture().addListener(future -> {
89                     checkState(future.isSuccess(), "Ssl handshake was not successful");
90                     LOG.debug("Ssl handshake complete");
91                     start();
92                 });
93             } else {
94                 start();
95             }
96         }
97     }
98
99     protected final synchronized boolean ifNegotiatedAlready() {
100         // Indicates whether negotiation already started
101         return this.state != State.IDLE;
102     }
103
104     private static @Nullable SslHandler getSslHandler(final Channel channel) {
105         return channel.pipeline().get(SslHandler.class);
106     }
107
108     public P getSessionPreferences() {
109         return sessionPreferences;
110     }
111
112     private void start() {
113         final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
114         LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);
115
116         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
117
118         sendMessage(helloMessage);
119
120         replaceHelloMessageOutboundHandler();
121         changeState(State.OPEN_WAIT);
122
123         timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
124     }
125
126     private synchronized void timeoutExpired(final Timeout timeout) {
127         if (state != State.ESTABLISHED) {
128             LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
129                 state);
130
131             // Do not fail negotiation if promise is done or canceled
132             // It would result in setting result of the promise second time and that throws exception
133             if (!promise.isDone() && !promise.isCancelled()) {
134                 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
135                     connectionTimeoutMillis);
136                 changeState(State.FAILED);
137
138                 channel.close().addListener((GenericFutureListener<ChannelFuture>) future -> {
139                     if (future.isSuccess()) {
140                         LOG.debug("Channel {} closed: success", future.channel());
141                     } else {
142                         LOG.warn("Channel {} closed: fail", future.channel());
143                     }
144                 });
145             }
146         } else if (channel.isOpen()) {
147             channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
148         }
149     }
150
151     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
152             justification = "https://github.com/spotbugs/spotbugs/issues/811")
153     private void cancelTimeout() {
154         if (timeoutTask != null) {
155             timeoutTask.cancel();
156         }
157     }
158
159     protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
160             throws NetconfDocumentedException {
161         final Document doc = netconfMessage.getDocument();
162
163         if (shouldUseChunkFraming(doc)) {
164             insertChunkFramingToPipeline();
165         }
166
167         changeState(State.ESTABLISHED);
168         return getSession(sessionListener, channel, netconfMessage);
169     }
170
171     /**
172      * Insert chunk framing handlers into the pipeline.
173      */
174     private void insertChunkFramingToPipeline() {
175         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
176                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
177         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
178                 new NetconfChunkAggregator());
179     }
180
181     private boolean shouldUseChunkFraming(final Document doc) {
182         return containsBase11Capability(doc)
183                 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
184     }
185
186     /**
187      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
188      *
189      * <p>
190      * Inbound hello message handler should be kept until negotiation is successful
191      * It caches any non-hello messages while negotiation is still in progress
192      */
193     protected final void replaceHelloMessageInboundHandler(final S session) {
194         ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
195                 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
196
197         checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
198                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
199         Iterable<NetconfMessage> netconfMessagesFromNegotiation =
200                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
201
202         // Process messages received during negotiation
203         // The hello message handler does not have to be synchronized,
204         // since it is always call from the same thread by netty.
205         // It means, we are now using the thread now
206         for (NetconfMessage message : netconfMessagesFromNegotiation) {
207             session.handleMessage(message);
208         }
209     }
210
211     /**
212      * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
213      */
214     private void replaceHelloMessageOutboundHandler() {
215         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
216                 new NetconfMessageToXMLEncoder());
217     }
218
219     private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
220                                                         final ChannelHandler decoder) {
221         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
222     }
223
224     @SuppressWarnings("checkstyle:hiddenField")
225     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
226             throws NetconfDocumentedException;
227
228     private synchronized void changeState(final State newState) {
229         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
230         checkState(isStateChangePermitted(state, newState),
231                 "Cannot change state from %s to %s for channel %s", state, newState, channel);
232         this.state = newState;
233     }
234
235     private static boolean containsBase11Capability(final Document doc) {
236         final NodeList nList = doc.getElementsByTagNameNS(
237             XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
238             XmlNetconfConstants.CAPABILITY);
239         for (int i = 0; i < nList.getLength(); i++) {
240             if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
241                 return true;
242             }
243         }
244         return false;
245     }
246
247     private static boolean isStateChangePermitted(final State state, final State newState) {
248         if (state == State.IDLE && newState == State.OPEN_WAIT) {
249             return true;
250         }
251         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
252             return true;
253         }
254         if (state == State.OPEN_WAIT && newState == State.FAILED) {
255             return true;
256         }
257         LOG.debug("Transition from {} to {} is not allowed", state, newState);
258         return false;
259     }
260
261     /**
262      * Handler to catch exceptions in pipeline during negotiation.
263      */
264     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
265         @Override
266         public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
267             LOG.warn("An exception occurred during negotiation with {} on channel {}",
268                     channel.remoteAddress(), channel, cause);
269             // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
270             cancelTimeout();
271             negotiationFailed(cause);
272             changeState(State.FAILED);
273         }
274     }
275
276     protected final void negotiationSuccessful(final S session) {
277         LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
278         channel.pipeline().replace(this, "session", session);
279         promise.setSuccess(session);
280     }
281
282     protected void negotiationFailed(final Throwable cause) {
283         LOG.debug("Negotiation on channel {} failed", channel, cause);
284         channel.close();
285         promise.setFailure(cause);
286     }
287
288     /**
289      * Send a message to peer and fail negotiation if it does not reach
290      * the peer.
291      *
292      * @param msg Message which should be sent.
293      */
294     protected final void sendMessage(final NetconfMessage msg) {
295         this.channel.writeAndFlush(msg).addListener(f -> {
296             if (!f.isSuccess()) {
297                 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
298                 negotiationFailed(f.cause());
299             } else {
300                 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
301             }
302         });
303     }
304
305     @Override
306     @SuppressWarnings("checkstyle:illegalCatch")
307     public final void channelActive(final ChannelHandlerContext ctx) {
308         LOG.debug("Starting session negotiation on channel {}", channel);
309         try {
310             startNegotiation();
311         } catch (final Exception e) {
312             LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
313             negotiationFailed(e);
314         }
315     }
316
317     @Override
318     @SuppressWarnings("checkstyle:illegalCatch")
319     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
320         LOG.debug("Negotiation read invoked on channel {}", channel);
321         try {
322             handleMessage((NetconfHelloMessage) msg);
323         } catch (final Exception e) {
324             LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
325             negotiationFailed(e);
326         }
327     }
328
329     @Override
330     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
331         LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
332         negotiationFailed(cause);
333     }
334
335     protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;
336 }