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.mdsal.dom.broker.osgi;
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;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Enumeration;
21 import java.util.List;
22 import java.util.concurrent.atomic.AtomicReference;
23 import javax.annotation.concurrent.GuardedBy;
24 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
25 import org.opendaylight.yangtools.concepts.ListenerRegistration;
26 import org.opendaylight.yangtools.concepts.Registration;
27 import org.opendaylight.yangtools.util.ListenerRegistry;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
31 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
32 import org.osgi.framework.Bundle;
33 import org.osgi.framework.BundleContext;
34 import org.osgi.framework.BundleEvent;
35 import org.osgi.framework.ServiceReference;
36 import org.osgi.util.tracker.BundleTracker;
37 import org.osgi.util.tracker.BundleTrackerCustomizer;
38 import org.osgi.util.tracker.ServiceTracker;
39 import org.osgi.util.tracker.ServiceTrackerCustomizer;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 public class OsgiBundleScanningSchemaService implements SchemaContextProvider, DOMSchemaService,
44 ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, AutoCloseable {
45 private static final Logger LOG = LoggerFactory.getLogger(OsgiBundleScanningSchemaService.class);
47 private static AtomicReference<OsgiBundleScanningSchemaService> globalInstance = new AtomicReference<>();
49 @GuardedBy(value = "lock")
50 private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
51 private final YangTextSchemaContextResolver contextResolver = YangTextSchemaContextResolver.create("global-bundle");
52 private final BundleScanner scanner = new BundleScanner();
53 private final BundleContext context;
55 private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
56 private BundleTracker<Iterable<Registration>> bundleTracker;
57 private boolean starting = true;
58 private volatile boolean stopping;
59 private final Object lock = new Object();
61 private OsgiBundleScanningSchemaService(final BundleContext context) {
62 this.context = Preconditions.checkNotNull(context);
65 public static OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
66 OsgiBundleScanningSchemaService instance = new OsgiBundleScanningSchemaService(ctx);
67 Preconditions.checkState(globalInstance.compareAndSet(null, instance));
72 public static OsgiBundleScanningSchemaService getInstance() {
73 OsgiBundleScanningSchemaService instance = globalInstance.get();
74 Preconditions.checkState(instance != null, "Global Instance was not instantiated");
79 public static void destroyInstance() {
80 OsgiBundleScanningSchemaService instance = globalInstance.getAndSet(null);
81 if (instance != null) {
86 public BundleContext getContext() {
90 private void start() {
91 checkState(context != null);
92 LOG.debug("start() starting");
94 listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class,
95 OsgiBundleScanningSchemaService.this);
96 bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING
97 | Bundle.STOPPING | Bundle.ACTIVE, scanner);
100 bundleTracker.open();
102 LOG.debug("BundleTracker.open() complete");
104 boolean hasExistingListeners = Iterables.size(listeners.getListeners()) > 0;
105 if (hasExistingListeners) {
106 tryToUpdateSchemaContext();
110 listenerTracker.open();
113 LOG.debug("start() complete");
117 public SchemaContext getSchemaContext() {
118 return getGlobalContext();
122 public SchemaContext getGlobalContext() {
123 return contextResolver.getSchemaContext().orNull();
127 public SchemaContext getSessionContext() {
128 throw new UnsupportedOperationException();
132 public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
133 final SchemaContextListener listener) {
134 synchronized (lock) {
135 final Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
136 if (potentialCtx.isPresent()) {
137 listener.onGlobalContextUpdated(potentialCtx.get());
139 return listeners.register(listener);
144 public void close() {
146 if (bundleTracker != null) {
147 bundleTracker.close();
149 if (listenerTracker != null) {
150 listenerTracker.close();
153 for (final ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
158 @SuppressWarnings("checkstyle:IllegalCatch")
160 @GuardedBy(value = "lock")
161 void notifyListeners(final SchemaContext snapshot) {
162 final Object[] services = listenerTracker.getServices();
163 for (final ListenerRegistration<SchemaContextListener> listener : listeners) {
165 listener.getInstance().onGlobalContextUpdated(snapshot);
166 } catch (final Exception e) {
167 LOG.error("Exception occured during invoking listener", e);
170 if (services != null) {
171 for (final Object rawListener : services) {
172 final SchemaContextListener listener = (SchemaContextListener) rawListener;
174 listener.onGlobalContextUpdated(snapshot);
175 } catch (final Exception e) {
176 LOG.error("Exception occured during invoking listener {}", listener, e);
182 @SuppressWarnings("checkstyle:IllegalCatch")
183 private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
185 public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
187 if (bundle.getBundleId() == 0) {
188 return Collections.emptyList();
191 final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
192 if (enumeration == null) {
193 return Collections.emptyList();
196 final List<Registration> urls = new ArrayList<>();
197 while (enumeration.hasMoreElements()) {
198 final URL u = enumeration.nextElement();
200 urls.add(contextResolver.registerSource(u));
201 LOG.debug("Registered {}", u);
202 } catch (final Exception e) {
203 LOG.warn("Failed to register {}, ignoring it", e);
207 if (!urls.isEmpty()) {
208 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
209 urls.size(), bundle.getSymbolicName());
210 tryToUpdateSchemaContext();
213 return ImmutableList.copyOf(urls);
217 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
221 * If removing YANG files makes yang store inconsistent, method
222 * {@link #getYangStoreSnapshot()} will throw exception. There is no
225 @SuppressWarnings("checkstyle:IllegalCatch")
227 public void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
228 for (final Registration url : urls) {
231 } catch (final Exception e) {
232 LOG.warn("Failed do unregister URL {}, proceeding", url, e);
236 final int numUrls = Iterables.size(urls);
238 if (LOG.isDebugEnabled()) {
239 LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(),
240 bundle.getState(), numUrls);
243 tryToUpdateSchemaContext();
249 public SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
251 final SchemaContextListener listener = context.getService(reference);
252 final SchemaContext _ctxContext = getGlobalContext();
253 if (getContext() != null && _ctxContext != null) {
254 listener.onGlobalContextUpdated(_ctxContext);
259 public void tryToUpdateSchemaContext() {
260 if (starting || stopping) {
264 synchronized (lock) {
265 final Optional<SchemaContext> schema = contextResolver.getSchemaContext();
266 if (schema.isPresent()) {
267 if (LOG.isDebugEnabled()) {
268 LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
271 notifyListeners(schema.get());
277 public void modifiedService(final ServiceReference<SchemaContextListener> reference,
278 final SchemaContextListener service) {
283 public void removedService(final ServiceReference<SchemaContextListener> reference,
284 final SchemaContextListener service) {
285 context.ungetService(reference);