e523dd81d60be4d218c071aaddfca4a1329b98bb
[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.io.ByteStreams;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.io.File;
21 import java.io.IOException;
22 import java.nio.charset.Charset;
23 import java.util.HashMap;
24 import java.util.Map;
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.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.CommonLeafsRevisionBuilder;
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.common.Revision;
42 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
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;
54
55 /**
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.
60  */
61 public class YangLibProvider implements AutoCloseable, SchemaSourceListener, YangLibService {
62     private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
63
64     private static final Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
65         input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
66
67     private final DataBroker dataBroker;
68     private final YanglibConfig yanglibConfig;
69     private final SharedSchemaRepository schemaRepository;
70     private SchemaListenerRegistration schemaListenerRegistration;
71
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);
77     }
78
79     @Override
80     public void close() {
81         if (schemaListenerRegistration != null) {
82             schemaListenerRegistration.close();
83         }
84     }
85
86     public void init() {
87         if (Strings.isNullOrEmpty(yanglibConfig.getCacheFolder())) {
88             LOG.info("No cache-folder set in yanglib-config - yang library services will not be available");
89             return;
90         }
91
92         final File cacheFolderFile = new File(yanglibConfig.getCacheFolder());
93         checkArgument(cacheFolderFile.exists(), "cache-folder %s does not exist", cacheFolderFile);
94         checkArgument(cacheFolderFile.isDirectory(), "cache-folder %s is not a directory", cacheFolderFile);
95
96         final FilesystemSchemaSourceCache<YangTextSchemaSource> cache =
97                 new FilesystemSchemaSourceCache<>(schemaRepository, YangTextSchemaSource.class, cacheFolderFile);
98         schemaRepository.registerSchemaSourceListener(cache);
99
100         schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
101
102         LOG.info("Started yang library with sources from {}", cacheFolderFile);
103     }
104
105     @Override
106     public void schemaSourceEncountered(final SchemaSourceRepresentation source) {
107         // NOOP
108     }
109
110     @Override
111     public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
112         final Map<ModuleKey, Module> newModules = new HashMap<>();
113
114         for (PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
115             final YangIdentifier moduleName = new YangIdentifier(potentialYangSource.getSourceIdentifier().getName());
116
117             final Module newModule = new ModuleBuilder()
118                     .setName(moduleName)
119                     .setRevision(CommonLeafsRevisionBuilder.fromYangCommon(
120                         potentialYangSource.getSourceIdentifier().getRevision()))
121                     .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
122                     .build();
123
124             newModules.put(newModule.key(), newModule);
125         }
126
127         if (newModules.isEmpty()) {
128             // If no new yang modules then do nothing
129             return;
130         }
131
132         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
133         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class),
134                 new ModulesStateBuilder().setModule(newModules).build());
135
136         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
137             @Override
138             public void onSuccess(final CommitInfo result) {
139                 LOG.debug("Modules state successfully populated with new modules");
140             }
141
142             @Override
143             public void onFailure(final Throwable throwable) {
144                 LOG.warn("Unable to update modules state", throwable);
145             }
146         }, MoreExecutors.directExecutor());
147     }
148
149     @Override
150     public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
151         if (!YANG_SCHEMA_SOURCE.apply(source)) {
152             // if representation of potential schema source is not yang text schema source do nothing
153             // we do not want to delete this module entry from module list
154             return;
155         }
156
157         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
158         tx.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class)
159             .child(Module.class, new ModuleKey(new YangIdentifier(source.getSourceIdentifier().getName()),
160                 CommonLeafsRevisionBuilder.fromYangCommon(source.getSourceIdentifier().getRevision()))));
161
162         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
163             @Override
164             public void onSuccess(final CommitInfo result) {
165                 LOG.debug("Modules state successfully updated.");
166             }
167
168             @Override
169             public void onFailure(final Throwable throwable) {
170                 LOG.warn("Unable to update modules state", throwable);
171             }
172         }, MoreExecutors.directExecutor());
173     }
174
175     @Override
176     public String getSchema(final String name, final String revision) {
177         LOG.debug("Attempting load for schema source {}:{}", name, revision);
178         final SourceIdentifier sourceId = RevisionSourceIdentifier.create(name,
179             revision.isEmpty() ? null : Revision.of(revision));
180
181         final ListenableFuture<YangTextSchemaSource> sourceFuture = schemaRepository.getSchemaSource(sourceId,
182             YangTextSchemaSource.class);
183
184         try {
185             final YangTextSchemaSource source = sourceFuture.get();
186             return new String(ByteStreams.toByteArray(source.openStream()), Charset.defaultCharset());
187         } catch (InterruptedException | ExecutionException | IOException e) {
188             throw new IllegalStateException("Unable to get schema " + sourceId, e);
189         }
190     }
191
192     private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
193         return new Uri("http://" + yanglibConfig.getBindingAddr() + ':' + yanglibConfig.getBindingPort()
194                 + "/yanglib/schemas/" + sourceIdentifier.getName() + '/' + revString(sourceIdentifier));
195     }
196
197     private static String revString(final SourceIdentifier id) {
198         return id.getRevision().map(Revision::toString).orElse("");
199     }
200 }