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