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.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;
21 import java.util.Collection;
23 import javax.xml.xpath.XPathConstants;
24 import javax.xml.xpath.XPathExpression;
26 import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
27 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.controller.netconf.api.NetconfMessage;
29 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
30 import org.opendaylight.controller.netconf.nettyutil.AbstractChannelInitializer;
31 import org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSessionNegotiator;
32 import org.opendaylight.controller.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
33 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
34 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
35 import org.opendaylight.controller.netconf.util.xml.XMLNetconfUtil;
36 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.w3c.dom.Document;
40 import org.w3c.dom.Node;
41 import org.w3c.dom.NodeList;
43 public class NetconfClientSessionNegotiator extends
44 AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession, NetconfClientSessionListener>
46 private static final Logger logger = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
48 private static final XPathExpression sessionIdXPath = XMLNetconfUtil
49 .compileXPath("/netconf:hello/netconf:session-id");
51 private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
53 protected NetconfClientSessionNegotiator(final NetconfClientSessionPreferences sessionPreferences,
54 final Promise<NetconfClientSession> promise,
55 final Channel channel,
57 final NetconfClientSessionListener sessionListener,
58 final long connectionTimeoutMillis) {
59 super(sessionPreferences, promise, channel, timer, sessionListener, connectionTimeoutMillis);
63 protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
64 final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
65 replaceHelloMessageInboundHandler(session);
67 // If exi should be used, try to initiate exi communication
68 // Call negotiationSuccessFul after exi negotiation is finished successfully or not
69 if (shouldUseExi(netconfMessage)) {
70 logger.debug("Netconf session {} should use exi.", session);
71 NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage();
72 tryToInitiateExi(session, startExiMessage);
73 // Exi is not supported, release session immediately
75 logger.debug("Netconf session {} isn't capable of using exi.", session);
76 negotiationSuccessful(session);
81 * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
83 * @param startExiMessage
85 void tryToInitiateExi(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
86 channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
87 ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER,
88 new ExiConfirmationInboundHandler(session, startExiMessage));
90 session.sendMessage(startExiMessage).addListener(new ChannelFutureListener() {
92 public void operationComplete(final ChannelFuture f) {
94 logger.warn("Failed to send start-exi message {} on session {}", startExiMessage, this, f.cause());
95 channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
97 logger.trace("Start-exi message {} sent to socket on session {}", startExiMessage, this);
103 private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
104 return containsExi10Capability(helloMsg.getDocument())
105 && containsExi10Capability(sessionPreferences.getHelloMessage().getDocument());
108 private boolean containsExi10Capability(final Document doc) {
109 final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
110 for (int i = 0; i < nList.getLength(); i++) {
111 if (nList.item(i).getTextContent().contains(EXI_1_0_CAPABILITY_MARKER)) {
118 private long extractSessionId(final Document doc) {
119 final Node sessionIdNode = (Node) XmlUtil.evaluateXPath(sessionIdXPath, doc, XPathConstants.NODE);
120 String textContent = sessionIdNode.getTextContent();
121 if (textContent == null || textContent.equals("")) {
122 throw new IllegalStateException("Session id not received from server");
125 return Long.valueOf(textContent);
129 protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
130 final NetconfHelloMessage message) throws NetconfDocumentedException {
131 long sessionId = extractSessionId(message.getDocument());
133 // Copy here is important: it disconnects the strings from the document
134 Collection<String> capabilities = ImmutableList.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message.getDocument()));
136 // FIXME: scalability: we could instantiate a cache to share the same collections
137 return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
141 * Handler to process response for start-exi message
143 private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
144 private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
146 private final NetconfClientSession session;
147 private final NetconfStartExiMessage startExiMessage;
149 ExiConfirmationInboundHandler(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
150 this.session = session;
151 this.startExiMessage = startExiMessage;
155 public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
156 ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
158 NetconfMessage netconfMessage = (NetconfMessage) msg;
160 // Ok response to start-exi, try to add exi handlers
161 if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
162 logger.trace("Positive response on start-exi call received on session {}", session);
164 session.startExiCommunication(startExiMessage);
165 } catch (RuntimeException e) {
166 // Unable to add exi, continue without exi
167 logger.warn("Unable to start exi communication, Communication will continue without exi on session {}", session, e);
171 } else if(NetconfMessageUtil.isErrorMessage(netconfMessage)) {
173 "Error response to start-exi message {}, Communication will continue without exi on session {}",
174 XmlUtil.toString(netconfMessage.getDocument()), session);
176 // Unexpected response to start-exi, throwing message away, continue without exi
179 "Unexpected response to start-exi message, should be ok, was {}, " +
180 "Communication will continue without exi and response message will be thrown away on session {}",
181 XmlUtil.toString(netconfMessage.getDocument()), session);
184 negotiationSuccessful(session);