Merge "Add some log messages in case controller failed to add connected node."
[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     // TODO what time ?
46     private static final long INITIAL_HOLDTIMER = 1;
47
48     private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
49     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
50
51     protected final P sessionPreferences;
52
53     private final SessionListener sessionListener;
54     private Timeout timeout;
55
56     /**
57      * Possible states for Finite State Machine
58      */
59     private enum State {
60         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
61     }
62
63     private State state = State.IDLE;
64     private final Timer timer;
65
66     protected AbstractNetconfSessionNegotiator(P sessionPreferences, Promise<S> promise, Channel channel, Timer timer,
67             SessionListener sessionListener) {
68         super(promise, channel);
69         this.sessionPreferences = sessionPreferences;
70         this.timer = timer;
71         this.sessionListener = sessionListener;
72     }
73
74     @Override
75     protected void startNegotiation() {
76         final Optional<SslHandler> sslHandler = getSslHandler(channel);
77         if (sslHandler.isPresent()) {
78             Future<Channel> future = sslHandler.get().handshakeFuture();
79             future.addListener(new GenericFutureListener<Future<? super Channel>>() {
80                 @Override
81                 public void operationComplete(Future<? super Channel> future) throws Exception {
82                     Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
83                     logger.debug("Ssl handshake complete");
84                     start();
85                 }
86             });
87         } else
88             start();
89     }
90
91     private static Optional<SslHandler> getSslHandler(Channel channel) {
92         final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
93         return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
94     }
95
96     private void start() {
97         final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
98         logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
99
100         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ChannelHandler() {
101             @Override
102             public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
103             }
104
105             @Override
106             public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
107             }
108
109             @Override
110             public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
111                 logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
112                 cancelTimeout();
113                 negotiationFailed(cause);
114                 changeState(State.FAILED);
115             }
116         });
117
118         timeout = this.timer.newTimeout(new TimerTask() {
119             @Override
120             public void run(final Timeout timeout) throws Exception {
121                 synchronized (this) {
122                     if (state != State.ESTABLISHED) {
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         }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
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 }