2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yanglib.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.Iterables;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.MoreExecutors;
18 import java.io.IOException;
19 import java.nio.charset.StandardCharsets;
20 import java.util.HashMap;
22 import java.util.Optional;
23 import java.util.concurrent.ExecutionException;
24 import java.util.function.Predicate;
25 import javax.ws.rs.NotFoundException;
26 import javax.ws.rs.WebApplicationException;
27 import org.opendaylight.mdsal.binding.api.DataBroker;
28 import org.opendaylight.mdsal.binding.api.WriteTransaction;
29 import org.opendaylight.mdsal.common.api.CommitInfo;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.LegacyRevisionUtils;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesState;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesStateBuilder;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.Module;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.ModuleBuilder;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.ModuleKey;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig;
40 import org.opendaylight.yanglib.api.YangLibService;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
42 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
43 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
44 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
45 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
46 import org.opendaylight.yangtools.yang.model.repo.fs.FilesystemSchemaSourceCache;
47 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
48 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
49 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
50 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
51 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * Listens on new schema sources registered event. For each new source
57 * registered generates URL representing its schema source and write this URL
58 * along with source identifier to
59 * ietf-netconf-yang-library/modules-state/module list.
61 public class YangLibProvider implements AutoCloseable, SchemaSourceListener, YangLibService {
62 private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
64 private static final Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
65 input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
67 private final DataBroker dataBroker;
68 private final YanglibConfig yanglibConfig;
69 private final SharedSchemaRepository schemaRepository;
70 private SchemaListenerRegistration schemaListenerRegistration;
72 public YangLibProvider(final YanglibConfig yanglibConfig, final DataBroker dataBroker,
73 final YangParserFactory parserFactory) {
74 this.yanglibConfig = requireNonNull(yanglibConfig);
75 this.dataBroker = requireNonNull(dataBroker);
76 schemaRepository = new SharedSchemaRepository("yang-library", parserFactory);
81 if (schemaListenerRegistration != null) {
82 schemaListenerRegistration.close();
87 if (Strings.isNullOrEmpty(yanglibConfig.getCacheFolder())) {
88 LOG.info("No cache-folder set in yanglib-config - yang library services will not be available");
92 final File cacheFolderFile = new File(yanglibConfig.getCacheFolder());
93 if (cacheFolderFile.exists()) {
94 LOG.info("cache-folder {} already exists", cacheFolderFile);
96 checkArgument(cacheFolderFile.mkdirs(), "cache-folder %s cannot be created", cacheFolderFile);
97 LOG.info("cache-folder {} was created", cacheFolderFile);
99 checkArgument(cacheFolderFile.isDirectory(), "cache-folder %s is not a directory", cacheFolderFile);
101 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache =
102 new FilesystemSchemaSourceCache<>(schemaRepository, YangTextSchemaSource.class, cacheFolderFile);
103 schemaRepository.registerSchemaSourceListener(cache);
105 schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
107 LOG.info("Started yang library with sources from {}", cacheFolderFile);
111 public void schemaSourceEncountered(final SchemaSourceRepresentation source) {
116 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
117 final Map<ModuleKey, Module> newModules = new HashMap<>();
119 for (PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE::test)) {
120 final YangIdentifier moduleName =
121 new YangIdentifier(potentialYangSource.getSourceIdentifier().name().getLocalName());
123 final Module newModule = new ModuleBuilder()
125 .setRevision(LegacyRevisionUtils.fromYangCommon(
126 Optional.ofNullable(potentialYangSource.getSourceIdentifier().revision())))
127 .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
130 newModules.put(newModule.key(), newModule);
133 if (newModules.isEmpty()) {
134 // If no new yang modules then do nothing
138 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
139 tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class),
140 new ModulesStateBuilder().setModule(newModules).build());
142 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
144 public void onSuccess(final CommitInfo result) {
145 LOG.debug("Modules state successfully populated with new modules");
149 public void onFailure(final Throwable throwable) {
150 LOG.warn("Unable to update modules state", throwable);
152 }, MoreExecutors.directExecutor());
156 public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
157 if (!YANG_SCHEMA_SOURCE.test(source)) {
158 // if representation of potential schema source is not yang text schema source do nothing
159 // we do not want to delete this module entry from module list
163 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
164 tx.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class)
165 .child(Module.class, new ModuleKey(new YangIdentifier(source.getSourceIdentifier().name().getLocalName()),
166 LegacyRevisionUtils.fromYangCommon(Optional.ofNullable(source.getSourceIdentifier().revision())))));
168 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
170 public void onSuccess(final CommitInfo result) {
171 LOG.debug("Modules state successfully updated.");
175 public void onFailure(final Throwable throwable) {
176 LOG.warn("Unable to update modules state", throwable);
178 }, MoreExecutors.directExecutor());
182 public String getSchema(final String name, final String revision) {
183 LOG.debug("Attempting load for schema source {}:{}", name, revision);
184 return getYangModel(name, revision.isEmpty() ? null : revision);
188 public String getSchema(final String name) {
189 LOG.debug("Attempting load for schema source {}: no-revision", name);
190 return getYangModel(name, null);
193 private String getYangModel(final String name, final String revision) {
194 final var sourceId = new SourceIdentifier(name, revision);
195 final var yangTextSchemaFuture = schemaRepository.getSchemaSource(sourceId, YangTextSchemaSource.class);
197 final var yangTextSchemaSource = yangTextSchemaFuture.get();
198 return yangTextSchemaSource.asCharSource(StandardCharsets.UTF_8).read();
199 } catch (ExecutionException e) {
200 if (e.getCause() instanceof MissingSchemaSourceException) {
201 throw new NotFoundException("Schema source " + sourceId + " not found", e);
203 throw new WebApplicationException("Unable to retrieve schema source " + sourceId, e);
204 } catch (IOException e) {
205 throw new WebApplicationException("Unable to read schema " + sourceId, e);
206 } catch (InterruptedException e) {
207 Thread.currentThread().interrupt();
208 throw new WebApplicationException("Retrieving schema source " + sourceId + " has been interrupted", e);
212 private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
213 return new Uri("http://" + yanglibConfig.getBindingAddr() + ':' + yanglibConfig.getBindingPort()
214 + "/yanglib/schemas/" + sourceIdentifier.name().getLocalName() + revString(sourceIdentifier));
217 private static String revString(final SourceIdentifier id) {
218 final var rev = id.revision();
219 return rev != null ? "/" + rev : "";