Merge "Fixed typo in SnapshotBackedWriteTransaction class"
[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 io.netty.channel.ChannelFuture;
12 import io.netty.channel.ChannelFutureListener;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.ChannelInboundHandlerAdapter;
15 import java.util.Collection;
16 import javax.xml.xpath.XPathConstants;
17 import javax.xml.xpath.XPathExpression;
18
19 import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
20 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
21 import org.opendaylight.controller.netconf.api.NetconfMessage;
22 import org.opendaylight.controller.netconf.util.AbstractChannelInitializer;
23 import org.opendaylight.controller.netconf.util.AbstractNetconfSessionNegotiator;
24 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
25 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
26 import org.opendaylight.controller.netconf.util.messages.NetconfStartExiMessage;
27 import org.opendaylight.controller.netconf.util.xml.XMLNetconfUtil;
28 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
29 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.w3c.dom.Document;
33 import org.w3c.dom.Node;
34 import org.w3c.dom.NodeList;
35
36 import io.netty.channel.Channel;
37 import io.netty.util.Timer;
38 import io.netty.util.concurrent.Promise;
39
40 public class NetconfClientSessionNegotiator extends
41         AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession, NetconfClientSessionListener>
42 {
43     private static final Logger logger = 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(NetconfClientSessionPreferences sessionPreferences,
51                                              Promise<NetconfClientSession> promise,
52                                              Channel channel,
53                                              Timer timer,
54                                              NetconfClientSessionListener sessionListener,
55                                              long connectionTimeoutMillis) {
56         super(sessionPreferences, promise, channel, timer, sessionListener, connectionTimeoutMillis);
57     }
58
59     @Override
60     protected void handleMessage(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             logger.debug("Netconf session {} should use exi.", session);
68             NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage();
69             tryToInitiateExi(session, startExiMessage);
70         // Exi is not supported, release session immediately
71         } else {
72             logger.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                     logger.warn("Failed to send start-exi message {} on session {}", startExiMessage, this, f.cause());
92                     channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
93                 } else {
94                     logger.trace("Start-exi message {} sent to socket on session {}", startExiMessage, this);
95                 }
96             }
97         });
98     }
99
100     private boolean shouldUseExi(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(Document doc) {
116         final Node sessionIdNode = (Node) XmlUtil.evaluateXPath(sessionIdXPath, doc, XPathConstants.NODE);
117         String textContent = sessionIdNode.getTextContent();
118         if (textContent == null || textContent.equals("")) {
119             throw new IllegalStateException("Session id not received from server");
120         }
121
122         return Long.valueOf(textContent);
123     }
124
125     @Override
126     protected NetconfClientSession getSession(NetconfClientSessionListener sessionListener, Channel channel,
127             NetconfHelloMessage message) throws NetconfDocumentedException {
128         long sessionId = extractSessionId(message.getDocument());
129         Collection<String> capabilities = NetconfMessageUtil.extractCapabilitiesFromHello(message.getDocument());
130         return new NetconfClientSession(sessionListener, channel, sessionId, capabilities);
131     }
132
133     /**
134      * Handler to process response for start-exi message
135      */
136     private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
137         private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
138
139         private final NetconfClientSession session;
140         private NetconfStartExiMessage startExiMessage;
141
142         ExiConfirmationInboundHandler(NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
143             this.session = session;
144             this.startExiMessage = startExiMessage;
145         }
146
147         @Override
148         public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
149             ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
150
151             NetconfMessage netconfMessage = (NetconfMessage) msg;
152
153             // Ok response to start-exi, try to add exi handlers
154             if (NetconfMessageUtil.isOKMessage(netconfMessage)) {
155                 logger.trace("Positive response on start-exi call received on session {}", session);
156                 try {
157                     session.startExiCommunication(startExiMessage);
158                 } catch (RuntimeException e) {
159                     // Unable to add exi, continue without exi
160                     logger.warn("Unable to start exi communication, Communication will continue without exi on session {}", session, e);
161                 }
162
163                 // Error response
164             } else if(NetconfMessageUtil.isErrorMessage(netconfMessage)) {
165                 logger.warn(
166                         "Error response to start-exi message {}, Communication will continue without exi on session {}",
167                         XmlUtil.toString(netconfMessage.getDocument()), session);
168
169                 // Unexpected response to start-exi, throwing message away, continue without exi
170             } else {
171                 logger.warn(
172                         "Unexpected response to start-exi message, should be ok, was {}, " +
173                                 "Communication will continue without exi and response message will be thrown away on session {}",
174                         XmlUtil.toString(netconfMessage.getDocument()), session);
175             }
176
177             negotiationSuccessful(session);
178         }
179     }
180
181 }