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