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