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