Add SchemaContext to NormalizedNode parser in NETCONF
[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
12 import com.google.common.base.Function;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicate;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.Maps;
18 import com.google.common.collect.Multimap;
19 import com.google.common.collect.Multimaps;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.NoSuchElementException;
26 import java.util.Set;
27 import javax.xml.stream.XMLStreamException;
28 import javax.xml.stream.XMLStreamWriter;
29 import javax.xml.transform.dom.DOMResult;
30 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
31 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
32 import org.opendaylight.controller.netconf.api.NetconfMessage;
33 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
34 import org.opendaylight.controller.netconf.util.xml.XmlElement;
35 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
36 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
37 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
38 import org.opendaylight.controller.sal.connect.util.MessageCounter;
39 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
47 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
49 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
50 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
51 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
53 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.w3c.dom.Element;
61
62 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
63
64     public static final String MESSAGE_ID_PREFIX = "m";
65
66     private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformer.class);
67
68
69     private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
70         @Override
71         public QName apply(final SchemaNode rpcDefinition) {
72             return rpcDefinition.getQName();
73         }
74     };
75
76     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
77         @Override
78         public QName apply(final SchemaNode notification) {
79             return QNAME_FUNCTION.apply(notification).withoutRevision();
80         }
81     };
82     private static final SchemaContext BASE_NETCONF_CTX;
83
84     static {
85         try {
86             final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
87             // TODO this should be used only if the base is not present
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
97     private final SchemaContext schemaContext;
98     private final MessageCounter counter;
99     private final Map<QName, RpcDefinition> mappedRpcs;
100     private final Multimap<QName, NotificationDefinition> mappedNotifications;
101     private final DomToNormalizedNodeParserFactory parserFactory;
102
103     public NetconfMessageTransformer(final SchemaContext schemaContext) {
104         this.counter = new MessageCounter();
105         this.schemaContext = schemaContext;
106         parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext);
107
108         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
109         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
110     }
111
112     @Override
113     public synchronized ContainerNode toNotification(final NetconfMessage message) {
114         final XmlElement stripped = stripNotification(message);
115         final QName notificationNoRev;
116         try {
117             // How to construct QName with no revision ?
118             notificationNoRev = QName.cachedReference(QName.create(stripped.getNamespace(), "0000-00-00", stripped.getName()).withoutRevision());
119         } catch (final MissingNameSpaceException e) {
120             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
121         }
122
123         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
124         Preconditions.checkArgument(notificationDefinitions.size() > 0,
125                 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
126
127         // FIXME if multiple revisions for same notifications are present, we should pick the most recent. Or ?
128         // 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.
129         final NotificationDefinition next = notificationDefinitions.iterator().next();
130
131         // We wrap the notification as a container node in order to reuse the parsers and builders for container node
132         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(next);
133         return parserFactory.getContainerNodeParser().parse(Collections.singleton(stripped.getDomElement()), notificationAsContainerSchemaNode);
134     }
135
136     // FIXME move somewhere to util
137     private static XmlElement stripNotification(final NetconfMessage message) {
138         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
139         final List<XmlElement> childElements = xmlElement.getChildElements();
140         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format", message);
141         try {
142             return Iterables.find(childElements, new Predicate<XmlElement>() {
143                 @Override
144                 public boolean apply(final XmlElement xmlElement) {
145                     return !xmlElement.getName().equals("eventTime");
146                 }
147             });
148         } catch (final NoSuchElementException e) {
149             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot strip notification metadata", e);
150         }
151     }
152
153     @Override
154     public NetconfMessage toRpcRequest(SchemaPath rpc, final ContainerNode payload) {
155         // In case no input for rpc is defined, we can simply construct the payload here
156         final QName rpcQName = rpc.getLastComponent();
157         Preconditions.checkNotNull(mappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, mappedRpcs.keySet());
158         if(mappedRpcs.get(rpcQName).getInput() == null) {
159             final Document document = XmlUtil.newDocument();
160             final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
161             document.appendChild(elementNS);
162             return new NetconfMessage(document);
163         }
164
165         // Set the path to the input of rpc for the node stream writer
166         rpc = rpc.createChild(QName.cachedReference(QName.create(rpcQName, "input")));
167         final DOMResult result = prepareDomResultForRpcRequest(rpcQName);
168
169         try {
170             writeNormalizedRpc(payload, result, rpc, schemaContext);
171         } catch (final XMLStreamException | IOException | IllegalStateException e) {
172             throw new IllegalStateException("Unable to serialize " + rpc, e);
173         }
174
175         final Document node = result.getNode().getOwnerDocument();
176
177         node.getDocumentElement().setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
178         return new NetconfMessage(node);
179     }
180
181     private DOMResult prepareDomResultForRpcRequest(final QName rpcQName) {
182         final Document document = XmlUtil.newDocument();
183         final Element rpcNS = document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
184         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
185         rpcNS.appendChild(elementNS);
186         document.appendChild(rpcNS);
187         return new DOMResult(elementNS);
188     }
189
190     private void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
191         final NormalizedNodeWriter normalizedNodeWriter;
192         NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
193         XMLStreamWriter writer = null;
194         try {
195             writer = NetconfMessageTransformUtil.XML_FACTORY.createXMLStreamWriter(result);
196             normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath);
197             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
198
199             for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> editElement : normalized.getValue()) {
200                 normalizedNodeWriter.write(editElement);
201             }
202             normalizedNodeWriter.flush();
203         } finally {
204             try {
205                 if(normalizedNodeStreamWriter != null) {
206                     normalizedNodeStreamWriter.close();
207                 }
208                 if(writer != null) {
209                     writer.close();
210                 }
211             } catch (final Exception e) {
212                 LOG.warn("Unable to close resource properly", e);
213             }
214         }
215     }
216
217     @Override
218     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
219         final NormalizedNode<?, ?> normalizedNode;
220         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpc.getLastComponent())) {
221             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
222             final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
223             final ContainerNode dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
224
225             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
226                     .withChild(dataNode).build();
227         } else {
228             final Set<Element> documentElement = Collections.singleton(message.getDocument().getDocumentElement());
229             final RpcDefinition rpcDefinition = mappedRpcs.get(rpc.getLastComponent());
230             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpc.getLastComponent());
231
232             // In case no input for rpc is defined, we can simply construct the payload here
233             if (rpcDefinition.getOutput() == null) {
234                 Preconditions.checkArgument(XmlElement.fromDomDocument(message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
235                         "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
236                 normalizedNode = null;
237             } else {
238                 normalizedNode = parserFactory.getContainerNodeParser().parse(documentElement, rpcDefinition.getOutput());
239             }
240         }
241         return new DefaultDOMRpcResult(normalizedNode);
242     }
243
244 }