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;
14 import io.netty.channel.Channel;
15 import io.netty.handler.ssl.SslHandler;
16 import io.netty.util.Timeout;
17 import io.netty.util.Timer;
18 import io.netty.util.TimerTask;
19 import io.netty.util.concurrent.Future;
20 import io.netty.util.concurrent.GenericFutureListener;
21 import io.netty.util.concurrent.Promise;
23 import org.opendaylight.controller.netconf.api.NetconfSession;
24 import org.opendaylight.controller.netconf.api.NetconfMessage;
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> {
46 private static final long INITIAL_HOLDTIMER = 1;
47 private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
49 protected final P sessionPreferences;
51 private final SessionListener sessionListener;
54 * Possible states for Finite State Machine
57 IDLE, OPEN_WAIT, FAILED, ESTABLISHED
60 private State state = State.IDLE;
61 private final Timer timer;
63 protected AbstractNetconfSessionNegotiator(P sessionPreferences, Promise<S> promise, Channel channel, Timer timer,
64 SessionListener sessionListener) {
65 super(promise, channel);
66 this.sessionPreferences = sessionPreferences;
68 this.sessionListener = sessionListener;
72 protected void startNegotiation() throws Exception {
73 final Optional<SslHandler> sslHandler = getSslHandler(channel);
74 if (sslHandler.isPresent()) {
75 Future<Channel> future = sslHandler.get().handshakeFuture();
76 future.addListener(new GenericFutureListener<Future<? super Channel>>() {
78 public void operationComplete(Future<? super Channel> future) throws Exception {
79 Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
80 logger.debug("Ssl handshake complete");
88 private static Optional<SslHandler> getSslHandler(Channel channel) {
89 final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
90 return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
93 private void start() {
94 final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
95 logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
97 sendMessage(helloMessage);
98 changeState(State.OPEN_WAIT);
100 this.timer.newTimeout(new TimerTask() {
102 public void run(final Timeout timeout) throws Exception {
103 synchronized (this) {
104 if (state != State.ESTABLISHED) {
105 final IllegalStateException cause = new IllegalStateException(
106 "Session was not established after " + timeout);
107 negotiationFailed(cause);
108 changeState(State.FAILED);
112 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
115 private void sendMessage(NetconfMessage message) {
116 this.channel.writeAndFlush(message);
120 protected void handleMessage(NetconfMessage netconfMessage) {
121 final Document doc = netconfMessage.getDocument();
123 if (isHelloMessage(doc)) {
124 if (containsBase11Capability(doc)
125 && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument())) {
126 channel.pipeline().replace("frameEncoder", "frameEncoder",
127 FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
128 channel.pipeline().replace("aggregator", "aggregator",
129 new NetconfMessageAggregator(FramingMechanism.CHUNK));
130 channel.pipeline().addAfter("aggregator", "chunkDecoder", new NetconfMessageChunkDecoder());
132 changeState(State.ESTABLISHED);
133 S session = getSession(sessionListener, channel, netconfMessage);
134 negotiationSuccessful(session);
136 final IllegalStateException cause = new IllegalStateException(
137 "Received message was not hello as expected, but was " + XmlUtil.toString(doc));
138 logger.warn("Negotiation of netconf session failed", cause);
139 negotiationFailed(cause);
143 protected abstract S getSession(SessionListener sessionListener, Channel channel, NetconfMessage message);
145 private boolean isHelloMessage(Document doc) {
147 XmlElement.fromDomElementWithExpected(doc.getDocumentElement(), "hello",
148 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
150 } catch (IllegalArgumentException | IllegalStateException e) {
156 private void changeState(final State newState) {
157 logger.debug("Changing state from : {} to : {}", state, newState);
158 Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
160 this.state = newState;
163 private boolean containsBase11Capability(final Document doc) {
164 final NodeList nList = doc.getElementsByTagName("capability");
165 for (int i = 0; i < nList.getLength(); i++) {
166 if (nList.item(i).getTextContent().contains("base:1.1")) {
173 private static boolean isStateChangePermitted(State state, State newState) {
174 if (state == State.IDLE && newState == State.OPEN_WAIT)
176 if (state == State.OPEN_WAIT && newState == State.ESTABLISHED)
178 if (state == State.OPEN_WAIT && newState == State.FAILED)