Bug 5824: Migrate netconf to the new XML parser #2
[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.base.Preconditions;
15 import com.google.common.collect.Maps;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Multimaps;
18 import java.io.IOException;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.Comparator;
22 import java.util.Date;
23 import java.util.Map;
24 import javax.annotation.Nonnull;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.transform.dom.DOMResult;
27 import javax.xml.transform.dom.DOMSource;
28 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
29 import org.opendaylight.controller.config.util.xml.XmlElement;
30 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
31 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
33 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
34 import org.opendaylight.netconf.api.NetconfMessage;
35 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
36 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
37 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
44 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.w3c.dom.Element;
57
58 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
59
60     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
61
62     private final SchemaContext schemaContext;
63     private final BaseSchema baseSchema;
64     private final MessageCounter counter;
65     private final Map<QName, RpcDefinition> mappedRpcs;
66     private final Multimap<QName, NotificationDefinition> mappedNotifications;
67
68     private final boolean strictParsing;
69
70     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
71         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
72     }
73
74     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
75                                      final BaseSchema baseSchema) {
76         this.counter = new MessageCounter();
77         this.schemaContext = schemaContext;
78         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
79         mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
80             node -> node.getQName().withoutRevision());
81         this.baseSchema = baseSchema;
82         this.strictParsing = strictParsing;
83     }
84
85     @SuppressWarnings("checkstyle:IllegalCatch")
86     @Override
87     public synchronized DOMNotification toNotification(final NetconfMessage message) {
88         final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
89         final QName notificationNoRev;
90         try {
91             notificationNoRev = QName.create(
92                     stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
93         } catch (final MissingNameSpaceException e) {
94             throw new IllegalArgumentException(
95                     "Unable to parse notification " + message + ", cannot find namespace", e);
96         }
97         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
98         Preconditions.checkArgument(notificationDefinitions.size() > 0,
99                 "Unable to parse notification %s, unknown notification. Available notifications: %s",
100                 notificationDefinitions, mappedNotifications.keySet());
101
102         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
103
104         final ContainerSchemaNode notificationAsContainerSchemaNode =
105                 NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
106
107         final Element element = stripped.getValue().getDomElement();
108         final ContainerNode content;
109         try {
110             final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
111             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
112             final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
113                     notificationAsContainerSchemaNode, strictParsing);
114             xmlParser.traverse(new DOMSource(element));
115             content = (ContainerNode) resultHolder.getResult();
116         } catch (final Exception e) {
117             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
118         }
119         return new NetconfDeviceNotification(content, stripped.getKey());
120     }
121
122     private static NotificationDefinition getMostRecentNotification(
123             final Collection<NotificationDefinition> notificationDefinitions) {
124         Comparator<NotificationDefinition> cmp = (o1, o2) ->
125                 o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
126
127         return Collections.max(notificationDefinitions, cmp);
128     }
129
130     @Override
131     public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
132         // In case no input for rpc is defined, we can simply construct the payload here
133         final QName rpcQName = rpc.getLastComponent();
134         Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
135
136         // Determine whether a base netconf operation is being invoked
137         // and also check if the device exposed model for base netconf.
138         // If no, use pre built base netconf operations model
139         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
140         if (needToUseBaseCtx) {
141             currentMappedRpcs = baseSchema.getMappedRpcs();
142         }
143
144         Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
145                 "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
146         if (currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
147             return new NetconfMessage(NetconfMessageTransformUtil
148                     .prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
149         }
150
151         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
152         Preconditions.checkArgument(payload instanceof ContainerNode,
153                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
154
155         // Set the path to the input of rpc for the node stream writer
156         rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
157         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
158
159         try {
160             // If the schema context for netconf device does not contain model for base netconf operations,
161             // use default pre build context with just the base model
162             // This way operations like lock/unlock are supported even if the source for base model was not provided
163             SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
164             NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, rpc, ctx);
165         } catch (final XMLStreamException | IOException | IllegalStateException e) {
166             throw new IllegalStateException("Unable to serialize " + rpc, e);
167         }
168
169         final Document node = result.getNode().getOwnerDocument();
170
171         return new NetconfMessage(node);
172     }
173
174     private static boolean isBaseOrNotificationRpc(final QName rpc) {
175         return rpc.getNamespace().equals(NETCONF_URI)
176                 || rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace())
177                 || rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
178     }
179
180     @SuppressWarnings("checkstyle:IllegalCatch")
181     @Override
182     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
183         final NormalizedNode<?, ?> normalizedNode;
184         final QName rpcQName = rpc.getLastComponent();
185         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
186             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
187             final ContainerSchemaNode schemaForDataRead =
188                     NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
189             final ContainerNode dataNode;
190
191             try {
192                 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
193                 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
194                 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext, schemaForDataRead,
195                         strictParsing);
196                 xmlParser.traverse(new DOMSource(xmlData));
197                 dataNode = (ContainerNode) resultHolder.getResult();
198             } catch (final Exception e) {
199                 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
200             }
201
202             normalizedNode = Builders.containerBuilder()
203                     .withNodeIdentifier(new YangInstanceIdentifier
204                             .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
205                     .withChild(dataNode).build();
206         } else {
207
208             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
209
210             // Determine whether a base netconf operation is being invoked
211             // and also check if the device exposed model for base netconf.
212             // If no, use pre built base netconf operations model
213             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
214             if (needToUseBaseCtx) {
215                 currentMappedRpcs = baseSchema.getMappedRpcs();
216             }
217
218             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
219             Preconditions.checkArgument(rpcDefinition != null,
220                     "Unable to parse response of %s, the rpc is unknown", rpcQName);
221
222             // In case no input for rpc is defined, we can simply construct the payload here
223             if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
224                 Preconditions.checkArgument(XmlElement.fromDomDocument(
225                     message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
226                     "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
227                 normalizedNode = null;
228             } else {
229                 final Element element = message.getDocument().getDocumentElement();
230                 try {
231                     final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
232                     final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
233                     final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
234                             rpcDefinition.getOutput(), strictParsing);
235                     xmlParser.traverse(new DOMSource(element));
236                     normalizedNode = resultHolder.getResult();
237                 } catch (final Exception e) {
238                     throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
239                 }
240             }
241         }
242         return new DefaultDOMRpcResult(normalizedNode);
243     }
244
245     static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
246         private final ContainerNode content;
247         private final SchemaPath schemaPath;
248         private final Date eventTime;
249
250         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
251             this.content = content;
252             this.eventTime = eventTime;
253             this.schemaPath = toPath(content.getNodeType());
254         }
255
256         @Nonnull
257         @Override
258         public SchemaPath getType() {
259             return schemaPath;
260
261         }
262
263         @Nonnull
264         @Override
265         public ContainerNode getBody() {
266             return content;
267         }
268
269         @Override
270         public Date getEventTime() {
271             return eventTime;
272         }
273     }
274 }