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 static OsgiBundleScanningSchemaService instance;
55 private OsgiBundleScanningSchemaService(final BundleContext context) {
56 this.context = Preconditions.checkNotNull(context);
59 public static synchronized OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
60 Preconditions.checkState(instance == null);
61 instance = new OsgiBundleScanningSchemaService(ctx);
66 public static synchronized OsgiBundleScanningSchemaService getInstance() {
67 Preconditions.checkState(instance != null, "Global Instance was not instantiated");
72 public static synchronized void destroyInstance() {
80 public BundleContext getContext() {
85 checkState(context != null);
86 LOG.debug("start() starting");
88 listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class,
89 OsgiBundleScanningSchemaService.this);
90 bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING
92 Bundle.STOPPING | Bundle.ACTIVE, scanner);
95 LOG.debug("BundleTracker.open() complete");
97 listenerTracker.open();
99 tryToUpdateSchemaContext();
101 LOG.debug("start() complete");
105 public SchemaContext getSchemaContext() {
106 return getGlobalContext();
110 public SchemaContext getGlobalContext() {
111 return contextResolver.getSchemaContext().orNull();
115 public SchemaContext getSessionContext() {
116 throw new UnsupportedOperationException();
120 public synchronized ListenerRegistration<SchemaContextListener>
121 registerSchemaContextListener(final SchemaContextListener listener) {
122 final Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
123 if (potentialCtx.isPresent()) {
124 listener.onGlobalContextUpdated(potentialCtx.get());
126 return listeners.register(listener);
130 public void close() {
131 if (bundleTracker != null) {
132 bundleTracker.close();
134 if (listenerTracker != null) {
135 listenerTracker.close();
138 for (final ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
143 @SuppressWarnings("checkstyle:IllegalCatch")
144 private synchronized void updateContext(final SchemaContext snapshot) {
145 final Object[] services = listenerTracker.getServices();
146 for (final ListenerRegistration<SchemaContextListener> listener : listeners) {
148 listener.getInstance().onGlobalContextUpdated(snapshot);
149 } catch (final Exception e) {
150 LOG.error("Exception occured during invoking listener", e);
153 if (services != null) {
154 for (final Object rawListener : services) {
155 final SchemaContextListener listener = (SchemaContextListener) rawListener;
157 listener.onGlobalContextUpdated(snapshot);
158 } catch (final Exception e) {
159 LOG.error("Exception occured during invoking listener {}", listener, e);
165 @SuppressWarnings("checkstyle:IllegalCatch")
166 private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
168 public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
170 if (bundle.getBundleId() == 0) {
171 return Collections.emptyList();
174 final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
175 if (enumeration == null) {
176 return Collections.emptyList();
179 final List<Registration> urls = new ArrayList<>();
180 while (enumeration.hasMoreElements()) {
181 final URL u = enumeration.nextElement();
183 urls.add(contextResolver.registerSource(u));
184 LOG.debug("Registered {}", u);
185 } catch (final Exception e) {
186 LOG.warn("Failed to register {}, ignoring it", e);
190 if (!urls.isEmpty()) {
191 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
192 urls.size(), bundle.getSymbolicName());
193 tryToUpdateSchemaContext();
196 return ImmutableList.copyOf(urls);
200 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
204 * If removing YANG files makes yang store inconsistent, method
205 * {@link #getYangStoreSnapshot()} will throw exception. There is no
208 @SuppressWarnings("checkstyle:IllegalCatch")
210 public synchronized void removedBundle(final Bundle bundle, final BundleEvent event,
211 final Iterable<Registration> urls) {
212 for (final Registration url : urls) {
215 } catch (final Exception e) {
216 LOG.warn("Failed do unregister URL {}, proceeding", url, e);
220 final int numUrls = Iterables.size(urls);
222 if (LOG.isDebugEnabled()) {
223 LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(),
224 bundle.getState(), numUrls);
227 tryToUpdateSchemaContext();
233 public synchronized SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
235 final SchemaContextListener listener = context.getService(reference);
236 final SchemaContext _ctxContext = getGlobalContext();
237 if (getContext() != null && _ctxContext != null) {
238 listener.onGlobalContextUpdated(_ctxContext);
243 public synchronized void tryToUpdateSchemaContext() {
247 final Optional<SchemaContext> schema = contextResolver.getSchemaContext();
248 if (schema.isPresent()) {
249 if (LOG.isDebugEnabled()) {
250 LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
253 updateContext(schema.get());
258 public void modifiedService(final ServiceReference<SchemaContextListener> reference,
259 final SchemaContextListener service) {
264 public void removedService(final ServiceReference<SchemaContextListener> reference,
265 final SchemaContextListener service) {
266 context.ungetService(reference);