BUG-2314 Migrate netconf-connector to NormalizedNode
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / schema / NetconfRemoteSchemaYangSourceProvider.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.controller.sal.connect.netconf.schema;
9
10 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.GET_SCHEMA_QNAME;
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.toId;
13
14 import com.google.common.base.Function;
15 import com.google.common.base.MoreObjects;
16 import com.google.common.base.Optional;
17 import com.google.common.base.Preconditions;
18 import com.google.common.util.concurrent.CheckedFuture;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import org.apache.commons.io.IOUtils;
24 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
25 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
26 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
27 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
28 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.Node;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
38 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
39 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
41 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
42 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
43 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSourceProvider<YangTextSchemaSource> {
48
49     private static final Logger logger = LoggerFactory.getLogger(NetconfRemoteSchemaYangSourceProvider.class);
50
51     private static final ExceptionMapper<SchemaSourceException> MAPPER = new ExceptionMapper<SchemaSourceException>(
52             "schemaDownload", SchemaSourceException.class) {
53         @Override
54         protected SchemaSourceException newWithCause(final String s, final Throwable throwable) {
55             return new SchemaSourceException(s, throwable);
56         }
57     };
58
59     private final DOMRpcService rpc;
60     private final RemoteDeviceId id;
61
62     public NetconfRemoteSchemaYangSourceProvider(final RemoteDeviceId id, final DOMRpcService rpc) {
63         this.id = id;
64         this.rpc = Preconditions.checkNotNull(rpc);
65     }
66
67     public static ContainerNode createGetSchemaRequest(final String moduleName, final Optional<String> revision) {
68         final QName identifierQName = QName.cachedReference(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "identifier"));
69         final YangInstanceIdentifier.NodeIdentifier identifierId = new YangInstanceIdentifier.NodeIdentifier(identifierQName);
70         final LeafNode<String> identifier = Builders.<String>leafBuilder().withNodeIdentifier(identifierId).withValue(moduleName).build();
71
72         final QName formatQName = QName.cachedReference(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "format"));
73         final YangInstanceIdentifier.NodeIdentifier formatId = new YangInstanceIdentifier.NodeIdentifier(formatQName);
74         final LeafNode<String> format = Builders.<String>leafBuilder().withNodeIdentifier(formatId).withValue("yang").build();
75
76         final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> builder = Builders.containerBuilder();
77
78         builder.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.GET_SCHEMA_QNAME))
79         .withChild(identifier)
80         .withChild(format);
81
82         if(revision.isPresent()) {
83             final QName revisionQName = QName.cachedReference(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "version"));
84             final YangInstanceIdentifier.NodeIdentifier revisionId = new YangInstanceIdentifier.NodeIdentifier(revisionQName);
85             final LeafNode<String> revisionNode = Builders.<String>leafBuilder().withNodeIdentifier(revisionId).withValue(revision.get()).build();
86
87             builder.withChild(revisionNode);
88         }
89
90         return builder.build();
91     }
92
93     private static Optional<String> getSchemaFromRpc(final RemoteDeviceId id, final NormalizedNode<?, ?> result) {
94         if (result == null) {
95             return Optional.absent();
96         }
97
98         final QName schemaWrapperNode = QName.cachedReference(QName.create(GET_SCHEMA_QNAME, NETCONF_DATA_QNAME.getLocalName()));
99         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = ((ContainerNode) result).getChild(toId(schemaWrapperNode));
100
101         Preconditions.checkState(child.isPresent() && child.get() instanceof AnyXmlNode,
102                 "%s Unexpected response to get-schema, expected response with one child %s, but was %s", id,
103                 schemaWrapperNode, result);
104
105         final Node<?> wrappedNode = (Node<?>) child.get().getValue();
106         final Object potential = wrappedNode.getValue();
107
108         return potential instanceof String ? Optional.of((String) potential) : Optional.<String> absent();
109     }
110
111     @Override
112     public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
113         final String moduleName = sourceIdentifier.getName();
114
115         // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request
116         final String formattedRevision = sourceIdentifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) ? null : sourceIdentifier.getRevision();
117         final Optional<String> revision = Optional.fromNullable(formattedRevision);
118         final NormalizedNode<?, ?> getSchemaRequest = createGetSchemaRequest(moduleName, revision);
119
120         logger.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision);
121
122         final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform(
123                 rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),
124                 new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));
125
126         final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed, MAPPER);
127
128         // / FIXME remove this get, it is only present to wait until source is retrieved
129         // (goal is to limit concurrent schema download, since NetconfDevice listener does not handle concurrent messages properly)
130         // TODO retest this
131         try {
132             logger.trace("{}: Blocking for {}", id, sourceIdentifier);
133             checked.checkedGet();
134         } catch (final SchemaSourceException e) {
135             return Futures.immediateFailedCheckedFuture(e);
136         }
137
138         return checked;
139     }
140
141     /**
142      * Transform composite node to string schema representation and then to ASTSchemaSource
143      */
144     private static final class ResultToYangSourceTransformer implements
145             Function<DOMRpcResult, YangTextSchemaSource> {
146
147         private final RemoteDeviceId id;
148         private final SourceIdentifier sourceIdentifier;
149         private final String moduleName;
150         private final Optional<String> revision;
151
152         public ResultToYangSourceTransformer(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
153                 final String moduleName, final Optional<String> revision) {
154             this.id = id;
155             this.sourceIdentifier = sourceIdentifier;
156             this.moduleName = moduleName;
157             this.revision = revision;
158         }
159
160         @Override
161         public YangTextSchemaSource apply(final DOMRpcResult input) {
162
163             if (input.getErrors().isEmpty()) {
164
165                 final Optional<String> schemaString = getSchemaFromRpc(id, input.getResult());
166
167                 Preconditions.checkState(schemaString.isPresent(),
168                         "%s: Unexpected response to get-schema, schema not present in message for: %s", id, sourceIdentifier);
169
170                 logger.debug("{}: YANG Schema successfully retrieved for {}:{}", id, moduleName, revision);
171                 return new NetconfYangTextSchemaSource(id, sourceIdentifier, schemaString);
172             }
173
174             logger.warn("{}: YANG schema was not successfully retrieved for {}. Errors: {}", id, sourceIdentifier,
175                     input.getErrors());
176
177             throw new IllegalStateException(String.format(
178                     "%s: YANG schema was not successfully retrieved for %s. Errors: %s", id, sourceIdentifier,
179                     input.getErrors()));
180         }
181
182     }
183
184     private static class NetconfYangTextSchemaSource extends YangTextSchemaSource {
185         private final RemoteDeviceId id;
186         private final Optional<String> schemaString;
187
188         public NetconfYangTextSchemaSource(final RemoteDeviceId id, final SourceIdentifier sId, final Optional<String> schemaString) {
189             super(sId);
190             this.id = id;
191             this.schemaString = schemaString;
192         }
193
194         @Override
195         protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
196             return toStringHelper.add("device", id);
197         }
198
199         @Override
200         public InputStream openStream() throws IOException {
201             return IOUtils.toInputStream(schemaString.get());
202         }
203     }
204 }