BUG-4521 Support milliseconds in event-time notification format
[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             notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
127         } catch (final MissingNameSpaceException e) {
128             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
129         }
130
131         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
132         Preconditions.checkArgument(notificationDefinitions.size() > 0,
133                 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
134
135         // FIXME if multiple revisions for same notifications are present, we should pick the most recent. Or ?
136         // 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.
137         final NotificationDefinition next = notificationDefinitions.iterator().next();
138
139         // We wrap the notification as a container node in order to reuse the parsers and builders for container node
140         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(next);
141         final ContainerNode content = parserFactory.getContainerNodeParser().parse(Collections.singleton(stripped.getValue().getDomElement()),
142                 notificationAsContainerSchemaNode);
143         return new NetconfDeviceNotification(content, stripped.getKey());
144     }
145
146     private static final ThreadLocal<SimpleDateFormat> EVENT_TIME_FORMAT = new ThreadLocal<SimpleDateFormat>() {
147         protected SimpleDateFormat initialValue() {
148             final SimpleDateFormat withMillis = new SimpleDateFormat(
149                 NetconfNotification.RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT);
150
151             return new SimpleDateFormat(NetconfNotification.RFC3339_DATE_FORMAT_BLUEPRINT) {
152                 @Override public Date parse(final String source) throws ParseException {
153                     try {
154                         return super.parse(source);
155                     } catch (ParseException e) {
156                         // In case of failure, try to parse with milliseconds
157                         return withMillis.parse(source);
158                     }
159                 }
160             };
161         }
162
163         public void set(SimpleDateFormat value) {
164             throw new UnsupportedOperationException();
165         }
166     };
167
168     // FIXME move somewhere to util
169     private static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
170         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
171         final List<XmlElement> childElements = xmlElement.getChildElements();
172         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format", message);
173
174         final XmlElement eventTimeElement;
175         final XmlElement notificationElement;
176
177         if (childElements.get(0).getName().equals(EVENT_TIME)) {
178             eventTimeElement = childElements.get(0);
179             notificationElement = childElements.get(1);
180         }
181         else if(childElements.get(1).getName().equals(EVENT_TIME)) {
182             eventTimeElement = childElements.get(1);
183             notificationElement = childElements.get(0);
184         } else {
185             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
186         }
187
188         try {
189             return new AbstractMap.SimpleEntry<>(EVENT_TIME_FORMAT.get().parse(eventTimeElement.getTextContent()), notificationElement);
190         } catch (NetconfDocumentedException e) {
191             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
192         } catch (ParseException e) {
193             LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e);
194             return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
195         }
196     }
197
198     @Override
199     public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
200         // In case no input for rpc is defined, we can simply construct the payload here
201         final QName rpcQName = rpc.getLastComponent();
202         Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
203
204         // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
205         // If no, use pre built base netconf operations model
206         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseRpc(rpcQName);
207         if(needToUseBaseCtx) {
208             currentMappedRpcs = MAPPED_BASE_RPCS;
209         }
210
211         Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
212         if(currentMappedRpcs.get(rpcQName).getInput() == null) {
213             return new NetconfMessage(prepareDomResultForRpcRequest(rpcQName).getNode().getOwnerDocument());
214         }
215
216         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
217         Preconditions.checkArgument(payload instanceof ContainerNode,
218                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
219
220         // Set the path to the input of rpc for the node stream writer
221         rpc = rpc.createChild(QName.cachedReference(QName.create(rpcQName, "input")));
222         final DOMResult result = prepareDomResultForRpcRequest(rpcQName);
223
224         try {
225             // 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
226             // This way operations like lock/unlock are supported even if the source for base model was not provided
227             writeNormalizedRpc(((ContainerNode) payload), result, rpc, needToUseBaseCtx ? BASE_NETCONF_CTX : schemaContext);
228         } catch (final XMLStreamException | IOException | IllegalStateException e) {
229             throw new IllegalStateException("Unable to serialize " + rpc, e);
230         }
231
232         final Document node = result.getNode().getOwnerDocument();
233
234         return new NetconfMessage(node);
235     }
236
237     private static boolean isBaseRpc(final QName rpc) {
238         return rpc.getNamespace().equals(NETCONF_URI);
239     }
240
241     private DOMResult prepareDomResultForRpcRequest(final QName rpcQName) {
242         final Document document = XmlUtil.newDocument();
243         final Element rpcNS = document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
244         // set msg id
245         rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
246         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
247         rpcNS.appendChild(elementNS);
248         document.appendChild(rpcNS);
249         return new DOMResult(elementNS);
250     }
251
252     private void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
253         final OrderedNormalizedNodeWriter normalizedNodeWriter;
254         NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
255         XMLStreamWriter writer = null;
256         try {
257             writer = NetconfMessageTransformUtil.XML_FACTORY.createXMLStreamWriter(result);
258             normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath);
259             normalizedNodeWriter = new OrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath);
260             Collection<DataContainerChild<?, ?>> value = (Collection) normalized.getValue();
261             normalizedNodeWriter.write(value);
262             normalizedNodeWriter.flush();
263         } finally {
264             try {
265                 if(normalizedNodeStreamWriter != null) {
266                     normalizedNodeStreamWriter.close();
267                 }
268                 if(writer != null) {
269                     writer.close();
270                 }
271             } catch (final Exception e) {
272                 LOG.warn("Unable to close resource properly", e);
273             }
274         }
275     }
276
277     @Override
278     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
279         final NormalizedNode<?, ?> normalizedNode;
280         final QName rpcQName = rpc.getLastComponent();
281         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
282             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
283             final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
284             final ContainerNode dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
285
286             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
287                     .withChild(dataNode).build();
288         } else {
289             final Set<Element> documentElement = Collections.singleton(message.getDocument().getDocumentElement());
290
291             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
292
293             // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
294             // If no, use pre built base netconf operations model
295             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseRpc(rpcQName);
296             if(needToUseBaseCtx) {
297                 currentMappedRpcs = MAPPED_BASE_RPCS;
298             }
299
300             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
301             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
302
303             // In case no input for rpc is defined, we can simply construct the payload here
304             if (rpcDefinition.getOutput() == null) {
305                 Preconditions.checkArgument(XmlElement.fromDomDocument(message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
306                         "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
307                 normalizedNode = null;
308             } else {
309                 normalizedNode = parserFactory.getContainerNodeParser().parse(documentElement, rpcDefinition.getOutput());
310             }
311         }
312         return new DefaultDOMRpcResult(normalizedNode);
313     }
314
315     private static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
316         private final ContainerNode content;
317         private final SchemaPath schemaPath;
318         private final Date eventTime;
319
320         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
321             this.content = content;
322             this.eventTime = eventTime;
323             this.schemaPath = toPath(content.getNodeType());
324         }
325
326         @Nonnull
327         @Override
328         public SchemaPath getType() {
329             return schemaPath;
330
331         }
332
333         @Nonnull
334         @Override
335         public ContainerNode getBody() {
336             return content;
337         }
338
339         @Override
340         public Date getEventTime() {
341             return eventTime;
342         }
343     }
344 }