a2af2f3103df21a6f31469a4bc386f07b4904c0c
[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.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import io.netty.channel.Channel;
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.concurrent.Future;
23 import io.netty.util.concurrent.Promise;
24 import java.util.concurrent.TimeUnit;
25 import org.checkerframework.checker.index.qual.NonNegative;
26 import org.checkerframework.checker.lock.qual.GuardedBy;
27 import org.checkerframework.checker.lock.qual.Holding;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.netconf.api.CapabilityURN;
31 import org.opendaylight.netconf.api.NamespaceURN;
32 import org.opendaylight.netconf.api.NetconfDocumentedException;
33 import org.opendaylight.netconf.api.NetconfSessionListener;
34 import org.opendaylight.netconf.api.messages.FramingMechanism;
35 import org.opendaylight.netconf.api.messages.HelloMessage;
36 import org.opendaylight.netconf.api.messages.NetconfMessage;
37 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
38 import org.opendaylight.netconf.nettyutil.handler.FramingMechanismHandlerFactory;
39 import org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator;
40 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
41 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder;
42 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.NodeList;
47
48 public abstract class AbstractNetconfSessionNegotiator<S extends AbstractNetconfSession<S, L>,
49             L extends NetconfSessionListener<S>>
50             extends ChannelInboundHandlerAdapter implements NetconfSessionNegotiator<S> {
51     /**
52      * Possible states for Finite State Machine.
53      */
54     protected enum State {
55         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
56     }
57
58     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
59     private static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
60     private static final String DEFAULT_MAXIMUM_CHUNK_SIZE_PROP = "org.opendaylight.netconf.default.maximum.chunk.size";
61     private static final int DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
62
63     /**
64      * Default upper bound on the size of an individual chunk. This value can be controlled through
65      * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_PROP} system property and defaults to
66      * {@value #DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT} bytes.
67      */
68     @Beta
69     public static final @NonNegative int DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE;
70
71     static {
72         final int propValue = Integer.getInteger(DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT);
73         if (propValue <= 0) {
74             LOG.warn("Ignoring invalid {} value {}", DEFAULT_MAXIMUM_CHUNK_SIZE_PROP, propValue);
75             DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = DEFAULT_MAXIMUM_CHUNK_SIZE_DEFAULT;
76         } else {
77             DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE = propValue;
78         }
79         LOG.debug("Default maximum incoming NETCONF chunk size is {} bytes", DEFAULT_MAXIMUM_INCOMING_CHUNK_SIZE);
80     }
81
82     private final @NonNull HelloMessage localHello;
83     protected final Channel channel;
84
85     private final @NonNegative int maximumIncomingChunkSize;
86     private final long connectionTimeoutMillis;
87     private final Promise<S> promise;
88     private final L sessionListener;
89     private final Timer timer;
90
91     @GuardedBy("this")
92     private Timeout timeoutTask;
93     @GuardedBy("this")
94     private State state = State.IDLE;
95
96     protected AbstractNetconfSessionNegotiator(final HelloMessage hello, final Promise<S> promise,
97                                                final Channel channel, final Timer timer, final L sessionListener,
98                                                final long connectionTimeoutMillis,
99                                                final @NonNegative int maximumIncomingChunkSize) {
100         localHello = requireNonNull(hello);
101         this.promise = requireNonNull(promise);
102         this.channel = requireNonNull(channel);
103         this.timer = timer;
104         this.sessionListener = sessionListener;
105         this.connectionTimeoutMillis = connectionTimeoutMillis;
106         this.maximumIncomingChunkSize = maximumIncomingChunkSize;
107         checkArgument(maximumIncomingChunkSize > 0, "Invalid maximum incoming chunk size %s", maximumIncomingChunkSize);
108     }
109
110     protected final @NonNull HelloMessage localHello() {
111         return localHello;
112     }
113
114     protected final void startNegotiation() {
115         if (ifNegotiatedAlready()) {
116             LOG.debug("Negotiation on channel {} already started", channel);
117         } else {
118             final var sslHandler = getSslHandler(channel);
119             if (sslHandler != null) {
120                 sslHandler.handshakeFuture().addListener(future -> {
121                     checkState(future.isSuccess(), "Ssl handshake was not successful");
122                     LOG.debug("Ssl handshake complete");
123                     start();
124                 });
125             } else {
126                 start();
127             }
128         }
129     }
130
131     protected final boolean ifNegotiatedAlready() {
132         // Indicates whether negotiation already started
133         return state() != State.IDLE;
134     }
135
136     private synchronized State state() {
137         return state;
138     }
139
140     private static @Nullable SslHandler getSslHandler(final Channel channel) {
141         return channel.pipeline().get(SslHandler.class);
142     }
143
144     private void start() {
145         LOG.debug("Sending negotiation proposal {} on channel {}", localHello, channel);
146
147         // Send the message out, but to not run listeners just yet, as we have some more state transitions to go through
148         final var helloFuture = channel.writeAndFlush(localHello);
149
150         // Quick check: if the future has already failed we call it quits before negotiation even started
151         final var helloCause = helloFuture.cause();
152         if (helloCause != null) {
153             LOG.warn("Failed to send negotiation proposal on channel {}", channel, helloCause);
154             failAndClose();
155             return;
156         }
157
158         // Catch any exceptions from this point on. Use a named class to ease debugging.
159         final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
160             @Override
161             public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
162                 LOG.warn("An exception occurred during negotiation with {} on channel {}",
163                         channel.remoteAddress(), channel, cause);
164                 // FIXME: this is quite suspect as it is competing with timeoutExpired() without synchronization
165                 cancelTimeout();
166                 negotiationFailed(cause);
167                 changeState(State.FAILED);
168             }
169         }
170
171         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
172
173         // Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
174         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
175             new NetconfMessageToXMLEncoder());
176
177         synchronized (this) {
178             lockedChangeState(State.OPEN_WAIT);
179
180             // Service the timeout on channel's eventloop, so that we do not get state transition problems
181             timeoutTask = timer.newTimeout(unused -> channel.eventLoop().execute(this::timeoutExpired),
182                 connectionTimeoutMillis, TimeUnit.MILLISECONDS);
183         }
184
185         LOG.debug("Session negotiation started on channel {}", channel);
186
187         // State transition completed, now run any additional processing
188         helloFuture.addListener(this::onHelloWriteComplete);
189     }
190
191     private void onHelloWriteComplete(final Future<?> future) {
192         final var cause = future.cause();
193         if (cause != null) {
194             LOG.info("Failed to send message {} on channel {}", localHello, channel, cause);
195             negotiationFailed(cause);
196         } else {
197             LOG.trace("Message {} sent to socket on channel {}", localHello, channel);
198         }
199     }
200
201     private synchronized void timeoutExpired() {
202         if (timeoutTask == null) {
203             // cancelTimeout() between expiry and execution on the loop
204             return;
205         }
206         timeoutTask = null;
207
208         if (state != State.ESTABLISHED) {
209             LOG.debug("Connection timeout after {}ms, session backed by channel {} is in state {}",
210                 connectionTimeoutMillis, channel, state);
211
212             // Do not fail negotiation if promise is done or canceled
213             // It would result in setting result of the promise second time and that throws exception
214             if (!promise.isDone() && !promise.isCancelled()) {
215                 LOG.warn("Netconf session backed by channel {} was not established after {}", channel,
216                     connectionTimeoutMillis);
217                 failAndClose();
218             }
219         } else if (channel.isOpen()) {
220             channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
221         }
222     }
223
224     private void failAndClose() {
225         changeState(State.FAILED);
226         channel.close().addListener(this::onChannelClosed);
227     }
228
229     private void onChannelClosed(final Future<?> future) {
230         final var cause = future.cause();
231         if (cause != null) {
232             LOG.warn("Channel {} closed: fail", channel, cause);
233         } else {
234             LOG.debug("Channel {} closed: success", channel);
235         }
236     }
237
238     private synchronized void cancelTimeout() {
239         if (timeoutTask != null && !timeoutTask.cancel()) {
240             // Late-coming cancel: make sure the task does not actually run
241             timeoutTask = null;
242         }
243     }
244
245     protected final S getSessionForHelloMessage(final HelloMessage netconfMessage)
246             throws NetconfDocumentedException {
247         final Document doc = netconfMessage.getDocument();
248
249         if (shouldUseChunkFraming(doc)) {
250             insertChunkFramingToPipeline();
251         }
252
253         changeState(State.ESTABLISHED);
254         return getSession(sessionListener, channel, netconfMessage);
255     }
256
257     protected abstract S getSession(L sessionListener, Channel channel, HelloMessage message)
258         throws NetconfDocumentedException;
259
260     /**
261      * Insert chunk framing handlers into the pipeline.
262      */
263     private void insertChunkFramingToPipeline() {
264         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
265                 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
266         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_AGGREGATOR,
267                 new NetconfChunkAggregator(maximumIncomingChunkSize));
268     }
269
270     private boolean shouldUseChunkFraming(final Document doc) {
271         return containsBase11Capability(doc) && containsBase11Capability(localHello.getDocument());
272     }
273
274     /**
275      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
276      *
277      * <p>
278      * Inbound hello message handler should be kept until negotiation is successful
279      * It caches any non-hello messages while negotiation is still in progress
280      */
281     protected final void replaceHelloMessageInboundHandler(final S session) {
282         ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
283                 AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
284
285         checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
286                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
287         Iterable<NetconfMessage> netconfMessagesFromNegotiation =
288                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
289
290         // Process messages received during negotiation
291         // The hello message handler does not have to be synchronized,
292         // since it is always call from the same thread by netty.
293         // It means, we are now using the thread now
294         for (NetconfMessage message : netconfMessagesFromNegotiation) {
295             session.handleMessage(message);
296         }
297     }
298
299     private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
300                                                         final ChannelHandler decoder) {
301         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
302     }
303
304     private synchronized void changeState(final State newState) {
305         lockedChangeState(newState);
306     }
307
308     @Holding("this")
309     private void lockedChangeState(final State newState) {
310         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
311         checkState(isStateChangePermitted(state, newState),
312                 "Cannot change state from %s to %s for channel %s", state, newState, channel);
313         state = newState;
314     }
315
316     private static boolean containsBase11Capability(final Document doc) {
317         final NodeList nList = doc.getElementsByTagNameNS(NamespaceURN.BASE, XmlNetconfConstants.CAPABILITY);
318         for (int i = 0; i < nList.getLength(); i++) {
319             if (nList.item(i).getTextContent().contains(CapabilityURN.BASE_1_1)) {
320                 return true;
321             }
322         }
323         return false;
324     }
325
326     private static boolean isStateChangePermitted(final State state, final State newState) {
327         if (state == State.IDLE && (newState == State.OPEN_WAIT || newState == State.FAILED)) {
328             return true;
329         }
330         if (state == State.OPEN_WAIT && (newState == State.ESTABLISHED || newState == State.FAILED)) {
331             return true;
332         }
333         LOG.debug("Transition from {} to {} is not allowed", state, newState);
334         return false;
335     }
336
337     protected final void negotiationSuccessful(final S session) {
338         LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
339         channel.pipeline().replace(this, "session", session);
340         promise.setSuccess(session);
341     }
342
343     protected void negotiationFailed(final Throwable cause) {
344         LOG.debug("Negotiation on channel {} failed", channel, cause);
345         channel.close();
346         promise.setFailure(cause);
347     }
348
349     @Override
350     @SuppressWarnings("checkstyle:illegalCatch")
351     public final void channelActive(final ChannelHandlerContext ctx) {
352         LOG.debug("Starting session negotiation on channel {}", channel);
353         try {
354             startNegotiation();
355         } catch (final Exception e) {
356             LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
357             negotiationFailed(e);
358         }
359     }
360
361     @Override
362     @SuppressWarnings("checkstyle:illegalCatch")
363     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
364         if (state() == State.FAILED) {
365             // We have already failed -- do not process any more messages
366             return;
367         }
368
369         LOG.debug("Negotiation read invoked on channel {}", channel);
370         try {
371             handleMessage((HelloMessage) msg);
372         } catch (final Exception e) {
373             LOG.debug("Unexpected error while handling negotiation message {} on channel {}", msg, channel, e);
374             negotiationFailed(e);
375         }
376     }
377
378     @Override
379     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
380         LOG.info("Unexpected error during negotiation on channel {}", channel, cause);
381         negotiationFailed(cause);
382     }
383
384     protected abstract void handleMessage(HelloMessage msg) throws Exception;
385 }