Add configurable connection timeout to netconf client.
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / 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
9 package org.opendaylight.controller.netconf.util;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import io.netty.channel.Channel;
14 import io.netty.channel.ChannelHandler;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.handler.ssl.SslHandler;
17 import io.netty.util.Timeout;
18 import io.netty.util.Timer;
19 import io.netty.util.TimerTask;
20 import io.netty.util.concurrent.Future;
21 import io.netty.util.concurrent.GenericFutureListener;
22 import io.netty.util.concurrent.Promise;
23 import org.opendaylight.controller.netconf.api.NetconfMessage;
24 import org.opendaylight.controller.netconf.api.NetconfSession;
25 import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
26 import org.opendaylight.controller.netconf.util.handler.FramingMechanismHandlerFactory;
27 import org.opendaylight.controller.netconf.util.handler.NetconfMessageAggregator;
28 import org.opendaylight.controller.netconf.util.handler.NetconfMessageChunkDecoder;
29 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
30 import org.opendaylight.controller.netconf.util.xml.XmlElement;
31 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
32 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
33 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
34 import org.opendaylight.protocol.framework.SessionListener;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.w3c.dom.Document;
38 import org.w3c.dom.NodeList;
39
40 import java.util.concurrent.TimeUnit;
41
42 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends NetconfSession>
43         extends AbstractSessionNegotiator<NetconfMessage, S> {
44
45     private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
46     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
47
48     protected final P sessionPreferences;
49
50     private final SessionListener sessionListener;
51     private Timeout timeout;
52
53     /**
54      * Possible states for Finite State Machine
55      */
56     private enum State {
57         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
58     }
59
60     private State state = State.IDLE;
61     private final Timer timer;
62     private final long connectionTimeoutMillis;
63
64     protected AbstractNetconfSessionNegotiator(P sessionPreferences, Promise<S> promise, Channel channel, Timer timer,
65             SessionListener sessionListener, long connectionTimeoutMillis) {
66         super(promise, channel);
67         this.sessionPreferences = sessionPreferences;
68         this.timer = timer;
69         this.sessionListener = sessionListener;
70         this.connectionTimeoutMillis = connectionTimeoutMillis;
71     }
72
73     @Override
74     protected void startNegotiation() {
75         final Optional<SslHandler> sslHandler = getSslHandler(channel);
76         if (sslHandler.isPresent()) {
77             Future<Channel> future = sslHandler.get().handshakeFuture();
78             future.addListener(new GenericFutureListener<Future<? super Channel>>() {
79                 @Override
80                 public void operationComplete(Future<? super Channel> future) throws Exception {
81                     Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
82                     logger.debug("Ssl handshake complete");
83                     start();
84                 }
85             });
86         } else
87             start();
88     }
89
90     private static Optional<SslHandler> getSslHandler(Channel channel) {
91         final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
92         return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
93     }
94
95     private void start() {
96         final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
97         logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
98
99         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ChannelHandler() {
100             @Override
101             public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
102             }
103
104             @Override
105             public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
106             }
107
108             @Override
109             public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
110                 logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
111                 cancelTimeout();
112                 negotiationFailed(cause);
113                 changeState(State.FAILED);
114             }
115         });
116
117         timeout = this.timer.newTimeout(new TimerTask() {
118             @Override
119             public void run(final Timeout timeout) throws Exception {
120                 synchronized (this) {
121                     if (state != State.ESTABLISHED) {
122                         logger.debug("Connection timeout after {}", timeout);
123                         final IllegalStateException cause = new IllegalStateException(
124                                 "Session was not established after " + timeout);
125                         negotiationFailed(cause);
126                         changeState(State.FAILED);
127                     } else if(channel.isOpen()) {
128                         channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
129                     }
130                 }
131             }
132         }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
133
134         sendMessage(helloMessage);
135         changeState(State.OPEN_WAIT);
136     }
137
138     private void cancelTimeout() {
139         if(timeout!=null)
140             timeout.cancel();
141     }
142
143     private void sendMessage(NetconfMessage message) {
144         this.channel.writeAndFlush(message);
145     }
146
147     @Override
148     protected void handleMessage(NetconfMessage netconfMessage) {
149         final Document doc = netconfMessage.getDocument();
150
151         if (isHelloMessage(doc)) {
152             if (containsBase11Capability(doc)
153                     && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument())) {
154                 channel.pipeline().replace("frameEncoder", "frameEncoder",
155                         FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
156                 channel.pipeline().replace("aggregator", "aggregator",
157                         new NetconfMessageAggregator(FramingMechanism.CHUNK));
158                 channel.pipeline().addAfter("aggregator", "chunkDecoder", new NetconfMessageChunkDecoder());
159             }
160             changeState(State.ESTABLISHED);
161             S session = getSession(sessionListener, channel, netconfMessage);
162             negotiationSuccessful(session);
163         } else {
164             final IllegalStateException cause = new IllegalStateException(
165                     "Received message was not hello as expected, but was " + XmlUtil.toString(doc));
166             logger.warn("Negotiation of netconf session failed", cause);
167             negotiationFailed(cause);
168         }
169     }
170
171     protected abstract S getSession(SessionListener sessionListener, Channel channel, NetconfMessage message);
172
173     private boolean isHelloMessage(Document doc) {
174         try {
175             XmlElement.fromDomElementWithExpected(doc.getDocumentElement(), "hello",
176                     XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
177
178         } catch (IllegalArgumentException | IllegalStateException e) {
179             return false;
180         }
181         return true;
182     }
183
184     private void changeState(final State newState) {
185         logger.debug("Changing state from : {} to : {}", state, newState);
186         Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
187                 newState);
188         this.state = newState;
189     }
190
191     private boolean containsBase11Capability(final Document doc) {
192         final NodeList nList = doc.getElementsByTagName("capability");
193         for (int i = 0; i < nList.getLength(); i++) {
194             if (nList.item(i).getTextContent().contains("base:1.1")) {
195                 return true;
196             }
197         }
198         return false;
199     }
200
201     private static boolean isStateChangePermitted(State state, State newState) {
202         if (state == State.IDLE && newState == State.OPEN_WAIT)
203             return true;
204         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED)
205             return true;
206         if (state == State.OPEN_WAIT && newState == State.FAILED)
207             return true;
208
209         return false;
210     }
211 }