Merge "More netconf-topology module unit tests"
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / 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.netconf.sal.connect.netconf.schema.mapping;
9
10 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.EVENT_TIME;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RPC_QNAME;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
15
16 import com.google.common.base.Function;
17 import com.google.common.base.Preconditions;
18 import com.google.common.collect.Lists;
19 import com.google.common.collect.Maps;
20 import com.google.common.collect.Multimap;
21 import com.google.common.collect.Multimaps;
22 import java.io.IOException;
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
25 import java.util.AbstractMap;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.Date;
29 import java.util.List;
30 import java.util.Map;
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.config.util.xml.DocumentedException;
36 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
37 import org.opendaylight.controller.config.util.xml.XmlElement;
38 import org.opendaylight.controller.config.util.xml.XmlUtil;
39 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
40 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
41 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
42 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
43 import org.opendaylight.netconf.api.NetconfMessage;
44 import org.opendaylight.netconf.notifications.NetconfNotification;
45 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
46 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
47 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
48 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
49 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
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.SchemaOrderedNormalizedNodeWriter;
60 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
61 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
63 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.w3c.dom.Document;
70 import org.w3c.dom.Element;
71
72 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
73
74     public enum BaseSchema {
75
76         BASE_NETCONF_CTX(
77                 Lists.newArrayList(
78                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
79                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
80                 )
81         ),
82         BASE_NETCONF_CTX_WITH_NOTIFICATIONS(
83                 Lists.newArrayList(
84                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
85                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
86                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
87                         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()
88                 )
89         );
90
91         private final Map<QName, RpcDefinition> mappedRpcs;
92         private final SchemaContext schemaContext;
93
94         BaseSchema(List<YangModuleInfo> modules) {
95             try {
96                 final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
97                 moduleInfoBackedContext.addModuleInfos(modules);
98                 schemaContext = moduleInfoBackedContext.tryToCreateSchemaContext().get();
99                 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
100             } catch (final RuntimeException e) {
101                 LOG.error("Unable to prepare schema context for base netconf ops", e);
102                 throw new ExceptionInInitializerError(e);
103             }
104         }
105
106         private Map<QName, RpcDefinition> getMappedRpcs() {
107             return mappedRpcs;
108         }
109
110         public SchemaContext getSchemaContext() {
111             return schemaContext;
112         }
113     }
114
115     public static final String MESSAGE_ID_PREFIX = "m";
116
117     private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformer.class);
118
119
120     private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
121         @Override
122         public QName apply(final SchemaNode rpcDefinition) {
123             return rpcDefinition.getQName();
124         }
125     };
126
127     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
128         @Override
129         public QName apply(final SchemaNode notification) {
130             return QNAME_FUNCTION.apply(notification).withoutRevision();
131         }
132     };
133
134     private final SchemaContext schemaContext;
135     private final BaseSchema baseSchema;
136     private final MessageCounter counter;
137     private final Map<QName, RpcDefinition> mappedRpcs;
138     private final Multimap<QName, NotificationDefinition> mappedNotifications;
139     private final DomToNormalizedNodeParserFactory parserFactory;
140
141     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
142         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
143     }
144
145     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
146         this.counter = new MessageCounter();
147         this.schemaContext = schemaContext;
148         parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
149         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
150         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
151         this.baseSchema = baseSchema;
152     }
153
154     @Override
155     public synchronized DOMNotification toNotification(final NetconfMessage message) {
156         final Map.Entry<Date, XmlElement> stripped = stripNotification(message);
157         final QName notificationNoRev;
158         try {
159             notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
160         } catch (final MissingNameSpaceException e) {
161             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
162         }
163
164         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
165         Preconditions.checkArgument(notificationDefinitions.size() > 0,
166                 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
167
168         // FIXME if multiple revisions for same notifications are present, we should pick the most recent. Or ?
169         // 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.
170         final NotificationDefinition next = notificationDefinitions.iterator().next();
171
172         // We wrap the notification as a container node in order to reuse the parsers and builders for container node
173         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(next);
174
175         final Element element = stripped.getValue().getDomElement();
176         final ContainerNode content;
177         try {
178             content = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
179                 notificationAsContainerSchemaNode);
180         } catch (IllegalArgumentException e) {
181             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
182         }
183         return new NetconfDeviceNotification(content, stripped.getKey());
184     }
185
186     private static final ThreadLocal<SimpleDateFormat> EVENT_TIME_FORMAT = new ThreadLocal<SimpleDateFormat>() {
187         @Override
188         protected SimpleDateFormat initialValue() {
189
190             final SimpleDateFormat withMillis = new SimpleDateFormat(
191                 NetconfNotification.RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT);
192
193             return new SimpleDateFormat(NetconfNotification.RFC3339_DATE_FORMAT_BLUEPRINT) {
194                 private static final long serialVersionUID = 1L;
195
196                 @Override public Date parse(final String source) throws ParseException {
197                     try {
198                         return super.parse(source);
199                     } catch (ParseException e) {
200                         // In case of failure, try to parse with milliseconds
201                         return withMillis.parse(source);
202                     }
203                 }
204             };
205         }
206
207         @Override
208         public void set(final SimpleDateFormat value) {
209             throw new UnsupportedOperationException();
210         }
211     };
212
213     // FIXME move somewhere to util
214     private static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
215         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
216         final List<XmlElement> childElements = xmlElement.getChildElements();
217         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format", message);
218
219         final XmlElement eventTimeElement;
220         final XmlElement notificationElement;
221
222         if (childElements.get(0).getName().equals(EVENT_TIME)) {
223             eventTimeElement = childElements.get(0);
224             notificationElement = childElements.get(1);
225         }
226         else if(childElements.get(1).getName().equals(EVENT_TIME)) {
227             eventTimeElement = childElements.get(1);
228             notificationElement = childElements.get(0);
229         } else {
230             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
231         }
232
233         try {
234             return new AbstractMap.SimpleEntry<>(EVENT_TIME_FORMAT.get().parse(eventTimeElement.getTextContent()), notificationElement);
235         } catch (DocumentedException e) {
236             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
237         } catch (ParseException e) {
238             LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e);
239             return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
240         }
241     }
242
243     @Override
244     public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
245         // In case no input for rpc is defined, we can simply construct the payload here
246         final QName rpcQName = rpc.getLastComponent();
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 && isBaseOrNotificationRpc(rpcQName);
252         if(needToUseBaseCtx) {
253             currentMappedRpcs = baseSchema.getMappedRpcs();
254         }
255
256         Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
257         if(currentMappedRpcs.get(rpcQName).getInput() == null) {
258             return new NetconfMessage(prepareDomResultForRpcRequest(rpcQName).getNode().getOwnerDocument());
259         }
260
261         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
262         Preconditions.checkArgument(payload instanceof ContainerNode,
263                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
264
265         // Set the path to the input of rpc for the node stream writer
266         rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
267         final DOMResult result = prepareDomResultForRpcRequest(rpcQName);
268
269         try {
270             // 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
271             // This way operations like lock/unlock are supported even if the source for base model was not provided
272             SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
273             writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
274         } catch (final XMLStreamException | IOException | IllegalStateException e) {
275             throw new IllegalStateException("Unable to serialize " + rpc, e);
276         }
277
278         final Document node = result.getNode().getOwnerDocument();
279
280         return new NetconfMessage(node);
281     }
282
283     private boolean isBaseOrNotificationRpc(final QName rpc) {
284         return rpc.getNamespace().equals(NETCONF_URI) ||
285                 rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
286                 rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
287     }
288
289     private DOMResult prepareDomResultForRpcRequest(final QName rpcQName) {
290         final Document document = XmlUtil.newDocument();
291         final Element rpcNS = document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
292         // set msg id
293         rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
294         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
295         rpcNS.appendChild(elementNS);
296         document.appendChild(rpcNS);
297         return new DOMResult(elementNS);
298     }
299
300     private static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
301             final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
302         final XMLStreamWriter writer = NetconfMessageTransformUtil.XML_FACTORY.createXMLStreamWriter(result);
303         try {
304             try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
305                     XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
306                 try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
307                         new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
308                     Collection<DataContainerChild<?, ?>> value = normalized.getValue();
309                     normalizedNodeWriter.write(value);
310                     normalizedNodeWriter.flush();
311                 }
312             }
313         } finally {
314             try {
315                 writer.close();
316             } catch (final Exception e) {
317                 LOG.warn("Unable to close resource properly", e);
318             }
319         }
320     }
321
322     @Override
323     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
324         final NormalizedNode<?, ?> normalizedNode;
325         final QName rpcQName = rpc.getLastComponent();
326         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
327             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
328             final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
329             final ContainerNode dataNode;
330
331             try {
332                 dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
333             } catch (IllegalArgumentException e) {
334                 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
335             }
336
337             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
338                     .withChild(dataNode).build();
339         } else {
340
341             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
342
343             // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
344             // If no, use pre built base netconf operations model
345             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
346             if(needToUseBaseCtx) {
347                 currentMappedRpcs = baseSchema.getMappedRpcs();
348             }
349
350             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
351             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
352
353             // In case no input for rpc is defined, we can simply construct the payload here
354             if (rpcDefinition.getOutput() == null) {
355                 Preconditions.checkArgument(XmlElement.fromDomDocument(
356                     message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
357                     "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
358                 normalizedNode = null;
359             } else {
360                 final Element element = message.getDocument().getDocumentElement();
361                 try {
362                     normalizedNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
363                         rpcDefinition.getOutput());
364                 } catch (IllegalArgumentException e) {
365                     throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
366                 }
367             }
368         }
369         return new DefaultDOMRpcResult(normalizedNode);
370     }
371
372     private static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
373         private final ContainerNode content;
374         private final SchemaPath schemaPath;
375         private final Date eventTime;
376
377         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
378             this.content = content;
379             this.eventTime = eventTime;
380             this.schemaPath = toPath(content.getNodeType());
381         }
382
383         @Nonnull
384         @Override
385         public SchemaPath getType() {
386             return schemaPath;
387
388         }
389
390         @Nonnull
391         @Override
392         public ContainerNode getBody() {
393             return content;
394         }
395
396         @Override
397         public Date getEventTime() {
398             return eventTime;
399         }
400     }
401 }