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