Use osgi-core constants
[mdsal.git] / dom / mdsal-dom-schema-service-osgi / src / main / java / org / opendaylight / mdsal / dom / schema / service / osgi / OsgiBundleScanningSchemaService.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.schema.service.osgi;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.Iterables;
16 import java.net.URL;
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 org.checkerframework.checker.lock.qual.GuardedBy;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.mdsal.dom.broker.schema.ScanningSchemaServiceProvider;
25 import org.opendaylight.yangtools.concepts.Registration;
26 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
27 import org.osgi.framework.Bundle;
28 import org.osgi.framework.BundleContext;
29 import org.osgi.framework.BundleEvent;
30 import org.osgi.framework.Constants;
31 import org.osgi.framework.ServiceReference;
32 import org.osgi.util.tracker.BundleTracker;
33 import org.osgi.util.tracker.BundleTrackerCustomizer;
34 import org.osgi.util.tracker.ServiceTracker;
35 import org.osgi.util.tracker.ServiceTrackerCustomizer;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 public final class OsgiBundleScanningSchemaService extends ScanningSchemaServiceProvider
40         implements ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener> {
41
42     private static final Logger LOG = LoggerFactory.getLogger(OsgiBundleScanningSchemaService.class);
43     private static final AtomicReference<OsgiBundleScanningSchemaService> GLOBAL_INSTANCE = new AtomicReference<>();
44
45     private final BundleScanner scanner = new BundleScanner();
46     private final BundleContext context;
47
48     @GuardedBy("lock")
49     private BundleTracker<Iterable<Registration>> bundleTracker;
50     private final Object lock = new Object();
51
52     private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
53     private boolean starting = true;
54
55     private volatile boolean stopping;
56
57     private OsgiBundleScanningSchemaService(final BundleContext context) {
58         this.context = requireNonNull(context);
59     }
60
61     public static @NonNull OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
62         final OsgiBundleScanningSchemaService instance = new OsgiBundleScanningSchemaService(ctx);
63         checkState(GLOBAL_INSTANCE.compareAndSet(null, instance));
64         instance.start();
65         return instance;
66     }
67
68     private void start() {
69         checkState(context != null);
70         LOG.debug("start() starting");
71
72         listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, this);
73         bundleTracker = new BundleTracker<>(context,
74                 Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE, scanner);
75
76         synchronized (lock) {
77             bundleTracker.open();
78
79             LOG.debug("BundleTracker.open() complete");
80
81             if (!hasListeners()) {
82                 tryToUpdateSchemaContext();
83             }
84         }
85
86         listenerTracker.open();
87         starting = false;
88
89         LOG.debug("start() complete");
90     }
91
92     public static OsgiBundleScanningSchemaService getInstance() {
93         final OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.get();
94         checkState(instance != null, "Global Instance was not instantiated");
95         return instance;
96     }
97
98     @VisibleForTesting
99     public static void destroyInstance() {
100         final OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.getAndSet(null);
101         if (instance != null) {
102             instance.closeInstance();
103         }
104     }
105
106     private void closeInstance() {
107         stopping = true;
108         if (bundleTracker != null) {
109             bundleTracker.close();
110             bundleTracker = null;
111         }
112         if (listenerTracker != null) {
113             listenerTracker.close();
114             listenerTracker = null;
115         }
116         close();
117     }
118
119     public BundleContext getContext() {
120         return context;
121     }
122
123     @SuppressWarnings("checkstyle:IllegalCatch")
124     private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
125         @Override
126         public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
127
128             if (bundle.getBundleId() == Constants.SYSTEM_BUNDLE_ID) {
129                 return Collections.emptyList();
130             }
131
132             final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
133             if (enumeration == null) {
134                 return Collections.emptyList();
135             }
136
137             final List<URL> urls = new ArrayList<>();
138             while (enumeration.hasMoreElements()) {
139                 final URL u = enumeration.nextElement();
140                 try {
141                     urls.add(u);
142                     LOG.debug("Registered {}", u);
143                 } catch (final Exception e) {
144                     LOG.warn("Failed to register {}, ignoring it", u, e);
145                 }
146             }
147
148             final List<Registration> registrations = registerAvailableYangs(urls);
149             if (!registrations.isEmpty()) {
150                 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
151                         registrations.size(), bundle.getSymbolicName());
152                 if (!starting && !stopping) {
153                     tryToUpdateSchemaContext();
154                 }
155             }
156             return ImmutableList.copyOf(registrations);
157         }
158
159         @Override
160         public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
161             if (bundle.getBundleId() == Constants.SYSTEM_BUNDLE_ID) {
162                 LOG.debug("Framework bundle {} got event {}", bundle, event.getType());
163                 if ((event.getType() & BundleEvent.STOPPING) != 0) {
164                     LOG.info("OSGi framework is being stopped, halting bundle scanning");
165                     stopping = true;
166                 }
167             }
168         }
169
170         /**
171          * If removing YANG files makes yang store inconsistent, method {@link #getYangStoreSnapshot()} will
172          * throw exception. There is no rollback.
173          */
174         @SuppressWarnings("checkstyle:IllegalCatch")
175         @Override
176         public void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
177             for (final Registration url : urls) {
178                 try {
179                     url.close();
180                 } catch (final Exception e) {
181                     LOG.warn("Failed do unregister URL {}, proceeding", url, e);
182                 }
183             }
184
185             final int numUrls = Iterables.size(urls);
186             if (numUrls > 0) {
187                 if (LOG.isDebugEnabled()) {
188                     LOG.debug("removedBundle: {}, state: {}, # urls: {}", bundle.getSymbolicName(), bundle.getState(),
189                             numUrls);
190                 }
191                 if (!starting && !stopping) {
192                     tryToUpdateSchemaContext();
193                 }
194             }
195         }
196     }
197
198     @Override
199     public SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
200         final SchemaContextListener listener = context.getService(reference);
201         registerSchemaContextListener(listener);
202         return listener;
203     }
204
205     @Override
206     public void modifiedService(final ServiceReference<SchemaContextListener> reference,
207             final SchemaContextListener service) {
208         // NOOP
209     }
210
211     @Override
212     public void removedService(final ServiceReference<SchemaContextListener> reference,
213             final SchemaContextListener service) {
214         context.ungetService(reference);
215         removeListener(service);
216     }
217 }