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.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.sal.connect.api.NetconfDeviceSchemas;
38 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
39 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
40 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
41 import org.opendaylight.netconf.util.NetconfUtil;
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.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
57 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
58 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.w3c.dom.Document;
62 import org.w3c.dom.Element;
63 import org.xml.sax.SAXException;
66 * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
68 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
69 public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(ImmutableSet.of());
71 private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
72 private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
73 YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
74 private static final @NonNull ContainerNode GET_SCHEMAS_RPC;
77 final Document document = XmlUtil.newDocument();
79 final Element filterElem = XmlUtil.createElement(document, NETCONF_FILTER_QNAME.getLocalName(),
80 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
81 filterElem.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
84 final Element stateElem = XmlUtil.createElement(document, NetconfState.QNAME.getLocalName(),
85 Optional.of(NetconfState.QNAME.getNamespace().toString()));
86 stateElem.appendChild(XmlUtil.createElement(document, Schemas.QNAME.getLocalName(),
87 Optional.of(Schemas.QNAME.getNamespace().toString())));
88 filterElem.appendChild(stateElem);
90 GET_SCHEMAS_RPC = Builders.containerBuilder()
91 .withNodeIdentifier(NETCONF_GET_NODEID)
92 .withChild(Builders.anyXmlBuilder()
93 .withNodeIdentifier(NETCONF_FILTER_NODEID)
94 .withValue(new DOMSource(filterElem))
99 private final Set<RemoteYangSchema> availableYangSchemas;
101 public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
102 this.availableYangSchemas = availableYangSchemas;
105 public Set<RemoteYangSchema> getAvailableYangSchemas() {
106 return availableYangSchemas;
110 public Set<QName> getAvailableYangSchemasQNames() {
111 return getAvailableYangSchemas().stream().map(RemoteYangSchema::getQName)
112 .collect(ImmutableSet.toImmutableSet());
116 * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
118 static NetconfStateSchemas create(final DOMRpcService deviceRpc,
119 final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
120 final EffectiveModelContext schemaContext) {
121 if (!remoteSessionCapabilities.isMonitoringSupported()) {
122 // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
123 // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
124 LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
128 final DOMRpcResult schemasNodeResult;
130 schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_QNAME, GET_SCHEMAS_RPC).get();
131 } catch (final InterruptedException e) {
132 Thread.currentThread().interrupt();
133 throw new RuntimeException(id
134 + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
135 } catch (final ExecutionException e) {
136 LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
140 if (!schemasNodeResult.getErrors().isEmpty()) {
141 LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
142 id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
146 final Optional<? extends NormalizedNode<?, ?>> optSchemasNode = findSchemasNode(schemasNodeResult.getResult(),
148 if (optSchemasNode.isEmpty()) {
149 LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
153 final NormalizedNode<?, ?> schemasNode = optSchemasNode.get();
154 checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
156 return create(id, (ContainerNode) schemasNode);
160 * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
163 protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
164 final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
166 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
167 schemasNode.getChild(toId(Schema.QNAME));
168 checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
170 checkState(child.get() instanceof MapNode,
171 "Unexpected structure for container: %s in response: %s. Expecting a list",
172 Schema.QNAME.withoutRevision(), schemasNode);
174 for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
175 final Optional<RemoteYangSchema> fromCompositeNode =
176 RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
177 fromCompositeNode.ifPresent(availableYangSchemas::add);
180 return new NetconfStateSchemas(availableYangSchemas);
183 private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result,
184 final EffectiveModelContext schemaContext) {
185 if (result == null) {
186 return Optional.empty();
188 final Optional<DataContainerChild<?, ?>> rpcResultOpt = ((ContainerNode)result).getChild(NETCONF_DATA_NODEID);
189 if (rpcResultOpt.isEmpty()) {
190 return Optional.empty();
193 final DataContainerChild<?, ?> rpcResult = rpcResultOpt.get();
194 verify(rpcResult instanceof DOMSourceAnyxmlNode, "Unexpected result %s", rpcResult);
195 final NormalizedNode<?, ?> dataNode;
198 dataNode = NetconfUtil.transformDOMSourceToNormalizedNode(schemaContext,
199 ((DOMSourceAnyxmlNode) rpcResult).getValue()).getResult();
200 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
201 LOG.warn("Failed to transform {}", rpcResult, e);
202 return Optional.empty();
205 final Optional<DataContainerChild<?, ?>> nStateNode = ((DataContainerNode<?>) dataNode).getChild(
206 toId(NetconfState.QNAME));
207 if (nStateNode.isEmpty()) {
208 return Optional.empty();
211 return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
214 public static final class RemoteYangSchema {
215 private final QName qname;
217 RemoteYangSchema(final QName qname) {
221 public QName getQName() {
225 static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
226 final MapEntryNode schemaNode) {
227 checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
229 QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
231 final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
233 if (!formatAsString.equals(Yang.QNAME.toString())) {
234 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
235 return Optional.empty();
238 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
239 final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
240 if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
241 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
242 return Optional.empty();
245 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
246 final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
247 if (namespaceValue.isEmpty()) {
248 LOG.warn("{}: Ignoring schema due to missing namespace", id);
249 return Optional.empty();
251 final String namespaceAsString = namespaceValue.get();
253 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
254 // Revision does not have to be filled
255 final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
257 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
258 final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
260 final QName moduleQName = revisionAsString.isPresent()
261 ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
262 : QName.create(URI.create(namespaceAsString), moduleNameAsString);
264 return Optional.of(new RemoteYangSchema(moduleQName));
268 * Extracts all values of a leaf-list node as a set of strings.
270 private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
271 final QName childNodeQName) {
272 final Set<String> extractedValues = new HashSet<>();
273 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
274 schemaNode.getChild(toId(childNodeQName));
275 checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
276 checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
277 for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
278 extractedValues.add(getValueOfSimpleNode(childNode).get());
280 return extractedValues;
283 private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
284 final QName childNode) {
285 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
286 schemaNode.getChild(toId(childNode));
287 if (node.isPresent()) {
288 return getValueOfSimpleNode(node.get());
290 LOG.debug("Child node {} not present", childNode);
291 return Optional.empty();
294 private static Optional<String> getValueOfSimpleNode(
295 final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
296 final String valueStr = node.getValue().toString();
297 return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
301 public boolean equals(final Object obj) {
305 if (obj == null || getClass() != obj.getClass()) {
309 final RemoteYangSchema that = (RemoteYangSchema) obj;
311 return qname.equals(that.qname);
315 public int hashCode() {
316 return qname.hashCode();