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.ContainerNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
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.EffectiveModelContext;
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 = Builders.containerBuilder()
71 .withNodeIdentifier(NETCONF_GET_NODEID)
72 .withChild(NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
73 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext())).build();
75 private final Set<RemoteYangSchema> availableYangSchemas;
77 public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
78 this.availableYangSchemas = availableYangSchemas;
81 public Set<RemoteYangSchema> getAvailableYangSchemas() {
82 return availableYangSchemas;
86 public Set<QName> getAvailableYangSchemasQNames() {
87 return getAvailableYangSchemas().stream().map(RemoteYangSchema::getQName)
88 .collect(ImmutableSet.toImmutableSet());
92 * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
94 static NetconfStateSchemas create(final DOMRpcService deviceRpc,
95 final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
96 final EffectiveModelContext schemaContext) {
97 if (!remoteSessionCapabilities.isMonitoringSupported()) {
98 // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
99 // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
100 LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
104 final DOMRpcResult schemasNodeResult;
106 schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_PATH, GET_SCHEMAS_RPC).get();
107 } catch (final InterruptedException e) {
108 Thread.currentThread().interrupt();
109 throw new RuntimeException(id
110 + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
111 } catch (final ExecutionException e) {
112 LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
116 if (!schemasNodeResult.getErrors().isEmpty()) {
117 LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
118 id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
122 final Optional<? extends NormalizedNode<?, ?>> optSchemasNode = findSchemasNode(schemasNodeResult.getResult(),
124 if (!optSchemasNode.isPresent()) {
125 LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
129 final NormalizedNode<?, ?> schemasNode = optSchemasNode.get();
130 checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
132 return create(id, (ContainerNode) schemasNode);
136 * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
139 protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
140 final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
142 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
143 schemasNode.getChild(toId(Schema.QNAME));
144 checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
146 checkState(child.get() instanceof MapNode,
147 "Unexpected structure for container: %s in response: %s. Expecting a list",
148 Schema.QNAME.withoutRevision(), schemasNode);
150 for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
151 final Optional<RemoteYangSchema> fromCompositeNode =
152 RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
153 if (fromCompositeNode.isPresent()) {
154 availableYangSchemas.add(fromCompositeNode.get());
158 return new NetconfStateSchemas(availableYangSchemas);
161 private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result,
162 final EffectiveModelContext schemaContext) {
163 if (result == null) {
164 return Optional.empty();
166 final Optional<DataContainerChild<?, ?>> rpcResultOpt = ((ContainerNode)result).getChild(NETCONF_DATA_NODEID);
167 if (!rpcResultOpt.isPresent()) {
168 return Optional.empty();
171 final DataContainerChild<?, ?> rpcResult = rpcResultOpt.get();
172 verify(rpcResult instanceof DOMSourceAnyxmlNode, "Unexpected result %s", rpcResult);
173 final NormalizedNode<?, ?> dataNode;
176 dataNode = NetconfUtil.transformDOMSourceToNormalizedNode(schemaContext,
177 ((DOMSourceAnyxmlNode) rpcResult).getValue()).getResult();
178 } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
179 LOG.warn("Failed to transform {}", rpcResult, e);
180 return Optional.empty();
183 final Optional<DataContainerChild<?, ?>> nStateNode = ((DataContainerNode<?>) dataNode).getChild(
184 toId(NetconfState.QNAME));
185 if (!nStateNode.isPresent()) {
186 return Optional.empty();
189 return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
192 public static final class RemoteYangSchema {
193 private final QName qname;
195 RemoteYangSchema(final QName qname) {
199 public QName getQName() {
203 static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
204 final MapEntryNode schemaNode) {
205 checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
207 QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
209 final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
211 if (!formatAsString.equals(Yang.QNAME.toString())) {
212 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
213 return Optional.empty();
216 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
217 final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
218 if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
219 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
220 return Optional.empty();
223 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
224 final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
225 if (!namespaceValue.isPresent()) {
226 LOG.warn("{}: Ignoring schema due to missing namespace", id);
227 return Optional.empty();
229 final String namespaceAsString = namespaceValue.get();
231 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
232 // Revision does not have to be filled
233 final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
235 childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
236 final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
238 final QName moduleQName = revisionAsString.isPresent()
239 ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
240 : QName.create(URI.create(namespaceAsString), moduleNameAsString);
242 return Optional.of(new RemoteYangSchema(moduleQName));
246 * Extracts all values of a leaf-list node as a set of strings.
248 private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
249 final QName childNodeQName) {
250 final Set<String> extractedValues = new HashSet<>();
251 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
252 schemaNode.getChild(toId(childNodeQName));
253 checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
254 checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
255 for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
256 extractedValues.add(getValueOfSimpleNode(childNode).get());
258 return extractedValues;
261 private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
262 final QName childNode) {
263 final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
264 schemaNode.getChild(toId(childNode));
265 if (node.isPresent()) {
266 return getValueOfSimpleNode(node.get());
268 LOG.debug("Child node {} not present", childNode);
269 return Optional.empty();
272 private static Optional<String> getValueOfSimpleNode(
273 final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
274 final String valueStr = node.getValue().toString();
275 return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
279 public boolean equals(final Object obj) {
283 if (obj == null || getClass() != obj.getClass()) {
287 final RemoteYangSchema that = (RemoteYangSchema) obj;
289 return qname.equals(that.qname);
293 public int hashCode() {
294 return qname.hashCode();