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 org.opendaylight.mdsal.dom.api.DOMSchemaService;
23 import org.opendaylight.yangtools.concepts.ListenerRegistration;
24 import org.opendaylight.yangtools.concepts.Registration;
25 import org.opendaylight.yangtools.util.ListenerRegistry;
26 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
27 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
29 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
30 import org.osgi.framework.Bundle;
31 import org.osgi.framework.BundleContext;
32 import org.osgi.framework.BundleEvent;
33 import org.osgi.framework.ServiceReference;
34 import org.osgi.util.tracker.BundleTracker;
35 import org.osgi.util.tracker.BundleTrackerCustomizer;
36 import org.osgi.util.tracker.ServiceTracker;
37 import org.osgi.util.tracker.ServiceTrackerCustomizer;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 public class OsgiBundleScanningSchemaService implements SchemaContextProvider, DOMSchemaService,
42 ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, AutoCloseable {
43 private static final Logger LOG = LoggerFactory.getLogger(OsgiBundleScanningSchemaService.class);
45 private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
46 private final YangTextSchemaContextResolver contextResolver = YangTextSchemaContextResolver.create("global-bundle");
47 private final BundleScanner scanner = new BundleScanner();
48 private final BundleContext context;
50 private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
51 private BundleTracker<Iterable<Registration>> bundleTracker;
52 private boolean starting = true;
53 private volatile boolean stopping;
54 private static OsgiBundleScanningSchemaService instance;
56 private OsgiBundleScanningSchemaService(final BundleContext context) {
57 this.context = Preconditions.checkNotNull(context);
60 public static synchronized OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
61 Preconditions.checkState(instance == null);
62 instance = new OsgiBundleScanningSchemaService(ctx);
67 public static synchronized OsgiBundleScanningSchemaService getInstance() {
68 Preconditions.checkState(instance != null, "Global Instance was not instantiated");
73 public static synchronized void destroyInstance() {
81 public BundleContext getContext() {
86 checkState(context != null);
87 LOG.debug("start() starting");
89 listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class,
90 OsgiBundleScanningSchemaService.this);
91 bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING
93 Bundle.STOPPING | Bundle.ACTIVE, scanner);
96 LOG.debug("BundleTracker.open() complete");
98 listenerTracker.open();
100 tryToUpdateSchemaContext();
102 LOG.debug("start() complete");
106 public SchemaContext getSchemaContext() {
107 return getGlobalContext();
111 public SchemaContext getGlobalContext() {
112 return contextResolver.getSchemaContext().orNull();
116 public SchemaContext getSessionContext() {
117 throw new UnsupportedOperationException();
121 public synchronized ListenerRegistration<SchemaContextListener>
122 registerSchemaContextListener(final SchemaContextListener listener) {
123 final Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
124 if (potentialCtx.isPresent()) {
125 listener.onGlobalContextUpdated(potentialCtx.get());
127 return listeners.register(listener);
131 public void close() {
133 if (bundleTracker != null) {
134 bundleTracker.close();
136 if (listenerTracker != null) {
137 listenerTracker.close();
140 for (final ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
145 @SuppressWarnings("checkstyle:IllegalCatch")
146 private synchronized void updateContext(final SchemaContext snapshot) {
147 final Object[] services = listenerTracker.getServices();
148 for (final ListenerRegistration<SchemaContextListener> listener : listeners) {
150 listener.getInstance().onGlobalContextUpdated(snapshot);
151 } catch (final Exception e) {
152 LOG.error("Exception occured during invoking listener", e);
155 if (services != null) {
156 for (final Object rawListener : services) {
157 final SchemaContextListener listener = (SchemaContextListener) rawListener;
159 listener.onGlobalContextUpdated(snapshot);
160 } catch (final Exception e) {
161 LOG.error("Exception occured during invoking listener {}", listener, e);
167 @SuppressWarnings("checkstyle:IllegalCatch")
168 private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
170 public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
172 if (bundle.getBundleId() == 0) {
173 return Collections.emptyList();
176 final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
177 if (enumeration == null) {
178 return Collections.emptyList();
181 final List<Registration> urls = new ArrayList<>();
182 while (enumeration.hasMoreElements()) {
183 final URL u = enumeration.nextElement();
185 urls.add(contextResolver.registerSource(u));
186 LOG.debug("Registered {}", u);
187 } catch (final Exception e) {
188 LOG.warn("Failed to register {}, ignoring it", e);
192 if (!urls.isEmpty()) {
193 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
194 urls.size(), bundle.getSymbolicName());
195 tryToUpdateSchemaContext();
198 return ImmutableList.copyOf(urls);
202 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
206 * If removing YANG files makes yang store inconsistent, method
207 * {@link #getYangStoreSnapshot()} will throw exception. There is no
210 @SuppressWarnings("checkstyle:IllegalCatch")
212 public synchronized void removedBundle(final Bundle bundle, final BundleEvent event,
213 final Iterable<Registration> urls) {
214 for (final Registration url : urls) {
217 } catch (final Exception e) {
218 LOG.warn("Failed do unregister URL {}, proceeding", url, e);
222 final int numUrls = Iterables.size(urls);
224 if (LOG.isDebugEnabled()) {
225 LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(),
226 bundle.getState(), numUrls);
229 tryToUpdateSchemaContext();
235 public synchronized SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
237 final SchemaContextListener listener = context.getService(reference);
238 final SchemaContext ctxContext = getGlobalContext();
239 if (getContext() != null && ctxContext != null) {
240 listener.onGlobalContextUpdated(ctxContext);
245 public synchronized void tryToUpdateSchemaContext() {
246 if (starting || stopping) {
249 final Optional<SchemaContext> schema = contextResolver.getSchemaContext();
250 if (schema.isPresent()) {
251 if (LOG.isDebugEnabled()) {
252 LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
255 updateContext(schema.get());
260 public void modifiedService(final ServiceReference<SchemaContextListener> reference,
261 final SchemaContextListener service) {
266 public void removedService(final ServiceReference<SchemaContextListener> reference,
267 final SchemaContextListener service) {
268 context.ungetService(reference);