bec05994ef3e8beda133821dcfa7a6b2b22e133e
[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 package org.opendaylight.netconf.sal.connect.netconf;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_NODEID;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_PATH;
15 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
16
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Strings;
19 import com.google.common.collect.ImmutableSet;
20 import java.net.URI;
21 import java.util.HashSet;
22 import java.util.Optional;
23 import java.util.Set;
24 import java.util.concurrent.ExecutionException;
25 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
26 import org.opendaylight.mdsal.dom.api.DOMRpcService;
27 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
28 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
29 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
30 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
31 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
40 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
52  */
53 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
54
55     private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
56
57     public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(ImmutableSet.of());
58
59     private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
60             YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
61
62     private static final ContainerNode GET_SCHEMAS_RPC;
63
64     static {
65         final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
66                 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext());
67         GET_SCHEMAS_RPC
68                 = Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID).withChild(filter).build();
69     }
70
71     private final Set<RemoteYangSchema> availableYangSchemas;
72
73     public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
74         this.availableYangSchemas = availableYangSchemas;
75     }
76
77     public Set<RemoteYangSchema> getAvailableYangSchemas() {
78         return availableYangSchemas;
79     }
80
81     @Override
82     public Set<QName> getAvailableYangSchemasQNames() {
83         return getAvailableYangSchemas().stream().map(RemoteYangSchema::getQName)
84                 .collect(ImmutableSet.toImmutableSet());
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(NETCONF_GET_PATH, 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<?, ?>> optSchemasNode = findSchemasNode(schemasNodeResult.getResult());
118         if (!optSchemasNode.isPresent()) {
119             LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
120             return EMPTY;
121         }
122
123         final NormalizedNode<?, ?> schemasNode = optSchemasNode.get();
124         checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
125             schemasNode);
126         return create(id, (ContainerNode) schemasNode);
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 = new HashSet<>();
135
136         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
137                 schemasNode.getChild(toId(Schema.QNAME));
138         checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
139             schemasNode);
140         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 = ((DataContainerNode<?>) result)
160                 .getChild(NETCONF_DATA_NODEID);
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             checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
188
189             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
190
191             final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
192
193             if (!formatAsString.equals(Yang.QNAME.toString())) {
194                 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
195                 return Optional.empty();
196             }
197
198             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
199             final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
200             if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
201                 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
202                 return Optional.empty();
203             }
204
205             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
206             final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
207             if (!namespaceValue.isPresent()) {
208                 LOG.warn("{}: Ignoring schema due to missing namespace", id);
209                 return Optional.empty();
210             }
211             final String namespaceAsString = namespaceValue.get();
212
213             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
214             // Revision does not have to be filled
215             final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
216
217             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
218             final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).get();
219
220             final QName moduleQName = revisionAsString.isPresent()
221                     ? QName.create(namespaceAsString, revisionAsString.get(), moduleNameAsString)
222                     : QName.create(URI.create(namespaceAsString), moduleNameAsString);
223
224             return Optional.of(new RemoteYangSchema(moduleQName));
225         }
226
227         /**
228          * Extracts all values of a leaf-list node as a set of strings.
229          */
230         private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
231                                                          final QName childNodeQName) {
232             final Set<String> extractedValues = new HashSet<>();
233             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
234                     schemaNode.getChild(toId(childNodeQName));
235             checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
236             checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
237             for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
238                 extractedValues.add(getValueOfSimpleNode(childNode).get());
239             }
240             return extractedValues;
241         }
242
243         private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
244                                                                 final QName childNode) {
245             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
246                     schemaNode.getChild(toId(childNode));
247             if (node.isPresent()) {
248                 return getValueOfSimpleNode(node.get());
249             }
250             LOG.debug("Child node {} not present", childNode);
251             return Optional.empty();
252         }
253
254         private static Optional<String> getValueOfSimpleNode(
255                 final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
256             final String valueStr = node.getValue().toString();
257             return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
258         }
259
260         @Override
261         public boolean equals(final Object obj) {
262             if (this == obj) {
263                 return true;
264             }
265             if (obj == null || getClass() != obj.getClass()) {
266                 return false;
267             }
268
269             final RemoteYangSchema that = (RemoteYangSchema) obj;
270
271             return qname.equals(that.qname);
272         }
273
274         @Override
275         public int hashCode() {
276             return qname.hashCode();
277         }
278     }
279 }