98cd8544ccefc101dfab5bf94ec1178b2da59bd0
[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 java.util.concurrent.atomic.AtomicReference;
23 import javax.annotation.concurrent.GuardedBy;
24 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
25 import org.opendaylight.yangtools.concepts.ListenerRegistration;
26 import org.opendaylight.yangtools.concepts.Registration;
27 import org.opendaylight.yangtools.util.ListenerRegistry;
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.YangTextSchemaContextResolver;
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;
42
43 public class OsgiBundleScanningSchemaService implements SchemaContextProvider, DOMSchemaService,
44         ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, AutoCloseable {
45     private static final Logger LOG = LoggerFactory.getLogger(OsgiBundleScanningSchemaService.class);
46
47     private static final AtomicReference<OsgiBundleScanningSchemaService> GLOBAL_INSTANCE = new AtomicReference<>();
48
49     private static final long FRAMEWORK_BUNDLE_ID = 0;
50
51     @GuardedBy("lock")
52     private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
53     private final YangTextSchemaContextResolver contextResolver = YangTextSchemaContextResolver.create("global-bundle");
54     private final BundleScanner scanner = new BundleScanner();
55     private final Object lock = new Object();
56     private final BundleContext context;
57
58     private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
59     private BundleTracker<Iterable<Registration>> bundleTracker;
60     private boolean starting = true;
61
62     private volatile boolean stopping;
63
64     private OsgiBundleScanningSchemaService(final BundleContext context) {
65         this.context = Preconditions.checkNotNull(context);
66     }
67
68     public static OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
69         OsgiBundleScanningSchemaService instance = new OsgiBundleScanningSchemaService(ctx);
70         Preconditions.checkState(GLOBAL_INSTANCE.compareAndSet(null, instance));
71         instance.start();
72         return instance;
73     }
74
75     public static OsgiBundleScanningSchemaService getInstance() {
76         OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.get();
77         Preconditions.checkState(instance != null, "Global Instance was not instantiated");
78         return instance;
79     }
80
81     @VisibleForTesting
82     public static void destroyInstance() {
83         OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.getAndSet(null);
84         if (instance != null) {
85             instance.close();
86         }
87     }
88
89     public BundleContext getContext() {
90         return context;
91     }
92
93     private void start() {
94         checkState(context != null);
95         LOG.debug("start() starting");
96
97         listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, this);
98         bundleTracker = new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING
99                 | Bundle.STOPPING | Bundle.ACTIVE, scanner);
100
101         synchronized (lock) {
102             bundleTracker.open();
103
104             LOG.debug("BundleTracker.open() complete");
105
106             if (Iterables.size(listeners.getListeners()) > 0) {
107                 tryToUpdateSchemaContext();
108             }
109         }
110
111         listenerTracker.open();
112         starting = false;
113
114         LOG.debug("start() complete");
115     }
116
117     @Override
118     public SchemaContext getSchemaContext() {
119         return getGlobalContext();
120     }
121
122     @Override
123     public SchemaContext getGlobalContext() {
124         return contextResolver.getSchemaContext().orNull();
125     }
126
127     @Override
128     public SchemaContext getSessionContext() {
129         throw new UnsupportedOperationException();
130     }
131
132     @Override
133     public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
134             final SchemaContextListener listener) {
135         synchronized (lock) {
136             final Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
137             if (potentialCtx.isPresent()) {
138                 listener.onGlobalContextUpdated(potentialCtx.get());
139             }
140             return listeners.register(listener);
141         }
142     }
143
144     @Override
145     public void close() {
146         synchronized (lock) {
147             stopping = true;
148             if (bundleTracker != null) {
149                 bundleTracker.close();
150                 bundleTracker = null;
151             }
152             if (listenerTracker != null) {
153                 listenerTracker.close();
154                 listenerTracker = null;
155             }
156
157             for (final ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
158                 l.close();
159             }
160         }
161     }
162
163     @SuppressWarnings("checkstyle:IllegalCatch")
164     @VisibleForTesting
165     @GuardedBy("lock")
166     void notifyListeners(final SchemaContext snapshot) {
167         final Object[] services = listenerTracker.getServices();
168         for (final ListenerRegistration<SchemaContextListener> listener : listeners) {
169             try {
170                 listener.getInstance().onGlobalContextUpdated(snapshot);
171             } catch (final Exception e) {
172                 LOG.error("Exception occured during invoking listener", e);
173             }
174         }
175         if (services != null) {
176             for (final Object rawListener : services) {
177                 final SchemaContextListener listener = (SchemaContextListener) rawListener;
178                 try {
179                     listener.onGlobalContextUpdated(snapshot);
180                 } catch (final Exception e) {
181                     LOG.error("Exception occured during invoking listener {}", listener, e);
182                 }
183             }
184         }
185     }
186
187     @SuppressWarnings("checkstyle:IllegalCatch")
188     private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
189         @Override
190         public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
191
192             if (bundle.getBundleId() == FRAMEWORK_BUNDLE_ID) {
193                 return Collections.emptyList();
194             }
195
196             final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
197             if (enumeration == null) {
198                 return Collections.emptyList();
199             }
200
201             final List<Registration> urls = new ArrayList<>();
202             while (enumeration.hasMoreElements()) {
203                 final URL u = enumeration.nextElement();
204                 try {
205                     urls.add(contextResolver.registerSource(u));
206                     LOG.debug("Registered {}", u);
207                 } catch (final Exception e) {
208                     LOG.warn("Failed to register {}, ignoring it", e);
209                 }
210             }
211
212             if (!urls.isEmpty()) {
213                 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
214                         urls.size(), bundle.getSymbolicName());
215                 tryToUpdateSchemaContext();
216             }
217
218             return ImmutableList.copyOf(urls);
219         }
220
221         @Override
222         public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
223             if (bundle.getBundleId() == FRAMEWORK_BUNDLE_ID) {
224                 LOG.debug("Framework bundle {} got event {}", bundle, event.getType());
225                 if ((event.getType() & BundleEvent.STOPPING) != 0) {
226                     LOG.info("OSGi framework is being stopped, halting bundle scanning");
227                     stopping = true;
228                 }
229             }
230         }
231
232         /**
233          * If removing YANG files makes yang store inconsistent, method
234          * {@link #getYangStoreSnapshot()} will throw exception. There is no
235          * rollback.
236          */
237         @SuppressWarnings("checkstyle:IllegalCatch")
238         @Override
239         public void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
240             for (final Registration url : urls) {
241                 try {
242                     url.close();
243                 } catch (final Exception e) {
244                     LOG.warn("Failed do unregister URL {}, proceeding", url, e);
245                 }
246             }
247
248             final int numUrls = Iterables.size(urls);
249             if (numUrls > 0 ) {
250                 if (LOG.isDebugEnabled()) {
251                     LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(),
252                             bundle.getState(), numUrls);
253                 }
254
255                 tryToUpdateSchemaContext();
256             }
257         }
258     }
259
260     @Override
261     public SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
262
263         final SchemaContextListener listener = context.getService(reference);
264         final SchemaContext _ctxContext = getGlobalContext();
265         if (getContext() != null && _ctxContext != null) {
266             listener.onGlobalContextUpdated(_ctxContext);
267         }
268         return listener;
269     }
270
271     public void tryToUpdateSchemaContext() {
272         if (starting || stopping) {
273             return;
274         }
275
276         synchronized (lock) {
277             final Optional<SchemaContext> schema = contextResolver.getSchemaContext();
278             if (schema.isPresent()) {
279                 if (LOG.isDebugEnabled()) {
280                     LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
281                 }
282
283                 notifyListeners(schema.get());
284             }
285         }
286     }
287
288     @Override
289     public void modifiedService(final ServiceReference<SchemaContextListener> reference,
290             final SchemaContextListener service) {
291         // NOOP
292     }
293
294     @Override
295     public void removedService(final ServiceReference<SchemaContextListener> reference,
296             final SchemaContextListener service) {
297         context.ungetService(reference);
298     }
299 }