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