Ignore incoming messages in State.FAILED
[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         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
165
166         replaceHelloMessageOutboundHandler();
167
168         synchronized (this) {
169             lockedChangeState(State.OPEN_WAIT);
170
171             // Service the timeout on channel's eventloop, so that we do not get state transition problems
172             timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
173                 connectionTimeoutMillis, TimeUnit.MILLISECONDS);
174         }
175
176         LOG.debug("Session negotiation started on channel {}", channel);
177
178         // State transition completed, now run any additional processing
179         helloFuture.addListener(this::onHelloWriteComplete);
180     }
181
182     private void onHelloWriteComplete(final Future<?> future) {
183         final var cause = future.cause();
184         if (cause != null) {
185             LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
186             negotiationFailed(cause);
187         } else {
188             LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
189         }
190     }
191
192     private synchronized void timeoutExpired() {
193         if (timeoutTask == null) {
194             // cancelTimeout() between expiry and execution on the loop
195             return;
196         }
197         timeoutTask = null;
198
199         if (state != State.ESTABLISHED) {
200             LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
201                 connectionTimeoutMillis, channel, state);
202
203             // Do not fail negotiation if promise is done or canceled
204             // It would result in setting result of the promise second time and that throws exception
205             if (!promise.isDone() && !promise.isCancelled()) {
206                 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
207                     connectionTimeoutMillis);
208                 failAndClose();
209             }
210         } else if (channel.isOpen()) {
211             channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
212         }
213     }
214
215     private void failAndClose() {
216         changeState(State.FAILED);
217         channel.close().addListener(this::onChannelClosed);
218     }
219
220     private void onChannelClosed(final Future<?> future) {
221         final var cause = future.cause();
222         if (cause != null) {
223             LOG.warn("Channel {} closed: fail", channel, cause);
224         } else {
225             LOG.debug("Channel {} closed: success", channel);
226         }
227     }
228
229     private synchronized void cancelTimeout() {
230         if (timeoutTask != null && !timeoutTask.cancel()) {
231             // Late-coming cancel: make sure the task does not actually run
232             timeoutTask = null;
233         }
234     }
235
236     protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
237             throws NetconfDocumentedException {
238         final Document doc = netconfMessage.getDocument();
239
240         if (shouldUseChunkFraming(doc)) {
241             insertChunkFramingToPipeline();
242         }
243
244         changeState(State.ESTABLISHED);
245         return getSession(sessionListener, channel, netconfMessage);
246     }
247
248     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
249         throws NetconfDocumentedException;
250
251     /**
252      * Insert chunk framing handlers into the pipeline.
253      */
254     private void insertChunkFramingToPipeline() {
255         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
256                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
257         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
258                 new NetconfChunkAggregator(maximumIncomingChunkSize));
259     }
260
261     private boolean shouldUseChunkFraming(final Document doc) {
262         return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
263     }
264
265     /**
266      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
267      *
268      * <p>
269      * Inbound hello message handler should be kept until negotiation is successful
270      * It caches any non-hello messages while negotiation is still in progress
271      */
272     protected final void replaceHelloMessageInboundHandler(final S session) {
273         ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
274                 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
275
276         checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
277                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
278         Iterable<NetconfMessage> netconfMessagesFromNegotiation =
279                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
280
281         // Process messages received during negotiation
282         // The hello message handler does not have to be synchronized,
283         // since it is always call from the same thread by netty.
284         // It means, we are now using the thread now
285         for (NetconfMessage message : netconfMessagesFromNegotiation) {
286             session.handleMessage(message);
287         }
288     }
289
290     /**
291      * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
292      */
293     private void replaceHelloMessageOutboundHandler() {
294         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
295                 new NetconfMessageToXMLEncoder());
296     }
297
298     private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
299                                                         final ChannelHandler decoder) {
300         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
301     }
302
303     private synchronized void changeState(final State newState) {
304         lockedChangeState(newState);
305     }
306
307     @Holding("this")
308     private void lockedChangeState(final State newState) {
309         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
310         checkState(isStateChangePermitted(state, newState),
311                 "Cannot change state from %s to %s for channel %s", state, newState, channel);
312         this.state = newState;
313     }
314
315     private static boolean containsBase11Capability(final Document doc) {
316         final NodeList nList = doc.getElementsByTagNameNS(
317             XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
318             XmlNetconfConstants.CAPABILITY);
319         for (int i = 0; i < nList.getLength(); i++) {
320             if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
321                 return true;
322             }
323         }
324         return false;
325     }
326
327     private static boolean isStateChangePermitted(final State state, final State newState) {
328         if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
329             return true;
330         }
331         if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
332             return true;
333         }
334         LOG.debug("Transition from {} to {} is not allowed", state, newState);
335         return false;
336     }
337
338     /**
339      * Handler to catch exceptions in pipeline during negotiation.
340      */
341     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
342         @Override
343         public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
344             LOG.warn("An exception occurred during negotiation with {} on channel {}",
345                     channel.remoteAddress(), channel, cause);
346             // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
347             cancelTimeout();
348             negotiationFailed(cause);
349             changeState(State.FAILED);
350         }
351     }
352
353     protected final void negotiationSuccessful(final S session) {
354         LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
355         channel.pipeline().replace(this, "session", session);
356         promise.setSuccess(session);
357     }
358
359     protected void negotiationFailed(final Throwable cause) {
360         LOG.debug("Negotiation on channel {} failed", channel, cause);
361         channel.close();
362         promise.setFailure(cause);
363     }
364
365     @Override
366     @SuppressWarnings("checkstyle:illegalCatch")
367     public final void channelActive(final ChannelHandlerContext ctx) {
368         LOG.debug("Starting session negotiation on channel {}", channel);
369         try {
370             startNegotiation();
371         } catch (final Exception e) {
372             LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
373             negotiationFailed(e);
374         }
375     }
376
377     @Override
378     @SuppressWarnings("checkstyle:illegalCatch")
379     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
380         if (state() == State.FAILED) {
381             // We have already failed -- do not process any more messages
382             return;
383         }
384
385         LOG.debug("Negotiation read invoked on channel {}", channel);
386         try {
387             handleMessage((NetconfHelloMessage) msg);
388         } catch (final Exception e) {
389             LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
390             negotiationFailed(e);
391         }
392     }
393
394     @Override
395     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
396         LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
397         negotiationFailed(cause);
398     }
399
400     protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;
401 }