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