Speed up OsgiBundleScanningSchemaService close
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / osgi / OsgiBundleScanningSchemaService.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.dom.broker.osgi;
9
10 import static com.google.common.base.Preconditions.checkState;
11
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;
17 import java.net.URL;
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;
40
41 public class OsgiBundleScanningSchemaService implements SchemaContextProvider, DOMSchemaService,
42         ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, AutoCloseable {
43     private static final Logger LOG = LoggerFactory.getLogger(OsgiBundleScanningSchemaService.class);
44
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;
49
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;
55
56     private OsgiBundleScanningSchemaService(final BundleContext context) {
57         this.context = Preconditions.checkNotNull(context);
58     }
59
60     public static synchronized OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
61         Preconditions.checkState(instance == null);
62         instance = new OsgiBundleScanningSchemaService(ctx);
63         instance.start();
64         return instance;
65     }
66
67     public static synchronized OsgiBundleScanningSchemaService getInstance() {
68         Preconditions.checkState(instance != null, "Global Instance was not instantiated");
69         return instance;
70     }
71
72     @VisibleForTesting
73     public static synchronized void destroyInstance() {
74         try {
75             instance.close();
76         } finally {
77             instance = null;
78         }
79     }
80
81     public BundleContext getContext() {
82         return context;
83     }
84
85     public void start() {
86         checkState(context != null);
87         LOG.debug("start() starting");
88
89         listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class,
90                 OsgiBundleScanningSchemaService.this);
91         bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING
92                 |
93                 Bundle.STOPPING | Bundle.ACTIVE, scanner);
94         bundleTracker.open();
95
96         LOG.debug("BundleTracker.open() complete");
97
98         listenerTracker.open();
99         starting = false;
100         tryToUpdateSchemaContext();
101
102         LOG.debug("start() complete");
103     }
104
105     @Override
106     public SchemaContext getSchemaContext() {
107         return getGlobalContext();
108     }
109
110     @Override
111     public SchemaContext getGlobalContext() {
112         return contextResolver.getSchemaContext().orNull();
113     }
114
115     @Override
116     public SchemaContext getSessionContext() {
117         throw new UnsupportedOperationException();
118     }
119
120     @Override
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());
126         }
127         return listeners.register(listener);
128     }
129
130     @Override
131     public void close() {
132         stopping = true;
133         if (bundleTracker != null) {
134             bundleTracker.close();
135         }
136         if (listenerTracker != null) {
137             listenerTracker.close();
138         }
139
140         for (final ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
141             l.close();
142         }
143     }
144
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) {
149             try {
150                 listener.getInstance().onGlobalContextUpdated(snapshot);
151             } catch (final Exception e) {
152                 LOG.error("Exception occured during invoking listener", e);
153             }
154         }
155         if (services != null) {
156             for (final Object rawListener : services) {
157                 final SchemaContextListener listener = (SchemaContextListener) rawListener;
158                 try {
159                     listener.onGlobalContextUpdated(snapshot);
160                 } catch (final Exception e) {
161                     LOG.error("Exception occured during invoking listener {}", listener, e);
162                 }
163             }
164         }
165     }
166
167     @SuppressWarnings("checkstyle:IllegalCatch")
168     private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
169         @Override
170         public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
171
172             if (bundle.getBundleId() == 0) {
173                 return Collections.emptyList();
174             }
175
176             final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
177             if (enumeration == null) {
178                 return Collections.emptyList();
179             }
180
181             final List<Registration> urls = new ArrayList<>();
182             while (enumeration.hasMoreElements()) {
183                 final URL u = enumeration.nextElement();
184                 try {
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);
189                 }
190             }
191
192             if (!urls.isEmpty()) {
193                 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
194                         urls.size(), bundle.getSymbolicName());
195                 tryToUpdateSchemaContext();
196             }
197
198             return ImmutableList.copyOf(urls);
199         }
200
201         @Override
202         public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
203         }
204
205         /**
206          * If removing YANG files makes yang store inconsistent, method
207          * {@link #getYangStoreSnapshot()} will throw exception. There is no
208          * rollback.
209          */
210         @SuppressWarnings("checkstyle:IllegalCatch")
211         @Override
212         public synchronized void removedBundle(final Bundle bundle, final BundleEvent event,
213                 final Iterable<Registration> urls) {
214             for (final Registration url : urls) {
215                 try {
216                     url.close();
217                 } catch (final Exception e) {
218                     LOG.warn("Failed do unregister URL {}, proceeding", url, e);
219                 }
220             }
221
222             final int numUrls = Iterables.size(urls);
223             if (numUrls > 0 ) {
224                 if (LOG.isDebugEnabled()) {
225                     LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(),
226                             bundle.getState(), numUrls);
227                 }
228
229                 tryToUpdateSchemaContext();
230             }
231         }
232     }
233
234     @Override
235     public synchronized SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
236
237         final SchemaContextListener listener = context.getService(reference);
238         final SchemaContext _ctxContext = getGlobalContext();
239         if (getContext() != null && _ctxContext != null) {
240             listener.onGlobalContextUpdated(_ctxContext);
241         }
242         return listener;
243     }
244
245     public synchronized void tryToUpdateSchemaContext() {
246         if (starting || stopping) {
247             return;
248         }
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());
253             }
254
255             updateContext(schema.get());
256         }
257     }
258
259     @Override
260     public void modifiedService(final ServiceReference<SchemaContextListener> reference,
261             final SchemaContextListener service) {
262         // NOOP
263     }
264
265     @Override
266     public void removedService(final ServiceReference<SchemaContextListener> reference,
267             final SchemaContextListener service) {
268         context.ungetService(reference);
269     }
270 }