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