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.netconf.client;
11 import com.google.common.base.Strings;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.Interner;
14 import com.google.common.collect.Interners;
15 import io.netty.channel.Channel;
16 import io.netty.channel.ChannelFuture;
17 import io.netty.channel.ChannelFutureListener;
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.channel.ChannelInboundHandlerAdapter;
20 import io.netty.util.Timer;
21 import io.netty.util.concurrent.Promise;
23 import javax.xml.xpath.XPathConstants;
24 import javax.xml.xpath.XPathExpression;
25 import org.opendaylight.controller.config.util.xml.XmlUtil;
26 import org.opendaylight.netconf.api.NetconfClientSessionPreferences;
27 import org.opendaylight.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.netconf.api.NetconfMessage;
29 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
30 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
31 import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
32 import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
33 import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
34 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
35 import org.opendaylight.netconf.util.xml.XMLNetconfUtil;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Node;
40 import org.w3c.dom.NodeList;
42 public class NetconfClientSessionNegotiator extends
43 AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession,
44 NetconfClientSessionListener> {
45 private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
47 private static final XPathExpression SESSION_ID_X_PATH = XMLNetconfUtil
48 .compileXPath("/netconf:hello/netconf:session-id");
50 private static final XPathExpression SESSION_ID_X_PATH_NO_NAMESPACE = XMLNetconfUtil
51 .compileXPath("/hello/session-id");
53 private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
55 private static final Interner<Set<String>> INTERNER = Interners.newWeakInterner();
57 protected NetconfClientSessionNegotiator(final NetconfClientSessionPreferences sessionPreferences,
58 final Promise<NetconfClientSession> promise,
59 final Channel channel,
61 final NetconfClientSessionListener sessionListener,
62 final long connectionTimeoutMillis) {
63 super(sessionPreferences, promise, channel, timer, sessionListener, connectionTimeoutMillis);
66 @SuppressWarnings("checkstyle:IllegalCatch")
68 protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
69 if (!ifNegotiatedAlready()) {
70 LOG.debug("Server hello message received, starting negotiation on channel {}", channel);
73 } catch (final Exception e) {
74 LOG.warn("Unexpected negotiation failure", e);
79 final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
80 replaceHelloMessageInboundHandler(session);
82 // If exi should be used, try to initiate exi communication
83 // Call negotiationSuccessFul after exi negotiation is finished successfully or not
84 if (shouldUseExi(netconfMessage)) {
85 LOG.debug("Netconf session {} should use exi.", session);
86 NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage();
87 tryToInitiateExi(session, startExiMessage);
89 // Exi is not supported, release session immediately
90 LOG.debug("Netconf session {} isn't capable of using exi.", session);
91 negotiationSuccessful(session);
96 * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
98 * @param startExiMessage Exi message for initilization of exi communication.
100 void tryToInitiateExi(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
101 channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
102 ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER,
103 new ExiConfirmationInboundHandler(session, startExiMessage));
105 session.sendMessage(startExiMessage).addListener(new ChannelFutureListener() {
107 public void operationComplete(final ChannelFuture channelFuture) {
108 if (!channelFuture.isSuccess()) {
109 LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, this,
110 channelFuture.cause());
111 channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
113 LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, this);
119 private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
120 return containsExi10Capability(helloMsg.getDocument())
121 && containsExi10Capability(sessionPreferences.getHelloMessage().getDocument());
124 private static boolean containsExi10Capability(final Document doc) {
125 final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
126 for (int i = 0; i < nList.getLength(); i++) {
127 if (nList.item(i).getTextContent().contains(EXI_1_0_CAPABILITY_MARKER)) {
134 private static long extractSessionId(final Document doc) {
135 String textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH);
136 if (Strings.isNullOrEmpty(textContent)) {
137 textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH_NO_NAMESPACE);
138 if (Strings.isNullOrEmpty(textContent)) {
139 throw new IllegalStateException("Session id not received from server, hello message: " + XmlUtil
144 return Long.valueOf(textContent);
147 private static String getSessionIdWithXPath(final Document doc, final XPathExpression sessionIdXPath) {
148 final Node sessionIdNode = (Node) XmlUtil.evaluateXPath(sessionIdXPath, doc, XPathConstants.NODE);
149 return sessionIdNode != null ? sessionIdNode.getTextContent() : null;
153 protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
154 final NetconfHelloMessage message) throws NetconfDocumentedException {
155 final long sessionId = extractSessionId(message.getDocument());
157 // Copy here is important: it disconnects the strings from the document
158 Set<String> capabilities = ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message
161 capabilities = INTERNER.intern(capabilities);
163 return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
167 * Handler to process response for start-exi message.
169 private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
170 private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
172 private final NetconfClientSession session;
173 private final NetconfStartExiMessage startExiMessage;
175 ExiConfirmationInboundHandler(final NetconfClientSession session,
176 final NetconfStartExiMessage startExiMessage) {
177 this.session = session;
178 this.startExiMessage = startExiMessage;
181 @SuppressWarnings("checkstyle:IllegalCatch")
183 public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
184 ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
186 NetconfMessage netconfMessage = (NetconfMessage) msg;
188 // Ok response to start-exi, try to add exi handlers
189 if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
190 LOG.trace("Positive response on start-exi call received on session {}", session);
192 session.startExiCommunication(startExiMessage);
193 } catch (RuntimeException e) {
194 // Unable to add exi, continue without exi
195 LOG.warn("Unable to start exi communication, Communication will continue without exi on session "
200 } else if (NetconfMessageUtil.isErrorMessage(netconfMessage)) {
202 "Error response to start-exi message {}, Communication will continue without exi on session {}",
203 netconfMessage, session);
205 // Unexpected response to start-exi, throwing message away, continue without exi
207 LOG.warn("Unexpected response to start-exi message, should be ok, was {}, "
208 + "Communication will continue without exi "
209 + "and response message will be thrown away on session {}",
210 netconfMessage, session);
213 negotiationSuccessful(session);