Add netconf.api.CapabilityURN
[netconf.git] / plugins / netconf-client-mdsal / src / main / java / org / opendaylight / netconf / client / mdsal / 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.client.mdsal;
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.client.mdsal.impl.NetconfMessageTransformUtil.IETF_NETCONF_MONITORING;
14 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_DATA_NODEID;
15 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_FILTER_NODEID;
16 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_FILTER_QNAME;
17 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
18 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_GET_QNAME;
19 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_TYPE_QNAME;
20 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.toId;
21
22 import com.google.common.annotations.VisibleForTesting;
23 import com.google.common.base.Strings;
24 import com.google.common.collect.ImmutableSet;
25 import java.io.IOException;
26 import java.net.URISyntaxException;
27 import java.util.HashSet;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.concurrent.ExecutionException;
31 import javax.xml.stream.XMLStreamException;
32 import javax.xml.transform.dom.DOMSource;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
35 import org.opendaylight.mdsal.dom.api.DOMRpcService;
36 import org.opendaylight.netconf.api.xml.XmlUtil;
37 import org.opendaylight.netconf.client.mdsal.api.NetconfDeviceSchemas;
38 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
39 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
40 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil;
41 import org.opendaylight.netconf.common.mdsal.NormalizedDataUtil;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.common.XMLNamespace;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
52 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
59 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.w3c.dom.Document;
63 import org.w3c.dom.Element;
64 import org.w3c.dom.Node;
65 import org.w3c.dom.traversal.DocumentTraversal;
66 import org.w3c.dom.traversal.NodeFilter;
67 import org.w3c.dom.traversal.TreeWalker;
68 import org.xml.sax.SAXException;
69
70 /**
71  * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
72  */
73 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
74     public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(ImmutableSet.of());
75
76     private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
77     private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER = YangInstanceIdentifier.builder()
78         .node(NetconfState.QNAME).node(Schemas.QNAME).build();
79     private static final String MONITORING_NAMESPACE = IETF_NETCONF_MONITORING.getNamespace().toString();
80     private static final @NonNull ContainerNode GET_SCHEMAS_RPC;
81
82     static {
83         final Document document = XmlUtil.newDocument();
84
85         final Element filterElem = XmlUtil.createElement(document, NETCONF_FILTER_QNAME.getLocalName(),
86             Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
87         filterElem.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
88             "subtree");
89
90         final Element stateElem = XmlUtil.createElement(document, NetconfState.QNAME.getLocalName(),
91             Optional.of(NetconfState.QNAME.getNamespace().toString()));
92         stateElem.appendChild(XmlUtil.createElement(document, Schemas.QNAME.getLocalName(),
93             Optional.of(Schemas.QNAME.getNamespace().toString())));
94         filterElem.appendChild(stateElem);
95
96         GET_SCHEMAS_RPC = Builders.containerBuilder()
97                 .withNodeIdentifier(NETCONF_GET_NODEID)
98                 .withChild(Builders.anyXmlBuilder()
99                     .withNodeIdentifier(NETCONF_FILTER_NODEID)
100                     .withValue(new DOMSource(filterElem))
101                     .build())
102                 .build();
103     }
104
105     private final Set<RemoteYangSchema> availableYangSchemas;
106
107     public NetconfStateSchemas(final Set<RemoteYangSchema> availableYangSchemas) {
108         this.availableYangSchemas = availableYangSchemas;
109     }
110
111     public Set<RemoteYangSchema> getAvailableYangSchemas() {
112         return availableYangSchemas;
113     }
114
115     @Override
116     public Set<QName> getAvailableYangSchemasQNames() {
117         return availableYangSchemas.stream()
118             .map(RemoteYangSchema::getQName)
119             .collect(ImmutableSet.toImmutableSet());
120     }
121
122     /**
123      * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
124      */
125     static NetconfStateSchemas create(final DOMRpcService deviceRpc,
126             final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
127             final EffectiveModelContext schemaContext) {
128         if (!remoteSessionCapabilities.isMonitoringSupported()) {
129             // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
130             // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
131             LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
132             return EMPTY;
133         }
134
135         final DOMRpcResult schemasNodeResult;
136         try {
137             schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_QNAME, GET_SCHEMAS_RPC).get();
138         } catch (final InterruptedException e) {
139             Thread.currentThread().interrupt();
140             throw new IllegalStateException(id
141                     + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
142         } catch (final ExecutionException e) {
143             LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
144             return EMPTY;
145         }
146
147         if (!schemasNodeResult.errors().isEmpty()) {
148             LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
149                     id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.errors());
150             return EMPTY;
151         }
152
153         final Optional<? extends NormalizedNode> optSchemasNode = findSchemasNode(schemasNodeResult.value(),
154                 schemaContext);
155         if (optSchemasNode.isEmpty()) {
156             LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
157             return EMPTY;
158         }
159
160         final NormalizedNode schemasNode = optSchemasNode.orElseThrow();
161         checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
162             schemasNode);
163         return create(id, (ContainerNode) schemasNode);
164     }
165
166     /**
167      * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
168      */
169     @VisibleForTesting
170     protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
171         final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
172
173         final DataContainerChild child = schemasNode.childByArg(toId(Schema.QNAME));
174         checkState(child != null, "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
175             schemasNode);
176         checkState(child instanceof MapNode,
177                 "Unexpected structure for container: %s in response: %s. Expecting a list",
178                 Schema.QNAME.withoutRevision(), schemasNode);
179
180         for (final MapEntryNode schemaNode : ((MapNode) child).body()) {
181             final Optional<RemoteYangSchema> fromCompositeNode =
182                     RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
183             fromCompositeNode.ifPresent(availableYangSchemas::add);
184         }
185
186         return new NetconfStateSchemas(availableYangSchemas);
187     }
188
189     private static Optional<? extends NormalizedNode> findSchemasNode(final NormalizedNode result,
190             final EffectiveModelContext schemaContext) {
191         if (result == null) {
192             return Optional.empty();
193         }
194         // FIXME: unchecked cast
195         final var rpcResult = ((ContainerNode) result).childByArg(NETCONF_DATA_NODEID);
196         if (rpcResult == null) {
197             return Optional.empty();
198         }
199
200         verify(rpcResult instanceof DOMSourceAnyxmlNode, "Unexpected result %s", rpcResult);
201
202         // Server may include additional data which we do not understand. Make sure we trim the input before we try
203         // to interpret it.
204         // FIXME: this is something NetconfUtil.transformDOMSourceToNormalizedNode(), and more generally, NormalizedNode
205         //        codecs should handle. We really want to a NormalizedNode tree which can be directly queried for known
206         //        things while completely ignoring XML content (and hence its semantics) of other elements.
207         final var filteredBody = ietfMonitoringCopy(((DOMSourceAnyxmlNode) rpcResult).body());
208
209         final NormalizedNode dataNode;
210         try {
211             dataNode = NormalizedDataUtil.transformDOMSourceToNormalizedNode(schemaContext, filteredBody).getResult();
212         } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
213             LOG.warn("Failed to transform {}", rpcResult, e);
214             return Optional.empty();
215         }
216
217         // FIXME: unchecked cast
218         final var nStateNode = ((DataContainerNode) dataNode).childByArg(toId(NetconfState.QNAME));
219         if (nStateNode == null) {
220             return Optional.empty();
221         }
222
223         // FIXME: unchecked cast
224         return ((DataContainerNode) nStateNode).findChildByArg(toId(Schemas.QNAME));
225     }
226
227     @VisibleForTesting
228     static DOMSource ietfMonitoringCopy(final DOMSource domSource) {
229         final var sourceDoc = XmlUtil.newDocument();
230         sourceDoc.appendChild(sourceDoc.importNode(domSource.getNode(), true));
231
232         final var treeWalker = ((DocumentTraversal) sourceDoc).createTreeWalker(sourceDoc.getDocumentElement(),
233             NodeFilter.SHOW_ALL, node -> {
234                 final var namespace = node.getNamespaceURI();
235                 return namespace == null || MONITORING_NAMESPACE.equals(namespace)
236                     ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
237             }, false);
238
239         final var filteredDoc = XmlUtil.newDocument();
240         filteredDoc.appendChild(filteredDoc.importNode(treeWalker.getRoot(), false));
241         final var filteredElement = filteredDoc.getDocumentElement();
242         copyChildren(treeWalker, filteredDoc, filteredElement);
243
244         return new DOMSource(filteredElement);
245     }
246
247     private static void copyChildren(final TreeWalker walker, final Document targetDoc, final Node targetNode) {
248         if (walker.firstChild() != null) {
249             for (var node = walker.getCurrentNode(); node != null; node = walker.nextSibling()) {
250                 final var importedNode = targetDoc.importNode(node, false);
251                 targetNode.appendChild(importedNode);
252                 copyChildren(walker, targetDoc, importedNode);
253                 walker.setCurrentNode(node);
254             }
255         }
256     }
257
258     public static final class RemoteYangSchema {
259         private final QName qname;
260
261         RemoteYangSchema(final QName qname) {
262             this.qname = qname;
263         }
264
265         public QName getQName() {
266             return qname;
267         }
268
269         static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
270                                                                    final MapEntryNode schemaNode) {
271             final QName schemaNodeId = schemaNode.getIdentifier().getNodeType();
272             checkArgument(schemaNodeId.equals(Schema.QNAME), "Wrong QName %s", schemaNodeId);
273
274             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
275
276             final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).orElseThrow();
277
278             if (!formatAsString.equals(Yang.QNAME.toString())) {
279                 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
280                 return Optional.empty();
281             }
282
283             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
284             final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
285             if (!locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString())) {
286                 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
287                 return Optional.empty();
288             }
289
290             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
291             final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
292             if (namespaceValue.isEmpty()) {
293                 LOG.warn("{}: Ignoring schema due to missing namespace", id);
294                 return Optional.empty();
295             }
296             final String namespaceAsString = namespaceValue.orElseThrow();
297
298             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_VERSION;
299             // Revision does not have to be filled
300             final Optional<String> revisionAsString = getSingleChildNodeValue(schemaNode, childNode);
301
302             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER;
303             final String moduleNameAsString = getSingleChildNodeValue(schemaNode, childNode).orElseThrow();
304
305             final QName moduleQName = revisionAsString.isPresent()
306                     ? QName.create(namespaceAsString, revisionAsString.orElseThrow(), moduleNameAsString)
307                     : QName.create(XMLNamespace.of(namespaceAsString), moduleNameAsString);
308
309             return Optional.of(new RemoteYangSchema(moduleQName));
310         }
311
312         /**
313          * Extracts all values of a leaf-list node as a set of strings.
314          */
315         private static Set<String> getAllChildNodeValues(final DataContainerNode schemaNode,
316                                                          final QName childNodeQName) {
317             final Set<String> extractedValues = new HashSet<>();
318             final DataContainerChild child = schemaNode.childByArg(toId(childNodeQName));
319             checkArgument(child != null, "Child nodes %s not present", childNodeQName);
320             checkArgument(child instanceof LeafSetNode, "Child nodes %s not present", childNodeQName);
321             for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child).body()) {
322                 extractedValues.add(getValueOfSimpleNode(childNode).orElseThrow());
323             }
324             return extractedValues;
325         }
326
327         private static Optional<String> getSingleChildNodeValue(final DataContainerNode schemaNode,
328                                                                 final QName childNode) {
329             final Optional<DataContainerChild> node = schemaNode.findChildByArg(toId(childNode));
330             if (node.isPresent()) {
331                 return getValueOfSimpleNode(node.orElseThrow());
332             }
333             LOG.debug("Child node {} not present", childNode);
334             return Optional.empty();
335         }
336
337         private static Optional<String> getValueOfSimpleNode(final NormalizedNode node) {
338             final String valueStr = node.body().toString();
339             return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
340         }
341
342         @Override
343         public boolean equals(final Object obj) {
344             if (this == obj) {
345                 return true;
346             }
347             if (obj == null || getClass() != obj.getClass()) {
348                 return false;
349             }
350
351             final RemoteYangSchema that = (RemoteYangSchema) obj;
352
353             return qname.equals(that.qname);
354         }
355
356         @Override
357         public int hashCode() {
358             return qname.hashCode();
359         }
360     }
361 }