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.controller.sal.dom.broker;
10 import static com.google.common.base.Preconditions.checkState;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.Iterables;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.Enumeration;
20 import java.util.List;
21 import java.util.concurrent.atomic.AtomicReference;
22 import javax.annotation.concurrent.GuardedBy;
23 import org.opendaylight.controller.sal.core.api.model.SchemaService;
24 import org.opendaylight.yangtools.concepts.ListenerRegistration;
25 import org.opendaylight.yangtools.concepts.Registration;
26 import org.opendaylight.yangtools.util.ListenerRegistry;
27 import org.opendaylight.yangtools.yang.model.api.Module;
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.URLSchemaContextResolver;
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 GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, AutoCloseable {
44 private static final Logger LOG = LoggerFactory.getLogger(GlobalBundleScanningSchemaServiceImpl.class);
46 private static AtomicReference<GlobalBundleScanningSchemaServiceImpl> globalInstance = new AtomicReference<>();
48 @GuardedBy(value = "lock")
49 private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
50 private final URLSchemaContextResolver contextResolver = URLSchemaContextResolver.create("global-bundle");
51 private final BundleScanner scanner = new BundleScanner();
52 private final BundleContext context;
54 private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
55 private BundleTracker<Iterable<Registration>> bundleTracker;
56 private boolean starting = true;
57 private volatile boolean stopping;
58 private final Object lock = new Object();
60 private GlobalBundleScanningSchemaServiceImpl(final BundleContext context) {
61 this.context = Preconditions.checkNotNull(context);
64 public static GlobalBundleScanningSchemaServiceImpl createInstance(final BundleContext ctx) {
65 GlobalBundleScanningSchemaServiceImpl instance = new GlobalBundleScanningSchemaServiceImpl(ctx);
66 Preconditions.checkState(globalInstance.compareAndSet(null, instance));
71 public static GlobalBundleScanningSchemaServiceImpl getInstance() {
72 GlobalBundleScanningSchemaServiceImpl instance = globalInstance.get();
73 Preconditions.checkState(instance != null, "Global Instance was not instantiated");
78 public static void destroyInstance() {
79 GlobalBundleScanningSchemaServiceImpl instance = globalInstance.getAndSet(null);
80 if(instance != null) {
85 public BundleContext getContext() {
90 checkState(context != null);
91 LOG.debug("start() starting");
93 listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, GlobalBundleScanningSchemaServiceImpl.this);
94 bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING |
95 Bundle.STOPPING | Bundle.ACTIVE, scanner);
100 LOG.debug("BundleTracker.open() complete");
102 boolean hasExistingListeners = Iterables.size(listeners.getListeners()) > 0;
103 if(hasExistingListeners) {
104 tryToUpdateSchemaContext();
108 listenerTracker.open();
111 LOG.debug("start() complete");
115 public SchemaContext getSchemaContext() {
116 return getGlobalContext();
120 public SchemaContext getGlobalContext() {
121 return contextResolver.getSchemaContext().orNull();
125 public void addModule(final Module module) {
126 throw new UnsupportedOperationException();
130 public SchemaContext getSessionContext() {
131 throw new UnsupportedOperationException();
135 public void removeModule(final Module module) {
136 throw new UnsupportedOperationException();
140 public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
142 Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
143 if(potentialCtx.isPresent()) {
144 listener.onGlobalContextUpdated(potentialCtx.get());
146 return listeners.register(listener);
151 public void close() {
153 if (bundleTracker != null) {
154 bundleTracker.close();
156 if (listenerTracker != null) {
157 listenerTracker.close();
160 for (ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
165 @GuardedBy(value = "lock")
166 private void notifyListeners(final SchemaContext snapshot) {
167 Object[] services = listenerTracker.getServices();
168 for (ListenerRegistration<SchemaContextListener> listener : listeners) {
170 listener.getInstance().onGlobalContextUpdated(snapshot);
171 } catch (Exception e) {
172 LOG.error("Exception occured during invoking listener", e);
175 if (services != null) {
176 for (Object rawListener : services) {
177 final SchemaContextListener listener = (SchemaContextListener) rawListener;
179 listener.onGlobalContextUpdated(snapshot);
180 } catch (Exception e) {
181 LOG.error("Exception occured during invoking listener {}", listener, e);
187 private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
189 public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
191 if (bundle.getBundleId() == 0) {
192 return Collections.emptyList();
195 final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
196 if (enumeration == null) {
197 return Collections.emptyList();
200 final List<Registration> urls = new ArrayList<>();
201 while (enumeration.hasMoreElements()) {
202 final URL u = enumeration.nextElement();
204 urls.add(contextResolver.registerSource(u));
205 LOG.debug("Registered {}", u);
206 } catch (Exception e) {
207 LOG.warn("Failed to register {}, ignoring it", e);
211 if (!urls.isEmpty()) {
212 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
213 urls.size(), bundle.getSymbolicName());
214 tryToUpdateSchemaContext();
217 return ImmutableList.copyOf(urls);
221 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
225 * If removing YANG files makes yang store inconsistent, method
226 * {@link #getYangStoreSnapshot()} will throw exception. There is no
231 public void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
232 for (Registration url : urls) {
235 } catch (Exception e) {
236 LOG.warn("Failed do unregister URL {}, proceeding", url, e);
240 int numUrls = Iterables.size(urls);
242 if(LOG.isDebugEnabled()) {
243 LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(), bundle.getState(), numUrls);
246 tryToUpdateSchemaContext();
252 public SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
254 SchemaContextListener listener = context.getService(reference);
255 SchemaContext _ctxContext = getGlobalContext();
256 if (getContext() != null && _ctxContext != null) {
257 listener.onGlobalContextUpdated(_ctxContext);
262 public void tryToUpdateSchemaContext() {
263 if (starting || stopping) {
268 Optional<SchemaContext> schema = contextResolver.getSchemaContext();
269 if(schema.isPresent()) {
270 if(LOG.isDebugEnabled()) {
271 LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
274 notifyListeners(schema.get());
280 public void modifiedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
285 public void removedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
286 context.ungetService(reference);