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