8e9b378a167168cbca982254df0e0a1620a82b5f
[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 com.google.common.base.Preconditions;
11 import com.google.common.base.Predicate;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.Iterables;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.io.File;
18 import java.util.ArrayList;
19 import java.util.List;
20 import javax.annotation.Nullable;
21 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
22 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesState;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesStateBuilder;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.OptionalRevision;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.RevisionIdentifier;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.ModuleBuilder;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.ModuleKey;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig;
34 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
35 import org.opendaylight.yangtools.yang.common.Revision;
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.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Listens on new schema sources registered event. For each new source
49  * registered generates URL representing its schema source and write this URL
50  * along with source identifier to
51  * ietf-netconf-yang-library/modules-state/module list.
52  */
53 public class YangLibProvider implements AutoCloseable, SchemaSourceListener {
54     private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
55
56     private static final OptionalRevision NO_REVISION = new OptionalRevision("");
57     private static final Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
58         input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
59
60     private final DataBroker dataBroker;
61     private final YanglibConfig yanglibConfig;
62     private final SharedSchemaRepository schemaRepository;
63     private SchemaListenerRegistration schemaListenerRegistration;
64
65     public YangLibProvider(final YanglibConfig yanglibConfig, final DataBroker dataBroker,
66             final SharedSchemaRepository schemaRepository) {
67         this.yanglibConfig = Preconditions.checkNotNull(yanglibConfig);
68         this.dataBroker = Preconditions.checkNotNull(dataBroker);
69         this.schemaRepository = Preconditions.checkNotNull(schemaRepository);
70     }
71
72     @Override
73     public void close() {
74         if (schemaListenerRegistration != null) {
75             schemaListenerRegistration.close();
76         }
77     }
78
79     public void init() {
80         if (Strings.isNullOrEmpty(yanglibConfig.getCacheFolder())) {
81             LOG.info("No cache-folder set in yanglib-config - yang library services will not be available");
82             return;
83         }
84
85         final File cacheFolderFile = new File(yanglibConfig.getCacheFolder());
86         Preconditions.checkArgument(cacheFolderFile.exists(), "cache-folder %s does not exist", cacheFolderFile);
87         Preconditions.checkArgument(cacheFolderFile.isDirectory(), "cache-folder %s is not a directory",
88                 cacheFolderFile);
89
90         final FilesystemSchemaSourceCache<YangTextSchemaSource> cache =
91                 new FilesystemSchemaSourceCache<>(schemaRepository, YangTextSchemaSource.class, cacheFolderFile);
92         schemaRepository.registerSchemaSourceListener(cache);
93
94         schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
95
96         LOG.info("Started yang library with sources from {}", cacheFolderFile);
97     }
98
99     @Override
100     public void schemaSourceEncountered(final SchemaSourceRepresentation source) {
101         // NOOP
102     }
103
104     @Override
105     public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
106         final List<Module> newModules = new ArrayList<>();
107
108         for (PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
109             final YangIdentifier moduleName = new YangIdentifier(potentialYangSource.getSourceIdentifier().getName());
110
111             final OptionalRevision moduleRevision = getRevisionForModule(potentialYangSource.getSourceIdentifier());
112
113             final Module newModule = new ModuleBuilder()
114                     .setName(moduleName)
115                     .setRevision(moduleRevision)
116                     .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
117                     .build();
118
119             newModules.add(newModule);
120         }
121
122         if (newModules.isEmpty()) {
123             // If no new yang modules then do nothing
124             return;
125         }
126
127         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
128         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class),
129                 new ModulesStateBuilder().setModule(newModules).build());
130
131         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
132             @Override
133             public void onSuccess(@Nullable final Void result) {
134                 LOG.debug("Modules state successfully populated with new modules");
135             }
136
137             @Override
138             public void onFailure(final Throwable throwable) {
139                 LOG.warn("Unable to update modules state", throwable);
140             }
141         }, MoreExecutors.directExecutor());
142     }
143
144     @Override
145     public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
146         if (!YANG_SCHEMA_SOURCE.apply(source)) {
147             // if representation of potential schema source is not yang text schema source do nothing
148             // we do not want to delete this module entry from module list
149             return;
150         }
151
152         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
153         tx.delete(LogicalDatastoreType.OPERATIONAL,
154                 InstanceIdentifier.create(ModulesState.class)
155                         .child(Module.class,
156                                 new ModuleKey(
157                                         new YangIdentifier(source.getSourceIdentifier().getName()),
158                                         getRevisionForModule(source.getSourceIdentifier()))));
159
160         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
161             @Override
162             public void onSuccess(@Nullable final Void result) {
163                 LOG.debug("Modules state successfully updated.");
164             }
165
166             @Override
167             public void onFailure(final Throwable throwable) {
168                 LOG.warn("Unable to update modules state", throwable);
169             }
170         }, MoreExecutors.directExecutor());
171     }
172
173
174
175     private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
176         return new Uri("http://" + yanglibConfig.getBindingAddr() + ':' + yanglibConfig.getBindingPort()
177                 + "/yanglib/schemas/" + sourceIdentifier.getName() + '/' + revString(sourceIdentifier));
178     }
179
180     private static String revString(final SourceIdentifier id) {
181         return id.getRevision().map(Revision::toString).orElse("");
182     }
183
184     private static OptionalRevision getRevisionForModule(final SourceIdentifier sourceIdentifier) {
185         return sourceIdentifier.getRevision().map(rev -> new OptionalRevision(new RevisionIdentifier(rev.toString())))
186                 .orElse(NO_REVISION);
187     }
188 }