Merge "Remove duplicate dependency declaration"
[controller.git] / opendaylight / netconf / netconf-client / src / main / java / org / opendaylight / controller / 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.controller.netconf.client;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import io.netty.channel.Channel;
14 import io.netty.channel.ChannelFuture;
15 import io.netty.channel.ChannelFutureListener;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.channel.ChannelInboundHandlerAdapter;
18 import io.netty.util.Timer;
19 import io.netty.util.concurrent.Promise;
20 import java.util.Collection;
21 import javax.xml.xpath.XPathConstants;
22 import javax.xml.xpath.XPathExpression;
23 import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
24 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.controller.netconf.api.NetconfMessage;
26 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
27 import org.opendaylight.controller.netconf.nettyutil.AbstractChannelInitializer;
28 import org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSessionNegotiator;
29 import org.opendaylight.controller.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
30 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
31 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
32 import org.opendaylight.controller.netconf.util.xml.XMLNetconfUtil;
33 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Node;
38 import org.w3c.dom.NodeList;
39
40 public class NetconfClientSessionNegotiator extends
41         AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession, NetconfClientSessionListener>
42 {
43     private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
44
45     private static final XPathExpression sessionIdXPath = XMLNetconfUtil
46             .compileXPath("/netconf:hello/netconf:session-id");
47
48     private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
49
50     protected NetconfClientSessionNegotiator(final NetconfClientSessionPreferences sessionPreferences,
51                                              final Promise<NetconfClientSession> promise,
52                                              final Channel channel,
53                                              final Timer timer,
54                                              final NetconfClientSessionListener sessionListener,
55                                              final long connectionTimeoutMillis) {
56         super(sessionPreferences, promise, channel, timer, sessionListener, connectionTimeoutMillis);
57     }
58
59     @Override
60     protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
61         final NetconfClientSession session = getSessionForHelloMessage(netconfMessage);
62         replaceHelloMessageInboundHandler(session);
63
64         // If exi should be used, try to initiate exi communication
65         // Call negotiationSuccessFul after exi negotiation is finished successfully or not
66         if (shouldUseExi(netconfMessage)) {
67             LOG.debug("Netconf session {} should use exi.", session);
68             NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage();
69             tryToInitiateExi(session, startExiMessage);
70         } else {
71             // Exi is not supported, release session immediately
72             LOG.debug("Netconf session {} isn't capable of using exi.", session);
73             negotiationSuccessful(session);
74         }
75     }
76
77     /**
78      * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
79      *
80      * @param startExiMessage
81      */
82     void tryToInitiateExi(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
83         channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
84                 ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER,
85                 new ExiConfirmationInboundHandler(session, startExiMessage));
86
87         session.sendMessage(startExiMessage).addListener(new ChannelFutureListener() {
88             @Override
89             public void operationComplete(final ChannelFuture f) {
90                 if (!f.isSuccess()) {
91                     LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, this, f.cause());
92                     channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
93                 } else {
94                     LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, this);
95                 }
96             }
97         });
98     }
99
100     private boolean shouldUseExi(final NetconfHelloMessage helloMsg) {
101         return containsExi10Capability(helloMsg.getDocument())
102                 && containsExi10Capability(sessionPreferences.getHelloMessage().getDocument());
103     }
104
105     private boolean containsExi10Capability(final Document doc) {
106         final NodeList nList = doc.getElementsByTagName(XmlNetconfConstants.CAPABILITY);
107         for (int i = 0; i < nList.getLength(); i++) {
108             if (nList.item(i).getTextContent().contains(EXI_1_0_CAPABILITY_MARKER)) {
109                 return true;
110             }
111         }
112         return false;
113     }
114
115     private long extractSessionId(final Document doc) {
116         final Node sessionIdNode = (Node) XmlUtil.evaluateXPath(sessionIdXPath, doc, XPathConstants.NODE);
117         Preconditions.checkState(sessionIdNode != null, "");
118         String textContent = sessionIdNode.getTextContent();
119         if (textContent == null || textContent.equals("")) {
120             throw new IllegalStateException("Session id not received from server");
121         }
122
123         return Long.valueOf(textContent);
124     }
125
126     @Override
127     protected NetconfClientSession getSession(final NetconfClientSessionListener sessionListener, final Channel channel,
128             final NetconfHelloMessage message) throws NetconfDocumentedException {
129         long sessionId = extractSessionId(message.getDocument());
130
131         // Copy here is important: it disconnects the strings from the document
132         Collection<String> capabilities = ImmutableList.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message.getDocument()));
133
134         // FIXME: scalability: we could instantiate a cache to share the same collections
135         return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
136     }
137
138     /**
139      * Handler to process response for start-exi message
140      */
141     private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
142         private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
143
144         private final NetconfClientSession session;
145         private final NetconfStartExiMessage startExiMessage;
146
147         ExiConfirmationInboundHandler(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
148             this.session = session;
149             this.startExiMessage = startExiMessage;
150         }
151
152         @Override
153         public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
154             ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
155
156             NetconfMessage netconfMessage = (NetconfMessage) msg;
157
158             // Ok response to start-exi, try to add exi handlers
159             if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
160                 LOG.trace("Positive response on start-exi call received on session {}", session);
161                 try {
162                     session.startExiCommunication(startExiMessage);
163                 } catch (RuntimeException e) {
164                     // Unable to add exi, continue without exi
165                     LOG.warn("Unable to start exi communication, Communication will continue without exi on session {}", session, e);
166                 }
167
168                 // Error response
169             } else if(NetconfMessageUtil.isErrorMessage(netconfMessage)) {
170                 LOG.warn(
171                         "Error response to start-exi message {}, Communication will continue without exi on session {}",
172                         netconfMessage, session);
173
174                 // Unexpected response to start-exi, throwing message away, continue without exi
175             } else {
176                 LOG.warn("Unexpected response to start-exi message, should be ok, was {}, " +
177                          "Communication will continue without exi and response message will be thrown away on session {}",
178                          netconfMessage, session);
179             }
180
181             negotiationSuccessful(session);
182         }
183     }
184
185 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.