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