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