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 final AtomicReference<OsgiBundleScanningSchemaService> GLOBAL_INSTANCE = new AtomicReference<>();
49 private static final long FRAMEWORK_BUNDLE_ID = 0;
52 private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
53 private final YangTextSchemaContextResolver contextResolver = YangTextSchemaContextResolver.create("global-bundle");
54 private final BundleScanner scanner = new BundleScanner();
55 private final Object lock = new Object();
56 private final BundleContext context;
58 private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
59 private BundleTracker<Iterable<Registration>> bundleTracker;
60 private boolean starting = true;
62 private volatile boolean stopping;
64 private OsgiBundleScanningSchemaService(final BundleContext context) {
65 this.context = Preconditions.checkNotNull(context);
68 public static OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
69 OsgiBundleScanningSchemaService instance = new OsgiBundleScanningSchemaService(ctx);
70 Preconditions.checkState(GLOBAL_INSTANCE.compareAndSet(null, instance));
75 public static OsgiBundleScanningSchemaService getInstance() {
76 OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.get();
77 Preconditions.checkState(instance != null, "Global Instance was not instantiated");
82 public static void destroyInstance() {
83 OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.getAndSet(null);
84 if (instance != null) {
89 public BundleContext getContext() {
93 private void start() {
94 checkState(context != null);
95 LOG.debug("start() starting");
97 listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, this);
98 bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING
99 | Bundle.STOPPING | Bundle.ACTIVE, scanner);
101 synchronized (lock) {
102 bundleTracker.open();
104 LOG.debug("BundleTracker.open() complete");
106 if (Iterables.size(listeners.getListeners()) > 0) {
107 tryToUpdateSchemaContext();
111 listenerTracker.open();
114 LOG.debug("start() complete");
118 public SchemaContext getSchemaContext() {
119 return getGlobalContext();
123 public SchemaContext getGlobalContext() {
124 return contextResolver.getSchemaContext().orNull();
128 public SchemaContext getSessionContext() {
129 throw new UnsupportedOperationException();
133 public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
134 final SchemaContextListener listener) {
135 synchronized (lock) {
136 final Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
137 if (potentialCtx.isPresent()) {
138 listener.onGlobalContextUpdated(potentialCtx.get());
140 return listeners.register(listener);
145 public void close() {
146 synchronized (lock) {
148 if (bundleTracker != null) {
149 bundleTracker.close();
150 bundleTracker = null;
152 if (listenerTracker != null) {
153 listenerTracker.close();
154 listenerTracker = null;
157 for (final ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
163 @SuppressWarnings("checkstyle:IllegalCatch")
166 void notifyListeners(final SchemaContext snapshot) {
167 final Object[] services = listenerTracker.getServices();
168 for (final ListenerRegistration<SchemaContextListener> listener : listeners) {
170 listener.getInstance().onGlobalContextUpdated(snapshot);
171 } catch (final Exception e) {
172 LOG.error("Exception occured during invoking listener", e);
175 if (services != null) {
176 for (final Object rawListener : services) {
177 final SchemaContextListener listener = (SchemaContextListener) rawListener;
179 listener.onGlobalContextUpdated(snapshot);
180 } catch (final Exception e) {
181 LOG.error("Exception occured during invoking listener {}", listener, e);
187 @SuppressWarnings("checkstyle:IllegalCatch")
188 private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
190 public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
192 if (bundle.getBundleId() == FRAMEWORK_BUNDLE_ID) {
193 return Collections.emptyList();
196 final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
197 if (enumeration == null) {
198 return Collections.emptyList();
201 final List<Registration> urls = new ArrayList<>();
202 while (enumeration.hasMoreElements()) {
203 final URL u = enumeration.nextElement();
205 urls.add(contextResolver.registerSource(u));
206 LOG.debug("Registered {}", u);
207 } catch (final Exception e) {
208 LOG.warn("Failed to register {}, ignoring it", e);
212 if (!urls.isEmpty()) {
213 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
214 urls.size(), bundle.getSymbolicName());
215 tryToUpdateSchemaContext();
218 return ImmutableList.copyOf(urls);
222 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
223 if (bundle.getBundleId() == FRAMEWORK_BUNDLE_ID) {
224 LOG.debug("Framework bundle {} got event {}", bundle, event.getType());
225 if ((event.getType() & BundleEvent.STOPPING) != 0) {
226 LOG.info("OSGi framework is being stopped, halting bundle scanning");
233 * If removing YANG files makes yang store inconsistent, method
234 * {@link #getYangStoreSnapshot()} will throw exception. There is no
237 @SuppressWarnings("checkstyle:IllegalCatch")
239 public void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
240 for (final Registration url : urls) {
243 } catch (final Exception e) {
244 LOG.warn("Failed do unregister URL {}, proceeding", url, e);
248 final int numUrls = Iterables.size(urls);
250 if (LOG.isDebugEnabled()) {
251 LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(),
252 bundle.getState(), numUrls);
255 tryToUpdateSchemaContext();
261 public SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
263 final SchemaContextListener listener = context.getService(reference);
264 final SchemaContext ctxContext = getGlobalContext();
265 if (getContext() != null && ctxContext != null) {
266 listener.onGlobalContextUpdated(ctxContext);
271 public void tryToUpdateSchemaContext() {
272 if (starting || stopping) {
276 synchronized (lock) {
277 final Optional<SchemaContext> schema = contextResolver.getSchemaContext();
278 if (schema.isPresent()) {
279 if (LOG.isDebugEnabled()) {
280 LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
283 notifyListeners(schema.get());
289 public void modifiedService(final ServiceReference<SchemaContextListener> reference,
290 final SchemaContextListener service) {
295 public void removedService(final ServiceReference<SchemaContextListener> reference,
296 final SchemaContextListener service) {
297 context.ungetService(reference);