2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.util;
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;
40 import java.util.concurrent.TimeUnit;
42 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends NetconfSession>
43 extends AbstractSessionNegotiator<NetconfMessage, S> {
45 private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
46 public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
48 protected final P sessionPreferences;
50 private final SessionListener sessionListener;
51 private Timeout timeout;
54 * Possible states for Finite State Machine
57 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
60 private State state = State.IDLE;
61 private final Timer timer;
62 private final long connectionTimeoutMillis;
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;
69 this.sessionListener = sessionListener;
70 this.connectionTimeoutMillis = connectionTimeoutMillis;
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>>() {
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");
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);
95 private void start() {
96 final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
97 logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
99 channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ChannelHandler() {
101 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
105 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
109 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
110 logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
112 negotiationFailed(cause);
113 changeState(State.FAILED);
117 timeout = this.timer.newTimeout(new TimerTask() {
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);
132 }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
134 sendMessage(helloMessage);
135 changeState(State.OPEN_WAIT);
138 private void cancelTimeout() {
143 private void sendMessage(NetconfMessage message) {
144 this.channel.writeAndFlush(message);
148 protected void handleMessage(NetconfMessage netconfMessage) {
149 final Document doc = netconfMessage.getDocument();
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());
160 changeState(State.ESTABLISHED);
161 S session = getSession(sessionListener, channel, netconfMessage);
162 negotiationSuccessful(session);
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);
171 protected abstract S getSession(SessionListener sessionListener, Channel channel, NetconfMessage message);
173 private boolean isHelloMessage(Document doc) {
175 XmlElement.fromDomElementWithExpected(doc.getDocumentElement(), "hello",
176 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
178 } catch (IllegalArgumentException | IllegalStateException e) {
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,
188 this.state = newState;
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")) {
201 private static boolean isStateChangePermitted(State state, State newState) {
202 if (state == State.IDLE && newState == State.OPEN_WAIT)
204 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED)
206 if (state == State.OPEN_WAIT && newState == State.FAILED)