a6e42046f925cacae02ea9966b13e32711070eba
[netconf.git] / plugins / netconf-client-mdsal / src / main / java / org / opendaylight / netconf / client / mdsal / impl / MonitoringSchemaSourceProvider.java
1 /*
2  * Copyright (c) 2014 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.client.mdsal.impl;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import java.util.Optional;
17 import javax.xml.transform.dom.DOMSource;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.netconf.client.mdsal.api.NetconfRpcService;
20 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
21 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.GetSchema;
22 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.get.schema.output.Data;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.common.Revision;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
30 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
31 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
32 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
34 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
35 import org.opendaylight.yangtools.yang.model.spi.source.StringYangTextSource;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Element;
39
40 /**
41  * A {@link SchemaSourceProvider} producing {@link YangTextSource}s based on a device's
42  * {@code ietf-netconf-monitoring} interface. The set of available sources is not pre-determined and each request is
43  * dispatched to the device, i.e. this provider reflects real-time updates to available schemas.
44  */
45 final class MonitoringSchemaSourceProvider implements SchemaSourceProvider<YangTextSource> {
46     private static final Logger LOG = LoggerFactory.getLogger(MonitoringSchemaSourceProvider.class);
47     private static final NodeIdentifier FORMAT_PATHARG =
48             NodeIdentifier.create(QName.create(GetSchema.QNAME, "format").intern());
49     private static final NodeIdentifier GET_SCHEMA_PATHARG = NodeIdentifier.create(GetSchema.QNAME);
50     private static final NodeIdentifier IDENTIFIER_PATHARG =
51             NodeIdentifier.create(QName.create(GetSchema.QNAME, "identifier").intern());
52     private static final NodeIdentifier VERSION_PATHARG =
53             NodeIdentifier.create(QName.create(GetSchema.QNAME, "version").intern());
54     private static final LeafNode<?> FORMAT_LEAF = ImmutableNodes.leafNode(FORMAT_PATHARG, Yang.QNAME);
55     private static final NodeIdentifier NETCONF_DATA_PATHARG = NodeIdentifier.create(Data.QNAME);
56
57     private final NetconfRpcService rpc;
58     private final RemoteDeviceId id;
59
60     MonitoringSchemaSourceProvider(final RemoteDeviceId id, final NetconfRpcService rpc) {
61         this.id = requireNonNull(id);
62         this.rpc = requireNonNull(rpc);
63     }
64
65     @Override
66     public ListenableFuture<YangTextSource> getSource(final SourceIdentifier sourceIdentifier) {
67         final String moduleName = sourceIdentifier.name().getLocalName();
68         final Revision revision = sourceIdentifier.revision();
69         final ContainerNode getSchemaRequest = createGetSchemaRequest(moduleName,
70             revision == null ? Optional.empty() : Optional.of(revision.toString()));
71
72         LOG.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision);
73         return Futures.transform(rpc.invokeNetconf(GetSchema.QNAME, getSchemaRequest),
74             result -> {
75                 // Transform composite node to string schema representation and then to ASTSchemaSource.
76                 if (result.errors().isEmpty()) {
77                     final String schemaString = getSchemaFromRpc(id, result.value())
78                         .orElseThrow(() -> new IllegalStateException(
79                             id + ": Unexpected response to get-schema, schema not present in message for: "
80                                 + sourceIdentifier));
81                     LOG.debug("{}: YANG Schema successfully retrieved for {}:{}", id, moduleName, revision);
82                     return new StringYangTextSource(sourceIdentifier, schemaString);
83                 }
84
85                 LOG.warn("{}: YANG schema was not successfully retrieved for {}. Errors: {}", id, sourceIdentifier,
86                     result.errors());
87                 throw new IllegalStateException(String.format(
88                     "%s: YANG schema was not successfully retrieved for %s. Errors: %s", id, sourceIdentifier,
89                     result.errors()));
90             }, MoreExecutors.directExecutor());
91     }
92
93     static @NonNull ContainerNode createGetSchemaRequest(final String moduleName, final Optional<String> revision) {
94         final var builder = ImmutableNodes.newContainerBuilder()
95             .withNodeIdentifier(GET_SCHEMA_PATHARG)
96             .withChild(ImmutableNodes.leafNode(IDENTIFIER_PATHARG, moduleName))
97             .withChild(FORMAT_LEAF);
98         revision.ifPresent(rev -> builder.withChild(ImmutableNodes.leafNode(VERSION_PATHARG, rev)));
99         return builder.build();
100     }
101
102     private static Optional<String> getSchemaFromRpc(final RemoteDeviceId id, final ContainerNode result) {
103         if (result == null) {
104             return Optional.empty();
105         }
106
107         final DataContainerChild child = result.childByArg(NETCONF_DATA_PATHARG);
108         checkState(child instanceof DOMSourceAnyxmlNode,
109                 "%s Unexpected response to get-schema, expected response with one child %s, but was %s", id,
110                 Data.QNAME, result);
111
112         final DOMSource wrappedNode = ((DOMSourceAnyxmlNode) child).body();
113         final Element dataNode = (Element) requireNonNull(wrappedNode.getNode());
114
115         return Optional.of(dataNode.getTextContent().trim());
116     }
117 }