2 * Copyright (c) 2014, 2015 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.client.mdsal;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.IETF_NETCONF_MONITORING;
14 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_DATA_NODEID;
15 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_FILTER_NODEID;
16 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_FILTER_QNAME;
17 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
18 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_GET_QNAME;
19 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_TYPE_QNAME;
20 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.toId;
22 import com.google.common.annotations.VisibleForTesting;
23 import com.google.common.base.Strings;
24 import com.google.common.collect.ImmutableSet;
25 import java.io.IOException;
26 import java.net.URISyntaxException;
27 import java.util.HashSet;
28 import java.util.Optional;
30 import java.util.concurrent.ExecutionException;
31 import javax.xml.stream.XMLStreamException;
32 import javax.xml.transform.dom.DOMSource;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
35 import org.opendaylight.mdsal.dom.api.DOMRpcService;
36 import org.opendaylight.netconf.api.xml.XmlUtil;
37 import org.opendaylight.netconf.client.mdsal.api.NetconfDeviceSchemas;
38 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
39 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil;
40 import org.opendaylight.netconf.common.mdsal.NormalizedDataUtil;
41 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.common.XMLNamespace;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
52 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
59 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.w3c.dom.Document;
63 import org.w3c.dom.Element;
64 import org.w3c.dom.Node;
65 import org.w3c.dom.traversal.DocumentTraversal;
66 import org.w3c.dom.traversal.NodeFilter;
67 import org.w3c.dom.traversal.TreeWalker;
68 import org.xml.sax.SAXException;
71 * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
73 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
74 public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(ImmutableSet.of());
76 private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
77 private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER = YangInstanceIdentifier.builder()
78 .node(NetconfState.QNAME).node(Schemas.QNAME).build();
79 private static final String MONITORING_NAMESPACE = IETF_NETCONF_MONITORING.getNamespace().toString();
80 private static final @NonNull ContainerNode GET_SCHEMAS_RPC;
83 final Document document = XmlUtil.newDocument();
85 final Element filterElem = XmlUtil.createElement(document, NETCONF_FILTER_QNAME.getLocalName(),
86 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
87 filterElem.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
90 final Element stateElem = XmlUtil.createElement(document, NetconfState.QNAME.getLocalName(),
91 Optional.of(NetconfState.QNAME.getNamespace().toString()));
92 stateElem.appendChild(XmlUtil.createElement(document, Schemas.QNAME.getLocalName(),
93 Optional.of(Schemas.QNAME.getNamespace().toString())));
94 filterElem.appendChild(stateElem);
96 GET_SCHEMAS_RPC = Builders.containerBuilder()
97 .withNodeIdentifier(NETCONF_GET_NODEID)
98 .withChild(Builders.anyXmlBuilder()
99 .withNodeIdentifier(NETCONF_FILTER_NODEID)
100 .withValue(new DOMSource(filterElem))
105 private final Set<RemoteYangSchema> availableYangSchemas;
107 public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
108 this.availableYangSchemas = availableYangSchemas;
111 public Set<RemoteYangSchema> getAvailableYangSchemas() {
112 return availableYangSchemas;
116 public Set<QName> getAvailableYangSchemasQNames() {
117 return getAvailableYangSchemas().stream().map(RemoteYangSchema::getQName)
118 .collect(ImmutableSet.toImmutableSet());
122 * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
124 static NetconfStateSchemas create(final DOMRpcService deviceRpc,
125 final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
126 final EffectiveModelContext schemaContext) {
127 if (!remoteSessionCapabilities.isMonitoringSupported()) {
128 // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
129 // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
130 LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
134 final DOMRpcResult schemasNodeResult;
136 schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_QNAME, GET_SCHEMAS_RPC).get();
137 } catch (final InterruptedException e) {
138 Thread.currentThread().interrupt();
139 throw new IllegalStateException(id
140 + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
141 } catch (final ExecutionException e) {
142 LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
146 if (!schemasNodeResult.errors().isEmpty()) {
147 LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
148 id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.errors());
152 final Optional<? extends NormalizedNode> optSchemasNode = findSchemasNode(schemasNodeResult.value(),
154 if (optSchemasNode.isEmpty()) {
155 LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
159 final NormalizedNode schemasNode = optSchemasNode.orElseThrow();
160 checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
162 return create(id, (ContainerNode) schemasNode);
166 * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
169 protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
170 final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
172 final DataContainerChild child = schemasNode.childByArg(toId(Schema.QNAME));
173 checkState(child != null, "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
175 checkState(child instanceof MapNode,
176 "Unexpected structure for container: %s in response: %s. Expecting a list",
177 Schema.QNAME.withoutRevision(), schemasNode);
179 for (final MapEntryNode schemaNode : ((MapNode) child).body()) {
180 final Optional<RemoteYangSchema> fromCompositeNode =
181 RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
182 fromCompositeNode.ifPresent(availableYangSchemas::add);
185 return new NetconfStateSchemas(availableYangSchemas);
188 private static Optional<? extends NormalizedNode> findSchemasNode(final NormalizedNode result,
189 final EffectiveModelContext schemaContext) {
190 if (result == null) {
191 return Optional.empty();
193 // FIXME: unchecked cast
194 final var rpcResult = ((ContainerNode) result).childByArg(NETCONF_DATA_NODEID);
195 if (rpcResult == null) {
196 return Optional.empty();
199 verify(rpcResult instanceof DOMSourceAnyxmlNode, "Unexpected result %s", rpcResult);
201 // Server may include additional data which we do not understand. Make sure we trim the input before we try
203 // FIXME: this is something NetconfUtil.transformDOMSourceToNormalizedNode(), and more generally, NormalizedNode
204 // codecs should handle. We really want to a NormalizedNode tree which can be directly queried for known
205 // things while completely ignoring XML content (and hence its semantics) of other elements.
206 final var filteredBody = ietfMonitoringCopy(((DOMSourceAnyxmlNode) rpcResult).body());
208 final NormalizedNode dataNode;
210 dataNode = NormalizedDataUtil.transformDOMSourceToNormalizedNode(schemaContext, filteredBody).getResult();
211 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
212 LOG.warn("Failed to transform {}", rpcResult, e);
213 return Optional.empty();
216 // FIXME: unchecked cast
217 final var nStateNode = ((DataContainerNode) dataNode).childByArg(toId(NetconfState.QNAME));
218 if (nStateNode == null) {
219 return Optional.empty();
222 // FIXME: unchecked cast
223 return ((DataContainerNode) nStateNode).findChildByArg(toId(Schemas.QNAME));
227 static DOMSource ietfMonitoringCopy(final DOMSource domSource) {
228 final var sourceDoc = XmlUtil.newDocument();
229 sourceDoc.appendChild(sourceDoc.importNode(domSource.getNode(), true));
231 final var treeWalker = ((DocumentTraversal) sourceDoc).createTreeWalker(sourceDoc.getDocumentElement(),
232 NodeFilter.SHOW_ALL, node -> {
233 final var namespace = node.getNamespaceURI();
234 return namespace == null || MONITORING_NAMESPACE.equals(namespace)
235 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
238 final var filteredDoc = XmlUtil.newDocument();
239 filteredDoc.appendChild(filteredDoc.importNode(treeWalker.getRoot(), false));
240 final var filteredElement = filteredDoc.getDocumentElement();
241 copyChildren(treeWalker, filteredDoc, filteredElement);
243 return new DOMSource(filteredElement);
246 private static void copyChildren(final TreeWalker walker, final Document targetDoc, final Node targetNode) {
247 if (walker.firstChild() != null) {
248 for (var node = walker.getCurrentNode(); node != null; node = walker.nextSibling()) {
249 final var importedNode = targetDoc.importNode(node, false);
250 targetNode.appendChild(importedNode);
251 copyChildren(walker, targetDoc, importedNode);
252 walker.setCurrentNode(node);
257 public static final class RemoteYangSchema {
258 private final QName qname;
260 RemoteYangSchema(final QName qname) {
264 public QName getQName() {
268 static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
269 final MapEntryNode schemaNode) {
270 final QName schemaNodeId = schemaNode.getIdentifier().getNodeType();
271 checkArgument(schemaNodeId.equals(Schema.QNAME), "Wrong QName %s", schemaNodeId);
273 QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
275 final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).orElseThrow();
277 if (!formatAsString.equals(Yang.QNAME.toString())) {
278 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
279 return Optional.empty();
282 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
283 final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
284 if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
285 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
286 return Optional.empty();
289 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
290 final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
291 if (namespaceValue.isEmpty()) {
292 LOG.warn("{}: Ignoring schema due to missing namespace", id);
293 return Optional.empty();
295 final String namespaceAsString = namespaceValue.orElseThrow();
297 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
298 // Revision does not have to be filled
299 final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
301 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
302 final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).orElseThrow();
304 final QName moduleQName = revisionAsString.isPresent()
305 ? QName.create(namespaceAsString, revisionAsString.orElseThrow(), moduleNameAsString)
306 : QName.create(XMLNamespace.of(namespaceAsString), moduleNameAsString);
308 return Optional.of(new RemoteYangSchema(moduleQName));
312 * Extracts all values of a leaf-list node as a set of strings.
314 private static Set<String> getAllChildNodeValues(final DataContainerNode schemaNode,
315 final QName childNodeQName) {
316 final Set<String> extractedValues = new HashSet<>();
317 final DataContainerChild child = schemaNode.childByArg(toId(childNodeQName));
318 checkArgument(child != null, "Child nodes %s not present", childNodeQName);
319 checkArgument(child instanceof LeafSetNode, "Child nodes %s not present", childNodeQName);
320 for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child).body()) {
321 extractedValues.add(getValueOfSimpleNode(childNode).orElseThrow());
323 return extractedValues;
326 private static Optional<String> getSingleChildNodeValue(final DataContainerNode schemaNode,
327 final QName childNode) {
328 final Optional<DataContainerChild> node = schemaNode.findChildByArg(toId(childNode));
329 if (node.isPresent()) {
330 return getValueOfSimpleNode(node.orElseThrow());
332 LOG.debug("Child node {} not present", childNode);
333 return Optional.empty();
336 private static Optional<String> getValueOfSimpleNode(final NormalizedNode node) {
337 final String valueStr = node.body().toString();
338 return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
342 public boolean equals(final Object obj) {
346 if (obj == null || getClass() != obj.getClass()) {
350 final RemoteYangSchema that = (RemoteYangSchema) obj;
352 return qname.equals(that.qname);
356 public int hashCode() {
357 return qname.hashCode();