Introduce NetconfTimer
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / NetconfSessionNegotiator.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.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import io.netty.channel.Channel;
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.concurrent.Future;
22 import io.netty.util.concurrent.Promise;
23 import java.util.concurrent.TimeUnit;
24 import org.checkerframework.checker.index.qual.NonNegative;
25 import org.checkerframework.checker.lock.qual.GuardedBy;
26 import org.checkerframework.checker.lock.qual.Holding;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.netconf.api.CapabilityURN;
30 import org.opendaylight.netconf.api.NamespaceURN;
31 import org.opendaylight.netconf.api.NetconfDocumentedException;
32 import org.opendaylight.netconf.api.NetconfSessionListener;
33 import org.opendaylight.netconf.api.messages.HelloMessage;
34 import org.opendaylight.netconf.api.messages.NetconfMessage;
35 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
36 import org.opendaylight.netconf.common.NetconfTimer;
37 import org.opendaylight.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder;
38 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
39 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
40 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
41 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Document;
45 import org.w3c.dom.NodeList;
46
47 /**
48  * A negotiator of a NETCONF session. It is responsible for message handling while the exact session parameters are not
49  * known. Once the session parameters are finalized, the negotiator replaces itself in the channel pipeline with the
50  * session.
51  *
52  * @param <S> Session type
53  * @param <L> Session listener type
54  */
55 public abstract class NetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
56             L extends NetconfSessionListener<S>> extends ChannelInboundHandlerAdapter {
57     /**
58      * Possible states for Finite State Machine.
59      */
60     protected enum State {
61         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
62     }
63
64     private static final Logger LOG = LoggerFactory.getLogger(NetconfSessionNegotiator.class);
65     private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
66     private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
67     private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
68
69     /**
70      * Default upper bound on the size of an individual chunk. This value can be controlled through
71      * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
72      * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
73      */
74     @Beta
75     public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
76
77     static {
78         final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
79         if (propValue <= 0) {
80             LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
81             DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
82         } else {
83             DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
84         }
85         LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
86     }
87
88     private final @NonNull HelloMessage localHello;
89     protected final Channel channel;
90
91     private final @NonNegative int maximumIncomingChunkSize;
92     private final long connectionTimeoutMillis;
93     private final Promise<S> promise;
94     private final L sessionListener;
95     private final NetconfTimer timer;
96
97     @GuardedBy("this")
98     private Timeout timeoutTask;
99     @GuardedBy("this")
100     private State state = State.IDLE;
101
102     protected NetconfSessionNegotiator(final HelloMessage hello, final Promise<S> promise, final Channel channel,
103             final NetconfTimer timer, final L sessionListener, final long connectionTimeoutMillis,
104             final @NonNegative int maximumIncomingChunkSize) {
105         localHello = requireNonNull(hello);
106         this.promise = requireNonNull(promise);
107         this.channel = requireNonNull(channel);
108         this.timer = requireNonNull(timer);
109         this.sessionListener = sessionListener;
110         this.connectionTimeoutMillis = connectionTimeoutMillis;
111         this.maximumIncomingChunkSize = maximumIncomingChunkSize;
112         checkArgument(maximumIncomingChunkSize > 0, "Invalid maximum incoming chunk size %s", maximumIncomingChunkSize);
113     }
114
115     protected final @NonNull HelloMessage localHello() {
116         return localHello;
117     }
118
119     protected final void startNegotiation() {
120         if (ifNegotiatedAlready()) {
121             LOG.debug("Negotiation on channel {} already started", channel);
122         } else {
123             final var sslHandler = getSslHandler(channel);
124             if (sslHandler != null) {
125                 sslHandler.handshakeFuture().addListener(future -> {
126                     checkState(future.isSuccess(), "Ssl handshake was not successful");
127                     LOG.debug("Ssl handshake complete");
128                     start();
129                 });
130             } else {
131                 start();
132             }
133         }
134     }
135
136     protected final boolean ifNegotiatedAlready() {
137         // Indicates whether negotiation already started
138         return state() != State.IDLE;
139     }
140
141     private synchronized State state() {
142         return state;
143     }
144
145     private static @Nullable SslHandler getSslHandler(final Channel channel) {
146         return channel.pipeline().get(SslHandler.class);
147     }
148
149     private void start() {
150         LOG.debug("Sending negotiation proposal {} on channel {}", localHello, channel);
151
152         // Send the message out, but to not run listeners just yet, as we have some more state transitions to go through
153         final var helloFuture = channel.writeAndFlush(localHello);
154
155         // Quick check: if the future has already failed we call it quits before negotiation even started
156         final var helloCause = helloFuture.cause();
157         if (helloCause != null) {
158             LOG.warn("Failed to send negotiation proposal on channel {}", channel, helloCause);
159             failAndClose();
160             return;
161         }
162
163         // Catch any exceptions from this point on. Use a named class to ease debugging.
164         final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
165             @Override
166             public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
167                 LOG.warn("An exception occurred during negotiation with {} on channel {}",
168                         channel.remoteAddress(), channel, cause);
169                 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
170                 cancelTimeout();
171                 negotiationFailed(cause);
172                 changeState(State.FAILED);
173             }
174         }
175
176         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
177
178         // Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
179         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
180             new NetconfMessageToXMLEncoder());
181
182         synchronized (this) {
183             lockedChangeState(State.OPEN_WAIT);
184
185             // Service the timeout on channel's eventloop, so that we do not get state transition problems
186             timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
187                 connectionTimeoutMillis, TimeUnit.MILLISECONDS);
188         }
189
190         LOG.debug("Session negotiation started on channel {}", channel);
191
192         // State transition completed, now run any additional processing
193         helloFuture.addListener(this::onHelloWriteComplete);
194     }
195
196     private void onHelloWriteComplete(final Future<?> future) {
197         final var cause = future.cause();
198         if (cause != null) {
199             LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
200             negotiationFailed(cause);
201         } else {
202             LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
203         }
204     }
205
206     private synchronized void timeoutExpired() {
207         if (timeoutTask == null) {
208             // cancelTimeout() between expiry and execution on the loop
209             return;
210         }
211         timeoutTask = null;
212
213         if (state != State.ESTABLISHED) {
214             LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
215                 connectionTimeoutMillis, channel, state);
216
217             // Do not fail negotiation if promise is done or canceled
218             // It would result in setting result of the promise second time and that throws exception
219             if (!promise.isDone() && !promise.isCancelled()) {
220                 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
221                     connectionTimeoutMillis);
222                 failAndClose();
223             }
224         } else if (channel.isOpen()) {
225             channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
226         }
227     }
228
229     private void failAndClose() {
230         changeState(State.FAILED);
231         channel.close().addListener(this::onChannelClosed);
232     }
233
234     private void onChannelClosed(final Future<?> future) {
235         final var cause = future.cause();
236         if (cause != null) {
237             LOG.warn("Channel {} closed: fail", channel, cause);
238         } else {
239             LOG.debug("Channel {} closed: success", channel);
240         }
241     }
242
243     private synchronized void cancelTimeout() {
244         if (timeoutTask != null && !timeoutTask.cancel()) {
245             // Late-coming cancel: make sure the task does not actually run
246             timeoutTask = null;
247         }
248     }
249
250     protected final S getSessionForHelloMessage(final HelloMessage netconfMessage)
251             throws NetconfDocumentedException {
252         final Document doc = netconfMessage.getDocument();
253
254         if (shouldUseChunkFraming(doc)) {
255             insertChunkFramingToPipeline();
256         }
257
258         changeState(State.ESTABLISHED);
259         return getSession(sessionListener, channel, netconfMessage);
260     }
261
262     protected abstract S getSession(L sessionListener, Channel channel, HelloMessage message)
263         throws NetconfDocumentedException;
264
265     /**
266      * Insert chunk framing handlers into the pipeline.
267      */
268     private void insertChunkFramingToPipeline() {
269         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
270             new ChunkedFramingMechanismEncoder());
271         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
272             new NetconfChunkAggregator(maximumIncomingChunkSize));
273     }
274
275     private boolean shouldUseChunkFraming(final Document doc) {
276         return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
277     }
278
279     /**
280      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
281      *
282      * <p>
283      * Inbound hello message handler should be kept until negotiation is successful
284      * It caches any non-hello messages while negotiation is still in progress
285      */
286     protected final void replaceHelloMessageInboundHandler(final S session) {
287         ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
288                 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
289
290         checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
291                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
292         Iterable<NetconfMessage> netconfMessagesFromNegotiation =
293                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
294
295         // Process messages received during negotiation
296         // The hello message handler does not have to be synchronized,
297         // since it is always call from the same thread by netty.
298         // It means, we are now using the thread now
299         for (NetconfMessage message : netconfMessagesFromNegotiation) {
300             session.handleMessage(message);
301         }
302     }
303
304     private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
305                                                         final ChannelHandler decoder) {
306         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
307     }
308
309     private synchronized void changeState(final State newState) {
310         lockedChangeState(newState);
311     }
312
313     @Holding("this")
314     private void lockedChangeState(final State newState) {
315         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
316         checkState(isStateChangePermitted(state, newState),
317                 "Cannot change state from %s to %s for channel %s", state, newState, channel);
318         state = newState;
319     }
320
321     private static boolean containsBase11Capability(final Document doc) {
322         final NodeList nList = doc.getElementsByTagNameNS(NamespaceURN.BASE, XmlNetconfConstants.CAPABILITY);
323         for (int i = 0; i < nList.getLength(); i++) {
324             if (nList.item(i).getTextContent().contains(CapabilityURN.BASE_1_1)) {
325                 return true;
326             }
327         }
328         return false;
329     }
330
331     private static boolean isStateChangePermitted(final State state, final State newState) {
332         if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
333             return true;
334         }
335         if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
336             return true;
337         }
338         LOG.debug("Transition from {} to {} is not allowed", state, newState);
339         return false;
340     }
341
342     protected final void negotiationSuccessful(final S session) {
343         LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
344         channel.pipeline().replace(this, "session", session);
345         promise.setSuccess(session);
346     }
347
348     protected void negotiationFailed(final Throwable cause) {
349         LOG.debug("Negotiation on channel {} failed", channel, cause);
350         channel.close();
351         promise.setFailure(cause);
352     }
353
354     @Override
355     @SuppressWarnings("checkstyle:illegalCatch")
356     public final void channelActive(final ChannelHandlerContext ctx) {
357         LOG.debug("Starting session negotiation on channel {}", channel);
358         try {
359             startNegotiation();
360         } catch (final Exception e) {
361             LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
362             negotiationFailed(e);
363         }
364     }
365
366     @Override
367     @SuppressWarnings("checkstyle:illegalCatch")
368     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
369         if (state() == State.FAILED) {
370             // We have already failed -- do not process any more messages
371             return;
372         }
373
374         LOG.debug("Negotiation read invoked on channel {}", channel);
375         try {
376             handleMessage((HelloMessage) msg);
377         } catch (final Exception e) {
378             LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
379             negotiationFailed(e);
380         }
381     }
382
383     @Override
384     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
385         LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
386         negotiationFailed(cause);
387     }
388
389     protected abstract void handleMessage(HelloMessage msg) throws Exception;
390 }