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