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