2 * Copyright (c) 2014 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.controller.sal.connect.netconf.schema.mapping;
10 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RPC_QNAME;
11 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
13 import com.google.common.base.Function;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicate;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Maps;
19 import com.google.common.collect.Multimap;
20 import com.google.common.collect.Multimaps;
21 import java.io.IOException;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
26 import java.util.NoSuchElementException;
28 import javax.xml.stream.XMLStreamException;
29 import javax.xml.stream.XMLStreamWriter;
30 import javax.xml.transform.dom.DOMResult;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
32 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
33 import org.opendaylight.controller.netconf.api.NetconfMessage;
34 import org.opendaylight.controller.netconf.util.OrderedNormalizedNodeWriter;
35 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
36 import org.opendaylight.controller.netconf.util.xml.XmlElement;
37 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
38 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
39 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
40 import org.opendaylight.controller.sal.connect.util.MessageCounter;
41 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
50 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
51 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
52 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
54 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.w3c.dom.Document;
61 import org.w3c.dom.Element;
63 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
65 public static final String MESSAGE_ID_PREFIX = "m";
67 private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformer.class);
70 private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
72 public QName apply(final SchemaNode rpcDefinition) {
73 return rpcDefinition.getQName();
77 private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
79 public QName apply(final SchemaNode notification) {
80 return QNAME_FUNCTION.apply(notification).withoutRevision();
83 private static final SchemaContext BASE_NETCONF_CTX;
87 final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
88 moduleInfoBackedContext.addModuleInfos(
89 Lists.newArrayList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
90 BASE_NETCONF_CTX = moduleInfoBackedContext.tryToCreateSchemaContext().get();
91 } catch (final RuntimeException e) {
92 LOG.error("Unable to prepare schema context for base netconf ops", e);
93 throw new ExceptionInInitializerError(e);
96 private static final Map<QName, RpcDefinition> MAPPED_BASE_RPCS = Maps.uniqueIndex(BASE_NETCONF_CTX.getOperations(), QNAME_FUNCTION);
98 private final SchemaContext schemaContext;
99 private final MessageCounter counter;
100 private final Map<QName, RpcDefinition> mappedRpcs;
101 private final Multimap<QName, NotificationDefinition> mappedNotifications;
102 private final DomToNormalizedNodeParserFactory parserFactory;
104 public NetconfMessageTransformer(final SchemaContext schemaContext) {
105 this.counter = new MessageCounter();
106 this.schemaContext = schemaContext;
107 parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext);
109 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
110 mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
114 public synchronized ContainerNode toNotification(final NetconfMessage message) {
115 final XmlElement stripped = stripNotification(message);
116 final QName notificationNoRev;
118 // How to construct QName with no revision ?
119 notificationNoRev = QName.cachedReference(QName.create(stripped.getNamespace(), "0000-00-00", stripped.getName()).withoutRevision());
120 } catch (final MissingNameSpaceException e) {
121 throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
124 final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
125 Preconditions.checkArgument(notificationDefinitions.size() > 0,
126 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
128 // FIXME if multiple revisions for same notifications are present, we should pick the most recent. Or ?
129 // We should probably just put the most recent notification versions into our map. We can expect that the device sends the data according to the latest available revision of a model.
130 final NotificationDefinition next = notificationDefinitions.iterator().next();
132 // We wrap the notification as a container node in order to reuse the parsers and builders for container node
133 final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(next);
134 return parserFactory.getContainerNodeParser().parse(Collections.singleton(stripped.getDomElement()), notificationAsContainerSchemaNode);
137 // FIXME move somewhere to util
138 private static XmlElement stripNotification(final NetconfMessage message) {
139 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
140 final List<XmlElement> childElements = xmlElement.getChildElements();
141 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format", message);
143 return Iterables.find(childElements, new Predicate<XmlElement>() {
145 public boolean apply(final XmlElement xmlElement) {
146 return !xmlElement.getName().equals("eventTime");
149 } catch (final NoSuchElementException e) {
150 throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot strip notification metadata", e);
155 public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
156 // In case no input for rpc is defined, we can simply construct the payload here
157 final QName rpcQName = rpc.getLastComponent();
158 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
160 // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
161 // If no, use pre built base netconf operations model
162 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseRpc(rpcQName);
163 if(needToUseBaseCtx) {
164 currentMappedRpcs = MAPPED_BASE_RPCS;
167 Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
168 if(currentMappedRpcs.get(rpcQName).getInput() == null) {
169 return new NetconfMessage(prepareDomResultForRpcRequest(rpcQName).getNode().getOwnerDocument());
172 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
173 Preconditions.checkArgument(payload instanceof ContainerNode,
174 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
176 // Set the path to the input of rpc for the node stream writer
177 rpc = rpc.createChild(QName.cachedReference(QName.create(rpcQName, "input")));
178 final DOMResult result = prepareDomResultForRpcRequest(rpcQName);
181 // If the schema context for netconf device does not contain model for base netconf operations, use default pre build context with just the base model
182 // This way operations like lock/unlock are supported even if the source for base model was not provided
183 writeNormalizedRpc(((ContainerNode) payload), result, rpc, needToUseBaseCtx ? BASE_NETCONF_CTX : schemaContext);
184 } catch (final XMLStreamException | IOException | IllegalStateException e) {
185 throw new IllegalStateException("Unable to serialize " + rpc, e);
188 final Document node = result.getNode().getOwnerDocument();
190 return new NetconfMessage(node);
193 private static boolean isBaseRpc(final QName rpc) {
194 return rpc.getNamespace().equals(NETCONF_URI);
197 private DOMResult prepareDomResultForRpcRequest(final QName rpcQName) {
198 final Document document = XmlUtil.newDocument();
199 final Element rpcNS = document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
201 rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
202 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
203 rpcNS.appendChild(elementNS);
204 document.appendChild(rpcNS);
205 return new DOMResult(elementNS);
208 private void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
209 final OrderedNormalizedNodeWriter normalizedNodeWriter;
210 NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
211 XMLStreamWriter writer = null;
213 writer = NetconfMessageTransformUtil.XML_FACTORY.createXMLStreamWriter(result);
214 normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath);
215 normalizedNodeWriter = new OrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath);
216 Collection<DataContainerChild<?, ?>> value = (Collection) normalized.getValue();
217 normalizedNodeWriter.write(value);
218 normalizedNodeWriter.flush();
221 if(normalizedNodeStreamWriter != null) {
222 normalizedNodeStreamWriter.close();
227 } catch (final Exception e) {
228 LOG.warn("Unable to close resource properly", e);
234 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
235 final NormalizedNode<?, ?> normalizedNode;
236 final QName rpcQName = rpc.getLastComponent();
237 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
238 final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
239 final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
240 final ContainerNode dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
242 normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
243 .withChild(dataNode).build();
245 final Set<Element> documentElement = Collections.singleton(message.getDocument().getDocumentElement());
247 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
249 // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
250 // If no, use pre built base netconf operations model
251 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseRpc(rpcQName);
252 if(needToUseBaseCtx) {
253 currentMappedRpcs = MAPPED_BASE_RPCS;
256 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
257 Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
259 // In case no input for rpc is defined, we can simply construct the payload here
260 if (rpcDefinition.getOutput() == null) {
261 Preconditions.checkArgument(XmlElement.fromDomDocument(message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
262 "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
263 normalizedNode = null;
265 normalizedNode = parserFactory.getContainerNodeParser().parse(documentElement, rpcDefinition.getOutput());
268 return new DefaultDOMRpcResult(normalizedNode);