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_GET_NODEID;
15 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_PATH;
16 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Strings;
20 import com.google.common.collect.ImmutableSet;
21 import java.io.IOException;
23 import java.net.URISyntaxException;
24 import java.util.HashSet;
25 import java.util.Optional;
27 import java.util.concurrent.ExecutionException;
28 import javax.xml.parsers.ParserConfigurationException;
29 import javax.xml.stream.XMLStreamException;
30 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
31 import org.opendaylight.mdsal.dom.api.DOMRpcService;
32 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
33 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
34 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
35 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
36 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
37 import org.opendaylight.netconf.util.NetconfUtil;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
47 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.xml.sax.SAXException;
60 * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
62 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
64 private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
66 public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(ImmutableSet.of());
68 private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
69 YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
71 private static final ContainerNode GET_SCHEMAS_RPC;
74 final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
75 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext());
77 = Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID).withChild(filter).build();
80 private final Set<RemoteYangSchema> availableYangSchemas;
82 public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
83 this.availableYangSchemas = availableYangSchemas;
86 public Set<RemoteYangSchema> getAvailableYangSchemas() {
87 return availableYangSchemas;
91 public Set<QName> getAvailableYangSchemasQNames() {
92 return getAvailableYangSchemas().stream().map(RemoteYangSchema::getQName)
93 .collect(ImmutableSet.toImmutableSet());
97 * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
99 static NetconfStateSchemas create(final DOMRpcService deviceRpc,
100 final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
101 final SchemaContext schemaContext) {
102 if (!remoteSessionCapabilities.isMonitoringSupported()) {
103 // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
104 // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
105 LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
109 final DOMRpcResult schemasNodeResult;
111 schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_PATH, GET_SCHEMAS_RPC).get();
112 } catch (final InterruptedException e) {
113 Thread.currentThread().interrupt();
114 throw new RuntimeException(id
115 + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
116 } catch (final ExecutionException e) {
117 LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
121 if (!schemasNodeResult.getErrors().isEmpty()) {
122 LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
123 id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
127 final Optional<? extends NormalizedNode<?, ?>> optSchemasNode = findSchemasNode(schemasNodeResult.getResult(),
129 if (!optSchemasNode.isPresent()) {
130 LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
134 final NormalizedNode<?, ?> schemasNode = optSchemasNode.get();
135 checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
137 return create(id, (ContainerNode) schemasNode);
141 * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
144 protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
145 final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
147 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
148 schemasNode.getChild(toId(Schema.QNAME));
149 checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
151 checkState(child.get() instanceof MapNode,
152 "Unexpected structure for container: %s in response: %s. Expecting a list",
153 Schema.QNAME.withoutRevision(), schemasNode);
155 for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
156 final Optional<RemoteYangSchema> fromCompositeNode =
157 RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
158 if (fromCompositeNode.isPresent()) {
159 availableYangSchemas.add(fromCompositeNode.get());
163 return new NetconfStateSchemas(availableYangSchemas);
166 private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result,
167 final SchemaContext schemaContext) {
168 if (result == null) {
169 return Optional.empty();
171 final Optional<DataContainerChild<?, ?>> rpcResultOpt = ((ContainerNode)result).getChild(NETCONF_DATA_NODEID);
172 if (!rpcResultOpt.isPresent()) {
173 return Optional.empty();
176 final DataContainerChild<?, ?> rpcResult = rpcResultOpt.get();
177 verify(rpcResult instanceof AnyXmlNode, "Unexpected result %s", rpcResult);
178 final NormalizedNode<?, ?> dataNode;
181 dataNode = NetconfUtil.transformDOMSourceToNormalizedNode(schemaContext,
182 ((AnyXmlNode) rpcResult).getValue()).getResult();
183 } catch (XMLStreamException | URISyntaxException | IOException | SAXException
184 | ParserConfigurationException e) {
185 LOG.warn("Failed to transform {}", rpcResult, e);
186 return Optional.empty();
189 final Optional<DataContainerChild<?, ?>> nStateNode = ((DataContainerNode<?>) dataNode).getChild(
190 toId(NetconfState.QNAME));
191 if (!nStateNode.isPresent()) {
192 return Optional.empty();
195 return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
198 public static final class RemoteYangSchema {
199 private final QName qname;
201 RemoteYangSchema(final QName qname) {
205 public QName getQName() {
209 static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
210 final MapEntryNode schemaNode) {
211 checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
213 QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
215 final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
217 if (!formatAsString.equals(Yang.QNAME.toString())) {
218 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
219 return Optional.empty();
222 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
223 final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
224 if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
225 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
226 return Optional.empty();
229 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
230 final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
231 if (!namespaceValue.isPresent()) {
232 LOG.warn("{}: Ignoring schema due to missing namespace", id);
233 return Optional.empty();
235 final String namespaceAsString = namespaceValue.get();
237 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
238 // Revision does not have to be filled
239 final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
241 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
242 final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
244 final QName moduleQName = revisionAsString.isPresent()
245 ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
246 : QName.create(URI.create(namespaceAsString), moduleNameAsString);
248 return Optional.of(new RemoteYangSchema(moduleQName));
252 * Extracts all values of a leaf-list node as a set of strings.
254 private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
255 final QName childNodeQName) {
256 final Set<String> extractedValues = new HashSet<>();
257 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
258 schemaNode.getChild(toId(childNodeQName));
259 checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
260 checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
261 for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
262 extractedValues.add(getValueOfSimpleNode(childNode).get());
264 return extractedValues;
267 private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
268 final QName childNode) {
269 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
270 schemaNode.getChild(toId(childNode));
271 if (node.isPresent()) {
272 return getValueOfSimpleNode(node.get());
274 LOG.debug("Child node {} not present", childNode);
275 return Optional.empty();
278 private static Optional<String> getValueOfSimpleNode(
279 final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
280 final String valueStr = node.getValue().toString();
281 return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
285 public boolean equals(final Object obj) {
289 if (obj == null || getClass() != obj.getClass()) {
293 final RemoteYangSchema that = (RemoteYangSchema) obj;
295 return qname.equals(that.qname);
299 public int hashCode() {
300 return qname.hashCode();