52f5587e500cb07533058a5bb57aa2545ac06350
[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.CREATE_SUBSCRIPTION_RPC_QNAME;
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_URI;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
14
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Preconditions;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableSet.Builder;
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.net.URI;
24 import java.net.URISyntaxException;
25 import java.time.Instant;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.Map;
29 import java.util.Set;
30 import javax.xml.stream.XMLStreamException;
31 import javax.xml.transform.dom.DOMResult;
32 import javax.xml.transform.dom.DOMSource;
33 import org.opendaylight.mdsal.dom.api.DOMActionResult;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
35 import org.opendaylight.mdsal.dom.api.DOMEvent;
36 import org.opendaylight.mdsal.dom.api.DOMNotification;
37 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
38 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
39 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
40 import org.opendaylight.netconf.api.NetconfMessage;
41 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
42 import org.opendaylight.netconf.api.xml.XmlElement;
43 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
44 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
45 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.common.Revision;
48 import org.opendaylight.yangtools.yang.common.RpcError;
49 import org.opendaylight.yangtools.yang.common.YangConstants;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
55 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
56 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
57 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
58 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
59 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
60 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
61 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
62 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
64 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
66 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
67 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73 import org.w3c.dom.Document;
74 import org.w3c.dom.Element;
75 import org.xml.sax.SAXException;
76
77 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
78
79     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
80
81     private static final ImmutableSet<URI> BASE_OR_NOTIFICATION_NS = ImmutableSet.of(
82         NETCONF_URI,
83         IETF_NETCONF_NOTIFICATIONS.getNamespace(),
84         CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
85
86     private final SchemaContext schemaContext;
87     private final BaseSchema baseSchema;
88     private final MessageCounter counter;
89     private final Map<QName, RpcDefinition> mappedRpcs;
90     private final Multimap<QName, NotificationDefinition> mappedNotifications;
91     private final boolean strictParsing;
92     private final Set<ActionDefinition> actions;
93
94     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
95         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
96     }
97
98     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
99                                      final BaseSchema baseSchema) {
100         this.counter = new MessageCounter();
101         this.schemaContext = schemaContext;
102         this.mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
103         this.actions = getActions();
104         this.mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
105             node -> node.getQName().withoutRevision());
106         this.baseSchema = baseSchema;
107         this.strictParsing = strictParsing;
108     }
109
110     @VisibleForTesting
111     Set<ActionDefinition> getActions() {
112         final Builder<ActionDefinition> builder = ImmutableSet.builder();
113         for (DataSchemaNode dataSchemaNode : schemaContext.getChildNodes()) {
114             if (dataSchemaNode instanceof ActionNodeContainer) {
115                 findAction(dataSchemaNode, builder);
116             }
117         }
118         return builder.build();
119     }
120
121     private void findAction(final DataSchemaNode dataSchemaNode, final Builder<ActionDefinition> builder) {
122         if (dataSchemaNode instanceof ActionNodeContainer) {
123             final ActionNodeContainer containerSchemaNode = (ActionNodeContainer) dataSchemaNode;
124             for (ActionDefinition actionDefinition : containerSchemaNode.getActions()) {
125                 builder.add(actionDefinition);
126             }
127         }
128         if (dataSchemaNode instanceof DataNodeContainer) {
129             for (DataSchemaNode innerDataSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
130                 findAction(innerDataSchemaNode, builder);
131             }
132         }
133     }
134
135     @Override
136     public synchronized DOMNotification toNotification(final NetconfMessage message) {
137         final Map.Entry<Instant, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
138         final QName notificationNoRev;
139         try {
140             notificationNoRev = QName.create(
141                     stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
142         } catch (final MissingNameSpaceException e) {
143             throw new IllegalArgumentException(
144                     "Unable to parse notification " + message + ", cannot find namespace", e);
145         }
146         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
147         Preconditions.checkArgument(notificationDefinitions.size() > 0,
148                 "Unable to parse notification %s, unknown notification. Available notifications: %s",
149                 notificationDefinitions, mappedNotifications.keySet());
150
151         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
152
153         final ContainerSchemaNode notificationAsContainerSchemaNode =
154                 NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
155
156         final Element element = stripped.getValue().getDomElement();
157         final ContainerNode content;
158         try {
159             final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
160             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
161             final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
162                     notificationAsContainerSchemaNode, strictParsing);
163             xmlParser.traverse(new DOMSource(element));
164             content = (ContainerNode) resultHolder.getResult();
165         } catch (XMLStreamException | URISyntaxException | IOException | SAXException
166                 | UnsupportedOperationException e) {
167             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
168         }
169         return new NetconfDeviceNotification(content, stripped.getKey());
170     }
171
172     private static NotificationDefinition getMostRecentNotification(
173             final Collection<NotificationDefinition> notificationDefinitions) {
174         return Collections.max(notificationDefinitions, (o1, o2) ->
175             Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
176     }
177
178     @Override
179     public NetconfMessage toRpcRequest(final SchemaPath rpc, final NormalizedNode<?, ?> payload) {
180         // In case no input for rpc is defined, we can simply construct the payload here
181         final QName rpcQName = rpc.getLastComponent();
182
183         // Determine whether a base netconf operation is being invoked
184         // and also check if the device exposed model for base netconf.
185         // If no, use pre built base netconf operations model
186         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
187         final Map<QName, RpcDefinition> currentMappedRpcs;
188         if (needToUseBaseCtx) {
189             currentMappedRpcs = baseSchema.getMappedRpcs();
190         } else {
191             currentMappedRpcs = mappedRpcs;
192         }
193
194         final RpcDefinition mappedRpc = Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
195                 "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
196         if (mappedRpc.getInput().getChildNodes().isEmpty()) {
197             return new NetconfMessage(NetconfMessageTransformUtil
198                     .prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
199         }
200
201         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
202
203         Preconditions.checkArgument(payload instanceof ContainerNode,
204                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
205         // Set the path to the input of rpc for the node stream writer
206         final SchemaPath rpcInput = rpc.createChild(YangConstants.operationInputQName(rpcQName.getModule()));
207         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
208
209         try {
210             // If the schema context for netconf device does not contain model for base netconf operations,
211             // use default pre build context with just the base model
212             // This way operations like lock/unlock are supported even if the source for base model was not provided
213             final SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
214             NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, rpcInput, ctx);
215         } catch (final XMLStreamException | IOException | IllegalStateException e) {
216             throw new IllegalStateException("Unable to serialize " + rpcInput, e);
217         }
218
219         final Document node = result.getNode().getOwnerDocument();
220
221         return new NetconfMessage(node);
222     }
223
224     @Override
225     public NetconfMessage toActionRequest(SchemaPath action, final DOMDataTreeIdentifier domDataTreeIdentifier,
226             final NormalizedNode<?, ?> payload) {
227         ActionDefinition actionDefinition = null;
228         SchemaPath schemaPath = action;
229         for (ActionDefinition actionDef : actions) {
230             if (actionDef.getPath().getLastComponent().equals(action.getLastComponent())) {
231                 actionDefinition = actionDef;
232                 schemaPath = actionDef.getPath();
233             }
234         }
235         Preconditions.checkNotNull(actionDefinition, "Action does not exist: %s", action.getLastComponent());
236
237         if (actionDefinition.getInput().getChildNodes().isEmpty()) {
238             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForActionRequest(
239                     DataSchemaContextTree.from(schemaContext), domDataTreeIdentifier, action, counter,
240                     actionDefinition.getQName().getLocalName())
241                     .getNode().getOwnerDocument());
242         }
243
244         Preconditions.checkNotNull(payload, "Transforming an action with input: %s, payload cannot be null",
245                 action.getLastComponent());
246         Preconditions.checkArgument(payload instanceof ContainerNode,
247                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s",
248                 action.getLastComponent(), payload);
249         // Set the path to the input of rpc for the node stream writer
250         action = action.createChild(QName.create(action.getLastComponent(), "input").intern());
251         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForActionRequest(
252                 DataSchemaContextTree.from(schemaContext), domDataTreeIdentifier, action, counter,
253                 actionDefinition.getQName().getLocalName());
254
255         try {
256             NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result,
257                     schemaPath.createChild(QName.create(action.getLastComponent(), "input").intern()), schemaContext);
258         } catch (final XMLStreamException | IOException | IllegalStateException e) {
259             throw new IllegalStateException("Unable to serialize " + action, e);
260         }
261
262         final Document node = result.getNode().getOwnerDocument();
263
264         return new NetconfMessage(node);
265     }
266
267     private static boolean isBaseOrNotificationRpc(final QName rpc) {
268         return BASE_OR_NOTIFICATION_NS.contains(rpc.getNamespace());
269     }
270
271     @Override
272     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
273         final NormalizedNode<?, ?> normalizedNode;
274         final QName rpcQName = rpc.getLastComponent();
275         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
276             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
277             final AnyXmlNode anyXmlNode = Builders.anyXmlBuilder()
278                     .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_NODEID)
279                     .withValue(new DOMSource(xmlData)).build();
280             normalizedNode = Builders.containerBuilder().withNodeIdentifier(
281                     new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
282                     .withChild(anyXmlNode).build();
283         } else {
284
285             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
286
287             // Determine whether a base netconf operation is being invoked
288             // and also check if the device exposed model for base netconf.
289             // If no, use pre built base netconf operations model
290             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
291             if (needToUseBaseCtx) {
292                 currentMappedRpcs = baseSchema.getMappedRpcs();
293             }
294
295             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
296             Preconditions.checkArgument(rpcDefinition != null,
297                     "Unable to parse response of %s, the rpc is unknown", rpcQName);
298
299             // In case no input for rpc is defined, we can simply construct the payload here
300             normalizedNode = parseResult(message, rpcDefinition);
301         }
302         return new DefaultDOMRpcResult(normalizedNode);
303     }
304
305     @Override
306     public DOMActionResult toActionResult(final SchemaPath action, final NetconfMessage message) {
307         ActionDefinition actionDefinition = null;
308         for (ActionDefinition actionDef : actions) {
309             if (actionDef.getPath().getLastComponent().equals(action.getLastComponent())) {
310                 actionDefinition = actionDef;
311             }
312         }
313         Preconditions.checkNotNull(actionDefinition, "Action does not exist: %s", action);
314         final ContainerNode normalizedNode = (ContainerNode) parseResult(message, actionDefinition);
315
316         if (normalizedNode == null) {
317             return new SimpleDOMActionResult(Collections.<RpcError>emptyList());
318         } else {
319             return new SimpleDOMActionResult(normalizedNode, Collections.<RpcError>emptyList());
320         }
321     }
322
323     private NormalizedNode<?, ?> parseResult(final NetconfMessage message,
324             final OperationDefinition operationDefinition) {
325         if (operationDefinition.getOutput().getChildNodes().isEmpty()) {
326             Preconditions.checkArgument(XmlElement.fromDomDocument(
327                 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
328                 "Unexpected content in response of rpc: %s, %s", operationDefinition.getQName(), message);
329             return null;
330         } else {
331             final Element element = message.getDocument().getDocumentElement();
332             try {
333                 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
334                 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
335                 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
336                         operationDefinition.getOutput(), strictParsing);
337                 xmlParser.traverse(new DOMSource(element));
338                 return resultHolder.getResult();
339             } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
340                 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
341             }
342         }
343     }
344
345     static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
346         private final ContainerNode content;
347         private final SchemaPath schemaPath;
348         private final Instant eventTime;
349
350         NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
351             this.content = content;
352             this.eventTime = eventTime;
353             this.schemaPath = toPath(content.getNodeType());
354         }
355
356         @Override
357         public SchemaPath getType() {
358             return schemaPath;
359         }
360
361         @Override
362         public ContainerNode getBody() {
363             return content;
364         }
365
366         @Override
367         public Instant getEventInstant() {
368             return eventTime;
369         }
370     }
371 }