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