9a9225b247f0c53ead8c1000e38d06561e7ccb1d
[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.concurrent.GenericFutureListener;
22 import io.netty.util.concurrent.Promise;
23 import java.util.Optional;
24 import java.util.concurrent.TimeUnit;
25 import org.checkerframework.checker.lock.qual.GuardedBy;
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      * Possible states for Finite State Machine.
48      */
49     protected enum State {
50         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
51     }
52
53     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
54
55     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
56
57     protected final P sessionPreferences;
58     protected final Channel channel;
59
60     private final long connectionTimeoutMillis;
61     private final Promise<S> promise;
62     private final L sessionListener;
63     private final Timer timer;
64
65     private Timeout timeoutTask;
66
67     @GuardedBy("this")
68     private State state = State.IDLE;
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         timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
123     }
124
125     private synchronized void timeoutExpired(final Timeout timeout) {
126         if (state != State.ESTABLISHED) {
127             LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
128                 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 (!promise.isDone() && !promise.isCancelled()) {
133                 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
134                     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     private void cancelTimeout() {
151         if (timeoutTask != null) {
152             timeoutTask.cancel();
153         }
154     }
155
156     protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
157             throws NetconfDocumentedException {
158         final Document doc = netconfMessage.getDocument();
159
160         if (shouldUseChunkFraming(doc)) {
161             insertChunkFramingToPipeline();
162         }
163
164         changeState(State.ESTABLISHED);
165         return getSession(sessionListener, channel, netconfMessage);
166     }
167
168     /**
169      * Insert chunk framing handlers into the pipeline.
170      */
171     private void insertChunkFramingToPipeline() {
172         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
173                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
174         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
175                 new NetconfChunkAggregator());
176     }
177
178     private boolean shouldUseChunkFraming(final Document doc) {
179         return containsBase11Capability(doc)
180                 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument());
181     }
182
183     /**
184      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
185      *
186      * <p>
187      * Inbound hello message handler should be kept until negotiation is successful
188      * It caches any non-hello messages while negotiation is still in progress
189      */
190     protected final void replaceHelloMessageInboundHandler(final S session) {
191         ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
192                 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
193
194         checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
195                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
196         Iterable<NetconfMessage> netconfMessagesFromNegotiation =
197                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
198
199         // Process messages received during negotiation
200         // The hello message handler does not have to be synchronized,
201         // since it is always call from the same thread by netty.
202         // It means, we are now using the thread now
203         for (NetconfMessage message : netconfMessagesFromNegotiation) {
204             session.handleMessage(message);
205         }
206     }
207
208     /**
209      * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
210      */
211     private void replaceHelloMessageOutboundHandler() {
212         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
213                 new NetconfMessageToXMLEncoder());
214     }
215
216     private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
217                                                         final ChannelHandler decoder) {
218         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
219     }
220
221     @SuppressWarnings("checkstyle:hiddenField")
222     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
223             throws NetconfDocumentedException;
224
225     private synchronized void changeState(final State newState) {
226         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
227         checkState(isStateChangePermitted(state, newState),
228                 "Cannot change state from %s to %s for channel %s", state, newState, channel);
229         this.state = newState;
230     }
231
232     private static boolean containsBase11Capability(final Document doc) {
233         final NodeList nList = doc.getElementsByTagNameNS(
234             XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
235             XmlNetconfConstants.CAPABILITY);
236         for (int i = 0; i < nList.getLength(); i++) {
237             if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
238                 return true;
239             }
240         }
241         return false;
242     }
243
244     private static boolean isStateChangePermitted(final State state, final State newState) {
245         if (state == State.IDLE && newState == State.OPEN_WAIT) {
246             return true;
247         }
248         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
249             return true;
250         }
251         if (state == State.OPEN_WAIT && newState == State.FAILED) {
252             return true;
253         }
254         LOG.debug("Transition from {} to {} is not allowed", state, newState);
255         return false;
256     }
257
258     /**
259      * Handler to catch exceptions in pipeline during negotiation.
260      */
261     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
262         @Override
263         public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
264             LOG.warn("An exception occurred during negotiation with {} on channel {}",
265                     channel.remoteAddress(), channel, cause);
266             // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
267             cancelTimeout();
268             negotiationFailed(cause);
269             changeState(State.FAILED);
270         }
271     }
272
273     protected final void negotiationSuccessful(final S session) {
274         LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
275         channel.pipeline().replace(this, "session", session);
276         promise.setSuccess(session);
277     }
278
279     protected void negotiationFailed(final Throwable cause) {
280         LOG.debug("Negotiation on channel {} failed", channel, cause);
281         channel.close();
282         promise.setFailure(cause);
283     }
284
285     /**
286      * Send a message to peer and fail negotiation if it does not reach
287      * the peer.
288      *
289      * @param msg Message which should be sent.
290      */
291     protected final void sendMessage(final NetconfMessage msg) {
292         this.channel.writeAndFlush(msg).addListener(f -> {
293             if (!f.isSuccess()) {
294                 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
295                 negotiationFailed(f.cause());
296             } else {
297                 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
298             }
299         });
300     }
301
302     @Override
303     @SuppressWarnings("checkstyle:illegalCatch")
304     public final void channelActive(final ChannelHandlerContext ctx) {
305         LOG.debug("Starting session negotiation on channel {}", channel);
306         try {
307             startNegotiation();
308         } catch (final Exception e) {
309             LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
310             negotiationFailed(e);
311         }
312     }
313
314     @Override
315     @SuppressWarnings("checkstyle:illegalCatch")
316     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
317         LOG.debug("Negotiation read invoked on channel {}", channel);
318         try {
319             handleMessage((NetconfHelloMessage) msg);
320         } catch (final Exception e) {
321             LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
322             negotiationFailed(e);
323         }
324     }
325
326     @Override
327     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
328         LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
329         negotiationFailed(cause);
330     }
331
332     protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;
333 }