2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.sal.dom.broker;
10 import static com.google.common.base.Preconditions.checkState;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Iterables;
17 import com.google.common.util.concurrent.CheckedFuture;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Enumeration;
22 import java.util.List;
23 import java.util.concurrent.atomic.AtomicReference;
24 import javax.annotation.concurrent.GuardedBy;
25 import org.opendaylight.controller.sal.core.api.model.SchemaService;
26 import org.opendaylight.controller.sal.core.api.model.YangTextSourceProvider;
27 import org.opendaylight.yangtools.concepts.ListenerRegistration;
28 import org.opendaylight.yangtools.concepts.Registration;
29 import org.opendaylight.yangtools.util.ListenerRegistry;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
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.parser.repo.URLSchemaContextResolver;
38 import org.osgi.framework.Bundle;
39 import org.osgi.framework.BundleContext;
40 import org.osgi.framework.BundleEvent;
41 import org.osgi.framework.ServiceReference;
42 import org.osgi.util.tracker.BundleTracker;
43 import org.osgi.util.tracker.BundleTrackerCustomizer;
44 import org.osgi.util.tracker.ServiceTracker;
45 import org.osgi.util.tracker.ServiceTrackerCustomizer;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, YangTextSourceProvider, AutoCloseable {
50 private static final Logger LOG = LoggerFactory.getLogger(GlobalBundleScanningSchemaServiceImpl.class);
52 private static AtomicReference<GlobalBundleScanningSchemaServiceImpl> globalInstance = new AtomicReference<>();
54 @GuardedBy(value = "lock")
55 private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
56 private final URLSchemaContextResolver contextResolver = URLSchemaContextResolver.create("global-bundle");
57 private final BundleScanner scanner = new BundleScanner();
58 private final BundleContext context;
60 private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
61 private BundleTracker<Iterable<Registration>> bundleTracker;
62 private boolean starting = true;
63 private volatile boolean stopping;
64 private final Object lock = new Object();
66 private GlobalBundleScanningSchemaServiceImpl(final BundleContext context) {
67 this.context = Preconditions.checkNotNull(context);
70 public static GlobalBundleScanningSchemaServiceImpl createInstance(final BundleContext ctx) {
71 GlobalBundleScanningSchemaServiceImpl instance = new GlobalBundleScanningSchemaServiceImpl(ctx);
72 Preconditions.checkState(globalInstance.compareAndSet(null, instance));
77 public static GlobalBundleScanningSchemaServiceImpl getInstance() {
78 GlobalBundleScanningSchemaServiceImpl instance = globalInstance.get();
79 Preconditions.checkState(instance != null, "Global Instance was not instantiated");
84 public static void destroyInstance() {
85 GlobalBundleScanningSchemaServiceImpl instance = globalInstance.getAndSet(null);
86 if(instance != null) {
91 public BundleContext getContext() {
96 checkState(context != null);
97 LOG.debug("start() starting");
99 listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, GlobalBundleScanningSchemaServiceImpl.this);
100 bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING |
101 Bundle.STOPPING | Bundle.ACTIVE, scanner);
104 bundleTracker.open();
106 LOG.debug("BundleTracker.open() complete");
108 boolean hasExistingListeners = Iterables.size(listeners.getListeners()) > 0;
109 if(hasExistingListeners) {
110 tryToUpdateSchemaContext();
114 listenerTracker.open();
117 LOG.debug("start() complete");
121 public SchemaContext getSchemaContext() {
122 return getGlobalContext();
126 public SchemaContext getGlobalContext() {
127 return contextResolver.getSchemaContext().orNull();
131 public void addModule(final Module module) {
132 throw new UnsupportedOperationException();
136 public SchemaContext getSessionContext() {
137 throw new UnsupportedOperationException();
141 public void removeModule(final Module module) {
142 throw new UnsupportedOperationException();
146 public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
148 Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
149 if(potentialCtx.isPresent()) {
150 listener.onGlobalContextUpdated(potentialCtx.get());
152 return listeners.register(listener);
157 public void close() {
159 if (bundleTracker != null) {
160 bundleTracker.close();
162 if (listenerTracker != null) {
163 listenerTracker.close();
166 for (ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
171 @GuardedBy(value = "lock")
172 private void notifyListeners(final SchemaContext snapshot) {
173 Object[] services = listenerTracker.getServices();
174 for (ListenerRegistration<SchemaContextListener> listener : listeners) {
176 listener.getInstance().onGlobalContextUpdated(snapshot);
177 } catch (Exception e) {
178 LOG.error("Exception occured during invoking listener", e);
181 if (services != null) {
182 for (Object rawListener : services) {
183 final SchemaContextListener listener = (SchemaContextListener) rawListener;
185 listener.onGlobalContextUpdated(snapshot);
186 } catch (Exception e) {
187 LOG.error("Exception occured during invoking listener {}", listener, e);
194 public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
195 return contextResolver.getSource(sourceIdentifier);
199 private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
201 public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
203 if (bundle.getBundleId() == 0) {
204 return Collections.emptyList();
207 final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
208 if (enumeration == null) {
209 return Collections.emptyList();
212 final List<Registration> urls = new ArrayList<>();
213 while (enumeration.hasMoreElements()) {
214 final URL u = enumeration.nextElement();
216 urls.add(contextResolver.registerSource(u));
217 LOG.debug("Registered {}", u);
218 } catch (Exception e) {
219 LOG.warn("Failed to register {}, ignoring it", e);
223 if (!urls.isEmpty()) {
224 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
225 urls.size(), bundle.getSymbolicName());
226 tryToUpdateSchemaContext();
229 return ImmutableList.copyOf(urls);
233 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
237 * If removing YANG files makes yang store inconsistent, method
238 * {@link #getYangStoreSnapshot()} will throw exception. There is no
243 public void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
244 for (Registration url : urls) {
247 } catch (Exception e) {
248 LOG.warn("Failed do unregister URL {}, proceeding", url, e);
252 int numUrls = Iterables.size(urls);
254 if(LOG.isDebugEnabled()) {
255 LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(), bundle.getState(), numUrls);
258 tryToUpdateSchemaContext();
264 public SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
266 SchemaContextListener listener = context.getService(reference);
267 SchemaContext _ctxContext = getGlobalContext();
268 if (getContext() != null && _ctxContext != null) {
269 listener.onGlobalContextUpdated(_ctxContext);
274 public void tryToUpdateSchemaContext() {
275 if (starting || stopping) {
280 Optional<SchemaContext> schema = contextResolver.getSchemaContext();
281 if(schema.isPresent()) {
282 if(LOG.isDebugEnabled()) {
283 LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
286 notifyListeners(schema.get());
292 public void modifiedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
297 public void removedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
298 context.ungetService(reference);