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.sal.connect.netconf;
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.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_NODEID;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_FILTER_NODEID;
15 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_FILTER_QNAME;
16 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
17 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_QNAME;
18 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_TYPE_QNAME;
19 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Strings;
23 import com.google.common.collect.ImmutableSet;
24 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.opendaylight.mdsal.dom.api.DOMRpcResult;
34 import org.opendaylight.mdsal.dom.api.DOMRpcService;
35 import org.opendaylight.netconf.api.xml.XmlUtil;
36 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
37 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
38 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
39 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
40 import org.opendaylight.netconf.util.NetconfUtil;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
50 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
57 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.w3c.dom.Document;
61 import org.w3c.dom.Element;
62 import org.xml.sax.SAXException;
65 * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
67 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
68 public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(ImmutableSet.of());
70 private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
71 private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
72 YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
73 private static final ContainerNode GET_SCHEMAS_RPC;
76 final Document document = XmlUtil.newDocument();
78 final Element filterElem = XmlUtil.createElement(document, NETCONF_FILTER_QNAME.getLocalName(),
79 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
80 filterElem.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
83 final Element stateElem = XmlUtil.createElement(document, NetconfState.QNAME.getLocalName(),
84 Optional.of(NetconfState.QNAME.getNamespace().toString()));
85 stateElem.appendChild(XmlUtil.createElement(document, Schemas.QNAME.getLocalName(),
86 Optional.of(Schemas.QNAME.getNamespace().toString())));
87 filterElem.appendChild(stateElem);
89 GET_SCHEMAS_RPC = Builders.containerBuilder()
90 .withNodeIdentifier(NETCONF_GET_NODEID)
91 .withChild(Builders.anyXmlBuilder()
92 .withNodeIdentifier(NETCONF_FILTER_NODEID)
93 .withValue(new DOMSource(filterElem))
98 private final Set<RemoteYangSchema> availableYangSchemas;
100 public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
101 this.availableYangSchemas = availableYangSchemas;
104 public Set<RemoteYangSchema> getAvailableYangSchemas() {
105 return availableYangSchemas;
109 public Set<QName> getAvailableYangSchemasQNames() {
110 return getAvailableYangSchemas().stream().map(RemoteYangSchema::getQName)
111 .collect(ImmutableSet.toImmutableSet());
115 * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
117 static NetconfStateSchemas create(final DOMRpcService deviceRpc,
118 final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
119 final EffectiveModelContext schemaContext) {
120 if (!remoteSessionCapabilities.isMonitoringSupported()) {
121 // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
122 // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
123 LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
127 final DOMRpcResult schemasNodeResult;
129 schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_QNAME, GET_SCHEMAS_RPC).get();
130 } catch (final InterruptedException e) {
131 Thread.currentThread().interrupt();
132 throw new RuntimeException(id
133 + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
134 } catch (final ExecutionException e) {
135 LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
139 if (!schemasNodeResult.getErrors().isEmpty()) {
140 LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
141 id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
145 final Optional<? extends NormalizedNode<?, ?>> optSchemasNode = findSchemasNode(schemasNodeResult.getResult(),
147 if (!optSchemasNode.isPresent()) {
148 LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
152 final NormalizedNode<?, ?> schemasNode = optSchemasNode.get();
153 checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
155 return create(id, (ContainerNode) schemasNode);
159 * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
162 protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
163 final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
165 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
166 schemasNode.getChild(toId(Schema.QNAME));
167 checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
169 checkState(child.get() instanceof MapNode,
170 "Unexpected structure for container: %s in response: %s. Expecting a list",
171 Schema.QNAME.withoutRevision(), schemasNode);
173 for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
174 final Optional<RemoteYangSchema> fromCompositeNode =
175 RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
176 if (fromCompositeNode.isPresent()) {
177 availableYangSchemas.add(fromCompositeNode.get());
181 return new NetconfStateSchemas(availableYangSchemas);
184 private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result,
185 final EffectiveModelContext schemaContext) {
186 if (result == null) {
187 return Optional.empty();
189 final Optional<DataContainerChild<?, ?>> rpcResultOpt = ((ContainerNode)result).getChild(NETCONF_DATA_NODEID);
190 if (!rpcResultOpt.isPresent()) {
191 return Optional.empty();
194 final DataContainerChild<?, ?> rpcResult = rpcResultOpt.get();
195 verify(rpcResult instanceof DOMSourceAnyxmlNode, "Unexpected result %s", rpcResult);
196 final NormalizedNode<?, ?> dataNode;
199 dataNode = NetconfUtil.transformDOMSourceToNormalizedNode(schemaContext,
200 ((DOMSourceAnyxmlNode) rpcResult).getValue()).getResult();
201 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
202 LOG.warn("Failed to transform {}", rpcResult, e);
203 return Optional.empty();
206 final Optional<DataContainerChild<?, ?>> nStateNode = ((DataContainerNode<?>) dataNode).getChild(
207 toId(NetconfState.QNAME));
208 if (!nStateNode.isPresent()) {
209 return Optional.empty();
212 return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
215 public static final class RemoteYangSchema {
216 private final QName qname;
218 RemoteYangSchema(final QName qname) {
222 public QName getQName() {
226 static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
227 final MapEntryNode schemaNode) {
228 checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
230 QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
232 final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
234 if (!formatAsString.equals(Yang.QNAME.toString())) {
235 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
236 return Optional.empty();
239 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
240 final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
241 if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
242 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
243 return Optional.empty();
246 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
247 final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
248 if (!namespaceValue.isPresent()) {
249 LOG.warn("{}: Ignoring schema due to missing namespace", id);
250 return Optional.empty();
252 final String namespaceAsString = namespaceValue.get();
254 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
255 // Revision does not have to be filled
256 final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
258 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
259 final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
261 final QName moduleQName = revisionAsString.isPresent()
262 ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
263 : QName.create(URI.create(namespaceAsString), moduleNameAsString);
265 return Optional.of(new RemoteYangSchema(moduleQName));
269 * Extracts all values of a leaf-list node as a set of strings.
271 private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
272 final QName childNodeQName) {
273 final Set<String> extractedValues = new HashSet<>();
274 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
275 schemaNode.getChild(toId(childNodeQName));
276 checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
277 checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
278 for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
279 extractedValues.add(getValueOfSimpleNode(childNode).get());
281 return extractedValues;
284 private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
285 final QName childNode) {
286 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
287 schemaNode.getChild(toId(childNode));
288 if (node.isPresent()) {
289 return getValueOfSimpleNode(node.get());
291 LOG.debug("Child node {} not present", childNode);
292 return Optional.empty();
295 private static Optional<String> getValueOfSimpleNode(
296 final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
297 final String valueStr = node.getValue().toString();
298 return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
302 public boolean equals(final Object obj) {
306 if (obj == null || getClass() != obj.getClass()) {
310 final RemoteYangSchema that = (RemoteYangSchema) obj;
312 return qname.equals(that.qname);
316 public int hashCode() {
317 return qname.hashCode();