303f3e692390ff8a396781377da9c2b99f2e4cd3
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / schema / mapping / NetconfMessageTransformer.java
1 /*
2  * Copyright (c) 2014 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.controller.sal.connect.netconf.schema.mapping;
9
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;
12
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;
25 import java.util.Map;
26 import java.util.NoSuchElementException;
27 import java.util.Set;
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;
62
63 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
64
65     public static final String MESSAGE_ID_PREFIX = "m";
66
67     private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformer.class);
68
69
70     private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
71         @Override
72         public QName apply(final SchemaNode rpcDefinition) {
73             return rpcDefinition.getQName();
74         }
75     };
76
77     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
78         @Override
79         public QName apply(final SchemaNode notification) {
80             return QNAME_FUNCTION.apply(notification).withoutRevision();
81         }
82     };
83     private static final SchemaContext BASE_NETCONF_CTX;
84
85     static {
86         try {
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);
94         }
95     }
96     private static final Map<QName, RpcDefinition> MAPPED_BASE_RPCS = Maps.uniqueIndex(BASE_NETCONF_CTX.getOperations(), QNAME_FUNCTION);
97
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;
103
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);
108
109         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
110         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
111     }
112
113     @Override
114     public synchronized ContainerNode toNotification(final NetconfMessage message) {
115         final XmlElement stripped = stripNotification(message);
116         final QName notificationNoRev;
117         try {
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);
122         }
123
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());
127
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();
131
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);
135     }
136
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);
142         try {
143             return Iterables.find(childElements, new Predicate<XmlElement>() {
144                 @Override
145                 public boolean apply(final XmlElement xmlElement) {
146                     return !xmlElement.getName().equals("eventTime");
147                 }
148             });
149         } catch (final NoSuchElementException e) {
150             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot strip notification metadata", e);
151         }
152     }
153
154     @Override
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;
159
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;
165         }
166
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());
170         }
171
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);
175
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);
179
180         try {
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);
186         }
187
188         final Document node = result.getNode().getOwnerDocument();
189
190         return new NetconfMessage(node);
191     }
192
193     private static boolean isBaseRpc(final QName rpc) {
194         return rpc.getNamespace().equals(NETCONF_URI);
195     }
196
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());
200         // set msg id
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);
206     }
207
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;
212         try {
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();
219         } finally {
220             try {
221                 if(normalizedNodeStreamWriter != null) {
222                     normalizedNodeStreamWriter.close();
223                 }
224                 if(writer != null) {
225                     writer.close();
226                 }
227             } catch (final Exception e) {
228                 LOG.warn("Unable to close resource properly", e);
229             }
230         }
231     }
232
233     @Override
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);
241
242             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
243                     .withChild(dataNode).build();
244         } else {
245             final Set<Element> documentElement = Collections.singleton(message.getDocument().getDocumentElement());
246
247             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
248
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;
254             }
255
256             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
257             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
258
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;
264             } else {
265                 normalizedNode = parserFactory.getContainerNodeParser().parse(documentElement, rpcDefinition.getOutput());
266             }
267         }
268         return new DefaultDOMRpcResult(normalizedNode);
269     }
270
271 }