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