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
8 package org.opendaylight.netconf.client;
10 import com.google.common.base.Strings;
11 import com.google.common.collect.ImmutableSet;
12 import com.google.common.collect.Interner;
13 import com.google.common.collect.Interners;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.channel.ChannelInboundHandlerAdapter;
17 import io.netty.util.Timer;
18 import io.netty.util.concurrent.Promise;
20 import javax.xml.xpath.XPathConstants;
21 import javax.xml.xpath.XPathExpression;
22 import org.opendaylight.netconf.api.NetconfDocumentedException;
23 import org.opendaylight.netconf.api.NetconfMessage;
24 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
25 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
26 import org.opendaylight.netconf.api.xml.XmlUtil;
27 import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
28 import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
29 import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
30 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
31 import org.opendaylight.netconf.util.xml.XMLNetconfUtil;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.w3c.dom.Document;
35 import org.w3c.dom.Node;
36 import org.w3c.dom.NodeList;
38 // Non-final for mocking
39 class NetconfClientSessionNegotiator
40 extends AbstractNetconfSessionNegotiator<NetconfClientSession, NetconfClientSessionListener> {
41 private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
43 private static final XPathExpression SESSION_ID_X_PATH = XMLNetconfUtil
44 .compileXPath("/netconf:hello/netconf:session-id");
46 private static final XPathExpression SESSION_ID_X_PATH_NO_NAMESPACE = XMLNetconfUtil
47 .compileXPath("/hello/session-id");
49 private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
51 private static final Interner<Set<String>> INTERNER = Interners.newWeakInterner();
53 private final NetconfStartExiMessage startExi;
55 NetconfClientSessionNegotiator(final NetconfHelloMessage hello, final NetconfStartExiMessage startExi,
56 final Promise<NetconfClientSession> promise, final Channel channel, final Timer timer,
57 final NetconfClientSessionListener sessionListener, final long connectionTimeoutMillis) {
58 super(hello, promise, channel, timer, sessionListener, connectionTimeoutMillis);
59 this.startExi = startExi;
62 @SuppressWarnings("checkstyle:IllegalCatch")
64 protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
65 if (!ifNegotiatedAlready()) {
66 LOG.debug("Server hello message received, starting negotiation on channel {}", channel);
69 } catch (final Exception e) {
70 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
75 final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
76 replaceHelloMessageInboundHandler(session);
78 // If exi should be used, try to initiate exi communication
79 // Call negotiationSuccessFul after exi negotiation is finished successfully or not
80 if (startExi != null && shouldUseExi(netconfMessage)) {
81 LOG.debug("Netconf session {} should use exi.", session);
82 tryToInitiateExi(session, startExi);
84 // Exi is not supported, release session immediately
85 LOG.debug("Netconf session {} isn't capable of using exi.", session);
86 negotiationSuccessful(session);
91 * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
93 * @param startExiMessage Exi message for initilization of exi communication.
95 void tryToInitiateExi(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
96 channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
97 ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER,
98 new ExiConfirmationInboundHandler(session, startExiMessage));
100 session.sendMessage(startExiMessage).addListener(channelFuture -> {
101 if (!channelFuture.isSuccess()) {
102 LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, session,
103 channelFuture.cause());
104 channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
106 LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, session);
111 private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
112 return containsExi10Capability(helloMsg.getDocument()) && containsExi10Capability(localHello().getDocument());
115 private static boolean containsExi10Capability(final Document doc) {
116 final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
117 for (int i = 0; i < nList.getLength(); i++) {
118 if (nList.item(i).getTextContent().contains(EXI_1_0_CAPABILITY_MARKER)) {
125 private static long extractSessionId(final Document doc) {
126 String textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH);
127 if (Strings.isNullOrEmpty(textContent)) {
128 textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH_NO_NAMESPACE);
129 if (Strings.isNullOrEmpty(textContent)) {
130 throw new IllegalStateException("Session id not received from server, hello message: " + XmlUtil
135 return Long.parseLong(textContent);
138 private static String getSessionIdWithXPath(final Document doc, final XPathExpression sessionIdXPath) {
139 final Node sessionIdNode = (Node) XmlUtil.evaluateXPath(sessionIdXPath, doc, XPathConstants.NODE);
140 return sessionIdNode != null ? sessionIdNode.getTextContent() : null;
144 protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
145 final NetconfHelloMessage message) {
146 final long sessionId = extractSessionId(message.getDocument());
148 // Copy here is important: it disconnects the strings from the document
149 Set<String> capabilities = ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message
152 capabilities = INTERNER.intern(capabilities);
154 return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
158 * Handler to process response for start-exi message.
160 private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
161 private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
163 private final NetconfClientSession session;
164 private final NetconfStartExiMessage startExiMessage;
166 ExiConfirmationInboundHandler(final NetconfClientSession session,
167 final NetconfStartExiMessage startExiMessage) {
168 this.session = session;
169 this.startExiMessage = startExiMessage;
172 @SuppressWarnings("checkstyle:IllegalCatch")
174 public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
175 ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
177 NetconfMessage netconfMessage = (NetconfMessage) msg;
179 // Ok response to start-exi, try to add exi handlers
180 if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
181 LOG.trace("Positive response on start-exi call received on session {}", session);
183 session.startExiCommunication(startExiMessage);
184 } catch (RuntimeException e) {
185 // Unable to add exi, continue without exi
186 LOG.warn("Unable to start exi communication, Communication will continue without exi on session "
191 } else if (NetconfMessageUtil.isErrorMessage(netconfMessage)) {
193 "Error response to start-exi message {}, Communication will continue without exi on session {}",
194 netconfMessage, session);
196 // Unexpected response to start-exi, throwing message away, continue without exi
198 LOG.warn("Unexpected response to start-exi message, should be ok, was {}, "
199 + "Communication will continue without exi "
200 + "and response message will be thrown away on session {}",
201 netconfMessage, session);
204 negotiationSuccessful(session);