Migrate netconf users of submit() to commit()
[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.MoreExecutors;
16 import java.io.File;
17 import java.util.ArrayList;
18 import java.util.List;
19 import javax.annotation.Nullable;
20 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
21 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.mdsal.common.api.CommitInfo;
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.rev160621.ModulesState;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.ModulesStateBuilder;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.RevisionUtils;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.module.list.Module;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.module.list.ModuleBuilder;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.module.list.ModuleKey;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.YangIdentifier;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.yanglib.impl.rev141210.YanglibConfig;
33 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
34 import org.opendaylight.yangtools.yang.common.Revision;
35 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
36 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
37 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
38 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
39 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
40 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
41 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
42 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Listens on new schema sources registered event. For each new source
48  * registered generates URL representing its schema source and write this URL
49  * along with source identifier to
50  * ietf-netconf-yang-library/modules-state/module list.
51  */
52 public class YangLibProvider implements AutoCloseable, SchemaSourceListener {
53     private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
54
55     private static final Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
56         input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
57
58     private final DataBroker dataBroker;
59     private final YanglibConfig yanglibConfig;
60     private final SharedSchemaRepository schemaRepository;
61     private SchemaListenerRegistration schemaListenerRegistration;
62
63     public YangLibProvider(final YanglibConfig yanglibConfig, final DataBroker dataBroker,
64             final SharedSchemaRepository schemaRepository) {
65         this.yanglibConfig = Preconditions.checkNotNull(yanglibConfig);
66         this.dataBroker = Preconditions.checkNotNull(dataBroker);
67         this.schemaRepository = Preconditions.checkNotNull(schemaRepository);
68     }
69
70     @Override
71     public void close() {
72         if (schemaListenerRegistration != null) {
73             schemaListenerRegistration.close();
74         }
75     }
76
77     public void init() {
78         if (Strings.isNullOrEmpty(yanglibConfig.getCacheFolder())) {
79             LOG.info("No cache-folder set in yanglib-config - yang library services will not be available");
80             return;
81         }
82
83         final File cacheFolderFile = new File(yanglibConfig.getCacheFolder());
84         Preconditions.checkArgument(cacheFolderFile.exists(), "cache-folder %s does not exist", cacheFolderFile);
85         Preconditions.checkArgument(cacheFolderFile.isDirectory(), "cache-folder %s is not a directory",
86                 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(@Nullable 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(@Nullable 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 }