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.stream.XMLStreamException;
29 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
30 import org.opendaylight.mdsal.dom.api.DOMRpcService;
31 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
32 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
33 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
34 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
35 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
36 import org.opendaylight.netconf.util.NetconfUtil;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
46 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.xml.sax.SAXException;
59 * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
61 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
63 private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
65 public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(ImmutableSet.of());
67 private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
68 YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
70 private static final ContainerNode GET_SCHEMAS_RPC;
73 final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
74 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext());
76 = Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID).withChild(filter).build();
79 private final Set<RemoteYangSchema> availableYangSchemas;
81 public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
82 this.availableYangSchemas = availableYangSchemas;
85 public Set<RemoteYangSchema> getAvailableYangSchemas() {
86 return availableYangSchemas;
90 public Set<QName> getAvailableYangSchemasQNames() {
91 return getAvailableYangSchemas().stream().map(RemoteYangSchema::getQName)
92 .collect(ImmutableSet.toImmutableSet());
96 * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
98 static NetconfStateSchemas create(final DOMRpcService deviceRpc,
99 final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
100 final SchemaContext schemaContext) {
101 if (!remoteSessionCapabilities.isMonitoringSupported()) {
102 // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
103 // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
104 LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
108 final DOMRpcResult schemasNodeResult;
110 schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_PATH, GET_SCHEMAS_RPC).get();
111 } catch (final InterruptedException e) {
112 Thread.currentThread().interrupt();
113 throw new RuntimeException(id
114 + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
115 } catch (final ExecutionException e) {
116 LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
120 if (!schemasNodeResult.getErrors().isEmpty()) {
121 LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
122 id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
126 final Optional<? extends NormalizedNode<?, ?>> optSchemasNode = findSchemasNode(schemasNodeResult.getResult(),
128 if (!optSchemasNode.isPresent()) {
129 LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
133 final NormalizedNode<?, ?> schemasNode = optSchemasNode.get();
134 checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
136 return create(id, (ContainerNode) schemasNode);
140 * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
143 protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
144 final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
146 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
147 schemasNode.getChild(toId(Schema.QNAME));
148 checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
150 checkState(child.get() instanceof MapNode,
151 "Unexpected structure for container: %s in response: %s. Expecting a list",
152 Schema.QNAME.withoutRevision(), schemasNode);
154 for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
155 final Optional<RemoteYangSchema> fromCompositeNode =
156 RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
157 if (fromCompositeNode.isPresent()) {
158 availableYangSchemas.add(fromCompositeNode.get());
162 return new NetconfStateSchemas(availableYangSchemas);
165 private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result,
166 final SchemaContext schemaContext) {
167 if (result == null) {
168 return Optional.empty();
170 final Optional<DataContainerChild<?, ?>> rpcResultOpt = ((ContainerNode)result).getChild(NETCONF_DATA_NODEID);
171 if (!rpcResultOpt.isPresent()) {
172 return Optional.empty();
175 final DataContainerChild<?, ?> rpcResult = rpcResultOpt.get();
176 verify(rpcResult instanceof AnyXmlNode, "Unexpected result %s", rpcResult);
177 final NormalizedNode<?, ?> dataNode;
180 dataNode = NetconfUtil.transformDOMSourceToNormalizedNode(schemaContext,
181 ((AnyXmlNode) rpcResult).getValue()).getResult();
182 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
183 LOG.warn("Failed to transform {}", rpcResult, e);
184 return Optional.empty();
187 final Optional<DataContainerChild<?, ?>> nStateNode = ((DataContainerNode<?>) dataNode).getChild(
188 toId(NetconfState.QNAME));
189 if (!nStateNode.isPresent()) {
190 return Optional.empty();
193 return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
196 public static final class RemoteYangSchema {
197 private final QName qname;
199 RemoteYangSchema(final QName qname) {
203 public QName getQName() {
207 static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
208 final MapEntryNode schemaNode) {
209 checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
211 QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
213 final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
215 if (!formatAsString.equals(Yang.QNAME.toString())) {
216 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
217 return Optional.empty();
220 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
221 final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
222 if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
223 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
224 return Optional.empty();
227 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
228 final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
229 if (!namespaceValue.isPresent()) {
230 LOG.warn("{}: Ignoring schema due to missing namespace", id);
231 return Optional.empty();
233 final String namespaceAsString = namespaceValue.get();
235 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
236 // Revision does not have to be filled
237 final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
239 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
240 final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
242 final QName moduleQName = revisionAsString.isPresent()
243 ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
244 : QName.create(URI.create(namespaceAsString), moduleNameAsString);
246 return Optional.of(new RemoteYangSchema(moduleQName));
250 * Extracts all values of a leaf-list node as a set of strings.
252 private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
253 final QName childNodeQName) {
254 final Set<String> extractedValues = new HashSet<>();
255 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
256 schemaNode.getChild(toId(childNodeQName));
257 checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
258 checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
259 for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
260 extractedValues.add(getValueOfSimpleNode(childNode).get());
262 return extractedValues;
265 private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
266 final QName childNode) {
267 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
268 schemaNode.getChild(toId(childNode));
269 if (node.isPresent()) {
270 return getValueOfSimpleNode(node.get());
272 LOG.debug("Child node {} not present", childNode);
273 return Optional.empty();
276 private static Optional<String> getValueOfSimpleNode(
277 final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
278 final String valueStr = node.getValue().toString();
279 return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
283 public boolean equals(final Object obj) {
287 if (obj == null || getClass() != obj.getClass()) {
291 final RemoteYangSchema that = (RemoteYangSchema) obj;
293 return qname.equals(that.qname);
297 public int hashCode() {
298 return qname.hashCode();