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