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