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.checkerframework.checker.index.qual.NonNegative;
23 import org.opendaylight.netconf.api.NetconfDocumentedException;
24 import org.opendaylight.netconf.api.NetconfMessage;
25 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
26 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
27 import org.opendaylight.netconf.api.xml.XmlUtil;
28 import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
29 import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
30 import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
31 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
32 import org.opendaylight.netconf.util.xml.XMLNetconfUtil;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.w3c.dom.Document;
36 import org.w3c.dom.Node;
37 import org.w3c.dom.NodeList;
39 // Non-final for mocking
40 class NetconfClientSessionNegotiator
41 extends AbstractNetconfSessionNegotiator<NetconfClientSession, NetconfClientSessionListener> {
42 private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
44 private static final XPathExpression SESSION_ID_X_PATH = XMLNetconfUtil
45 .compileXPath("/netconf:hello/netconf:session-id");
47 private static final XPathExpression SESSION_ID_X_PATH_NO_NAMESPACE = XMLNetconfUtil
48 .compileXPath("/hello/session-id");
50 private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
52 private static final Interner<Set<String>> INTERNER = Interners.newWeakInterner();
54 private final NetconfStartExiMessage startExi;
56 NetconfClientSessionNegotiator(final NetconfHelloMessage hello, final NetconfStartExiMessage startExi,
57 final Promise<NetconfClientSession> promise, final Channel channel, final Timer timer,
58 final NetconfClientSessionListener sessionListener, final long connectionTimeoutMillis,
59 final @NonNegative int maximumIncomingChunkSize) {
60 super(hello, promise, channel, timer, sessionListener, connectionTimeoutMillis, maximumIncomingChunkSize);
61 this.startExi = startExi;
64 @SuppressWarnings("checkstyle:IllegalCatch")
66 protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
67 if (!ifNegotiatedAlready()) {
68 LOG.debug("Server hello message received, starting negotiation on channel {}", channel);
71 } catch (final Exception e) {
72 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
77 final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
78 replaceHelloMessageInboundHandler(session);
80 // If exi should be used, try to initiate exi communication
81 // Call negotiationSuccessFul after exi negotiation is finished successfully or not
82 if (startExi != null && shouldUseExi(netconfMessage)) {
83 LOG.debug("Netconf session {} should use exi.", session);
84 tryToInitiateExi(session, startExi);
86 // Exi is not supported, release session immediately
87 LOG.debug("Netconf session {} isn't capable of using exi.", session);
88 negotiationSuccessful(session);
93 * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
95 * @param startExiMessage Exi message for initilization of exi communication.
97 void tryToInitiateExi(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
98 channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
99 ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER,
100 new ExiConfirmationInboundHandler(session, startExiMessage));
102 session.sendMessage(startExiMessage).addListener(channelFuture -> {
103 if (!channelFuture.isSuccess()) {
104 LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, session,
105 channelFuture.cause());
106 channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
108 LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, session);
113 private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
114 return containsExi10Capability(helloMsg.getDocument()) && containsExi10Capability(localHello().getDocument());
117 private static boolean containsExi10Capability(final Document doc) {
118 final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
119 for (int i = 0; i < nList.getLength(); i++) {
120 if (nList.item(i).getTextContent().contains(EXI_1_0_CAPABILITY_MARKER)) {
127 private static long extractSessionId(final Document doc) {
128 String textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH);
129 if (Strings.isNullOrEmpty(textContent)) {
130 textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH_NO_NAMESPACE);
131 if (Strings.isNullOrEmpty(textContent)) {
132 throw new IllegalStateException("Session id not received from server, hello message: " + XmlUtil
137 return Long.parseLong(textContent);
140 private static String getSessionIdWithXPath(final Document doc, final XPathExpression sessionIdXPath) {
141 final Node sessionIdNode = (Node) XmlUtil.evaluateXPath(sessionIdXPath, doc, XPathConstants.NODE);
142 return sessionIdNode != null ? sessionIdNode.getTextContent() : null;
146 protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
147 final NetconfHelloMessage message) {
148 final long sessionId = extractSessionId(message.getDocument());
150 // Copy here is important: it disconnects the strings from the document
151 Set<String> capabilities = ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message
154 capabilities = INTERNER.intern(capabilities);
156 return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
160 * Handler to process response for start-exi message.
162 private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
163 private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
165 private final NetconfClientSession session;
166 private final NetconfStartExiMessage startExiMessage;
168 ExiConfirmationInboundHandler(final NetconfClientSession session,
169 final NetconfStartExiMessage startExiMessage) {
170 this.session = session;
171 this.startExiMessage = startExiMessage;
174 @SuppressWarnings("checkstyle:IllegalCatch")
176 public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
177 ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
179 NetconfMessage netconfMessage = (NetconfMessage) msg;
181 // Ok response to start-exi, try to add exi handlers
182 if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
183 LOG.trace("Positive response on start-exi call received on session {}", session);
185 session.startExiCommunication(startExiMessage);
186 } catch (RuntimeException e) {
187 // Unable to add exi, continue without exi
188 LOG.warn("Unable to start exi communication, Communication will continue without exi on session "
193 } else if (NetconfMessageUtil.isErrorMessage(netconfMessage)) {
195 "Error response to start-exi message {}, Communication will continue without exi on session {}",
196 netconfMessage, session);
198 // Unexpected response to start-exi, throwing message away, continue without exi
200 LOG.warn("Unexpected response to start-exi message, should be ok, was {}, "
201 + "Communication will continue without exi "
202 + "and response message will be thrown away on session {}",
203 netconfMessage, session);
206 negotiationSuccessful(session);