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