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