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