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 org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Preconditions;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Maps;
20 import com.google.common.collect.Multimap;
21 import com.google.common.collect.Multimaps;
22 import java.io.IOException;
24 import java.net.URISyntaxException;
25 import java.time.Instant;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
31 import javax.xml.stream.XMLStreamException;
32 import javax.xml.transform.dom.DOMResult;
33 import javax.xml.transform.dom.DOMSource;
34 import org.opendaylight.mdsal.dom.api.DOMActionResult;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
36 import org.opendaylight.mdsal.dom.api.DOMEvent;
37 import org.opendaylight.mdsal.dom.api.DOMNotification;
38 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
39 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
40 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
41 import org.opendaylight.netconf.api.NetconfMessage;
42 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
43 import org.opendaylight.netconf.api.xml.XmlElement;
44 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
45 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
46 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.Revision;
49 import org.opendaylight.yangtools.yang.common.YangConstants;
50 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
54 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
55 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
56 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
57 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
58 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
59 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
64 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
66 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
67 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73 import org.w3c.dom.Document;
74 import org.w3c.dom.Element;
75 import org.xml.sax.SAXException;
77 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
79 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
81 private static final ImmutableSet<URI> BASE_OR_NOTIFICATION_NS = ImmutableSet.of(
83 IETF_NETCONF_NOTIFICATIONS.getNamespace(),
84 CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
86 private final SchemaContext schemaContext;
87 private final BaseSchema baseSchema;
88 private final MessageCounter counter;
89 private final ImmutableMap<QName, RpcDefinition> mappedRpcs;
90 private final Multimap<QName, NotificationDefinition> mappedNotifications;
91 private final boolean strictParsing;
92 private final ImmutableMap<SchemaPath, ActionDefinition> actions;
94 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
95 this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
98 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
99 final BaseSchema baseSchema) {
100 this.counter = new MessageCounter();
101 this.schemaContext = schemaContext;
102 this.mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
103 this.actions = Maps.uniqueIndex(getActions(schemaContext), ActionDefinition::getPath);
104 this.mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
105 node -> node.getQName().withoutRevision());
106 this.baseSchema = baseSchema;
107 this.strictParsing = strictParsing;
111 static List<ActionDefinition> getActions(final SchemaContext schemaContext) {
112 final List<ActionDefinition> builder = new ArrayList<>();
113 findAction(schemaContext, builder);
117 private static void findAction(final DataSchemaNode dataSchemaNode, final List<ActionDefinition> builder) {
118 if (dataSchemaNode instanceof ActionNodeContainer) {
119 for (ActionDefinition actionDefinition : ((ActionNodeContainer) dataSchemaNode).getActions()) {
120 builder.add(actionDefinition);
123 if (dataSchemaNode instanceof DataNodeContainer) {
124 for (DataSchemaNode innerDataSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
125 findAction(innerDataSchemaNode, builder);
127 } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
128 for (CaseSchemaNode caze : ((ChoiceSchemaNode) dataSchemaNode).getCases().values()) {
129 findAction(caze, builder);
135 public synchronized DOMNotification toNotification(final NetconfMessage message) {
136 final Map.Entry<Instant, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
137 final QName notificationNoRev;
139 notificationNoRev = QName.create(
140 stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
141 } catch (final MissingNameSpaceException e) {
142 throw new IllegalArgumentException(
143 "Unable to parse notification " + message + ", cannot find namespace", e);
145 final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
146 Preconditions.checkArgument(notificationDefinitions.size() > 0,
147 "Unable to parse notification %s, unknown notification. Available notifications: %s",
148 notificationDefinitions, mappedNotifications.keySet());
150 final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
152 final ContainerSchemaNode notificationAsContainerSchemaNode =
153 NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
155 final Element element = stripped.getValue().getDomElement();
156 final ContainerNode content;
158 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
159 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
160 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
161 notificationAsContainerSchemaNode, strictParsing);
162 xmlParser.traverse(new DOMSource(element));
163 content = (ContainerNode) resultHolder.getResult();
164 } catch (XMLStreamException | URISyntaxException | IOException | SAXException
165 | UnsupportedOperationException e) {
166 throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
168 return new NetconfDeviceNotification(content, stripped.getKey());
171 private static NotificationDefinition getMostRecentNotification(
172 final Collection<NotificationDefinition> notificationDefinitions) {
173 return Collections.max(notificationDefinitions, (o1, o2) ->
174 Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
178 public NetconfMessage toRpcRequest(final SchemaPath rpc, final NormalizedNode<?, ?> payload) {
179 // In case no input for rpc is defined, we can simply construct the payload here
180 final QName rpcQName = rpc.getLastComponent();
182 // Determine whether a base netconf operation is being invoked
183 // and also check if the device exposed model for base netconf.
184 // If no, use pre built base netconf operations model
185 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
186 final ImmutableMap<QName, RpcDefinition> currentMappedRpcs;
187 if (needToUseBaseCtx) {
188 currentMappedRpcs = baseSchema.getMappedRpcs();
190 currentMappedRpcs = mappedRpcs;
193 final RpcDefinition mappedRpc = Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
194 "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
195 if (mappedRpc.getInput().getChildNodes().isEmpty()) {
196 return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter)
197 .getNode().getOwnerDocument());
200 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
202 Preconditions.checkArgument(payload instanceof ContainerNode,
203 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
204 // Set the path to the input of rpc for the node stream writer
205 final SchemaPath rpcInput = rpc.createChild(YangConstants.operationInputQName(rpcQName.getModule()));
206 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
209 // If the schema context for netconf device does not contain model for base netconf operations,
210 // use default pre build context with just the base model
211 // This way operations like lock/unlock are supported even if the source for base model was not provided
212 final SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
213 NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, rpcInput, ctx);
214 } catch (final XMLStreamException | IOException | IllegalStateException e) {
215 throw new IllegalStateException("Unable to serialize " + rpcInput, e);
218 final Document node = result.getNode().getOwnerDocument();
220 return new NetconfMessage(node);
224 public NetconfMessage toActionRequest(final SchemaPath action, final DOMDataTreeIdentifier domDataTreeIdentifier,
225 final NormalizedNode<?, ?> payload) {
226 final ActionDefinition actionDef = actions.get(action);
227 Preconditions.checkArgument(actionDef != null, "Action does not exist: %s", action);
229 final ContainerSchemaNode inputDef = actionDef.getInput();
230 if (inputDef.getChildNodes().isEmpty()) {
231 return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForActionRequest(
232 DataSchemaContextTree.from(schemaContext), domDataTreeIdentifier, action, counter,
233 actionDef.getQName().getLocalName()).getNode().getOwnerDocument());
236 Preconditions.checkNotNull(payload, "Transforming an action with input: %s, payload cannot be null", action);
237 Preconditions.checkArgument(payload instanceof ContainerNode,
238 "Transforming an action with input: %s, payload has to be a container, but was: %s", action, payload);
240 // Set the path to the input of action for the node stream writer
241 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForActionRequest(
242 DataSchemaContextTree.from(schemaContext), domDataTreeIdentifier, inputDef.getPath(), counter,
243 actionDef.getQName().getLocalName());
246 NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, inputDef.getPath(),
248 } catch (final XMLStreamException | IOException | IllegalStateException e) {
249 throw new IllegalStateException("Unable to serialize " + action, e);
252 return new NetconfMessage(result.getNode().getOwnerDocument());
255 private static boolean isBaseOrNotificationRpc(final QName rpc) {
256 return BASE_OR_NOTIFICATION_NS.contains(rpc.getNamespace());
260 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
261 final NormalizedNode<?, ?> normalizedNode;
262 final QName rpcQName = rpc.getLastComponent();
263 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
264 normalizedNode = Builders.containerBuilder()
265 .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_NODEID)
266 .withChild(Builders.anyXmlBuilder()
267 .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_NODEID)
268 .withValue(new DOMSource(NetconfMessageTransformUtil.getDataSubtree(message.getDocument())))
272 // Determine whether a base netconf operation is being invoked
273 // and also check if the device exposed model for base netconf.
274 // If no, use pre built base netconf operations model
275 final ImmutableMap<QName, RpcDefinition> currentMappedRpcs;
276 if (mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName)) {
277 currentMappedRpcs = baseSchema.getMappedRpcs();
279 currentMappedRpcs = mappedRpcs;
282 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
283 Preconditions.checkArgument(rpcDefinition != null,
284 "Unable to parse response of %s, the rpc is unknown", rpcQName);
286 // In case no input for rpc is defined, we can simply construct the payload here
287 normalizedNode = parseResult(message, rpcDefinition);
289 return new DefaultDOMRpcResult(normalizedNode);
293 public DOMActionResult toActionResult(final SchemaPath action, final NetconfMessage message) {
294 final ActionDefinition actionDefinition = actions.get(action);
295 Preconditions.checkArgument(actionDefinition != null, "Action does not exist: %s", action);
296 final ContainerNode normalizedNode = (ContainerNode) parseResult(message, actionDefinition);
298 if (normalizedNode == null) {
299 return new SimpleDOMActionResult(Collections.emptyList());
301 return new SimpleDOMActionResult(normalizedNode, Collections.emptyList());
305 private NormalizedNode<?, ?> parseResult(final NetconfMessage message,
306 final OperationDefinition operationDefinition) {
307 if (operationDefinition.getOutput().getChildNodes().isEmpty()) {
308 Preconditions.checkArgument(XmlElement.fromDomDocument(
309 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
310 "Unexpected content in response of rpc: %s, %s", operationDefinition.getQName(), message);
313 final Element element = message.getDocument().getDocumentElement();
315 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
316 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
317 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
318 operationDefinition.getOutput(), strictParsing);
319 xmlParser.traverse(new DOMSource(element));
320 return resultHolder.getResult();
321 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
322 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
327 static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
328 private final ContainerNode content;
329 private final SchemaPath schemaPath;
330 private final Instant eventTime;
332 NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
333 this.content = content;
334 this.eventTime = eventTime;
335 this.schemaPath = toPath(content.getNodeType());
339 public SchemaPath getType() {
344 public ContainerNode getBody() {
349 public Instant getEventInstant() {