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