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