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