Upgrade ietf-{inet,yang}-types to 2013-07-15
[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 Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE = new Predicate<PotentialSchemaSource<?>>() {
58         @Override
59         public boolean apply(final PotentialSchemaSource<?> input) {
60             // filter out non yang sources
61             return YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
62         }
63     };
64
65     protected DataBroker dataBroker;
66     protected SchemaListenerRegistration schemaListenerRegistration;
67     protected final SharedSchemaRepository schemaRepository;
68     private final String bindingAddress;
69     private final long bindingPort;
70
71     public YangLibProvider(final SharedSchemaRepository schemaRepository,
72                            final String bindingAddress, final long bindingPort) {
73         this.schemaRepository = schemaRepository;
74         this.bindingAddress = bindingAddress;
75         this.bindingPort = bindingPort;
76     }
77
78     @Override
79     public void close() throws Exception {
80         dataBroker = null;
81         schemaListenerRegistration.close();
82     }
83
84     @Override
85     public void onSessionInitiated(final BindingAwareBroker.ProviderContext providerContext) {
86         this.dataBroker = providerContext.getSALService(DataBroker.class);
87         schemaListenerRegistration = schemaRepository.registerSchemaSourceListener(this);
88         getObjectFromBundleContext(YangLibRestAppService.class, YangLibRestAppService.class.getName())
89         .getYangLibService().setSchemaRepository(schemaRepository);
90     }
91
92     @Override
93     public void schemaSourceEncountered(final SchemaSourceRepresentation source) {
94         // NOOP
95     }
96
97     @Override
98     public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
99         final List<Module> newModules = new ArrayList<>();
100
101         for(PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
102             final YangIdentifier moduleName = new YangIdentifier(potentialYangSource.getSourceIdentifier().getName());
103
104             final OptionalRevision moduleRevision = getRevisionForModule(potentialYangSource.getSourceIdentifier());
105
106             final Module newModule = new ModuleBuilder()
107                     .setName(moduleName)
108                     .setRevision(moduleRevision)
109                     .setSchema(getUrlForModule(potentialYangSource.getSourceIdentifier()))
110                     .build();
111
112             newModules.add(newModule);
113         }
114
115         if(newModules.isEmpty()) {
116             // If no new yang modules then do nothing
117             return;
118         }
119
120         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
121         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(ModulesState.class),
122                 new ModulesStateBuilder().setModule(newModules).build());
123
124         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
125             @Override
126             public void onSuccess(@Nullable Void result) {
127                 LOG.debug("Modules state successfully populated with new modules");
128             }
129
130             @Override
131             public void onFailure(Throwable t) {
132                 LOG.warn("Unable to update modules state", t);
133             }
134         });
135     }
136
137     @Override
138     public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
139         if(!YANG_SCHEMA_SOURCE.apply(source)) {
140             // if representation of potential schema source is not yang text schema source do nothing
141             // we do not want to delete this module entry from module list
142             return;
143         }
144
145         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
146         tx.delete(LogicalDatastoreType.OPERATIONAL,
147                 InstanceIdentifier.create(ModulesState.class)
148                         .child(Module.class,
149                                 new ModuleKey(
150                                         new YangIdentifier(source.getSourceIdentifier().getName()),
151                                         getRevisionForModule(source.getSourceIdentifier()))));
152
153         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
154             @Override
155             public void onSuccess(@Nullable Void result) {
156                 LOG.debug("Modules state successfully updated.");
157             }
158
159             @Override
160             public void onFailure(Throwable t) {
161                 LOG.warn("Unable to update modules state", t);
162             }
163         });
164     }
165
166     private Uri getUrlForModule(final SourceIdentifier sourceIdentifier) {
167         final String revision = sourceIdentifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION)
168                 ? "" : sourceIdentifier.getRevision();
169         return new Uri("http://" + bindingAddress + ":" + bindingPort
170                 + "/yanglib/schemas/" + sourceIdentifier.getName() + "/" + revision);
171     }
172
173     private OptionalRevision getRevisionForModule(final SourceIdentifier sourceIdentifier) {
174         return sourceIdentifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION)
175                 ? new OptionalRevision("")
176                 : new OptionalRevision(new RevisionIdentifier(sourceIdentifier.getRevision()));
177     }
178
179     private <T> T getObjectFromBundleContext(final Class<T> type, final String serviceRefName) {
180         final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
181         final ServiceReference<?> serviceReference = bundleContext.getServiceReference(serviceRefName);
182         return (T) bundleContext.getService(serviceReference);
183     }
184 }