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