3949db62d2e21b4fc9397a9701f950b16f01b5c2
[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.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.netconf.api.NetconfDocumentedException;
26 import org.opendaylight.netconf.api.NetconfMessage;
27 import org.opendaylight.netconf.api.NetconfSessionListener;
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<S extends AbstractNetconfSession<S, L>,
42             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     private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
53
54     private final @NonNull NetconfHelloMessage localHello;
55     protected final Channel channel;
56
57     private final long connectionTimeoutMillis;
58     private final Promise<S> promise;
59     private final L sessionListener;
60     private final Timer timer;
61
62     private Timeout timeoutTask;
63
64     @GuardedBy("this")
65     private State state = State.IDLE;
66
67     protected AbstractNetconfSessionNegotiator(final NetconfHelloMessage hello, final Promise<S> promise,
68                                                final Channel channel, final Timer timer,
69                                                final L sessionListener, final long connectionTimeoutMillis) {
70         this.localHello = requireNonNull(hello);
71         this.promise = requireNonNull(promise);
72         this.channel = requireNonNull(channel);
73         this.timer = timer;
74         this.sessionListener = sessionListener;
75         this.connectionTimeoutMillis = connectionTimeoutMillis;
76     }
77
78     protected final @NonNull NetconfHelloMessage localHello() {
79         return localHello;
80     }
81
82     protected final void startNegotiation() {
83         if (ifNegotiatedAlready()) {
84             LOG.debug("Negotiation on channel {} already started", channel);
85         } else {
86             final Optional<SslHandler> sslHandler = getSslHandler(channel);
87             if (sslHandler.isPresent()) {
88                 sslHandler.get().handshakeFuture().addListener(future -> {
89                     checkState(future.isSuccess(), "Ssl handshake was not successful");
90                     LOG.debug("Ssl handshake complete");
91                     start();
92                 });
93             } else {
94                 start();
95             }
96         }
97     }
98
99     protected final synchronized boolean ifNegotiatedAlready() {
100         // Indicates whether negotiation already started
101         return this.state != State.IDLE;
102     }
103
104     private static Optional<SslHandler> getSslHandler(final Channel channel) {
105         return Optional.ofNullable(channel.pipeline().get(SslHandler.class));
106     }
107
108     private void start() {
109         LOG.debug("Session negotiation started with hello message {} on channel {}", localHello, channel);
110
111         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
112
113         sendMessage(localHello);
114
115         replaceHelloMessageOutboundHandler();
116         changeState(State.OPEN_WAIT);
117
118         timeoutTask = this.timer.newTimeout(this::timeoutExpired, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
119     }
120
121     private synchronized void timeoutExpired(final Timeout timeout) {
122         if (state != State.ESTABLISHED) {
123             LOG.debug("Connection timeout after {}, session backed by channel {} is in state {}", timeout, channel,
124                 state);
125
126             // Do not fail negotiation if promise is done or canceled
127             // It would result in setting result of the promise second time and that throws exception
128             if (!promise.isDone() && !promise.isCancelled()) {
129                 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
130                     connectionTimeoutMillis);
131                 changeState(State.FAILED);
132
133                 channel.close().addListener(future -> {
134                     if (future.isSuccess()) {
135                         LOG.debug("Channel {} closed: success", channel);
136                     } else {
137                         LOG.warn("Channel {} closed: fail", channel);
138                     }
139                 });
140             }
141         } else if (channel.isOpen()) {
142             channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
143         }
144     }
145
146     private void cancelTimeout() {
147         if (timeoutTask != null) {
148             timeoutTask.cancel();
149         }
150     }
151
152     protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
153             throws NetconfDocumentedException {
154         final Document doc = netconfMessage.getDocument();
155
156         if (shouldUseChunkFraming(doc)) {
157             insertChunkFramingToPipeline();
158         }
159
160         changeState(State.ESTABLISHED);
161         return getSession(sessionListener, channel, netconfMessage);
162     }
163
164     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
165         throws NetconfDocumentedException;
166
167     /**
168      * Insert chunk framing handlers into the pipeline.
169      */
170     private void insertChunkFramingToPipeline() {
171         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
172                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
173         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
174                 new NetconfChunkAggregator());
175     }
176
177     private boolean shouldUseChunkFraming(final Document doc) {
178         return containsBase11Capability(doc) && containsBase11Capability(localHello.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     private synchronized void changeState(final State newState) {
220         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
221         checkState(isStateChangePermitted(state, newState),
222                 "Cannot change state from %s to %s for channel %s", state, newState, channel);
223         this.state = newState;
224     }
225
226     private static boolean containsBase11Capability(final Document doc) {
227         final NodeList nList = doc.getElementsByTagNameNS(
228             XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
229             XmlNetconfConstants.CAPABILITY);
230         for (int i = 0; i < nList.getLength(); i++) {
231             if (nList.item(i).getTextContent().contains(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1)) {
232                 return true;
233             }
234         }
235         return false;
236     }
237
238     private static boolean isStateChangePermitted(final State state, final State newState) {
239         if (state == State.IDLE && newState == State.OPEN_WAIT) {
240             return true;
241         }
242         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
243             return true;
244         }
245         if (state == State.OPEN_WAIT && newState == State.FAILED) {
246             return true;
247         }
248         LOG.debug("Transition from {} to {} is not allowed", state, newState);
249         return false;
250     }
251
252     /**
253      * Handler to catch exceptions in pipeline during negotiation.
254      */
255     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
256         @Override
257         public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
258             LOG.warn("An exception occurred during negotiation with {} on channel {}",
259                     channel.remoteAddress(), channel, cause);
260             // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
261             cancelTimeout();
262             negotiationFailed(cause);
263             changeState(State.FAILED);
264         }
265     }
266
267     protected final void negotiationSuccessful(final S session) {
268         LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
269         channel.pipeline().replace(this, "session", session);
270         promise.setSuccess(session);
271     }
272
273     protected void negotiationFailed(final Throwable cause) {
274         LOG.debug("Negotiation on channel {} failed", channel, cause);
275         channel.close();
276         promise.setFailure(cause);
277     }
278
279     /**
280      * Send a message to peer and fail negotiation if it does not reach
281      * the peer.
282      *
283      * @param msg Message which should be sent.
284      */
285     protected final void sendMessage(final NetconfMessage msg) {
286         this.channel.writeAndFlush(msg).addListener(f -> {
287             if (!f.isSuccess()) {
288                 LOG.info("Failed to send message {} on channel {}", msg, channel, f.cause());
289                 negotiationFailed(f.cause());
290             } else {
291                 LOG.trace("Message {} sent to socket on channel {}", msg, channel);
292             }
293         });
294     }
295
296     @Override
297     @SuppressWarnings("checkstyle:illegalCatch")
298     public final void channelActive(final ChannelHandlerContext ctx) {
299         LOG.debug("Starting session negotiation on channel {}", channel);
300         try {
301             startNegotiation();
302         } catch (final Exception e) {
303             LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
304             negotiationFailed(e);
305         }
306     }
307
308     @Override
309     @SuppressWarnings("checkstyle:illegalCatch")
310     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
311         LOG.debug("Negotiation read invoked on channel {}", channel);
312         try {
313             handleMessage((NetconfHelloMessage) msg);
314         } catch (final Exception e) {
315             LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
316             negotiationFailed(e);
317         }
318     }
319
320     @Override
321     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
322         LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
323         negotiationFailed(cause);
324     }
325
326     protected abstract void handleMessage(NetconfHelloMessage msg) throws Exception;
327 }