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