BUG-2627: do not duplicate descriptions
[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         if(schemasNode == null) {
119             logger.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
120             return EMPTY;
121         }
122
123         return create(id, schemasNode);
124     }
125
126     /**
127      * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas
128      */
129     @VisibleForTesting
130     protected static NetconfStateSchemas create(final RemoteDeviceId id, final CompositeNode schemasNode) {
131         final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
132
133         for (final CompositeNode schemaNode : schemasNode.getCompositesByName(Schema.QNAME.withoutRevision())) {
134             final Optional<RemoteYangSchema> fromCompositeNode = RemoteYangSchema.createFromCompositeNode(id, schemaNode);
135             if(fromCompositeNode.isPresent()) {
136                 availableYangSchemas.add(fromCompositeNode.get());
137             }
138         }
139
140         return new NetconfStateSchemas(availableYangSchemas);
141     }
142
143     public final static class RemoteYangSchema {
144         private final QName qname;
145
146         private RemoteYangSchema(final QName qname) {
147             this.qname = qname;
148         }
149
150         public QName getQName() {
151             return qname;
152         }
153
154         static Optional<RemoteYangSchema> createFromCompositeNode(final RemoteDeviceId id, final CompositeNode schemaNode) {
155             Preconditions.checkArgument(schemaNode.getKey().equals(Schema.QNAME.withoutRevision()), "Wrong QName %s", schemaNode.getKey());
156
157             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT.withoutRevision();
158
159             String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
160             //This is HotFix for situations where format statement in netconf-monitoring might be passed with prefix.
161             if (formatAsString.contains(":")) {
162                 String[] prefixedString = formatAsString.split(":");
163                 //FIXME: might be good idea to check prefix against model namespace
164                 formatAsString = prefixedString[1];
165             }
166             if(formatAsString.equals(Yang.QNAME.getLocalName()) == false) {
167                 logger.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
168                 return Optional.absent();
169             }
170
171             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION.withoutRevision();
172             final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
173             if(locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
174                 logger.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
175                 return Optional.absent();
176             }
177
178             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE.withoutRevision();
179             final String namespaceAsString = getSingleChildNodeValue(schemaNode, childNode).get();
180
181             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION.withoutRevision();
182             // Revision does not have to be filled
183             final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
184
185             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER.withoutRevision();
186             final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
187
188             final QName moduleQName = revisionAsString.isPresent()
189                     ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
190                     : QName.create(URI.create(namespaceAsString), null, moduleNameAsString).withoutRevision();
191
192             return Optional.of(new RemoteYangSchema(moduleQName));
193         }
194
195         private static Set<String> getAllChildNodeValues(final CompositeNode schemaNode, final QName childNodeQName) {
196             final Set<String> extractedValues = Sets.newHashSet();
197             for (final SimpleNode<?> childNode : schemaNode.getSimpleNodesByName(childNodeQName)) {
198                 extractedValues.add(getValueOfSimpleNode(childNodeQName, childNode).get());
199             }
200             return extractedValues;
201         }
202
203         private static Optional<String> getSingleChildNodeValue(final CompositeNode schemaNode, final QName childNode) {
204             final SimpleNode<?> node = schemaNode.getFirstSimpleByName(childNode);
205             return getValueOfSimpleNode(childNode, node);
206         }
207
208         private static Optional<String> getValueOfSimpleNode(final QName childNode, final SimpleNode<?> node) {
209             Preconditions.checkNotNull(node, "Child node %s not present", childNode);
210             final Object value = node.getValue();
211             return value == null ? Optional.<String>absent() : Optional.of(value.toString().trim());
212         }
213
214         @Override
215         public boolean equals(final Object o) {
216             if (this == o) {
217                 return true;
218             }
219             if (o == null || getClass() != o.getClass()) {
220                 return false;
221             }
222
223             final RemoteYangSchema that = (RemoteYangSchema) o;
224
225             if (!qname.equals(that.qname)) {
226                 return false;
227             }
228
229             return true;
230         }
231
232         @Override
233         public int hashCode() {
234             return qname.hashCode();
235         }
236     }
237 }