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