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_RPC_REPLY_NODEID;
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.ImmutableSet;
19 import com.google.common.collect.ImmutableSet.Builder;
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.Collection;
28 import java.util.Collections;
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.RpcError;
50 import org.opendaylight.yangtools.yang.common.YangConstants;
51 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
54 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
55 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
56 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
57 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
58 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
59 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
60 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
61 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
63 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
65 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
66 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.w3c.dom.Document;
73 import org.w3c.dom.Element;
74 import org.xml.sax.SAXException;
76 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
78 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
80 private static final ImmutableSet<URI> BASE_OR_NOTIFICATION_NS = ImmutableSet.of(
82 IETF_NETCONF_NOTIFICATIONS.getNamespace(),
83 CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
85 private final SchemaContext schemaContext;
86 private final BaseSchema baseSchema;
87 private final MessageCounter counter;
88 private final Map<QName, RpcDefinition> mappedRpcs;
89 private final Multimap<QName, NotificationDefinition> mappedNotifications;
90 private final boolean strictParsing;
91 private final Set<ActionDefinition> actions;
93 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
94 this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
97 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
98 final BaseSchema baseSchema) {
99 this.counter = new MessageCounter();
100 this.schemaContext = schemaContext;
101 this.mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
102 this.actions = getActions();
103 this.mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
104 node -> node.getQName().withoutRevision());
105 this.baseSchema = baseSchema;
106 this.strictParsing = strictParsing;
110 Set<ActionDefinition> getActions() {
111 Builder<ActionDefinition> builder = ImmutableSet.builder();
112 for (DataSchemaNode dataSchemaNode : schemaContext.getChildNodes()) {
113 if (dataSchemaNode instanceof ActionNodeContainer) {
114 findAction(dataSchemaNode, builder);
117 return builder.build();
120 private void findAction(final DataSchemaNode dataSchemaNode, final Builder<ActionDefinition> builder) {
121 if (dataSchemaNode instanceof ActionNodeContainer) {
122 final ActionNodeContainer containerSchemaNode = (ActionNodeContainer) dataSchemaNode;
123 for (ActionDefinition actionDefinition : containerSchemaNode.getActions()) {
124 builder.add(actionDefinition);
127 if (dataSchemaNode instanceof DataNodeContainer) {
128 for (DataSchemaNode innerDataSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
129 findAction(innerDataSchemaNode, 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 Map<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
197 .prepareDomResultForRpcRequest(rpcQName, counter).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 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(SchemaPath action, final DOMDataTreeIdentifier domDataTreeIdentifier,
225 final NormalizedNode<?, ?> payload) {
226 ActionDefinition actionDefinition = null;
227 SchemaPath schemaPath = action;
228 for (ActionDefinition actionDef : actions) {
229 if (actionDef.getPath().getLastComponent().equals(action.getLastComponent())) {
230 actionDefinition = actionDef;
231 schemaPath = actionDef.getPath();
234 Preconditions.checkNotNull(actionDefinition, "Action does not exist: %s", action.getLastComponent());
236 if (actionDefinition.getInput().getChildNodes().isEmpty()) {
237 return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForActionRequest(
238 DataSchemaContextTree.from(schemaContext), domDataTreeIdentifier, action, counter,
239 actionDefinition.getQName().getLocalName())
240 .getNode().getOwnerDocument());
243 Preconditions.checkNotNull(payload, "Transforming an action with input: %s, payload cannot be null",
244 action.getLastComponent());
245 Preconditions.checkArgument(payload instanceof ContainerNode,
246 "Transforming an rpc with input: %s, payload has to be a container, but was: %s",
247 action.getLastComponent(), payload);
248 // Set the path to the input of rpc for the node stream writer
249 action = action.createChild(QName.create(action.getLastComponent(), "input").intern());
250 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForActionRequest(
251 DataSchemaContextTree.from(schemaContext), domDataTreeIdentifier, action, counter,
252 actionDefinition.getQName().getLocalName());
255 NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result,
256 schemaPath.createChild(QName.create(action.getLastComponent(), "input").intern()), schemaContext);
257 } catch (final XMLStreamException | IOException | IllegalStateException e) {
258 throw new IllegalStateException("Unable to serialize " + action, e);
261 final Document node = result.getNode().getOwnerDocument();
263 return new NetconfMessage(node);
266 private static boolean isBaseOrNotificationRpc(final QName rpc) {
267 return BASE_OR_NOTIFICATION_NS.contains(rpc.getNamespace());
271 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
272 final NormalizedNode<?, ?> normalizedNode;
273 final QName rpcQName = rpc.getLastComponent();
274 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
275 final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
276 final ContainerSchemaNode schemaForDataRead =
277 NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
278 final ContainerNode dataNode;
281 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
282 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
283 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext, schemaForDataRead,
285 xmlParser.traverse(new DOMSource(xmlData));
286 dataNode = (ContainerNode) resultHolder.getResult();
287 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
288 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
291 normalizedNode = Builders.containerBuilder()
292 .withNodeIdentifier(NETCONF_RPC_REPLY_NODEID)
293 .withChild(dataNode).build();
296 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
298 // Determine whether a base netconf operation is being invoked
299 // and also check if the device exposed model for base netconf.
300 // If no, use pre built base netconf operations model
301 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
302 if (needToUseBaseCtx) {
303 currentMappedRpcs = baseSchema.getMappedRpcs();
306 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
307 Preconditions.checkArgument(rpcDefinition != null,
308 "Unable to parse response of %s, the rpc is unknown", rpcQName);
310 // In case no input for rpc is defined, we can simply construct the payload here
311 normalizedNode = parseResult(message, rpcDefinition);
313 return new DefaultDOMRpcResult(normalizedNode);
317 public DOMActionResult toActionResult(final SchemaPath action, final NetconfMessage message) {
318 ActionDefinition actionDefinition = null;
319 for (ActionDefinition actionDef : actions) {
320 if (actionDef.getPath().getLastComponent().equals(action.getLastComponent())) {
321 actionDefinition = actionDef;
324 Preconditions.checkNotNull(actionDefinition, "Action does not exist: %s", action);
325 ContainerNode normalizedNode = (ContainerNode) parseResult(message, actionDefinition);
327 if (normalizedNode == null) {
328 return new SimpleDOMActionResult(Collections.<RpcError>emptyList());
330 return new SimpleDOMActionResult(normalizedNode, Collections.<RpcError>emptyList());
334 private NormalizedNode<?, ?> parseResult(final NetconfMessage message,
335 final OperationDefinition operationDefinition) {
336 if (operationDefinition.getOutput().getChildNodes().isEmpty()) {
337 Preconditions.checkArgument(XmlElement.fromDomDocument(
338 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
339 "Unexpected content in response of rpc: %s, %s", operationDefinition.getQName(), message);
342 final Element element = message.getDocument().getDocumentElement();
344 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
345 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
346 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
347 operationDefinition.getOutput(), strictParsing);
348 xmlParser.traverse(new DOMSource(element));
349 return resultHolder.getResult();
350 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
351 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
356 static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
357 private final ContainerNode content;
358 private final SchemaPath schemaPath;
359 private final Instant eventTime;
361 NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
362 this.content = content;
363 this.eventTime = eventTime;
364 this.schemaPath = toPath(content.getNodeType());
368 public SchemaPath getType() {
373 public ContainerNode getBody() {
378 public Instant getEventInstant() {