Remove Netconf(Client)SessionPreferences
[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 package org.opendaylight.netconf.client;
9
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;
19 import java.util.Set;
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;
37
38 // Non-final for mocking
39 class NetconfClientSessionNegotiator
40         extends AbstractNetconfSessionNegotiator<NetconfClientSession, NetconfClientSessionListener> {
41     private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
42
43     private static final XPathExpression SESSION_ID_X_PATH = XMLNetconfUtil
44             .compileXPath("/netconf:hello/netconf:session-id");
45
46     private static final XPathExpression SESSION_ID_X_PATH_NO_NAMESPACE = XMLNetconfUtil
47             .compileXPath("/hello/session-id");
48
49     private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
50
51     private static final Interner<Set<String>> INTERNER = Interners.newWeakInterner();
52
53     private final NetconfStartExiMessage startExi;
54
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;
60     }
61
62     @SuppressWarnings("checkstyle:IllegalCatch")
63     @Override
64     protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
65         if (!ifNegotiatedAlready()) {
66             LOG.debug("Server hello message received, starting negotiation on channel {}", channel);
67             try {
68                 startNegotiation();
69             } catch (final Exception e) {
70                 LOG.warn("Unexpected negotiation failure on channel {}", channel, e);
71                 negotiationFailed(e);
72                 return;
73             }
74         }
75         final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
76         replaceHelloMessageInboundHandler(session);
77
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);
83         } else {
84             // Exi is not supported, release session immediately
85             LOG.debug("Netconf session {} isn't capable of using exi.", session);
86             negotiationSuccessful(session);
87         }
88     }
89
90     /**
91      * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
92      *
93      * @param startExiMessage Exi message for initilization of exi communication.
94      */
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));
99
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);
105             } else {
106                 LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, session);
107             }
108         });
109     }
110
111     private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
112         return containsExi10Capability(helloMsg.getDocument()) && containsExi10Capability(localHello().getDocument());
113     }
114
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)) {
119                 return true;
120             }
121         }
122         return false;
123     }
124
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
131                         .toString(doc));
132             }
133         }
134
135         return Long.parseLong(textContent);
136     }
137
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;
141     }
142
143     @Override
144     protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
145                                               final NetconfHelloMessage message) {
146         final long sessionId = extractSessionId(message.getDocument());
147
148         // Copy here is important: it disconnects the strings from the document
149         Set<String> capabilities = ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message
150                 .getDocument()));
151
152         capabilities = INTERNER.intern(capabilities);
153
154         return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
155     }
156
157     /**
158      * Handler to process response for start-exi message.
159      */
160     private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
161         private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
162
163         private final NetconfClientSession session;
164         private final NetconfStartExiMessage startExiMessage;
165
166         ExiConfirmationInboundHandler(final NetconfClientSession session,
167                                       final NetconfStartExiMessage startExiMessage) {
168             this.session = session;
169             this.startExiMessage = startExiMessage;
170         }
171
172         @SuppressWarnings("checkstyle:IllegalCatch")
173         @Override
174         public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
175             ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
176
177             NetconfMessage netconfMessage = (NetconfMessage) msg;
178
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);
182                 try {
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 "
187                             + "{}", session, e);
188                 }
189
190                 // Error response
191             } else if (NetconfMessageUtil.isErrorMessage(netconfMessage)) {
192                 LOG.warn(
193                         "Error response to start-exi message {}, Communication will continue without exi on session {}",
194                         netconfMessage, session);
195
196                 // Unexpected response to start-exi, throwing message away, continue without exi
197             } else {
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);
202             }
203
204             negotiationSuccessful(session);
205         }
206     }
207
208 }