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