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.client;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import io.netty.channel.Channel;
14 import io.netty.channel.ChannelFuture;
15 import io.netty.channel.ChannelFutureListener;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.channel.ChannelInboundHandlerAdapter;
18 import io.netty.util.Timer;
19 import io.netty.util.concurrent.Promise;
20 import java.util.Collection;
21 import javax.xml.xpath.XPathConstants;
22 import javax.xml.xpath.XPathExpression;
23 import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
24 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.controller.netconf.api.NetconfMessage;
26 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
27 import org.opendaylight.controller.netconf.nettyutil.AbstractChannelInitializer;
28 import org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSessionNegotiator;
29 import org.opendaylight.controller.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
30 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
31 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
32 import org.opendaylight.controller.netconf.util.xml.XMLNetconfUtil;
33 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Node;
38 import org.w3c.dom.NodeList;
40 public class NetconfClientSessionNegotiator extends
41 AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession, NetconfClientSessionListener>
43 private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
45 private static final XPathExpression sessionIdXPath = XMLNetconfUtil
46 .compileXPath("/netconf:hello/netconf:session-id");
48 private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
50 protected NetconfClientSessionNegotiator(final NetconfClientSessionPreferences sessionPreferences,
51 final Promise<NetconfClientSession> promise,
52 final Channel channel,
54 final NetconfClientSessionListener sessionListener,
55 final long connectionTimeoutMillis) {
56 super(sessionPreferences, promise, channel, timer, sessionListener, connectionTimeoutMillis);
60 protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
61 final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
62 replaceHelloMessageInboundHandler(session);
64 // If exi should be used, try to initiate exi communication
65 // Call negotiationSuccessFul after exi negotiation is finished successfully or not
66 if (shouldUseExi(netconfMessage)) {
67 LOG.debug("Netconf session {} should use exi.", session);
68 NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage();
69 tryToInitiateExi(session, startExiMessage);
71 // Exi is not supported, release session immediately
72 LOG.debug("Netconf session {} isn't capable of using exi.", session);
73 negotiationSuccessful(session);
78 * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
80 * @param startExiMessage
82 void tryToInitiateExi(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
83 channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
84 ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER,
85 new ExiConfirmationInboundHandler(session, startExiMessage));
87 session.sendMessage(startExiMessage).addListener(new ChannelFutureListener() {
89 public void operationComplete(final ChannelFuture f) {
91 LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, this, f.cause());
92 channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
94 LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, this);
100 private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
101 return containsExi10Capability(helloMsg.getDocument())
102 && containsExi10Capability(sessionPreferences.getHelloMessage().getDocument());
105 private boolean containsExi10Capability(final Document doc) {
106 final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
107 for (int i = 0; i < nList.getLength(); i++) {
108 if (nList.item(i).getTextContent().contains(EXI_1_0_CAPABILITY_MARKER)) {
115 private long extractSessionId(final Document doc) {
116 final Node sessionIdNode = (Node) XmlUtil.evaluateXPath(sessionIdXPath, doc, XPathConstants.NODE);
117 Preconditions.checkState(sessionIdNode != null, "");
118 String textContent = sessionIdNode.getTextContent();
119 if (textContent == null || textContent.equals("")) {
120 throw new IllegalStateException("Session id not received from server");
123 return Long.valueOf(textContent);
127 protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
128 final NetconfHelloMessage message) throws NetconfDocumentedException {
129 long sessionId = extractSessionId(message.getDocument());
131 // Copy here is important: it disconnects the strings from the document
132 Collection<String> capabilities = ImmutableList.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message.getDocument()));
134 // FIXME: scalability: we could instantiate a cache to share the same collections
135 return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
139 * Handler to process response for start-exi message
141 private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
142 private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
144 private final NetconfClientSession session;
145 private final NetconfStartExiMessage startExiMessage;
147 ExiConfirmationInboundHandler(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
148 this.session = session;
149 this.startExiMessage = startExiMessage;
153 public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
154 ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
156 NetconfMessage netconfMessage = (NetconfMessage) msg;
158 // Ok response to start-exi, try to add exi handlers
159 if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
160 LOG.trace("Positive response on start-exi call received on session {}", session);
162 session.startExiCommunication(startExiMessage);
163 } catch (RuntimeException e) {
164 // Unable to add exi, continue without exi
165 LOG.warn("Unable to start exi communication, Communication will continue without exi on session {}", session, e);
169 } else if(NetconfMessageUtil.isErrorMessage(netconfMessage)) {
171 "Error response to start-exi message {}, Communication will continue without exi on session {}",
172 netconfMessage, session);
174 // Unexpected response to start-exi, throwing message away, continue without exi
176 LOG.warn("Unexpected response to start-exi message, should be ok, was {}, " +
177 "Communication will continue without exi and response message will be thrown away on session {}",
178 netconfMessage, session);
181 negotiationSuccessful(session);