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