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