Merge "Converted Inventory Manager to use Transaction Chaining"
[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 com.google.common.annotations.VisibleForTesting;
4 import com.google.common.base.Function;
5 import com.google.common.base.Optional;
6 import com.google.common.base.Preconditions;
7 import com.google.common.collect.Collections2;
8 import com.google.common.collect.Lists;
9 import com.google.common.collect.Sets;
10 import java.net.URI;
11 import java.util.Collections;
12 import java.util.Set;
13 import java.util.concurrent.ExecutionException;
14 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
15 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceRpc;
16 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
17 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
18 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
19 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
20 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
21 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.common.RpcResult;
24 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
25 import org.opendaylight.yangtools.yang.data.api.Node;
26 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas
34  */
35 public final class NetconfStateSchemas {
36
37     private static final Logger logger = LoggerFactory.getLogger(NetconfStateSchemas.class);
38
39     /**
40      * Factory for NetconfStateSchemas
41      */
42     public interface NetconfStateSchemasResolver {
43         NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionCapabilities remoteSessionCapabilities, final RemoteDeviceId id);
44     }
45
46     /**
47      * Default implementation resolving schemas QNames from netconf-state
48      */
49     public static final class NetconfStateSchemasResolverImpl implements NetconfStateSchemasResolver {
50
51         @Override
52         public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionCapabilities remoteSessionCapabilities, final RemoteDeviceId id) {
53             return NetconfStateSchemas.create(deviceRpc, remoteSessionCapabilities, id);
54         }
55     }
56
57     public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(Collections.<RemoteYangSchema>emptySet());
58
59     private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
60             YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
61     private static final YangInstanceIdentifier DATA_STATE_SCHEMAS_IDENTIFIER =
62             YangInstanceIdentifier.builder().node(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)
63                     .node(NetconfState.QNAME).node(Schemas.QNAME).build();
64
65     private static final CompositeNode GET_SCHEMAS_RPC;
66     static {
67         final Node<?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER);
68         GET_SCHEMAS_RPC
69                 = NodeFactory.createImmutableCompositeNode(NetconfMessageTransformUtil.NETCONF_GET_QNAME, null, Lists.<Node<?>>newArrayList(filter));
70     }
71
72     private final Set<RemoteYangSchema> availableYangSchemas;
73
74     public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
75         this.availableYangSchemas = availableYangSchemas;
76     }
77
78     public Set<RemoteYangSchema> getAvailableYangSchemas() {
79         return availableYangSchemas;
80     }
81
82     public Set<QName> getAvailableYangSchemasQNames() {
83         return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), new Function<RemoteYangSchema, QName>() {
84             @Override
85             public QName apply(final RemoteYangSchema input) {
86                 return input.getQName();
87             }
88         }));
89     }
90
91     /**
92      * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas
93      */
94     private static NetconfStateSchemas create(final NetconfDeviceRpc deviceRpc, final NetconfSessionCapabilities remoteSessionCapabilities, final RemoteDeviceId id) {
95         if(remoteSessionCapabilities.isMonitoringSupported() == false) {
96             logger.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas");
97             return EMPTY;
98         }
99
100         final RpcResult<CompositeNode> schemasNodeResult;
101         try {
102             schemasNodeResult = deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME, GET_SCHEMAS_RPC).get();
103         } catch (final InterruptedException e) {
104             Thread.currentThread().interrupt();
105             throw new RuntimeException(id + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
106         } catch (final ExecutionException e) {
107             logger.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
108             return EMPTY;
109         }
110
111         if(schemasNodeResult.isSuccessful() == false) {
112             logger.warn("{}: Unable to detect available schemas, get to {} failed, {}", id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
113             return EMPTY;
114         }
115
116         final CompositeNode schemasNode =
117                 (CompositeNode) NetconfMessageTransformUtil.findNode(schemasNodeResult.getResult(), DATA_STATE_SCHEMAS_IDENTIFIER);
118         return create(id, schemasNode);
119     }
120
121     /**
122      * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas
123      */
124     @VisibleForTesting
125     protected static NetconfStateSchemas create(final RemoteDeviceId id, final CompositeNode schemasNode) {
126         final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
127
128         for (final CompositeNode schemaNode : schemasNode.getCompositesByName(Schema.QNAME.withoutRevision())) {
129             final Optional<RemoteYangSchema> fromCompositeNode = RemoteYangSchema.createFromCompositeNode(id, schemaNode);
130             if(fromCompositeNode.isPresent()) {
131                 availableYangSchemas.add(fromCompositeNode.get());
132             }
133         }
134
135         return new NetconfStateSchemas(availableYangSchemas);
136     }
137
138     public final static class RemoteYangSchema {
139         private final QName qname;
140
141         private RemoteYangSchema(final QName qname) {
142             this.qname = qname;
143         }
144
145         public QName getQName() {
146             return qname;
147         }
148
149         static Optional<RemoteYangSchema> createFromCompositeNode(final RemoteDeviceId id, final CompositeNode schemaNode) {
150             Preconditions.checkArgument(schemaNode.getKey().equals(Schema.QNAME.withoutRevision()), "Wrong QName %s", schemaNode.getKey());
151
152             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT.withoutRevision();
153
154             final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
155             if(formatAsString.equals(Yang.QNAME.getLocalName()) == false) {
156                 logger.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
157                 return Optional.absent();
158             }
159
160             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION.withoutRevision();
161             final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
162             if(locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
163                 logger.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
164                 return Optional.absent();
165             }
166
167             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE.withoutRevision();
168             final String namespaceAsString = getSingleChildNodeValue(schemaNode, childNode).get();
169
170             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION.withoutRevision();
171             // Revision does not have to be filled
172             final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
173
174             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER.withoutRevision();
175             final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
176
177             final QName moduleQName = revisionAsString.isPresent()
178                     ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
179                     : QName.create(URI.create(namespaceAsString), null, moduleNameAsString).withoutRevision();
180
181             return Optional.of(new RemoteYangSchema(moduleQName));
182         }
183
184         private static Set<String> getAllChildNodeValues(final CompositeNode schemaNode, final QName childNodeQName) {
185             final Set<String> extractedValues = Sets.newHashSet();
186             for (final SimpleNode<?> childNode : schemaNode.getSimpleNodesByName(childNodeQName)) {
187                 extractedValues.add(getValueOfSimpleNode(childNodeQName, childNode).get());
188             }
189             return extractedValues;
190         }
191
192         private static Optional<String> getSingleChildNodeValue(final CompositeNode schemaNode, final QName childNode) {
193             final SimpleNode<?> node = schemaNode.getFirstSimpleByName(childNode);
194             return getValueOfSimpleNode(childNode, node);
195         }
196
197         private static Optional<String> getValueOfSimpleNode(final QName childNode, final SimpleNode<?> node) {
198             Preconditions.checkNotNull(node, "Child node %s not present", childNode);
199             final Object value = node.getValue();
200             return value == null ? Optional.<String>absent() : Optional.of(value.toString().trim());
201         }
202
203         @Override
204         public boolean equals(final Object o) {
205             if (this == o) return true;
206             if (o == null || getClass() != o.getClass()) return false;
207
208             final RemoteYangSchema that = (RemoteYangSchema) o;
209
210             if (!qname.equals(that.qname)) return false;
211
212             return true;
213         }
214
215         @Override
216         public int hashCode() {
217             return qname.hashCode();
218         }
219     }
220 }