Merge "BUG-997 Use shared schema context factory in netconf-connector"
[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(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 CompositeNode schemasNode) {
126         final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
127
128         for (final CompositeNode schemaNode : schemasNode.getCompositesByName(Schema.QNAME.withoutRevision())) {
129             availableYangSchemas.add(RemoteYangSchema.createFromCompositeNode(schemaNode));
130         }
131
132         return new NetconfStateSchemas(availableYangSchemas);
133     }
134
135     public final static class RemoteYangSchema {
136         private final QName qname;
137
138         private RemoteYangSchema(final QName qname) {
139             this.qname = qname;
140         }
141
142         public QName getQName() {
143             return qname;
144         }
145
146         static RemoteYangSchema createFromCompositeNode(final CompositeNode schemaNode) {
147             Preconditions.checkArgument(schemaNode.getKey().equals(Schema.QNAME.withoutRevision()), "Wrong QName %s", schemaNode.getKey());
148
149             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT.withoutRevision();
150
151             final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
152             Preconditions.checkArgument(formatAsString.equals(Yang.QNAME.getLocalName()),
153                     "Expecting format to be only %s, not %s", Yang.QNAME.getLocalName(), formatAsString);
154
155             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION.withoutRevision();
156             final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
157             Preconditions.checkArgument(locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()),
158                     "Expecting location to be %s, not %s", Schema.Location.Enumeration.NETCONF.toString(), locationsAsString);
159
160             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE.withoutRevision();
161             final String namespaceAsString = getSingleChildNodeValue(schemaNode, childNode).get();
162
163             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION.withoutRevision();
164             // Revision does not have to be filled
165             final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
166
167             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER.withoutRevision();
168             final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
169
170             final QName moduleQName = revisionAsString.isPresent()
171                     ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
172                     : QName.create(URI.create(namespaceAsString), null, moduleNameAsString).withoutRevision();
173
174             return new RemoteYangSchema(moduleQName);
175         }
176
177         private static Set<String> getAllChildNodeValues(final CompositeNode schemaNode, final QName childNodeQName) {
178             final Set<String> extractedValues = Sets.newHashSet();
179             for (final SimpleNode<?> childNode : schemaNode.getSimpleNodesByName(childNodeQName)) {
180                 extractedValues.add(getValueOfSimpleNode(childNodeQName, childNode).get());
181             }
182             return extractedValues;
183         }
184
185         private static Optional<String> getSingleChildNodeValue(final CompositeNode schemaNode, final QName childNode) {
186             final SimpleNode<?> node = schemaNode.getFirstSimpleByName(childNode);
187             return getValueOfSimpleNode(childNode, node);
188         }
189
190         private static Optional<String> getValueOfSimpleNode(final QName childNode, final SimpleNode<?> node) {
191             Preconditions.checkNotNull(node, "Child node %s not present", childNode);
192             final Object value = node.getValue();
193             return value == null ? Optional.<String>absent() : Optional.of(value.toString().trim());
194         }
195
196         @Override
197         public boolean equals(final Object o) {
198             if (this == o) return true;
199             if (o == null || getClass() != o.getClass()) return false;
200
201             final RemoteYangSchema that = (RemoteYangSchema) o;
202
203             if (!qname.equals(that.qname)) return false;
204
205             return true;
206         }
207
208         @Override
209         public int hashCode() {
210             return qname.hashCode();
211         }
212     }
213 }