Make RuntimeRpc revision aware
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / RuntimeRpc.java
1 /*
2  * Copyright (c) 2015 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.netconf.mdsal.connector.ops;
10
11 import com.google.common.base.Optional;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import java.io.IOException;
14 import java.net.URI;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.Map;
18 import javax.annotation.Nullable;
19 import javax.xml.stream.XMLOutputFactory;
20 import javax.xml.stream.XMLStreamException;
21 import javax.xml.stream.XMLStreamWriter;
22 import javax.xml.transform.dom.DOMResult;
23 import javax.xml.transform.dom.DOMSource;
24 import org.opendaylight.controller.config.util.xml.DocumentedException;
25 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
26 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
27 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
28 import org.opendaylight.controller.config.util.xml.XmlElement;
29 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
30 import org.opendaylight.controller.config.util.xml.XmlUtil;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
34 import org.opendaylight.netconf.api.NetconfDocumentedException;
35 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
36 import org.opendaylight.netconf.mapping.api.HandlingPriority;
37 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
38 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
39 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
46 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
47 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
48 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
49 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.Module;
51 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
52 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Attr;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.Node;
59 import org.w3c.dom.NodeList;
60
61 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
62
63     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
64
65     private static final XMLOutputFactory XML_OUTPUT_FACTORY;
66
67     static {
68         XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
69         XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
70     }
71
72     private final CurrentSchemaContext schemaContext;
73     private final DOMRpcService rpcService;
74
75     public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
76                       final DOMRpcService rpcService) {
77         super(netconfSessionIdForReporting);
78         this.schemaContext = schemaContext;
79         this.rpcService = rpcService;
80     }
81
82     @Override
83     protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
84         final URI namespaceURI = createNsUri(namespace);
85         final Optional<Module> module = getModule(namespaceURI);
86
87         if (!module.isPresent()) {
88             LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
89             return HandlingPriority.CANNOT_HANDLE;
90         }
91
92         getRpcDefinitionFromModule(module.get(), namespaceURI, netconfOperationName);
93         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
94
95     }
96
97     @Override
98     protected String getOperationName() {
99         throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
100     }
101
102     private static URI createNsUri(final String namespace) {
103         // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
104         return URI.create(namespace);
105     }
106
107     //this returns module with the newest revision if more then 1 module with same namespace is found
108     private Optional<Module> getModule(final URI namespaceURI) {
109         return Optional.fromJavaUtil(schemaContext.getCurrentContext().findModules(namespaceURI).stream().findFirst());
110     }
111
112     private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
113             final String name) {
114         for (final RpcDefinition rpcDef : module.getRpcs()) {
115             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
116                     && rpcDef.getQName().getLocalName().equals(name)) {
117                 return Optional.of(rpcDef);
118             }
119         }
120         return Optional.absent();
121     }
122
123     @Override
124     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
125             throws DocumentedException {
126
127         final String netconfOperationName = operationElement.getName();
128         final String netconfOperationNamespace;
129         try {
130             netconfOperationNamespace = operationElement.getNamespace();
131         } catch (final DocumentedException e) {
132             LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
133             throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e,
134                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
135         }
136
137         final URI namespaceURI = createNsUri(netconfOperationNamespace);
138         final Optional<Module> moduleOptional = getModule(namespaceURI);
139
140         if (!moduleOptional.isPresent()) {
141             throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
142                         + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
143                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
144         }
145
146         final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
147                 namespaceURI, netconfOperationName);
148
149         if (!rpcDefinitionOptional.isPresent()) {
150             throw new DocumentedException(
151                     "Unable to find RpcDefinition with namespace and name : "
152                         + namespaceURI + " " + netconfOperationName,
153                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
154         }
155
156         final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
157         final SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(rpcDefinition.getQName()), true);
158         final NormalizedNode<?, ?> inputNode = rpcToNNode(operationElement, rpcDefinition.getInput());
159
160         final CheckedFuture<DOMRpcResult, DOMRpcException> rpcFuture = rpcService.invokeRpc(schemaPath, inputNode);
161         try {
162             final DOMRpcResult result = rpcFuture.checkedGet();
163             if (result.getResult() == null) {
164                 return XmlUtil.createElement(document, XmlNetconfConstants.OK,
165                         Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
166             }
167             return (Element) transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
168         } catch (final DOMRpcException e) {
169             throw DocumentedException.wrap(e);
170         }
171     }
172
173     @Override
174     public Document handle(final Document requestMessage,
175                            final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
176
177         final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
178
179         final Document document = XmlUtil.newDocument();
180
181         final XmlElement operationElement = requestElement.getOnlyChildElement();
182         final Map<String, Attr> attributes = requestElement.getAttributes();
183
184         final Element response = handle(document, operationElement, subsequentOperation);
185         final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
186                 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
187
188         if (XmlElement.fromDomElement(response).hasNamespace()) {
189             rpcReply.appendChild(response);
190         } else {
191             final NodeList list = response.getChildNodes();
192             if (list.getLength() == 0) {
193                 rpcReply.appendChild(response);
194             } else {
195                 while (list.getLength() != 0) {
196                     rpcReply.appendChild(list.item(0));
197                 }
198             }
199         }
200
201         for (final Attr attribute : attributes.values()) {
202             rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
203         }
204         document.appendChild(rpcReply);
205         return document;
206     }
207
208     private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
209                                          final SchemaPath rpcOutputPath) {
210         final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
211
212         final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
213
214         final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
215                 schemaContext.getCurrentContext(), rpcOutputPath);
216
217         final SchemaOrderedNormalizedNodeWriter nnWriter =
218                 new SchemaOrderedNormalizedNodeWriter(nnStreamWriter, schemaContext.getCurrentContext(), rpcOutputPath);
219
220         writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
221         try {
222             nnStreamWriter.close();
223             xmlWriter.close();
224         } catch (IOException | XMLStreamException e) {
225             LOG.warn("Error while closing streams", e);
226         }
227
228         return result.getNode();
229     }
230
231     private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
232         try {
233             return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
234         } catch (final XMLStreamException e) {
235             throw new RuntimeException(e);
236         }
237     }
238
239     private static void writeRootElement(final XMLStreamWriter xmlWriter,
240             final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
241         try {
242             final Collection<DataContainerChild<?, ?>> value = data.getValue();
243             nnWriter.write(value);
244             nnWriter.flush();
245             xmlWriter.flush();
246         } catch (XMLStreamException | IOException e) {
247             throw new RuntimeException(e);
248         }
249     }
250
251     /**
252      * Parses xml element rpc input into normalized node or null if rpc does not take any input.
253      *
254      * @param element rpc xml element
255      * @param input   input container schema node, or null if rpc does not take any input
256      * @return parsed rpc into normalized node, or null if input schema is null
257      */
258     @SuppressWarnings("checkstyle:IllegalCatch")
259     @Nullable
260     private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input)
261             throws DocumentedException {
262         if (input.getChildNodes().isEmpty()) {
263             return null;
264         }
265
266         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
267         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
268         final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext.getCurrentContext(), input);
269
270         try {
271             xmlParser.traverse(new DOMSource(element.getDomElement()));
272         } catch (final Exception ex) {
273             throw new NetconfDocumentedException("Error parsing input: " + ex.getMessage(), ex, ErrorType.PROTOCOL,
274                     ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
275         }
276
277         return resultHolder.getResult();
278     }
279
280 }