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