Merge "Bug 8153: Enforce check-style rules for netconf - yanglib"
[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.Predicate;
12 import com.google.common.collect.Iterables;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import java.util.ArrayList;
16 import java.util.List;
17 import javax.annotation.Nullable;
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
22 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesState;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesStateBuilder;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.OptionalRevision;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.RevisionIdentifier;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.ModuleBuilder;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.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.yanglib.api.YangLibRestAppService;
33 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
35 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
36 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
37 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
38 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
39 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
40 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
41 import org.osgi.framework.BundleContext;
42 import org.osgi.framework.FrameworkUtil;
43 import org.osgi.framework.ServiceReference;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47
48 /**
49  * Listens on new schema sources registered event. For each new source
50  * registered generates URL representing its schema source and write this URL
51  * along with source identifier to
52  * ietf-netconf-yang-library/modules-state/module list.
53  */
54 public class YangLibProvider implements BindingAwareProvider, AutoCloseable, SchemaSourceListener {
55     private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
56
57     private static final OptionalRevision NO_REVISION = new OptionalRevision("");
58     private static final Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
59         input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
60
61     protected DataBroker dataBroker;
62     protected SchemaListenerRegistration schemaListenerRegistration;
63     protected final SharedSchemaRepository schemaRepository;
64     private final String bindingAddress;
65     private final long bindingPort;
66
67     public YangLibProvider(final SharedSchemaRepository schemaRepository,
68                            final String bindingAddress, final long bindingPort) {
69         this.schemaRepository = schemaRepository;
70         this.bindingAddress = bindingAddress;
71         this.bindingPort = bindingPort;
72     }
73
74     @Override
75     public void close() throws Exception {
76         dataBroker = null;
77         schemaListenerRegistration.close();
78     }
79
80     @Override
81     public void onSessionInitiated(final BindingAwareBroker.ProviderContext providerContext) {
82         this.dataBroker = providerContext.getSALService(DataBroker.class);
83         schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
84         getObjectFromBundleContext(YangLibRestAppService.class, YangLibRestAppService.class.getName())
85         .getYangLibService().setSchemaRepository(schemaRepository);
86     }
87
88     @Override
89     public void schemaSourceEncountered(final SchemaSourceRepresentation source) {
90         // NOOP
91     }
92
93     @Override
94     public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
95         final List<Module> newModules = new ArrayList<>();
96
97         for (PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
98             final YangIdentifier moduleName = new YangIdentifier(potentialYangSource.getSourceIdentifier().getName());
99
100             final OptionalRevision moduleRevision = getRevisionForModule(potentialYangSource.getSourceIdentifier());
101
102             final Module newModule = new ModuleBuilder()
103                     .setName(moduleName)
104                     .setRevision(moduleRevision)
105                     .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
106                     .build();
107
108             newModules.add(newModule);
109         }
110
111         if (newModules.isEmpty()) {
112             // If no new yang modules then do nothing
113             return;
114         }
115
116         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
117         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class),
118                 new ModulesStateBuilder().setModule(newModules).build());
119
120         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
121             @Override
122             public void onSuccess(@Nullable final Void result) {
123                 LOG.debug("Modules state successfully populated with new modules");
124             }
125
126             @Override
127             public void onFailure(final Throwable throwable) {
128                 LOG.warn("Unable to update modules state", throwable);
129             }
130         });
131     }
132
133     @Override
134     public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
135         if (!YANG_SCHEMA_SOURCE.apply(source)) {
136             // if representation of potential schema source is not yang text schema source do nothing
137             // we do not want to delete this module entry from module list
138             return;
139         }
140
141         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
142         tx.delete(LogicalDatastoreType.OPERATIONAL,
143                 InstanceIdentifier.create(ModulesState.class)
144                         .child(Module.class,
145                                 new ModuleKey(
146                                         new YangIdentifier(source.getSourceIdentifier().getName()),
147                                         getRevisionForModule(source.getSourceIdentifier()))));
148
149         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
150             @Override
151             public void onSuccess(@Nullable final Void result) {
152                 LOG.debug("Modules state successfully updated.");
153             }
154
155             @Override
156             public void onFailure(final Throwable throwable) {
157                 LOG.warn("Unable to update modules state", throwable);
158             }
159         });
160     }
161
162
163
164     private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
165         return new Uri("http://" + bindingAddress + ':' + bindingPort + "/yanglib/schemas/"
166                 + sourceIdentifier.getName() + '/' + revString(sourceIdentifier));
167     }
168
169     private static String revString(final SourceIdentifier id) {
170         final String rev = id.getRevision();
171         return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? "" : rev;
172     }
173
174     private static OptionalRevision getRevisionForModule(final SourceIdentifier sourceIdentifier) {
175         final String rev = sourceIdentifier.getRevision();
176         return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? NO_REVISION
177                 : new OptionalRevision(new RevisionIdentifier(rev));
178     }
179
180     private <T> T getObjectFromBundleContext(final Class<T> type, final String serviceRefName) {
181         final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
182         final ServiceReference<?> serviceReference = bundleContext.getServiceReference(serviceRefName);
183         return (T) bundleContext.getService(serviceReference);
184     }
185 }