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