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