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