68f2bef0639d0c7525af4187a7e6c7dd610b96a4
[netconf.git] / netconf / netconf-client / src / main / java / org / opendaylight / netconf / client / NetconfClientSessionNegotiator.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.client;
10
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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import io.netty.channel.Channel;
17 import io.netty.channel.ChannelHandlerContext;
18 import io.netty.channel.ChannelInboundHandlerAdapter;
19 import io.netty.util.Timer;
20 import io.netty.util.concurrent.Promise;
21 import java.util.Set;
22 import javax.xml.xpath.XPathConstants;
23 import javax.xml.xpath.XPathExpression;
24 import org.opendaylight.netconf.api.NetconfClientSessionPreferences;
25 import org.opendaylight.netconf.api.NetconfDocumentedException;
26 import org.opendaylight.netconf.api.NetconfMessage;
27 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
28 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
29 import org.opendaylight.netconf.api.xml.XmlUtil;
30 import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
31 import org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator;
32 import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
33 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
34 import org.opendaylight.netconf.util.xml.XMLNetconfUtil;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.w3c.dom.Document;
38 import org.w3c.dom.Node;
39 import org.w3c.dom.NodeList;
40
41 public class NetconfClientSessionNegotiator extends
42         AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession,
43                 NetconfClientSessionListener> {
44     private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
45
46     private static final XPathExpression SESSION_ID_X_PATH = XMLNetconfUtil
47             .compileXPath("/netconf:hello/netconf:session-id");
48
49     private static final XPathExpression SESSION_ID_X_PATH_NO_NAMESPACE = XMLNetconfUtil
50             .compileXPath("/hello/session-id");
51
52     private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
53
54     private static final Interner<Set<String>> INTERNER = Interners.newWeakInterner();
55
56     protected NetconfClientSessionNegotiator(final NetconfClientSessionPreferences sessionPreferences,
57                                              final Promise<NetconfClientSession> promise,
58                                              final Channel channel,
59                                              final Timer timer,
60                                              final NetconfClientSessionListener sessionListener,
61                                              final long connectionTimeoutMillis) {
62         super(sessionPreferences, promise, channel, timer, sessionListener, connectionTimeoutMillis);
63     }
64
65     @SuppressWarnings("checkstyle:IllegalCatch")
66     @Override
67     @SuppressFBWarnings("BC_UNCONFIRMED_CAST")
68     protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
69         if (!ifNegotiatedAlready()) {
70             LOG.debug("Server hello message received, starting negotiation on channel {}", channel);
71             try {
72                 startNegotiation();
73             } catch (final Exception e) {
74                 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
75                 negotiationFailed(e);
76                 return;
77             }
78         }
79         final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
80         replaceHelloMessageInboundHandler(session);
81
82         // If exi should be used, try to initiate exi communication
83         // Call negotiationSuccessFul after exi negotiation is finished successfully or not
84         final NetconfMessage startExiMessage = sessionPreferences.getStartExiMessage();
85         if (shouldUseExi(netconfMessage) && startExiMessage instanceof NetconfStartExiMessage) {
86             LOG.debug("Netconf session {} should use exi.", session);
87             tryToInitiateExi(session, (NetconfStartExiMessage) startExiMessage);
88         } else {
89             // Exi is not supported, release session immediately
90             LOG.debug("Netconf session {} isn't capable of using exi.", session);
91             negotiationSuccessful(session);
92         }
93     }
94
95     /**
96      * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
97      *
98      * @param startExiMessage Exi message for initilization of exi communication.
99      */
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));
104
105         session.sendMessage(startExiMessage).addListener(channelFuture -> {
106             if (!channelFuture.isSuccess()) {
107                 LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, session,
108                         channelFuture.cause());
109                 channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
110             } else {
111                 LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, session);
112             }
113         });
114     }
115
116     @SuppressFBWarnings("BC_UNCONFIRMED_CAST")
117     private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
118         return containsExi10Capability(helloMsg.getDocument())
119                 && containsExi10Capability(sessionPreferences.getHelloMessage().getDocument());
120     }
121
122     private static boolean containsExi10Capability(final Document doc) {
123         final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
124         for (int i = 0; i < nList.getLength(); i++) {
125             if (nList.item(i).getTextContent().contains(EXI_1_0_CAPABILITY_MARKER)) {
126                 return true;
127             }
128         }
129         return false;
130     }
131
132     private static long extractSessionId(final Document doc) {
133         String textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH);
134         if (Strings.isNullOrEmpty(textContent)) {
135             textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH_NO_NAMESPACE);
136             if (Strings.isNullOrEmpty(textContent)) {
137                 throw new IllegalStateException("Session id not received from server, hello message: " + XmlUtil
138                         .toString(doc));
139             }
140         }
141
142         return Long.parseLong(textContent);
143     }
144
145     private static String getSessionIdWithXPath(final Document doc, final XPathExpression sessionIdXPath) {
146         final Node sessionIdNode = (Node) XmlUtil.evaluateXPath(sessionIdXPath, doc, XPathConstants.NODE);
147         return sessionIdNode != null ? sessionIdNode.getTextContent() : null;
148     }
149
150     @Override
151     protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
152                                               final NetconfHelloMessage message) {
153         final long sessionId = extractSessionId(message.getDocument());
154
155         // Copy here is important: it disconnects the strings from the document
156         Set<String> capabilities = ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message
157                 .getDocument()));
158
159         capabilities = INTERNER.intern(capabilities);
160
161         return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
162     }
163
164     /**
165      * Handler to process response for start-exi message.
166      */
167     private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
168         private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
169
170         private final NetconfClientSession session;
171         private final NetconfStartExiMessage startExiMessage;
172
173         ExiConfirmationInboundHandler(final NetconfClientSession session,
174                                       final NetconfStartExiMessage startExiMessage) {
175             this.session = session;
176             this.startExiMessage = startExiMessage;
177         }
178
179         @SuppressWarnings("checkstyle:IllegalCatch")
180         @Override
181         public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
182             ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
183
184             NetconfMessage netconfMessage = (NetconfMessage) msg;
185
186             // Ok response to start-exi, try to add exi handlers
187             if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
188                 LOG.trace("Positive response on start-exi call received on session {}", session);
189                 try {
190                     session.startExiCommunication(startExiMessage);
191                 } catch (RuntimeException e) {
192                     // Unable to add exi, continue without exi
193                     LOG.warn("Unable to start exi communication, Communication will continue without exi on session "
194                             + "{}", session, e);
195                 }
196
197                 // Error response
198             } else if (NetconfMessageUtil.isErrorMessage(netconfMessage)) {
199                 LOG.warn(
200                         "Error response to start-exi message {}, Communication will continue without exi on session {}",
201                         netconfMessage, session);
202
203                 // Unexpected response to start-exi, throwing message away, continue without exi
204             } else {
205                 LOG.warn("Unexpected response to start-exi message, should be ok, was {}, "
206                         + "Communication will continue without exi "
207                         + "and response message will be thrown away on session {}",
208                         netconfMessage, session);
209             }
210
211             negotiationSuccessful(session);
212         }
213     }
214
215 }