5a80e167bc0ec8cf8d1b208c1f81e9051b8d4780
[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.stmt.SchemaNodeIdentifier.Absolute;
47 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.w3c.dom.Attr;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53 import org.w3c.dom.NodeList;
54 import org.xml.sax.SAXException;
55
56 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
57
58     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
59
60     private static final XMLOutputFactory XML_OUTPUT_FACTORY;
61
62     static {
63         XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
64         XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
65     }
66
67     private final CurrentSchemaContext schemaContext;
68     private final DOMRpcService rpcService;
69
70     public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
71                       final DOMRpcService rpcService) {
72         super(netconfSessionIdForReporting);
73         this.schemaContext = schemaContext;
74         this.rpcService = rpcService;
75     }
76
77     @Override
78     protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
79         final XMLNamespace namespaceURI = createNsUri(namespace);
80         final Optional<? extends Module> module = getModule(namespaceURI);
81
82         if (module.isEmpty()) {
83             LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
84             return HandlingPriority.CANNOT_HANDLE;
85         }
86
87         getRpcDefinitionFromModule(module.get(), namespaceURI, netconfOperationName);
88         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
89
90     }
91
92     @Override
93     protected String getOperationName() {
94         throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
95     }
96
97     private static XMLNamespace createNsUri(final String namespace) {
98         // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
99         return XMLNamespace.of(namespace);
100     }
101
102     //this returns module with the newest revision if more then 1 module with same namespace is found
103     private Optional<? extends Module> getModule(final XMLNamespace namespace) {
104         return schemaContext.getCurrentContext().findModules(namespace).stream().findFirst();
105     }
106
107     private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final XMLNamespace namespace,
108             final String name) {
109         for (final RpcDefinition rpcDef : module.getRpcs()) {
110             if (rpcDef.getQName().getNamespace().equals(namespace) && rpcDef.getQName().getLocalName().equals(name)) {
111                 return Optional.of(rpcDef);
112             }
113         }
114         return Optional.empty();
115     }
116
117     @Override
118     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
119             throws DocumentedException {
120
121         final String netconfOperationName = operationElement.getName();
122         final String netconfOperationNamespace;
123         try {
124             netconfOperationNamespace = operationElement.getNamespace();
125         } catch (final DocumentedException e) {
126             LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
127             throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e,
128                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
129         }
130
131         final XMLNamespace namespaceURI = createNsUri(netconfOperationNamespace);
132         final Optional<? extends Module> moduleOptional = getModule(namespaceURI);
133
134         if (moduleOptional.isEmpty()) {
135             throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
136                         + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
137                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
138         }
139
140         final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
141                 namespaceURI, netconfOperationName);
142
143         if (rpcDefinitionOptional.isEmpty()) {
144             throw new DocumentedException(
145                     "Unable to find RpcDefinition with namespace and name : "
146                         + namespaceURI + " " + netconfOperationName,
147                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
148         }
149
150         final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
151         final ContainerNode inputNode = rpcToNNode(operationElement, rpcDefinition);
152
153         final DOMRpcResult result;
154         try {
155             result = rpcService.invokeRpc(rpcDefinition.getQName(), inputNode).get();
156         } catch (final InterruptedException | ExecutionException e) {
157             throw DocumentedException.wrap(e);
158         }
159         if (result.getResult() == null) {
160             return XmlUtil.createElement(document, XmlNetconfConstants.OK,
161                 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
162         }
163         return transformNormalizedNode(document, result.getResult(),
164                 Absolute.of(rpcDefinition.getQName(), rpcDefinition.getOutput().getQName()));
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 Absolute 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 = new SchemaOrderedNormalizedNodeWriter(nnStreamWriter,
212                 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,
263                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
264         }
265
266         return (ContainerNode) resultHolder.getResult();
267     }
268 }