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.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;
14 import com.google.common.base.Function;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.Maps;
17 import com.google.common.collect.Multimap;
18 import com.google.common.collect.Multimaps;
19 import java.io.IOException;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Comparator;
23 import java.util.Date;
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.md.sal.dom.api.DOMEvent;
31 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
33 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
34 import org.opendaylight.netconf.api.NetconfMessage;
35 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
36 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
37 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
43 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
44 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
45 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
56 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
58 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
60 private static final Function<SchemaNode, QName> QNAME_FUNCTION = rpcDefinition -> rpcDefinition.getQName();
62 private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
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 private final DomToNormalizedNodeParserFactory parserFactory;
71 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
72 this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
75 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
76 this.counter = new MessageCounter();
77 this.schemaContext = schemaContext;
78 parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
79 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
80 mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
81 this.baseSchema = baseSchema;
85 public synchronized DOMNotification toNotification(final NetconfMessage message) {
86 final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
87 final QName notificationNoRev;
89 notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
90 } catch (final MissingNameSpaceException e) {
91 throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
93 final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
94 Preconditions.checkArgument(notificationDefinitions.size() > 0,
95 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
97 final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
99 final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
101 final Element element = stripped.getValue().getDomElement();
102 final ContainerNode content;
104 content = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
105 notificationAsContainerSchemaNode);
106 } catch (IllegalArgumentException e) {
107 throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
109 return new NetconfDeviceNotification(content, stripped.getKey());
112 private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
113 Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
115 return Collections.max(notificationDefinitions, cmp);
119 public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
120 // In case no input for rpc is defined, we can simply construct the payload here
121 final QName rpcQName = rpc.getLastComponent();
122 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
124 // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
125 // If no, use pre built base netconf operations model
126 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
127 if(needToUseBaseCtx) {
128 currentMappedRpcs = baseSchema.getMappedRpcs();
131 Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
132 if(currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
133 return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
136 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
137 Preconditions.checkArgument(payload instanceof ContainerNode,
138 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
140 // Set the path to the input of rpc for the node stream writer
141 rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
142 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
145 // If the schema context for netconf device does not contain model for base netconf operations, use default pre build context with just the base model
146 // This way operations like lock/unlock are supported even if the source for base model was not provided
147 SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
148 NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
149 } catch (final XMLStreamException | IOException | IllegalStateException e) {
150 throw new IllegalStateException("Unable to serialize " + rpc, e);
153 final Document node = result.getNode().getOwnerDocument();
155 return new NetconfMessage(node);
158 private static boolean isBaseOrNotificationRpc(final QName rpc) {
159 return rpc.getNamespace().equals(NETCONF_URI) ||
160 rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
161 rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
166 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
167 final NormalizedNode<?, ?> normalizedNode;
168 final QName rpcQName = rpc.getLastComponent();
169 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
170 final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
171 final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
172 final ContainerNode dataNode;
175 dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
176 } catch (IllegalArgumentException e) {
177 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
180 normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
181 .withChild(dataNode).build();
184 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
186 // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
187 // If no, use pre built base netconf operations model
188 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
189 if(needToUseBaseCtx) {
190 currentMappedRpcs = baseSchema.getMappedRpcs();
193 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
194 Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
196 // In case no input for rpc is defined, we can simply construct the payload here
197 if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
198 Preconditions.checkArgument(XmlElement.fromDomDocument(
199 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
200 "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
201 normalizedNode = null;
203 final Element element = message.getDocument().getDocumentElement();
205 normalizedNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
206 rpcDefinition.getOutput());
207 } catch (IllegalArgumentException e) {
208 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
212 return new DefaultDOMRpcResult(normalizedNode);
215 static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
216 private final ContainerNode content;
217 private final SchemaPath schemaPath;
218 private final Date eventTime;
220 NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
221 this.content = content;
222 this.eventTime = eventTime;
223 this.schemaPath = toPath(content.getNodeType());
228 public SchemaPath getType() {
235 public ContainerNode getBody() {
240 public Date getEventTime() {