Merge "Startup archetype: remove 'Impl' from config subsystem Module name."
[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 com.google.common.base.Function;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import org.apache.commons.io.IOUtils;
20 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
21 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
22 import org.opendaylight.controller.sal.core.api.RpcImplementation;
23 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.common.RpcResult;
26 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
27 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
28 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
29 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
30 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
31 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
32 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
33 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSourceProvider<YangTextSchemaSource> {
38
39     public static final QName GET_SCHEMA_QNAME = QName.create(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING,"get-schema");
40     public static final QName GET_DATA_QNAME = QName.create(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING, "data");
41
42     private static final Logger logger = LoggerFactory.getLogger(NetconfRemoteSchemaYangSourceProvider.class);
43
44     private static final ExceptionMapper<SchemaSourceException> MAPPER = new ExceptionMapper<SchemaSourceException>(
45             "schemaDownload", SchemaSourceException.class) {
46         @Override
47         protected SchemaSourceException newWithCause(final String s, final Throwable throwable) {
48             return new SchemaSourceException(s, throwable);
49         }
50     };
51
52     private final RpcImplementation rpc;
53     private final RemoteDeviceId id;
54
55     public NetconfRemoteSchemaYangSourceProvider(final RemoteDeviceId id, final RpcImplementation rpc) {
56         this.id = id;
57         this.rpc = Preconditions.checkNotNull(rpc);
58     }
59
60     private ImmutableCompositeNode createGetSchemaRequest(final String moduleName, final Optional<String> revision) {
61         final CompositeNodeBuilder<ImmutableCompositeNode> request = ImmutableCompositeNode.builder();
62         request.setQName(GET_SCHEMA_QNAME).addLeaf("identifier", moduleName);
63         if (revision.isPresent()) {
64             request.addLeaf("version", revision.get());
65         }
66         request.addLeaf("format", "yang");
67         return request.toInstance();
68     }
69
70     private static Optional<String> getSchemaFromRpc(final RemoteDeviceId id, final CompositeNode result) {
71         if (result == null) {
72             return Optional.absent();
73         }
74         final SimpleNode<?> simpleNode = result.getFirstSimpleByName(GET_DATA_QNAME.withoutRevision());
75
76         Preconditions.checkNotNull(simpleNode,
77                 "%s Unexpected response to get-schema, expected response with one child %s, but was %s", id,
78                 GET_DATA_QNAME.withoutRevision(), result);
79
80         final Object potential = simpleNode.getValue();
81         return potential instanceof String ? Optional.of((String) potential) : Optional.<String> absent();
82     }
83
84     @Override
85     public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
86         final String moduleName = sourceIdentifier.getName();
87
88         // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request
89         final String formattedRevision = sourceIdentifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) ? null : sourceIdentifier.getRevision();
90         final Optional<String> revision = Optional.fromNullable(formattedRevision);
91         final ImmutableCompositeNode getSchemaRequest = createGetSchemaRequest(moduleName, revision);
92
93         logger.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision);
94
95         final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform(
96                 rpc.invokeRpc(GET_SCHEMA_QNAME, getSchemaRequest),
97                 new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));
98
99         final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed, MAPPER);
100
101         // / FIXME remove this get, it is only present to wait until source is retrieved
102         // (goal is to limit concurrent schema download, since NetconfDevice listener does not handle concurrent messages properly)
103         try {
104             logger.trace("{}: Blocking for {}", id, sourceIdentifier);
105             checked.checkedGet();
106         } catch (final SchemaSourceException e) {
107             return Futures.immediateFailedCheckedFuture(e);
108         }
109
110         return checked;
111     }
112
113     /**
114      * Transform composite node to string schema representation and then to ASTSchemaSource
115      */
116     private static final class ResultToYangSourceTransformer implements
117             Function<RpcResult<CompositeNode>, YangTextSchemaSource> {
118
119         private final RemoteDeviceId id;
120         private final SourceIdentifier sourceIdentifier;
121         private final String moduleName;
122         private final Optional<String> revision;
123
124         public ResultToYangSourceTransformer(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
125                 final String moduleName, final Optional<String> revision) {
126             this.id = id;
127             this.sourceIdentifier = sourceIdentifier;
128             this.moduleName = moduleName;
129             this.revision = revision;
130         }
131
132         @Override
133         public YangTextSchemaSource apply(final RpcResult<CompositeNode> input) {
134
135             if (input.isSuccessful()) {
136
137                 final Optional<String> schemaString = getSchemaFromRpc(id, input.getResult());
138
139                 Preconditions.checkState(schemaString.isPresent(),
140                         "%s: Unexpected response to get-schema, schema not present in message for: %s", id, sourceIdentifier);
141
142                 logger.debug("{}: YANG Schema successfully retrieved for {}:{}", id, moduleName, revision);
143
144                 return new NetconfYangTextSchemaSource(id, sourceIdentifier, schemaString);
145             }
146
147             logger.warn("{}: YANG schema was not successfully retrieved for {}. Errors: {}", id, sourceIdentifier,
148                     input.getErrors());
149
150             throw new IllegalStateException(String.format(
151                     "%s: YANG schema was not successfully retrieved for %s. Errors: %s", id, sourceIdentifier,
152                     input.getErrors()));
153
154         }
155
156     }
157
158     private static class NetconfYangTextSchemaSource extends YangTextSchemaSource {
159         private final RemoteDeviceId id;
160         private final Optional<String> schemaString;
161
162         public NetconfYangTextSchemaSource(final RemoteDeviceId id, final SourceIdentifier sId, final Optional<String> schemaString) {
163             super(sId);
164             this.id = id;
165             this.schemaString = schemaString;
166         }
167
168         @Override
169         protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
170             return toStringHelper.add("device", id);
171         }
172
173         @Override
174         public InputStream openStream() throws IOException {
175             return IOUtils.toInputStream(schemaString.get());
176         }
177     }
178 }