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