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