5b579a0a8a3ecd936e6e5b6605b065dcc3f3fd6e
[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.EVENT_TIME;
11 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RPC_QNAME;
12 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
13 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
14
15 import com.google.common.base.Function;
16 import com.google.common.base.Preconditions;
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.text.ParseException;
23 import java.text.SimpleDateFormat;
24 import java.util.AbstractMap;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Date;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import javax.annotation.Nonnull;
32 import javax.xml.stream.XMLStreamException;
33 import javax.xml.stream.XMLStreamWriter;
34 import javax.xml.transform.dom.DOMResult;
35 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
36 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
37 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
38 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
39 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
40 import org.opendaylight.controller.netconf.api.NetconfMessage;
41 import org.opendaylight.controller.netconf.notifications.NetconfNotification;
42 import org.opendaylight.controller.netconf.util.OrderedNormalizedNodeWriter;
43 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
44 import org.opendaylight.controller.netconf.util.xml.XmlElement;
45 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
46 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
47 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
48 import org.opendaylight.controller.sal.connect.util.MessageCounter;
49 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
56 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
57 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
58 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
59 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
60 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
62 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68 import org.w3c.dom.Document;
69 import org.w3c.dom.Element;
70
71 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
72
73     public static final String MESSAGE_ID_PREFIX = "m";
74
75     private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformer.class);
76
77
78     private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
79         @Override
80         public QName apply(final SchemaNode rpcDefinition) {
81             return rpcDefinition.getQName();
82         }
83     };
84
85     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
86         @Override
87         public QName apply(final SchemaNode notification) {
88             return QNAME_FUNCTION.apply(notification).withoutRevision();
89         }
90     };
91     private static final SchemaContext BASE_NETCONF_CTX;
92
93     static {
94         try {
95             final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
96             moduleInfoBackedContext.addModuleInfos(
97                     Lists.newArrayList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
98             BASE_NETCONF_CTX = moduleInfoBackedContext.tryToCreateSchemaContext().get();
99         } catch (final RuntimeException e) {
100             LOG.error("Unable to prepare schema context for base netconf ops", e);
101             throw new ExceptionInInitializerError(e);
102         }
103     }
104     private static final Map<QName, RpcDefinition> MAPPED_BASE_RPCS = Maps.uniqueIndex(BASE_NETCONF_CTX.getOperations(), QNAME_FUNCTION);
105
106     private final SchemaContext schemaContext;
107     private final MessageCounter counter;
108     private final Map<QName, RpcDefinition> mappedRpcs;
109     private final Multimap<QName, NotificationDefinition> mappedNotifications;
110     private final DomToNormalizedNodeParserFactory parserFactory;
111
112     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
113         this.counter = new MessageCounter();
114         this.schemaContext = schemaContext;
115         parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
116
117         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
118         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
119     }
120
121     @Override
122     public synchronized DOMNotification toNotification(final NetconfMessage message) {
123         final Map.Entry<Date, XmlElement> stripped = stripNotification(message);
124         final QName notificationNoRev;
125         try {
126             // How to construct QName with no revision ?
127             notificationNoRev = QName.cachedReference(QName.create(stripped.getValue().getNamespace(), "0000-00-00", stripped.getValue().getName()).withoutRevision());
128         } catch (final MissingNameSpaceException e) {
129             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
130         }
131
132         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
133         Preconditions.checkArgument(notificationDefinitions.size() > 0,
134                 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
135
136         // FIXME if multiple revisions for same notifications are present, we should pick the most recent. Or ?
137         // 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.
138         final NotificationDefinition next = notificationDefinitions.iterator().next();
139
140         // We wrap the notification as a container node in order to reuse the parsers and builders for container node
141         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(next);
142         final ContainerNode content = parserFactory.getContainerNodeParser().parse(Collections.singleton(stripped.getValue().getDomElement()),
143                 notificationAsContainerSchemaNode);
144         return new NetconfDeviceNotification(content, stripped.getKey());
145     }
146
147     // FIXME move somewhere to util
148     private static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
149         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
150         final List<XmlElement> childElements = xmlElement.getChildElements();
151         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format", message);
152
153         final XmlElement eventTimeElement;
154         final XmlElement notificationElement;
155
156         if (childElements.get(0).getName().equals(EVENT_TIME)) {
157             eventTimeElement = childElements.get(0);
158             notificationElement = childElements.get(1);
159         }
160         else if(childElements.get(1).getName().equals(EVENT_TIME)) {
161             eventTimeElement = childElements.get(1);
162             notificationElement = childElements.get(0);
163         } else {
164             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
165         }
166
167         try {
168             return new AbstractMap.SimpleEntry<>(parseEventTime(eventTimeElement.getTextContent()), notificationElement);
169         } catch (NetconfDocumentedException e) {
170             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
171         }
172     }
173
174     private static Date parseEventTime(final String eventTime) {
175         try {
176             return new SimpleDateFormat(NetconfNotification.RFC3339_DATE_FORMAT_BLUEPRINT).parse(eventTime);
177         } catch (ParseException e) {
178             throw new IllegalArgumentException("Unable to parse event time from " + eventTime, e);
179         }
180     }
181
182     @Override
183     public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
184         // In case no input for rpc is defined, we can simply construct the payload here
185         final QName rpcQName = rpc.getLastComponent();
186         Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
187
188         // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
189         // If no, use pre built base netconf operations model
190         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseRpc(rpcQName);
191         if(needToUseBaseCtx) {
192             currentMappedRpcs = MAPPED_BASE_RPCS;
193         }
194
195         Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
196         if(currentMappedRpcs.get(rpcQName).getInput() == null) {
197             return new NetconfMessage(prepareDomResultForRpcRequest(rpcQName).getNode().getOwnerDocument());
198         }
199
200         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
201         Preconditions.checkArgument(payload instanceof ContainerNode,
202                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
203
204         // Set the path to the input of rpc for the node stream writer
205         rpc = rpc.createChild(QName.cachedReference(QName.create(rpcQName, "input")));
206         final DOMResult result = prepareDomResultForRpcRequest(rpcQName);
207
208         try {
209             // 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
210             // This way operations like lock/unlock are supported even if the source for base model was not provided
211             writeNormalizedRpc(((ContainerNode) payload), result, rpc, needToUseBaseCtx ? BASE_NETCONF_CTX : schemaContext);
212         } catch (final XMLStreamException | IOException | IllegalStateException e) {
213             throw new IllegalStateException("Unable to serialize " + rpc, e);
214         }
215
216         final Document node = result.getNode().getOwnerDocument();
217
218         return new NetconfMessage(node);
219     }
220
221     private static boolean isBaseRpc(final QName rpc) {
222         return rpc.getNamespace().equals(NETCONF_URI);
223     }
224
225     private DOMResult prepareDomResultForRpcRequest(final QName rpcQName) {
226         final Document document = XmlUtil.newDocument();
227         final Element rpcNS = document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
228         // set msg id
229         rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
230         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
231         rpcNS.appendChild(elementNS);
232         document.appendChild(rpcNS);
233         return new DOMResult(elementNS);
234     }
235
236     private void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
237         final OrderedNormalizedNodeWriter normalizedNodeWriter;
238         NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
239         XMLStreamWriter writer = null;
240         try {
241             writer = NetconfMessageTransformUtil.XML_FACTORY.createXMLStreamWriter(result);
242             normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath);
243             normalizedNodeWriter = new OrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath);
244             Collection<DataContainerChild<?, ?>> value = (Collection) normalized.getValue();
245             normalizedNodeWriter.write(value);
246             normalizedNodeWriter.flush();
247         } finally {
248             try {
249                 if(normalizedNodeStreamWriter != null) {
250                     normalizedNodeStreamWriter.close();
251                 }
252                 if(writer != null) {
253                     writer.close();
254                 }
255             } catch (final Exception e) {
256                 LOG.warn("Unable to close resource properly", e);
257             }
258         }
259     }
260
261     @Override
262     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
263         final NormalizedNode<?, ?> normalizedNode;
264         final QName rpcQName = rpc.getLastComponent();
265         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
266             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
267             final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
268             final ContainerNode dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
269
270             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
271                     .withChild(dataNode).build();
272         } else {
273             final Set<Element> documentElement = Collections.singleton(message.getDocument().getDocumentElement());
274
275             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
276
277             // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
278             // If no, use pre built base netconf operations model
279             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseRpc(rpcQName);
280             if(needToUseBaseCtx) {
281                 currentMappedRpcs = MAPPED_BASE_RPCS;
282             }
283
284             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
285             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
286
287             // In case no input for rpc is defined, we can simply construct the payload here
288             if (rpcDefinition.getOutput() == null) {
289                 Preconditions.checkArgument(XmlElement.fromDomDocument(message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
290                         "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
291                 normalizedNode = null;
292             } else {
293                 normalizedNode = parserFactory.getContainerNodeParser().parse(documentElement, rpcDefinition.getOutput());
294             }
295         }
296         return new DefaultDOMRpcResult(normalizedNode);
297     }
298
299     private static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
300         private final ContainerNode content;
301         private final SchemaPath schemaPath;
302         private final Date eventTime;
303
304         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
305             this.content = content;
306             this.eventTime = eventTime;
307             this.schemaPath = toPath(content.getNodeType());
308         }
309
310         @Nonnull
311         @Override
312         public SchemaPath getType() {
313             return schemaPath;
314
315         }
316
317         @Nonnull
318         @Override
319         public ContainerNode getBody() {
320             return content;
321         }
322
323         @Override
324         public Date getEventTime() {
325             return eventTime;
326         }
327     }
328 }