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