Replace deprecated Futures.addCallback by the newer version
[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
9 package org.opendaylight.yanglib.impl;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicate;
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.Futures;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.io.File;
19 import java.util.ArrayList;
20 import java.util.List;
21 import javax.annotation.Nullable;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
24 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesState;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesStateBuilder;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.OptionalRevision;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.RevisionIdentifier;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.ModuleBuilder;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.ModuleKey;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
37 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
38 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
39 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
40 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
41 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
42 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
43 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
44 import org.osgi.framework.BundleContext;
45 import org.osgi.framework.FrameworkUtil;
46 import org.osgi.framework.ServiceReference;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50
51 /**
52  * Listens on new schema sources registered event. For each new source
53  * registered generates URL representing its schema source and write this URL
54  * along with source identifier to
55  * ietf-netconf-yang-library/modules-state/module list.
56  */
57 public class YangLibProvider implements AutoCloseable, SchemaSourceListener {
58     private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
59
60     private static final OptionalRevision NO_REVISION = new OptionalRevision("");
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 YangLibServiceImpl yangLibService;
66     private final YanglibConfig yanglibConfig;
67     private SchemaListenerRegistration schemaListenerRegistration;
68     private SharedSchemaRepository schemaRepository;
69
70     public YangLibProvider(final YanglibConfig yanglibConfig, final DataBroker dataBroker,
71             final YangLibServiceImpl yangLibService) {
72         this.yanglibConfig = Preconditions.checkNotNull(yanglibConfig);
73         this.dataBroker = Preconditions.checkNotNull(dataBroker);
74         this.yangLibService = Preconditions.checkNotNull(yangLibService);
75     }
76
77     @Override
78     public void close() {
79         yangLibService.setSchemaRepository(null);
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         Preconditions.checkArgument(cacheFolderFile.exists(), "cache-folder %s does not exist", cacheFolderFile);
93         Preconditions.checkArgument(cacheFolderFile.isDirectory(), "cache-folder %s is not a directory",
94                 cacheFolderFile);
95
96         schemaRepository = new SharedSchemaRepository("yang-library");
97         final FilesystemSchemaSourceCache<YangTextSchemaSource> cache =
98                 new FilesystemSchemaSourceCache<>(schemaRepository, YangTextSchemaSource.class, cacheFolderFile);
99         schemaRepository.registerSchemaSourceListener(cache);
100
101         schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
102         yangLibService.setSchemaRepository(schemaRepository);
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 List<Module> newModules = new ArrayList<>();
115
116         for (PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
117             final YangIdentifier moduleName = new YangIdentifier(potentialYangSource.getSourceIdentifier().getName());
118
119             final OptionalRevision moduleRevision = getRevisionForModule(potentialYangSource.getSourceIdentifier());
120
121             final Module newModule = new ModuleBuilder()
122                     .setName(moduleName)
123                     .setRevision(moduleRevision)
124                     .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
125                     .build();
126
127             newModules.add(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         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
140             @Override
141             public void onSuccess(@Nullable final Void 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,
162                 InstanceIdentifier.create(ModulesState.class)
163                         .child(Module.class,
164                                 new ModuleKey(
165                                         new YangIdentifier(source.getSourceIdentifier().getName()),
166                                         getRevisionForModule(source.getSourceIdentifier()))));
167
168         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
169             @Override
170             public void onSuccess(@Nullable final Void result) {
171                 LOG.debug("Modules state successfully updated.");
172             }
173
174             @Override
175             public void onFailure(final Throwable throwable) {
176                 LOG.warn("Unable to update modules state", throwable);
177             }
178         }, MoreExecutors.directExecutor());
179     }
180
181
182
183     private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
184         return new Uri("http://" + yanglibConfig.getBindingAddr() + ':' + yanglibConfig.getBindingPort()
185                 + "/yanglib/schemas/" + sourceIdentifier.getName() + '/' + revString(sourceIdentifier));
186     }
187
188     private static String revString(final SourceIdentifier id) {
189         final String rev = id.getRevision();
190         return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? "" : rev;
191     }
192
193     private static OptionalRevision getRevisionForModule(final SourceIdentifier sourceIdentifier) {
194         final String rev = sourceIdentifier.getRevision();
195         return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? NO_REVISION
196                 : new OptionalRevision(new RevisionIdentifier(rev));
197     }
198
199     private <T> T getObjectFromBundleContext(final Class<T> type, final String serviceRefName) {
200         final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
201         final ServiceReference<?> serviceReference = bundleContext.getServiceReference(serviceRefName);
202         return (T) bundleContext.getService(serviceReference);
203     }
204 }