Adjust to yangtools-2.0.0/odlparent-3.0.0 changes
[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.Preconditions;
18 import com.google.common.base.Strings;
19 import com.google.common.collect.Collections2;
20 import com.google.common.collect.Sets;
21 import java.net.URI;
22 import java.util.Collections;
23 import java.util.Optional;
24 import java.util.Set;
25 import java.util.concurrent.ExecutionException;
26 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
27 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
28 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
29 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
30 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
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 implements NetconfDeviceSchemas {
55
56     private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
57
58     public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(Collections.<RemoteYangSchema>emptySet());
59
60     private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
61             YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
62
63     private static final ContainerNode GET_SCHEMAS_RPC;
64
65     static {
66         final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
67                 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext());
68         GET_SCHEMAS_RPC
69                 = Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_GET_QNAME)).withChild(filter).build();
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     @Override
83     public Set<QName> getAvailableYangSchemasQNames() {
84         return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), RemoteYangSchema::getQName));
85     }
86
87     /**
88      * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
89      */
90     static NetconfStateSchemas create(final DOMRpcService deviceRpc,
91                                   final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
92         if (!remoteSessionCapabilities.isMonitoringSupported()) {
93             // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
94             // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
95             LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
96             return EMPTY;
97         }
98
99         final DOMRpcResult schemasNodeResult;
100         try {
101             schemasNodeResult = deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_SCHEMAS_RPC).get();
102         } catch (final InterruptedException e) {
103             Thread.currentThread().interrupt();
104             throw new RuntimeException(id
105                     + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
106         } catch (final ExecutionException e) {
107             LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
108             return EMPTY;
109         }
110
111         if (!schemasNodeResult.getErrors().isEmpty()) {
112             LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
113                     id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
114             return EMPTY;
115         }
116
117         final Optional<? extends NormalizedNode<?, ?>> schemasNode = findSchemasNode(schemasNodeResult.getResult());
118
119         if (schemasNode.isPresent()) {
120             Preconditions.checkState(schemasNode.get() instanceof ContainerNode,
121                     "Expecting container containing schemas, but was %s", schemasNode.get());
122             return create(id, (ContainerNode) schemasNode.get());
123         } else {
124             LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
125             return EMPTY;
126         }
127     }
128
129     /**
130      * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
131      */
132     @VisibleForTesting
133     protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
134         final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
135
136         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
137                 schemasNode.getChild(toId(Schema.QNAME));
138         Preconditions.checkState(child.isPresent(),
139                 "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode);
140         Preconditions.checkState(child.get() instanceof MapNode,
141                 "Unexpected structure for container: %s in response: %s. Expecting a list",
142                 Schema.QNAME.withoutRevision(), schemasNode);
143
144         for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
145             final Optional<RemoteYangSchema> fromCompositeNode =
146                     RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
147             if (fromCompositeNode.isPresent()) {
148                 availableYangSchemas.add(fromCompositeNode.get());
149             }
150         }
151
152         return new NetconfStateSchemas(availableYangSchemas);
153     }
154
155     private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
156         if (result == null) {
157             return Optional.empty();
158         }
159         final Optional<DataContainerChild<?, ?>> dataNode =
160                 ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
161         if (!dataNode.isPresent()) {
162             return Optional.empty();
163         }
164
165         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
166                 ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
167         if (!nStateNode.isPresent()) {
168             return Optional.empty();
169         }
170
171         return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
172     }
173
174     public static final 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,
186                                                                    final MapEntryNode schemaNode) {
187             Preconditions.checkArgument(
188                     schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
189
190             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
191
192             final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
193
194             if (!formatAsString.equals(Yang.QNAME.toString())) {
195                 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
196                 return Optional.empty();
197             }
198
199             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
200             final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
201             if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
202                 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
203                 return Optional.empty();
204             }
205
206             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
207             final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
208             if (!namespaceValue.isPresent()) {
209                 LOG.warn("{}: Ignoring schema due to missing namespace", id);
210                 return Optional.empty();
211             }
212             final String namespaceAsString = namespaceValue.get();
213
214             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
215             // Revision does not have to be filled
216             final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
217
218             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
219             final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
220
221             final QName moduleQName = revisionAsString.isPresent()
222                     ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
223                     : QName.create(URI.create(namespaceAsString), moduleNameAsString);
224
225             return Optional.of(new RemoteYangSchema(moduleQName));
226         }
227
228         /**
229          * Extracts all values of a leaf-list node as a set of strings.
230          */
231         private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
232                                                          final QName childNodeQName) {
233             final Set<String> extractedValues = Sets.newHashSet();
234             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
235                     schemaNode.getChild(toId(childNodeQName));
236             Preconditions.checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
237             Preconditions.checkArgument(child.get() instanceof LeafSetNode<?>,
238                     "Child nodes %s not present", childNodeQName);
239             for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
240                 extractedValues.add(getValueOfSimpleNode(childNode).get());
241             }
242             return extractedValues;
243         }
244
245         private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
246                                                                 final QName childNode) {
247             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
248                     schemaNode.getChild(toId(childNode));
249             if (node.isPresent()) {
250                 return getValueOfSimpleNode(node.get());
251             } else {
252                 LOG.debug("Child node {} not present", childNode);
253                 return Optional.empty();
254             }
255         }
256
257         private static Optional<String> getValueOfSimpleNode(
258                 final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
259             final Object value = node.getValue();
260             return value == null || Strings.isNullOrEmpty(value.toString())
261                     ? Optional.empty() : Optional.of(value.toString().trim());
262         }
263
264         @Override
265         public boolean equals(final Object obj) {
266             if (this == obj) {
267                 return true;
268             }
269             if (obj == null || getClass() != obj.getClass()) {
270                 return false;
271             }
272
273             final RemoteYangSchema that = (RemoteYangSchema) obj;
274
275             return qname.equals(that.qname);
276         }
277
278         @Override
279         public int hashCode() {
280             return qname.hashCode();
281         }
282     }
283 }