Fix action lookups
[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.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.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Map;
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.CaseSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
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 ImmutableMap<QName, RpcDefinition> mappedRpcs;
90     private final Multimap<QName, NotificationDefinition> mappedNotifications;
91     private final boolean strictParsing;
92     private final ImmutableMap<SchemaPath, 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 = Maps.uniqueIndex(getActions(schemaContext), ActionDefinition::getPath);
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     static List<ActionDefinition> getActions(final SchemaContext schemaContext) {
112         final List<ActionDefinition> builder = new ArrayList<>();
113         findAction(schemaContext, builder);
114         return builder;
115     }
116
117     private static void findAction(final DataSchemaNode dataSchemaNode, final List<ActionDefinition> builder) {
118         if (dataSchemaNode instanceof ActionNodeContainer) {
119             for (ActionDefinition actionDefinition : ((ActionNodeContainer) dataSchemaNode).getActions()) {
120                 builder.add(actionDefinition);
121             }
122         }
123         if (dataSchemaNode instanceof DataNodeContainer) {
124             for (DataSchemaNode innerDataSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
125                 findAction(innerDataSchemaNode, builder);
126             }
127         } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
128             for (CaseSchemaNode caze : ((ChoiceSchemaNode) dataSchemaNode).getCases().values()) {
129                 findAction(caze, 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(final SchemaPath action, final DOMDataTreeIdentifier domDataTreeIdentifier,
225             final NormalizedNode<?, ?> payload) {
226         final ActionDefinition actionDef = actions.get(action);
227         Preconditions.checkArgument(actionDef != null, "Action does not exist: %s", action);
228
229         final ContainerSchemaNode inputDef = actionDef.getInput();
230         if (inputDef.getChildNodes().isEmpty()) {
231             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForActionRequest(
232                     DataSchemaContextTree.from(schemaContext), domDataTreeIdentifier, action, counter,
233                     actionDef.getQName().getLocalName()).getNode().getOwnerDocument());
234         }
235
236         Preconditions.checkNotNull(payload, "Transforming an action with input: %s, payload cannot be null", action);
237         Preconditions.checkArgument(payload instanceof ContainerNode,
238                 "Transforming an action with input: %s, payload has to be a container, but was: %s", action, payload);
239
240         // Set the path to the input of action for the node stream writer
241         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForActionRequest(
242                 DataSchemaContextTree.from(schemaContext), domDataTreeIdentifier, inputDef.getPath(), counter,
243                 actionDef.getQName().getLocalName());
244
245         try {
246             NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, inputDef.getPath(),
247                 schemaContext);
248         } catch (final XMLStreamException | IOException | IllegalStateException e) {
249             throw new IllegalStateException("Unable to serialize " + action, e);
250         }
251
252         return new NetconfMessage(result.getNode().getOwnerDocument());
253     }
254
255     private static boolean isBaseOrNotificationRpc(final QName rpc) {
256         return BASE_OR_NOTIFICATION_NS.contains(rpc.getNamespace());
257     }
258
259     @Override
260     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
261         final NormalizedNode<?, ?> normalizedNode;
262         final QName rpcQName = rpc.getLastComponent();
263         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
264             normalizedNode = Builders.containerBuilder()
265                     .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_NODEID)
266                     .withChild(Builders.anyXmlBuilder()
267                         .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_NODEID)
268                         .withValue(new DOMSource(NetconfMessageTransformUtil.getDataSubtree(message.getDocument())))
269                         .build())
270                     .build();
271         } else {
272             // Determine whether a base netconf operation is being invoked
273             // and also check if the device exposed model for base netconf.
274             // If no, use pre built base netconf operations model
275             final ImmutableMap<QName, RpcDefinition> currentMappedRpcs;
276             if (mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName)) {
277                 currentMappedRpcs = baseSchema.getMappedRpcs();
278             } else {
279                 currentMappedRpcs = mappedRpcs;
280             }
281
282             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
283             Preconditions.checkArgument(rpcDefinition != null,
284                     "Unable to parse response of %s, the rpc is unknown", rpcQName);
285
286             // In case no input for rpc is defined, we can simply construct the payload here
287             normalizedNode = parseResult(message, rpcDefinition);
288         }
289         return new DefaultDOMRpcResult(normalizedNode);
290     }
291
292     @Override
293     public DOMActionResult toActionResult(final SchemaPath action, final NetconfMessage message) {
294         final ActionDefinition actionDefinition = actions.get(action);
295         Preconditions.checkArgument(actionDefinition != null, "Action does not exist: %s", action);
296         final ContainerNode normalizedNode = (ContainerNode) parseResult(message, actionDefinition);
297
298         if (normalizedNode == null) {
299             return new SimpleDOMActionResult(Collections.emptyList());
300         } else {
301             return new SimpleDOMActionResult(normalizedNode, Collections.emptyList());
302         }
303     }
304
305     private NormalizedNode<?, ?> parseResult(final NetconfMessage message,
306             final OperationDefinition operationDefinition) {
307         if (operationDefinition.getOutput().getChildNodes().isEmpty()) {
308             Preconditions.checkArgument(XmlElement.fromDomDocument(
309                 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
310                 "Unexpected content in response of rpc: %s, %s", operationDefinition.getQName(), message);
311             return null;
312         } else {
313             final Element element = message.getDocument().getDocumentElement();
314             try {
315                 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
316                 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
317                 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
318                         operationDefinition.getOutput(), strictParsing);
319                 xmlParser.traverse(new DOMSource(element));
320                 return resultHolder.getResult();
321             } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
322                 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
323             }
324         }
325     }
326
327     static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
328         private final ContainerNode content;
329         private final SchemaPath schemaPath;
330         private final Instant eventTime;
331
332         NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
333             this.content = content;
334             this.eventTime = eventTime;
335             this.schemaPath = toPath(content.getNodeType());
336         }
337
338         @Override
339         public SchemaPath getType() {
340             return schemaPath;
341         }
342
343         @Override
344         public ContainerNode getBody() {
345             return content;
346         }
347
348         @Override
349         public Instant getEventInstant() {
350             return eventTime;
351         }
352     }
353 }