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.ImmutableMap;
17 import com.google.common.collect.Iterables;
18 import com.google.common.util.concurrent.CheckedFuture;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.Enumeration;
23 import java.util.List;
25 import java.util.concurrent.atomic.AtomicReference;
26 import javax.annotation.Nonnull;
27 import javax.annotation.concurrent.GuardedBy;
28 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
29 import org.opendaylight.mdsal.dom.api.DOMSchemaServiceExtension;
30 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
31 import org.opendaylight.yangtools.concepts.ListenerRegistration;
32 import org.opendaylight.yangtools.concepts.Registration;
33 import org.opendaylight.yangtools.util.ListenerRegistry;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
37 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
38 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
39 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
40 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
41 import org.osgi.framework.Bundle;
42 import org.osgi.framework.BundleContext;
43 import org.osgi.framework.BundleEvent;
44 import org.osgi.framework.ServiceReference;
45 import org.osgi.util.tracker.BundleTracker;
46 import org.osgi.util.tracker.BundleTrackerCustomizer;
47 import org.osgi.util.tracker.ServiceTracker;
48 import org.osgi.util.tracker.ServiceTrackerCustomizer;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public class OsgiBundleScanningSchemaService implements SchemaContextProvider, DOMSchemaService,
53 ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, DOMYangTextSourceProvider,
55 private static final Logger LOG = LoggerFactory.getLogger(OsgiBundleScanningSchemaService.class);
57 private static final AtomicReference<OsgiBundleScanningSchemaService> GLOBAL_INSTANCE = new AtomicReference<>();
59 private static final long FRAMEWORK_BUNDLE_ID = 0;
62 private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
63 private final YangTextSchemaContextResolver contextResolver = YangTextSchemaContextResolver.create("global-bundle");
64 private final BundleScanner scanner = new BundleScanner();
65 private final Object lock = new Object();
66 private final BundleContext context;
68 private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
69 private BundleTracker<Iterable<Registration>> bundleTracker;
70 private boolean starting = true;
72 private volatile boolean stopping;
74 private OsgiBundleScanningSchemaService(final BundleContext context) {
75 this.context = Preconditions.checkNotNull(context);
78 public static @Nonnull OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
79 OsgiBundleScanningSchemaService instance = new OsgiBundleScanningSchemaService(ctx);
80 Preconditions.checkState(GLOBAL_INSTANCE.compareAndSet(null, instance));
85 public static OsgiBundleScanningSchemaService getInstance() {
86 OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.get();
87 Preconditions.checkState(instance != null, "Global Instance was not instantiated");
92 public static void destroyInstance() {
93 OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.getAndSet(null);
94 if (instance != null) {
99 public BundleContext getContext() {
103 private void start() {
104 checkState(context != null);
105 LOG.debug("start() starting");
107 listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, this);
108 bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING
109 | Bundle.STOPPING | Bundle.ACTIVE, scanner);
111 synchronized (lock) {
112 bundleTracker.open();
114 LOG.debug("BundleTracker.open() complete");
116 if (Iterables.size(listeners.getListeners()) > 0) {
117 tryToUpdateSchemaContext();
121 listenerTracker.open();
124 LOG.debug("start() complete");
128 public SchemaContext getSchemaContext() {
129 return getGlobalContext();
133 public SchemaContext getGlobalContext() {
134 return contextResolver.getSchemaContext().orNull();
138 public SchemaContext getSessionContext() {
139 throw new UnsupportedOperationException();
143 public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
144 final SchemaContextListener listener) {
145 synchronized (lock) {
146 final Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
147 if (potentialCtx.isPresent()) {
148 listener.onGlobalContextUpdated(potentialCtx.get());
150 return listeners.register(listener);
155 public void close() {
156 synchronized (lock) {
158 if (bundleTracker != null) {
159 bundleTracker.close();
160 bundleTracker = null;
162 if (listenerTracker != null) {
163 listenerTracker.close();
164 listenerTracker = null;
167 for (final ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
173 @SuppressWarnings("checkstyle:IllegalCatch")
176 void notifyListeners(final SchemaContext snapshot) {
177 final Object[] services = listenerTracker.getServices();
178 for (final ListenerRegistration<SchemaContextListener> listener : listeners) {
180 listener.getInstance().onGlobalContextUpdated(snapshot);
181 } catch (final Exception e) {
182 LOG.error("Exception occured during invoking listener", e);
185 if (services != null) {
186 for (final Object rawListener : services) {
187 final SchemaContextListener listener = (SchemaContextListener) rawListener;
189 listener.onGlobalContextUpdated(snapshot);
190 } catch (final Exception e) {
191 LOG.error("Exception occured during invoking listener {}", listener, e);
197 @SuppressWarnings("checkstyle:IllegalCatch")
198 private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
200 public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
202 if (bundle.getBundleId() == FRAMEWORK_BUNDLE_ID) {
203 return Collections.emptyList();
206 final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
207 if (enumeration == null) {
208 return Collections.emptyList();
211 final List<Registration> urls = new ArrayList<>();
212 while (enumeration.hasMoreElements()) {
213 final URL u = enumeration.nextElement();
215 urls.add(contextResolver.registerSource(u));
216 LOG.debug("Registered {}", u);
217 } catch (final Exception e) {
218 LOG.warn("Failed to register {}, ignoring it", e);
222 if (!urls.isEmpty()) {
223 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
224 urls.size(), bundle.getSymbolicName());
225 tryToUpdateSchemaContext();
228 return ImmutableList.copyOf(urls);
232 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
233 if (bundle.getBundleId() == FRAMEWORK_BUNDLE_ID) {
234 LOG.debug("Framework bundle {} got event {}", bundle, event.getType());
235 if ((event.getType() & BundleEvent.STOPPING) != 0) {
236 LOG.info("OSGi framework is being stopped, halting bundle scanning");
243 * If removing YANG files makes yang store inconsistent, method
244 * {@link #getYangStoreSnapshot()} will throw exception. There is no
247 @SuppressWarnings("checkstyle:IllegalCatch")
249 public void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
250 for (final Registration url : urls) {
253 } catch (final Exception e) {
254 LOG.warn("Failed do unregister URL {}, proceeding", url, e);
258 final int numUrls = Iterables.size(urls);
260 if (LOG.isDebugEnabled()) {
261 LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(),
262 bundle.getState(), numUrls);
265 tryToUpdateSchemaContext();
271 public SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
273 final SchemaContextListener listener = context.getService(reference);
274 final SchemaContext _ctxContext = getGlobalContext();
275 if (getContext() != null && _ctxContext != null) {
276 listener.onGlobalContextUpdated(_ctxContext);
281 public void tryToUpdateSchemaContext() {
282 if (starting || stopping) {
286 synchronized (lock) {
287 final Optional<SchemaContext> schema = contextResolver.getSchemaContext();
288 if (schema.isPresent()) {
289 if (LOG.isDebugEnabled()) {
290 LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
293 notifyListeners(schema.get());
299 public void modifiedService(final ServiceReference<SchemaContextListener> reference,
300 final SchemaContextListener service) {
305 public void removedService(final ServiceReference<SchemaContextListener> reference,
306 final SchemaContextListener service) {
307 context.ungetService(reference);
311 public Map<Class<? extends DOMSchemaServiceExtension>, DOMSchemaServiceExtension> getSupportedExtensions() {
312 return ImmutableMap.of(DOMYangTextSourceProvider.class, this);
316 public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
317 final SourceIdentifier sourceIdentifier) {
318 return contextResolver.getSource(sourceIdentifier);