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.NetconfSessionPreferences;
39 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
40 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil;
41 import org.opendaylight.netconf.common.mdsal.NormalizedDataUtil;
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 availableYangSchemas.stream()
118 .map(RemoteYangSchema::getQName)
119 .collect(ImmutableSet.toImmutableSet());
123 * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
125 static NetconfStateSchemas create(final DOMRpcService deviceRpc,
126 final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
127 final EffectiveModelContext schemaContext) {
128 if (!remoteSessionCapabilities.isMonitoringSupported()) {
129 // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
130 // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
131 LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
135 final DOMRpcResult schemasNodeResult;
137 schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_QNAME, GET_SCHEMAS_RPC).get();
138 } catch (final InterruptedException e) {
139 Thread.currentThread().interrupt();
140 throw new IllegalStateException(id
141 + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
142 } catch (final ExecutionException e) {
143 LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
147 if (!schemasNodeResult.errors().isEmpty()) {
148 LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
149 id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.errors());
153 final Optional<? extends NormalizedNode> optSchemasNode = findSchemasNode(schemasNodeResult.value(),
155 if (optSchemasNode.isEmpty()) {
156 LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
160 final NormalizedNode schemasNode = optSchemasNode.orElseThrow();
161 checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
163 return create(id, (ContainerNode) schemasNode);
167 * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
170 protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
171 final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
173 final DataContainerChild child = schemasNode.childByArg(toId(Schema.QNAME));
174 checkState(child != null, "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
176 checkState(child instanceof MapNode,
177 "Unexpected structure for container: %s in response: %s. Expecting a list",
178 Schema.QNAME.withoutRevision(), schemasNode);
180 for (final MapEntryNode schemaNode : ((MapNode) child).body()) {
181 final Optional<RemoteYangSchema> fromCompositeNode =
182 RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
183 fromCompositeNode.ifPresent(availableYangSchemas::add);
186 return new NetconfStateSchemas(availableYangSchemas);
189 private static Optional<? extends NormalizedNode> findSchemasNode(final NormalizedNode result,
190 final EffectiveModelContext schemaContext) {
191 if (result == null) {
192 return Optional.empty();
194 // FIXME: unchecked cast
195 final var rpcResult = ((ContainerNode) result).childByArg(NETCONF_DATA_NODEID);
196 if (rpcResult == null) {
197 return Optional.empty();
200 verify(rpcResult instanceof DOMSourceAnyxmlNode, "Unexpected result %s", rpcResult);
202 // Server may include additional data which we do not understand. Make sure we trim the input before we try
204 // FIXME: this is something NetconfUtil.transformDOMSourceToNormalizedNode(), and more generally, NormalizedNode
205 // codecs should handle. We really want to a NormalizedNode tree which can be directly queried for known
206 // things while completely ignoring XML content (and hence its semantics) of other elements.
207 final var filteredBody = ietfMonitoringCopy(((DOMSourceAnyxmlNode) rpcResult).body());
209 final NormalizedNode dataNode;
211 dataNode = NormalizedDataUtil.transformDOMSourceToNormalizedNode(schemaContext, filteredBody).getResult();
212 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
213 LOG.warn("Failed to transform {}", rpcResult, e);
214 return Optional.empty();
217 // FIXME: unchecked cast
218 final var nStateNode = ((DataContainerNode) dataNode).childByArg(toId(NetconfState.QNAME));
219 if (nStateNode == null) {
220 return Optional.empty();
223 // FIXME: unchecked cast
224 return ((DataContainerNode) nStateNode).findChildByArg(toId(Schemas.QNAME));
228 static DOMSource ietfMonitoringCopy(final DOMSource domSource) {
229 final var sourceDoc = XmlUtil.newDocument();
230 sourceDoc.appendChild(sourceDoc.importNode(domSource.getNode(), true));
232 final var treeWalker = ((DocumentTraversal) sourceDoc).createTreeWalker(sourceDoc.getDocumentElement(),
233 NodeFilter.SHOW_ALL, node -> {
234 final var namespace = node.getNamespaceURI();
235 return namespace == null || MONITORING_NAMESPACE.equals(namespace)
236 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
239 final var filteredDoc = XmlUtil.newDocument();
240 filteredDoc.appendChild(filteredDoc.importNode(treeWalker.getRoot(), false));
241 final var filteredElement = filteredDoc.getDocumentElement();
242 copyChildren(treeWalker, filteredDoc, filteredElement);
244 return new DOMSource(filteredElement);
247 private static void copyChildren(final TreeWalker walker, final Document targetDoc, final Node targetNode) {
248 if (walker.firstChild() != null) {
249 for (var node = walker.getCurrentNode(); node != null; node = walker.nextSibling()) {
250 final var importedNode = targetDoc.importNode(node, false);
251 targetNode.appendChild(importedNode);
252 copyChildren(walker, targetDoc, importedNode);
253 walker.setCurrentNode(node);
258 public static final class RemoteYangSchema {
259 private final QName qname;
261 RemoteYangSchema(final QName qname) {
265 public QName getQName() {
269 static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
270 final MapEntryNode schemaNode) {
271 final QName schemaNodeId = schemaNode.getIdentifier().getNodeType();
272 checkArgument(schemaNodeId.equals(Schema.QNAME), "Wrong QName %s", schemaNodeId);
274 QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
276 final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).orElseThrow();
278 if (!formatAsString.equals(Yang.QNAME.toString())) {
279 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
280 return Optional.empty();
283 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
284 final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
285 if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
286 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
287 return Optional.empty();
290 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
291 final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
292 if (namespaceValue.isEmpty()) {
293 LOG.warn("{}: Ignoring schema due to missing namespace", id);
294 return Optional.empty();
296 final String namespaceAsString = namespaceValue.orElseThrow();
298 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
299 // Revision does not have to be filled
300 final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
302 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
303 final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).orElseThrow();
305 final QName moduleQName = revisionAsString.isPresent()
306 ? QName.create(namespaceAsString, revisionAsString.orElseThrow(), moduleNameAsString)
307 : QName.create(XMLNamespace.of(namespaceAsString), moduleNameAsString);
309 return Optional.of(new RemoteYangSchema(moduleQName));
313 * Extracts all values of a leaf-list node as a set of strings.
315 private static Set<String> getAllChildNodeValues(final DataContainerNode schemaNode,
316 final QName childNodeQName) {
317 final Set<String> extractedValues = new HashSet<>();
318 final DataContainerChild child = schemaNode.childByArg(toId(childNodeQName));
319 checkArgument(child != null, "Child nodes %s not present", childNodeQName);
320 checkArgument(child instanceof LeafSetNode, "Child nodes %s not present", childNodeQName);
321 for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child).body()) {
322 extractedValues.add(getValueOfSimpleNode(childNode).orElseThrow());
324 return extractedValues;
327 private static Optional<String> getSingleChildNodeValue(final DataContainerNode schemaNode,
328 final QName childNode) {
329 final Optional<DataContainerChild> node = schemaNode.findChildByArg(toId(childNode));
330 if (node.isPresent()) {
331 return getValueOfSimpleNode(node.orElseThrow());
333 LOG.debug("Child node {} not present", childNode);
334 return Optional.empty();
337 private static Optional<String> getValueOfSimpleNode(final NormalizedNode node) {
338 final String valueStr = node.body().toString();
339 return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
343 public boolean equals(final Object obj) {
347 if (obj == null || getClass() != obj.getClass()) {
351 final RemoteYangSchema that = (RemoteYangSchema) obj;
353 return qname.equals(that.qname);
357 public int hashCode() {
358 return qname.hashCode();