24503f00aa307c9a37c9cd20955f1d26b7e2fde1
[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.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.NormalizationResultHolder;
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
57 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
58     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
59     private static final XMLOutputFactory XML_OUTPUT_FACTORY;
60
61     static {
62         XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
63         XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
64     }
65
66     private final CurrentSchemaContext schemaContext;
67     private final DOMRpcService rpcService;
68
69     public RuntimeRpc(final SessionIdType sessionId, final CurrentSchemaContext schemaContext,
70             final DOMRpcService rpcService) {
71         super(sessionId);
72         this.schemaContext = schemaContext;
73         this.rpcService = rpcService;
74     }
75
76     @Override
77     protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
78         final XMLNamespace namespaceURI = createNsUri(namespace);
79         final Optional<? extends Module> module = getModule(namespaceURI);
80
81         if (module.isEmpty()) {
82             LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
83             return HandlingPriority.CANNOT_HANDLE;
84         }
85
86         getRpcDefinitionFromModule(module.orElseThrow(), namespaceURI, netconfOperationName);
87         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
88     }
89
90     @Override
91     protected String getOperationName() {
92         throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
93     }
94
95     private static XMLNamespace createNsUri(final String namespace) {
96         // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
97         return XMLNamespace.of(namespace);
98     }
99
100     //this returns module with the newest revision if more then 1 module with same namespace is found
101     private Optional<? extends Module> getModule(final XMLNamespace namespace) {
102         return schemaContext.getCurrentContext().findModules(namespace).stream().findFirst();
103     }
104
105     private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final XMLNamespace namespace,
106             final String name) {
107         for (final RpcDefinition rpcDef : module.getRpcs()) {
108             if (rpcDef.getQName().getNamespace().equals(namespace) && rpcDef.getQName().getLocalName().equals(name)) {
109                 return Optional.of(rpcDef);
110             }
111         }
112         return Optional.empty();
113     }
114
115     @Override
116     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
117             throws DocumentedException {
118
119         final String netconfOperationName = operationElement.getName();
120         final String netconfOperationNamespace;
121         try {
122             netconfOperationNamespace = operationElement.getNamespace();
123         } catch (final DocumentedException e) {
124             LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
125             throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e,
126                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
127         }
128
129         final XMLNamespace namespaceURI = createNsUri(netconfOperationNamespace);
130         final Optional<? extends Module> moduleOptional = getModule(namespaceURI);
131
132         if (moduleOptional.isEmpty()) {
133             throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
134                         + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
135                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
136         }
137
138         final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.orElseThrow(),
139                 namespaceURI, netconfOperationName);
140
141         if (rpcDefinitionOptional.isEmpty()) {
142             throw new DocumentedException(
143                     "Unable to find RpcDefinition with namespace and name : "
144                         + namespaceURI + " " + netconfOperationName,
145                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
146         }
147
148         final RpcDefinition rpcDefinition = rpcDefinitionOptional.orElseThrow();
149         final ContainerNode inputNode = rpcToNNode(operationElement, rpcDefinition);
150
151         final DOMRpcResult result;
152         try {
153             result = rpcService.invokeRpc(rpcDefinition.getQName(), inputNode).get();
154         } catch (final InterruptedException | ExecutionException e) {
155             throw DocumentedException.wrap(e);
156         }
157         if (result.value() == null) {
158             return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.of(NamespaceURN.BASE));
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, RpcReplyMessage.ELEMENT_NAME,
174                 Optional.of(NamespaceURN.BASE));
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(RpcReplyMessage.ELEMENT_NAME));
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 NormalizationResultHolder resultHolder = new NormalizationResultHolder();
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 | IOException 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().data();
263     }
264 }