2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.connect.netconf.schema.mapping;
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;
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;
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;
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;
79 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
81 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
83 private static final ImmutableSet<URI> BASE_OR_NOTIFICATION_NS = ImmutableSet.of(
85 IETF_NETCONF_NOTIFICATIONS.getNamespace(),
86 CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
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;
97 public NetconfMessageTransformer(final MountPointContext mountContext, final boolean strictParsing) {
98 this(mountContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
101 public NetconfMessageTransformer(final MountPointContext mountContext, final boolean strictParsing,
102 final BaseSchema baseSchema) {
103 this.counter = new MessageCounter();
104 this.mountContext = requireNonNull(mountContext);
106 final SchemaContext schemaContext = mountContext.getSchemaContext();
107 this.contextTree = DataSchemaContextTree.from(schemaContext);
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;
118 static List<ActionDefinition> getActions(final SchemaContext schemaContext) {
119 final List<ActionDefinition> builder = new ArrayList<>();
120 findAction(schemaContext, builder);
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);
130 if (dataSchemaNode instanceof DataNodeContainer) {
131 for (DataSchemaNode innerDataSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
132 findAction(innerDataSchemaNode, builder);
134 } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
135 for (CaseSchemaNode caze : ((ChoiceSchemaNode) dataSchemaNode).getCases().values()) {
136 findAction(caze, builder);
142 public synchronized DOMNotification toNotification(final NetconfMessage message) {
143 final Map.Entry<Instant, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
144 final QName notificationNoRev;
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);
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());
157 final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
159 final ContainerSchemaNode notificationAsContainerSchemaNode =
160 NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
162 final Element element = stripped.getValue().getDomElement();
163 final ContainerNode content;
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);
175 return new NetconfDeviceNotification(content, stripped.getKey());
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()));
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();
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();
197 currentMappedRpcs = mappedRpcs;
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());
207 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
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);
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);
226 final Document node = result.getNode().getOwnerDocument();
228 return new NetconfMessage(node);
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);
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());
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);
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());
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);
259 return new NetconfMessage(result.getNode().getOwnerDocument());
262 private static boolean isBaseOrNotificationRpc(final QName rpc) {
263 return BASE_OR_NOTIFICATION_NS.contains(rpc.getNamespace());
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())))
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();
286 currentMappedRpcs = mappedRpcs;
289 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
290 Preconditions.checkArgument(rpcDefinition != null,
291 "Unable to parse response of %s, the rpc is unknown", rpcQName);
293 // In case no input for rpc is defined, we can simply construct the payload here
294 normalizedNode = parseResult(message, rpcDefinition);
296 return new DefaultDOMRpcResult(normalizedNode);
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);
305 if (normalizedNode == null) {
306 return new SimpleDOMActionResult(Collections.emptyList());
308 return new SimpleDOMActionResult(normalizedNode, Collections.emptyList());
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);
320 final Element element = message.getDocument().getDocumentElement();
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);
334 static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
335 private final ContainerNode content;
336 private final SchemaPath schemaPath;
337 private final Instant eventTime;
339 NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
340 this.content = content;
341 this.eventTime = eventTime;
342 this.schemaPath = toPath(content.getNodeType());
346 public SchemaPath getType() {
351 public ContainerNode getBody() {
356 public Instant getEventInstant() {