Convert yanglib to OSGi DS
[netconf.git] / netconf / yanglib / src / main / java / org / opendaylight / yanglib / impl / YangLibProvider.java
1 /*
2  * Copyright (c) 2016 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.yanglib.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Predicate;
15 import com.google.common.collect.Iterables;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.io.File;
19 import java.io.IOException;
20 import java.util.HashMap;
21 import java.util.Optional;
22 import java.util.concurrent.ExecutionException;
23 import javax.annotation.PreDestroy;
24 import javax.inject.Inject;
25 import javax.inject.Singleton;
26 import javax.ws.rs.NotFoundException;
27 import javax.ws.rs.WebApplicationException;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.mdsal.binding.api.DataBroker;
30 import org.opendaylight.mdsal.binding.api.WriteTransaction;
31 import org.opendaylight.mdsal.common.api.CommitInfo;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.LegacyRevisionUtils;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesState;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesStateBuilder;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.Module;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.ModuleBuilder;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.ModuleKey;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier;
41 import org.opendaylight.yanglib.api.YangLibService;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
43 import org.opendaylight.yangtools.yang.common.Uint32;
44 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
45 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
46 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
47 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
48 import org.opendaylight.yangtools.yang.model.repo.fs.FilesystemSchemaSourceCache;
49 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
50 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
51 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
52 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
53 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
54 import org.osgi.service.component.annotations.Activate;
55 import org.osgi.service.component.annotations.Component;
56 import org.osgi.service.component.annotations.Deactivate;
57 import org.osgi.service.component.annotations.Reference;
58 import org.osgi.service.metatype.annotations.AttributeDefinition;
59 import org.osgi.service.metatype.annotations.Designate;
60 import org.osgi.service.metatype.annotations.ObjectClassDefinition;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 /**
65  * Listens on new schema sources registered event. For each new source
66  * registered generates URL representing its schema source and write this URL
67  * along with source identifier to
68  * ietf-netconf-yang-library/modules-state/module list.
69  */
70 @Singleton
71 @Component(service = YangLibService.class, configurationPid = "org.opendaylight.netconf.yanglib")
72 @Designate(ocd = YangLibProvider.Configuration.class)
73 public final class YangLibProvider implements YangLibService, SchemaSourceListener, AutoCloseable {
74     @ObjectClassDefinition
75     public @interface Configuration {
76         @AttributeDefinition(min = "1",
77             description = "Local filesystem folder to use as cache + to load yang models from")
78         @NonNull String cache$_$folder() default "cache/schema";
79
80         @AttributeDefinition(
81             description = "Binding address is necessary for generating proper URLS (accessible from the outside world) "
82                 + "for models present directly in the library")
83         @NonNull String binding$_$address() default "localhost";
84
85         @AttributeDefinition(required = true, min = "1", max = "65535",
86             description = "binding port is necessary for generating proper URLS (accessible from the outside world) "
87                 + "for models present directly in the library")
88         int binding$_$port() default 8181;
89     }
90
91     private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
92
93     private static final Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
94         input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
95
96     private final DataBroker dataBroker;
97     private final String bindingAddress;
98     private final Uint32 bindingPort;
99     private final SharedSchemaRepository schemaRepository;
100
101     private final SchemaListenerRegistration schemaListenerRegistration;
102
103     @Inject
104     @Activate
105     public YangLibProvider(@Reference final @NonNull DataBroker dataBroker,
106             @Reference final @NonNull YangParserFactory parserFactory, final @NonNull Configuration configuration) {
107         this(dataBroker, parserFactory, configuration.cache$_$folder(), configuration.binding$_$address(),
108                 Uint32.valueOf(configuration.binding$_$port()));
109     }
110
111     @VisibleForTesting
112     YangLibProvider(final @NonNull DataBroker dataBroker, final @NonNull YangParserFactory parserFactory,
113                     final @NonNull String cacheFolder, final @NonNull String bindingAddress,
114                     final @NonNull Uint32 bindingPort) {
115         this.bindingAddress = bindingAddress;
116         this.bindingPort = bindingPort;
117         this.dataBroker = requireNonNull(dataBroker);
118
119         final File cacheFolderFile = new File(cacheFolder);
120         if (cacheFolderFile.exists()) {
121             LOG.info("cache-folder {} already exists", cacheFolderFile);
122         } else {
123             checkArgument(cacheFolderFile.mkdirs(), "cache-folder %s cannot be created", cacheFolderFile);
124             LOG.info("cache-folder {} was created", cacheFolderFile);
125         }
126         checkArgument(cacheFolderFile.isDirectory(), "cache-folder %s is not a directory", cacheFolderFile);
127
128         schemaRepository = new SharedSchemaRepository("yang-library", parserFactory);
129         final var cache = new FilesystemSchemaSourceCache<>(schemaRepository, YangTextSchemaSource.class,
130             cacheFolderFile);
131         schemaRepository.registerSchemaSourceListener(cache);
132
133         schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
134
135         LOG.info("Started yang library with sources from {}", cacheFolderFile);
136     }
137
138     @PreDestroy
139     @Deactivate
140     @Override
141     public void close() {
142         schemaListenerRegistration.close();
143     }
144
145     @Override
146     public void schemaSourceEncountered(final SchemaSourceRepresentation source) {
147         // NOOP
148     }
149
150     @Override
151     public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
152         final var newModules = new HashMap<ModuleKey, Module>();
153
154         for (var potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE::test)) {
155             final var moduleName = new YangIdentifier(potentialYangSource.getSourceIdentifier().name().getLocalName());
156
157             final var newModule = new ModuleBuilder()
158                     .setName(moduleName)
159                     .setRevision(LegacyRevisionUtils.fromYangCommon(
160                         Optional.ofNullable(potentialYangSource.getSourceIdentifier().revision())))
161                     .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
162                     .build();
163
164             newModules.put(newModule.key(), newModule);
165         }
166
167         if (newModules.isEmpty()) {
168             // If no new yang modules then do nothing
169             return;
170         }
171
172         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
173         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class),
174                 new ModulesStateBuilder().setModule(newModules).build());
175
176         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
177             @Override
178             public void onSuccess(final CommitInfo result) {
179                 LOG.debug("Modules state successfully populated with new modules");
180             }
181
182             @Override
183             public void onFailure(final Throwable throwable) {
184                 LOG.warn("Unable to update modules state", throwable);
185             }
186         }, MoreExecutors.directExecutor());
187     }
188
189     @Override
190     public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
191         if (!YANG_SCHEMA_SOURCE.test(source)) {
192             // if representation of potential schema source is not yang text schema source do nothing
193             // we do not want to delete this module entry from module list
194             return;
195         }
196
197         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
198         tx.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class)
199             .child(Module.class, new ModuleKey(new YangIdentifier(source.getSourceIdentifier().name().getLocalName()),
200                 LegacyRevisionUtils.fromYangCommon(Optional.ofNullable(source.getSourceIdentifier().revision())))));
201
202         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
203             @Override
204             public void onSuccess(final CommitInfo result) {
205                 LOG.debug("Modules state successfully updated.");
206             }
207
208             @Override
209             public void onFailure(final Throwable throwable) {
210                 LOG.warn("Unable to update modules state", throwable);
211             }
212         }, MoreExecutors.directExecutor());
213     }
214
215     @Override
216     public String getSchema(final String name, final String revision) {
217         LOG.debug("Attempting load for schema source {}:{}", name, revision);
218         return getYangModel(name, revision.isEmpty() ? null : revision);
219     }
220
221     @Override
222     public String getSchema(final String name) {
223         LOG.debug("Attempting load for schema source {}: no-revision", name);
224         return getYangModel(name, null);
225     }
226
227     private String getYangModel(final String name, final String revision) {
228         final var sourceId = new SourceIdentifier(name, revision);
229         final var yangTextSchemaFuture = schemaRepository.getSchemaSource(sourceId, YangTextSchemaSource.class);
230         try {
231             final var yangTextSchemaSource = yangTextSchemaFuture.get();
232             return yangTextSchemaSource.read();
233         } catch (ExecutionException e) {
234             if (e.getCause() instanceof MissingSchemaSourceException) {
235                 throw new NotFoundException("Schema source " + sourceId + " not found", e);
236             }
237             throw new WebApplicationException("Unable to retrieve schema source " + sourceId, e);
238         } catch (IOException e) {
239             throw new WebApplicationException("Unable to read schema " + sourceId, e);
240         } catch (InterruptedException e) {
241             Thread.currentThread().interrupt();
242             throw new WebApplicationException("Retrieving schema source " + sourceId + " has been interrupted", e);
243         }
244     }
245
246     private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
247         return new Uri("http://" + bindingAddress + ':' + bindingPort + "/yanglib/schemas/"
248                 + sourceIdentifier.name().getLocalName() + revString(sourceIdentifier));
249     }
250
251     private static String revString(final SourceIdentifier id) {
252         final var rev = id.revision();
253         return rev != null ? "/" + rev : "";
254     }
255 }