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