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