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 java.util.Optional;
33 import javax.xml.stream.XMLStreamException;
34 import javax.xml.transform.dom.DOMResult;
35 import javax.xml.transform.dom.DOMSource;
36 import org.opendaylight.mdsal.dom.api.DOMActionResult;
37 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
38 import org.opendaylight.mdsal.dom.api.DOMEvent;
39 import org.opendaylight.mdsal.dom.api.DOMNotification;
40 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
41 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
42 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
43 import org.opendaylight.netconf.api.NetconfMessage;
44 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
45 import org.opendaylight.netconf.api.xml.XmlElement;
46 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
47 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
48 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
49 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.common.Revision;
52 import org.opendaylight.yangtools.yang.common.YangConstants;
53 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
56 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
57 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
58 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
59 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
60 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
61 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
62 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
63 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
67 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
69 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
70 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76 import org.w3c.dom.Document;
77 import org.w3c.dom.Element;
78 import org.xml.sax.SAXException;
80 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, ? extends RpcDefinition> mappedRpcs;
93 private final Multimap<QName, ? extends 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()) {
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<? extends NotificationDefinition> notificationDefinitions =
153 mappedNotifications.get(notificationNoRev);
154 Preconditions.checkArgument(notificationDefinitions.size() > 0,
155 "Unable to parse notification %s, unknown notification. Available notifications: %s",
156 notificationDefinitions, mappedNotifications.keySet());
158 final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
160 final ContainerSchemaNode notificationAsContainerSchemaNode =
161 NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
163 final Element element = stripped.getValue().getDomElement();
164 final ContainerNode content;
166 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
167 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
168 final XmlParserStream xmlParser = XmlParserStream.create(writer, mountContext,
169 notificationAsContainerSchemaNode, strictParsing);
170 xmlParser.traverse(new DOMSource(element));
171 content = (ContainerNode) resultHolder.getResult();
172 } catch (XMLStreamException | URISyntaxException | IOException | SAXException
173 | UnsupportedOperationException e) {
174 throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
176 return new NetconfDeviceNotification(content, stripped.getKey());
179 private static NotificationDefinition getMostRecentNotification(
180 final Collection<? extends NotificationDefinition> notificationDefinitions) {
181 return Collections.max(notificationDefinitions, (o1, o2) ->
182 Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
186 public NetconfMessage toRpcRequest(final SchemaPath rpc, final NormalizedNode<?, ?> payload) {
187 // In case no input for rpc is defined, we can simply construct the payload here
188 final QName rpcQName = rpc.getLastComponent();
190 // Determine whether a base netconf operation is being invoked
191 // and also check if the device exposed model for base netconf.
192 // If no, use pre built base netconf operations model
193 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
194 final ImmutableMap<QName, ? extends RpcDefinition> currentMappedRpcs;
195 if (needToUseBaseCtx) {
196 currentMappedRpcs = baseSchema.getMappedRpcs();
198 currentMappedRpcs = mappedRpcs;
201 final RpcDefinition mappedRpc = Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
202 "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
203 if (mappedRpc.getInput().getChildNodes().isEmpty()) {
204 return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter)
205 .getNode().getOwnerDocument());
208 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
210 Preconditions.checkArgument(payload instanceof ContainerNode,
211 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
212 // Set the path to the input of rpc for the node stream writer
213 final SchemaPath rpcInput = rpc.createChild(YangConstants.operationInputQName(rpcQName.getModule()));
214 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
217 // If the schema context for netconf device does not contain model for base netconf operations,
218 // use default pre build context with just the base model
219 // This way operations like lock/unlock are supported even if the source for base model was not provided
220 final SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext()
221 : mountContext.getSchemaContext();
222 NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, rpcInput, ctx);
223 } catch (final XMLStreamException | IOException | IllegalStateException e) {
224 throw new IllegalStateException("Unable to serialize " + rpcInput, e);
227 final Document node = result.getNode().getOwnerDocument();
229 return new NetconfMessage(node);
233 public NetconfMessage toActionRequest(final SchemaPath action, final DOMDataTreeIdentifier domDataTreeIdentifier,
234 final NormalizedNode<?, ?> payload) {
235 final ActionDefinition actionDef = actions.get(action);
236 Preconditions.checkArgument(actionDef != null, "Action does not exist: %s", action);
238 final ContainerSchemaNode inputDef = actionDef.getInput();
239 if (inputDef.getChildNodes().isEmpty()) {
240 return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForActionRequest(contextTree,
241 domDataTreeIdentifier, action, counter,
242 actionDef.getQName()).getNode().getOwnerDocument());
245 Preconditions.checkNotNull(payload, "Transforming an action with input: %s, payload cannot be null", action);
246 Preconditions.checkArgument(payload instanceof ContainerNode,
247 "Transforming an action with input: %s, payload has to be a container, but was: %s", action, payload);
249 // Set the path to the input of action for the node stream writer
250 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForActionRequest(contextTree,
251 domDataTreeIdentifier, inputDef.getPath(), counter, actionDef.getQName());
254 NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, inputDef.getPath(),
255 mountContext.getSchemaContext());
256 } catch (final XMLStreamException | IOException | IllegalStateException e) {
257 throw new IllegalStateException("Unable to serialize " + action, e);
260 return new NetconfMessage(result.getNode().getOwnerDocument());
263 private static boolean isBaseOrNotificationRpc(final QName rpc) {
264 return BASE_OR_NOTIFICATION_NS.contains(rpc.getNamespace());
268 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
269 final NormalizedNode<?, ?> normalizedNode;
270 final QName rpcQName = rpc.getLastComponent();
271 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
272 normalizedNode = Builders.containerBuilder()
273 .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_NODEID)
274 .withChild(Builders.anyXmlBuilder()
275 .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_NODEID)
276 .withValue(new DOMSource(NetconfMessageTransformUtil.getDataSubtree(message.getDocument())))
280 // Determine whether a base netconf operation is being invoked
281 // and also check if the device exposed model for base netconf.
282 // If no, use pre built base netconf operations model
283 final ImmutableMap<QName, ? extends RpcDefinition> currentMappedRpcs;
284 if (mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName)) {
285 currentMappedRpcs = baseSchema.getMappedRpcs();
287 currentMappedRpcs = mappedRpcs;
290 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
291 Preconditions.checkArgument(rpcDefinition != null,
292 "Unable to parse response of %s, the rpc is unknown", rpcQName);
294 // In case no input for rpc is defined, we can simply construct the payload here
295 normalizedNode = parseResult(message, rpcDefinition);
297 return new DefaultDOMRpcResult(normalizedNode);
301 public DOMActionResult toActionResult(final SchemaPath action, final NetconfMessage message) {
302 final ActionDefinition actionDefinition = actions.get(action);
303 Preconditions.checkArgument(actionDefinition != null, "Action does not exist: %s", action);
304 final ContainerNode normalizedNode = (ContainerNode) parseResult(message, actionDefinition);
306 if (normalizedNode == null) {
307 return new SimpleDOMActionResult(Collections.emptyList());
309 return new SimpleDOMActionResult(normalizedNode, Collections.emptyList());
313 private NormalizedNode<?, ?> parseResult(final NetconfMessage message,
314 final OperationDefinition operationDefinition) {
315 final Optional<XmlElement> okResponseElement = XmlElement.fromDomDocument(message.getDocument())
316 .getOnlyChildElementWithSameNamespaceOptionally("ok");
317 if (operationDefinition.getOutput().getChildNodes().isEmpty()) {
318 Preconditions.checkArgument(okResponseElement.isPresent(),
319 "Unexpected content in response of rpc: %s, %s", operationDefinition.getQName(), message);
322 if (okResponseElement.isPresent()) {
323 LOG.debug("Received response <ok/> for RPC with defined Output");
327 Element element = message.getDocument().getDocumentElement();
329 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
330 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
331 final XmlParserStream xmlParser = XmlParserStream.create(writer, mountContext,
332 operationDefinition.getOutput(), strictParsing);
333 xmlParser.traverse(new DOMSource(element));
334 return resultHolder.getResult();
335 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
336 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
341 static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
342 private final ContainerNode content;
343 private final SchemaPath schemaPath;
344 private final Instant eventTime;
346 NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
347 this.content = content;
348 this.eventTime = eventTime;
349 this.schemaPath = toPath(content.getNodeType());
353 public SchemaPath getType() {
358 public ContainerNode getBody() {
363 public Instant getEventInstant() {