9791e70b632974a6769c54d9c4c536a077cd67e6
[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.util.ArrayList;
20 import java.util.List;
21 import org.opendaylight.mdsal.binding.api.DataBroker;
22 import org.opendaylight.mdsal.binding.api.WriteTransaction;
23 import org.opendaylight.mdsal.common.api.CommitInfo;
24 import org.opendaylight.mdsal.common.api.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.rev160621.ModulesState;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.ModulesStateBuilder;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.RevisionUtils;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.module.list.Module;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.module.list.ModuleBuilder;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.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 Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
57         input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
58
59     private final DataBroker dataBroker;
60     private final YanglibConfig yanglibConfig;
61     private final SharedSchemaRepository schemaRepository;
62     private SchemaListenerRegistration schemaListenerRegistration;
63
64     public YangLibProvider(final YanglibConfig yanglibConfig, final DataBroker dataBroker,
65             final SharedSchemaRepository schemaRepository) {
66         this.yanglibConfig = requireNonNull(yanglibConfig);
67         this.dataBroker = requireNonNull(dataBroker);
68         this.schemaRepository = requireNonNull(schemaRepository);
69     }
70
71     @Override
72     public void close() {
73         if (schemaListenerRegistration != null) {
74             schemaListenerRegistration.close();
75         }
76     }
77
78     public void init() {
79         if (Strings.isNullOrEmpty(yanglibConfig.getCacheFolder())) {
80             LOG.info("No cache-folder set in yanglib-config - yang library services will not be available");
81             return;
82         }
83
84         final File cacheFolderFile = new File(yanglibConfig.getCacheFolder());
85         checkArgument(cacheFolderFile.exists(), "cache-folder %s does not exist", cacheFolderFile);
86         checkArgument(cacheFolderFile.isDirectory(), "cache-folder %s is not a directory", cacheFolderFile);
87
88         final FilesystemSchemaSourceCache<YangTextSchemaSource> cache =
89                 new FilesystemSchemaSourceCache<>(schemaRepository, YangTextSchemaSource.class, cacheFolderFile);
90         schemaRepository.registerSchemaSourceListener(cache);
91
92         schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
93
94         LOG.info("Started yang library with sources from {}", cacheFolderFile);
95     }
96
97     @Override
98     public void schemaSourceEncountered(final SchemaSourceRepresentation source) {
99         // NOOP
100     }
101
102     @Override
103     public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
104         final List<Module> newModules = new ArrayList<>();
105
106         for (PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
107             final YangIdentifier moduleName = new YangIdentifier(potentialYangSource.getSourceIdentifier().getName());
108
109             final Module newModule = new ModuleBuilder()
110                     .setName(moduleName)
111                     .setRevision(RevisionUtils.fromYangCommon(potentialYangSource.getSourceIdentifier().getRevision()))
112                     .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
113                     .build();
114
115             newModules.add(newModule);
116         }
117
118         if (newModules.isEmpty()) {
119             // If no new yang modules then do nothing
120             return;
121         }
122
123         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
124         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class),
125                 new ModulesStateBuilder().setModule(newModules).build());
126
127         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
128             @Override
129             public void onSuccess(final CommitInfo result) {
130                 LOG.debug("Modules state successfully populated with new modules");
131             }
132
133             @Override
134             public void onFailure(final Throwable throwable) {
135                 LOG.warn("Unable to update modules state", throwable);
136             }
137         }, MoreExecutors.directExecutor());
138     }
139
140     @Override
141     public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
142         if (!YANG_SCHEMA_SOURCE.apply(source)) {
143             // if representation of potential schema source is not yang text schema source do nothing
144             // we do not want to delete this module entry from module list
145             return;
146         }
147
148         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
149         tx.delete(LogicalDatastoreType.OPERATIONAL,
150                 InstanceIdentifier.create(ModulesState.class)
151                         .child(Module.class,
152                                 new ModuleKey(
153                                         new YangIdentifier(source.getSourceIdentifier().getName()),
154                                         RevisionUtils.fromYangCommon(source.getSourceIdentifier().getRevision()))));
155
156         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
157             @Override
158             public void onSuccess(final CommitInfo result) {
159                 LOG.debug("Modules state successfully updated.");
160             }
161
162             @Override
163             public void onFailure(final Throwable throwable) {
164                 LOG.warn("Unable to update modules state", throwable);
165             }
166         }, MoreExecutors.directExecutor());
167     }
168
169
170
171     private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
172         return new Uri("http://" + yanglibConfig.getBindingAddr() + ':' + yanglibConfig.getBindingPort()
173                 + "/yanglib/schemas/" + sourceIdentifier.getName() + '/' + revString(sourceIdentifier));
174     }
175
176     private static String revString(final SourceIdentifier id) {
177         return id.getRevision().map(Revision::toString).orElse("");
178     }
179 }