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.server.mdsal.operations;
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.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;
58 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
59 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
60 private static final XMLOutputFactory XML_OUTPUT_FACTORY;
63 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
64 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
67 private final CurrentSchemaContext schemaContext;
68 private final DOMRpcService rpcService;
70 public RuntimeRpc(final SessionIdType sessionId, final CurrentSchemaContext schemaContext,
71 final DOMRpcService rpcService) {
73 this.schemaContext = schemaContext;
74 this.rpcService = rpcService;
78 protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
79 final XMLNamespace namespaceURI = createNsUri(namespace);
80 final Optional<? extends Module> module = getModule(namespaceURI);
82 if (module.isEmpty()) {
83 LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
84 return HandlingPriority.CANNOT_HANDLE;
87 getRpcDefinitionFromModule(module.orElseThrow(), namespaceURI, netconfOperationName);
88 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
92 protected String getOperationName() {
93 throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
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);
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();
106 private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final XMLNamespace namespace,
108 for (final RpcDefinition rpcDef : module.getRpcs()) {
109 if (rpcDef.getQName().getNamespace().equals(namespace) && rpcDef.getQName().getLocalName().equals(name)) {
110 return Optional.of(rpcDef);
113 return Optional.empty();
117 protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
118 throws DocumentedException {
120 final String netconfOperationName = operationElement.getName();
121 final String netconfOperationNamespace;
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);
130 final XMLNamespace namespaceURI = createNsUri(netconfOperationNamespace);
131 final Optional<? extends Module> moduleOptional = getModule(namespaceURI);
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);
139 final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.orElseThrow(),
140 namespaceURI, netconfOperationName);
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);
149 final RpcDefinition rpcDefinition = rpcDefinitionOptional.orElseThrow();
150 final ContainerNode inputNode = rpcToNNode(operationElement, rpcDefinition);
152 final DOMRpcResult result;
154 result = rpcService.invokeRpc(rpcDefinition.getQName(), inputNode).get();
155 } catch (final InterruptedException | ExecutionException e) {
156 throw DocumentedException.wrap(e);
158 if (result.value() == null) {
159 return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.of(NamespaceURN.BASE));
161 return transformNormalizedNode(document, result.value(),
162 Absolute.of(rpcDefinition.getQName(), rpcDefinition.getOutput().getQName()));
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();
173 final Element response = handle(document, operationElement, subsequentOperation);
174 final Element rpcReply = XmlUtil.createElement(document, XmlNetconfConstants.RPC_REPLY_KEY,
175 Optional.of(NamespaceURN.BASE));
177 if (XmlElement.fromDomElement(response).hasNamespace()) {
178 rpcReply.appendChild(response);
180 final NodeList list = response.getChildNodes();
181 if (list.getLength() == 0) {
182 rpcReply.appendChild(response);
184 while (list.getLength() != 0) {
185 rpcReply.appendChild(list.item(0));
190 for (final Attr attribute : attributes.values()) {
191 rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
193 document.appendChild(rpcReply);
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));
201 final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
203 final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
204 schemaContext.getCurrentContext(), rpcOutputPath);
206 final SchemaOrderedNormalizedNodeWriter nnWriter = new SchemaOrderedNormalizedNodeWriter(nnStreamWriter,
207 schemaContext.getCurrentContext(), rpcOutputPath);
209 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
211 nnStreamWriter.close();
213 } catch (IOException | XMLStreamException e) {
214 // FIXME: throw DocumentedException
215 LOG.warn("Error while closing streams", e);
218 return (Element) result.getNode();
221 private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
223 return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
224 } catch (final XMLStreamException e) {
225 throw new IllegalStateException(e);
229 private static void writeRootElement(final XMLStreamWriter xmlWriter,
230 final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
232 nnWriter.write(data.body());
235 } catch (XMLStreamException | IOException e) {
236 // FIXME: throw DocumentedException
237 throw new IllegalStateException(e);
242 * Parses xml element rpc input into normalized node or null if rpc does not take any input.
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
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());
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);
263 return (ContainerNode) resultHolder.getResult();