645028b13f8e842c4317f7526d05f90f66eab81f
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / NetconfStateSchemas.java
1 package org.opendaylight.controller.sal.connect.netconf;
2
3 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
4 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_QNAME;
5 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
6 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
7
8 import com.google.common.annotations.VisibleForTesting;
9 import com.google.common.base.Function;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.Sets;
15 import java.net.URI;
16 import java.util.Collections;
17 import java.util.Set;
18 import java.util.concurrent.ExecutionException;
19 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
20 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
21 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceRpc;
22 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
23 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
32 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas
44  */
45 public final class NetconfStateSchemas {
46
47     private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
48
49     /**
50      * Factory for NetconfStateSchemas
51      */
52     public interface NetconfStateSchemasResolver {
53         NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id);
54     }
55
56     /**
57      * Default implementation resolving schemas QNames from netconf-state
58      */
59     public static final class NetconfStateSchemasResolverImpl implements NetconfStateSchemasResolver {
60
61         @Override
62         public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
63             return NetconfStateSchemas.create(deviceRpc, remoteSessionCapabilities, id);
64         }
65     }
66
67     public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(Collections.<RemoteYangSchema>emptySet());
68
69     private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
70             YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
71
72     private static final ContainerNode GET_SCHEMAS_RPC;
73     static {
74         final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER, NetconfDevice.INIT_SCHEMA_CTX);
75         GET_SCHEMAS_RPC
76                 = Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_GET_QNAME)).withChild(filter).build();
77     }
78
79     private final Set<RemoteYangSchema> availableYangSchemas;
80
81     public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
82         this.availableYangSchemas = availableYangSchemas;
83     }
84
85     public Set<RemoteYangSchema> getAvailableYangSchemas() {
86         return availableYangSchemas;
87     }
88
89     public Set<QName> getAvailableYangSchemasQNames() {
90         return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), new Function<RemoteYangSchema, QName>() {
91             @Override
92             public QName apply(final RemoteYangSchema input) {
93                 return input.getQName();
94             }
95         }));
96     }
97
98     /**
99      * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas
100      */
101     private static NetconfStateSchemas create(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
102         if(remoteSessionCapabilities.isMonitoringSupported() == false) {
103             LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas");
104             return EMPTY;
105         }
106
107         final DOMRpcResult schemasNodeResult;
108         try {
109             schemasNodeResult = deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_SCHEMAS_RPC).get();
110         } catch (final InterruptedException e) {
111             Thread.currentThread().interrupt();
112             throw new RuntimeException(id + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
113         } catch (final ExecutionException e) {
114             LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
115             return EMPTY;
116         }
117
118         if(schemasNodeResult.getErrors().isEmpty() == false) {
119             LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}", id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
120             return EMPTY;
121         }
122
123         final Optional<? extends NormalizedNode<?, ?>> schemasNode = findSchemasNode(schemasNodeResult.getResult());
124
125         if(schemasNode.isPresent()) {
126             Preconditions.checkState(schemasNode.get() instanceof ContainerNode,
127                     "Expecting container containing schemas, but was %s", schemasNode.get());
128             return create(id, ((ContainerNode) schemasNode.get()));
129         } else {
130             LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
131             return EMPTY;
132         }
133     }
134
135     private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
136         if(result == null) {
137             return Optional.absent();
138         }
139         final Optional<DataContainerChild<?, ?>> dataNode = ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
140         if(dataNode.isPresent() == false) {
141             return Optional.absent();
142         }
143
144         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
145                 ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
146         if(nStateNode.isPresent() == false) {
147             return Optional.absent();
148         }
149
150         return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
151     }
152
153     /**
154      * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas
155      */
156     @VisibleForTesting
157     protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
158         final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
159
160         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = schemasNode.getChild(toId(Schema.QNAME));
161         Preconditions.checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode);
162         Preconditions.checkState(child.get() instanceof MapNode, "Unexpected structure for container: %s in response: %s. Expecting a list", Schema.QNAME.withoutRevision(), schemasNode);
163
164         for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
165             final Optional<RemoteYangSchema> fromCompositeNode = RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
166             if(fromCompositeNode.isPresent()) {
167                 availableYangSchemas.add(fromCompositeNode.get());
168             }
169         }
170
171         return new NetconfStateSchemas(availableYangSchemas);
172     }
173
174     public final static class RemoteYangSchema {
175         private final QName qname;
176
177         RemoteYangSchema(final QName qname) {
178             this.qname = qname;
179         }
180
181         public QName getQName() {
182             return qname;
183         }
184
185         static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id, final MapEntryNode schemaNode) {
186             Preconditions.checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
187
188             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
189
190             String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
191
192             if(formatAsString.equals(Yang.QNAME.toString()) == false) {
193                 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
194                 return Optional.absent();
195             }
196
197             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
198             final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
199             if(locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
200                 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
201                 return Optional.absent();
202             }
203
204             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
205             final String namespaceAsString = getSingleChildNodeValue(schemaNode, childNode).get();
206
207             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
208             // Revision does not have to be filled
209             final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
210
211             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
212             final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
213
214             final QName moduleQName = revisionAsString.isPresent()
215                     ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
216                     : QName.create(URI.create(namespaceAsString), null, moduleNameAsString);
217
218             return Optional.of(new RemoteYangSchema(moduleQName));
219         }
220
221         /**
222          * Extracts all values of a leaf-list node as a set of strings
223          */
224         private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode, final QName childNodeQName) {
225             final Set<String> extractedValues = Sets.newHashSet();
226             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = schemaNode.getChild(toId(childNodeQName));
227             Preconditions.checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
228             Preconditions.checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
229             for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
230                 extractedValues.add(getValueOfSimpleNode(childNode).get());
231             }
232             return extractedValues;
233         }
234
235         private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode, final QName childNode) {
236             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node = schemaNode.getChild(toId(childNode));
237             Preconditions.checkArgument(node.isPresent(), "Child node %s not present", childNode);
238             return getValueOfSimpleNode(node.get());
239         }
240
241         private static Optional<String> getValueOfSimpleNode(final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
242             final Object value = node.getValue();
243             return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.<String>absent() : Optional.of(value.toString().trim());
244         }
245
246         @Override
247         public boolean equals(final Object o) {
248             if (this == o) {
249                 return true;
250             }
251             if (o == null || getClass() != o.getClass()) {
252                 return false;
253             }
254
255             final RemoteYangSchema that = (RemoteYangSchema) o;
256
257             if (!qname.equals(that.qname)) {
258                 return false;
259             }
260
261             return true;
262         }
263
264         @Override
265         public int hashCode() {
266             return qname.hashCode();
267         }
268     }
269 }