Fix odl-yanglib feature usage
[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.base.Predicate;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.Iterables;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.io.File;
20 import java.io.IOException;
21 import java.nio.charset.StandardCharsets;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.Optional;
25 import java.util.concurrent.ExecutionException;
26 import org.opendaylight.mdsal.binding.api.DataBroker;
27 import org.opendaylight.mdsal.binding.api.WriteTransaction;
28 import org.opendaylight.mdsal.common.api.CommitInfo;
29 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.LegacyRevisionUtils;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesState;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.ModulesStateBuilder;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.Module;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.ModuleBuilder;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev190104.module.list.ModuleKey;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig;
39 import org.opendaylight.yanglib.api.YangLibService;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
42 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
43 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
44 import org.opendaylight.yangtools.yang.model.repo.fs.FilesystemSchemaSourceCache;
45 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
46 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
47 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
48 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
49 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * Listens on new schema sources registered event. For each new source
55  * registered generates URL representing its schema source and write this URL
56  * along with source identifier to
57  * ietf-netconf-yang-library/modules-state/module list.
58  */
59 public class YangLibProvider implements AutoCloseable, SchemaSourceListener, YangLibService {
60     private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
61
62     private static final Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
63         input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
64
65     private final DataBroker dataBroker;
66     private final YanglibConfig yanglibConfig;
67     private final SharedSchemaRepository schemaRepository;
68     private SchemaListenerRegistration schemaListenerRegistration;
69
70     public YangLibProvider(final YanglibConfig yanglibConfig, final DataBroker dataBroker,
71             final YangParserFactory parserFactory) {
72         this.yanglibConfig = requireNonNull(yanglibConfig);
73         this.dataBroker = requireNonNull(dataBroker);
74         schemaRepository = new SharedSchemaRepository("yang-library", parserFactory);
75     }
76
77     @Override
78     public void close() {
79         if (schemaListenerRegistration != null) {
80             schemaListenerRegistration.close();
81         }
82     }
83
84     public void init() {
85         if (Strings.isNullOrEmpty(yanglibConfig.getCacheFolder())) {
86             LOG.info("No cache-folder set in yanglib-config - yang library services will not be available");
87             return;
88         }
89
90         final File cacheFolderFile = new File(yanglibConfig.getCacheFolder());
91         if (cacheFolderFile.exists()) {
92             LOG.info("cache-folder {} already exists", cacheFolderFile);
93         } else {
94             checkArgument(cacheFolderFile.mkdirs(), "cache-folder %s cannot be created", cacheFolderFile);
95             LOG.info("cache-folder {} was created", cacheFolderFile);
96         }
97         checkArgument(cacheFolderFile.isDirectory(), "cache-folder %s is not a directory", cacheFolderFile);
98
99         final FilesystemSchemaSourceCache<YangTextSchemaSource> cache =
100                 new FilesystemSchemaSourceCache<>(schemaRepository, YangTextSchemaSource.class, cacheFolderFile);
101         schemaRepository.registerSchemaSourceListener(cache);
102
103         schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
104
105         LOG.info("Started yang library with sources from {}", cacheFolderFile);
106     }
107
108     @Override
109     public void schemaSourceEncountered(final SchemaSourceRepresentation source) {
110         // NOOP
111     }
112
113     @Override
114     public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
115         final Map<ModuleKey, Module> newModules = new HashMap<>();
116
117         for (PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
118             final YangIdentifier moduleName =
119                 new YangIdentifier(potentialYangSource.getSourceIdentifier().name().getLocalName());
120
121             final Module newModule = new ModuleBuilder()
122                     .setName(moduleName)
123                     .setRevision(LegacyRevisionUtils.fromYangCommon(
124                         Optional.ofNullable(potentialYangSource.getSourceIdentifier().revision())))
125                     .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
126                     .build();
127
128             newModules.put(newModule.key(), newModule);
129         }
130
131         if (newModules.isEmpty()) {
132             // If no new yang modules then do nothing
133             return;
134         }
135
136         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
137         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class),
138                 new ModulesStateBuilder().setModule(newModules).build());
139
140         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
141             @Override
142             public void onSuccess(final CommitInfo result) {
143                 LOG.debug("Modules state successfully populated with new modules");
144             }
145
146             @Override
147             public void onFailure(final Throwable throwable) {
148                 LOG.warn("Unable to update modules state", throwable);
149             }
150         }, MoreExecutors.directExecutor());
151     }
152
153     @Override
154     public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
155         if (!YANG_SCHEMA_SOURCE.apply(source)) {
156             // if representation of potential schema source is not yang text schema source do nothing
157             // we do not want to delete this module entry from module list
158             return;
159         }
160
161         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
162         tx.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class)
163             .child(Module.class, new ModuleKey(new YangIdentifier(source.getSourceIdentifier().name().getLocalName()),
164                 LegacyRevisionUtils.fromYangCommon(Optional.ofNullable(source.getSourceIdentifier().revision())))));
165
166         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
167             @Override
168             public void onSuccess(final CommitInfo result) {
169                 LOG.debug("Modules state successfully updated.");
170             }
171
172             @Override
173             public void onFailure(final Throwable throwable) {
174                 LOG.warn("Unable to update modules state", throwable);
175             }
176         }, MoreExecutors.directExecutor());
177     }
178
179     @Override
180     public String getSchema(final String name, final String revision) {
181         LOG.debug("Attempting load for schema source {}:{}", name, revision);
182         final SourceIdentifier sourceId = new SourceIdentifier(name, revision.isEmpty() ? null : revision);
183
184         final ListenableFuture<YangTextSchemaSource> sourceFuture = schemaRepository.getSchemaSource(sourceId,
185             YangTextSchemaSource.class);
186
187         final YangTextSchemaSource source;
188         try {
189             source = sourceFuture.get();
190         } catch (InterruptedException | ExecutionException e) {
191             throw new IllegalStateException("Unable to get schema " + sourceId, e);
192         }
193
194         try {
195             return source.asCharSource(StandardCharsets.UTF_8).read();
196         } catch (IOException e) {
197             throw new IllegalStateException("Unable to read schema " + sourceId, e);
198         }
199     }
200
201     private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
202         return new Uri("http://" + yanglibConfig.getBindingAddr() + ':' + yanglibConfig.getBindingPort()
203                 + "/yanglib/schemas/" + sourceIdentifier.name().getLocalName() + '/' + revString(sourceIdentifier));
204     }
205
206     private static String revString(final SourceIdentifier id) {
207         final var rev = id.revision();
208         return rev != null ? rev.toString() : "";
209     }
210 }