2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.mdsal.connector.ops;
10 import java.io.IOException;
11 import java.net.URISyntaxException;
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;
56 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
57 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
58 private static final XMLOutputFactory XML_OUTPUT_FACTORY;
61 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
62 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
65 private final CurrentSchemaContext schemaContext;
66 private final DOMRpcService rpcService;
68 public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
69 final DOMRpcService rpcService) {
70 super(netconfSessionIdForReporting);
71 this.schemaContext = schemaContext;
72 this.rpcService = rpcService;
76 protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
77 final XMLNamespace namespaceURI = createNsUri(namespace);
78 final Optional<? extends Module> module = getModule(namespaceURI);
80 if (module.isEmpty()) {
81 LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
82 return HandlingPriority.CANNOT_HANDLE;
85 getRpcDefinitionFromModule(module.orElseThrow(), namespaceURI, netconfOperationName);
86 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
90 protected String getOperationName() {
91 throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
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);
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();
104 private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final XMLNamespace namespace,
106 for (final RpcDefinition rpcDef : module.getRpcs()) {
107 if (rpcDef.getQName().getNamespace().equals(namespace) && rpcDef.getQName().getLocalName().equals(name)) {
108 return Optional.of(rpcDef);
111 return Optional.empty();
115 protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
116 throws DocumentedException {
118 final String netconfOperationName = operationElement.getName();
119 final String netconfOperationNamespace;
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);
128 final XMLNamespace namespaceURI = createNsUri(netconfOperationNamespace);
129 final Optional<? extends Module> moduleOptional = getModule(namespaceURI);
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);
137 final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.orElseThrow(),
138 namespaceURI, netconfOperationName);
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);
147 final RpcDefinition rpcDefinition = rpcDefinitionOptional.orElseThrow();
148 final ContainerNode inputNode = rpcToNNode(operationElement, rpcDefinition);
150 final DOMRpcResult result;
152 result = rpcService.invokeRpc(rpcDefinition.getQName(), inputNode).get();
153 } catch (final InterruptedException | ExecutionException e) {
154 throw DocumentedException.wrap(e);
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));
160 return transformNormalizedNode(document, result.value(),
161 Absolute.of(rpcDefinition.getQName(), rpcDefinition.getOutput().getQName()));
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();
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));
176 if (XmlElement.fromDomElement(response).hasNamespace()) {
177 rpcReply.appendChild(response);
179 final NodeList list = response.getChildNodes();
180 if (list.getLength() == 0) {
181 rpcReply.appendChild(response);
183 while (list.getLength() != 0) {
184 rpcReply.appendChild(list.item(0));
189 for (final Attr attribute : attributes.values()) {
190 rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
192 document.appendChild(rpcReply);
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));
200 final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
202 final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
203 schemaContext.getCurrentContext(), rpcOutputPath);
205 final SchemaOrderedNormalizedNodeWriter nnWriter = new SchemaOrderedNormalizedNodeWriter(nnStreamWriter,
206 schemaContext.getCurrentContext(), rpcOutputPath);
208 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
210 nnStreamWriter.close();
212 } catch (IOException | XMLStreamException e) {
213 // FIXME: throw DocumentedException
214 LOG.warn("Error while closing streams", e);
217 return (Element) result.getNode();
220 private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
222 return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
223 } catch (final XMLStreamException e) {
224 throw new IllegalStateException(e);
228 private static void writeRootElement(final XMLStreamWriter xmlWriter,
229 final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
231 nnWriter.write(data.body());
234 } catch (XMLStreamException | IOException e) {
235 // FIXME: throw DocumentedException
236 throw new IllegalStateException(e);
241 * Parses xml element rpc input into normalized node or null if rpc does not take any input.
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
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());
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);
262 return (ContainerNode) resultHolder.getResult();