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