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