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