Binding codec v2 - cast case type to get serializer
[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 com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.Iterables;
15 import java.net.URL;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.Enumeration;
19 import java.util.List;
20 import java.util.concurrent.atomic.AtomicReference;
21 import javax.annotation.Nonnull;
22 import javax.annotation.concurrent.GuardedBy;
23 import org.opendaylight.mdsal.dom.broker.schema.ScanningSchemaServiceProvider;
24 import org.opendaylight.yangtools.concepts.Registration;
25 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
26 import org.osgi.framework.Bundle;
27 import org.osgi.framework.BundleContext;
28 import org.osgi.framework.BundleEvent;
29 import org.osgi.framework.ServiceReference;
30 import org.osgi.util.tracker.BundleTracker;
31 import org.osgi.util.tracker.BundleTrackerCustomizer;
32 import org.osgi.util.tracker.ServiceTracker;
33 import org.osgi.util.tracker.ServiceTrackerCustomizer;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 public class OsgiBundleScanningSchemaService extends ScanningSchemaServiceProvider
38         implements ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener> {
39
40     private static final Logger LOG = LoggerFactory.getLogger(OsgiBundleScanningSchemaService.class);
41     private static final AtomicReference<OsgiBundleScanningSchemaService> GLOBAL_INSTANCE = new AtomicReference<>();
42     private static final long FRAMEWORK_BUNDLE_ID = 0;
43
44     private final BundleScanner scanner = new BundleScanner();
45     private final BundleContext context;
46
47     @GuardedBy("lock")
48     private BundleTracker<Iterable<Registration>> bundleTracker;
49     private final Object lock = new Object();
50
51     private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
52     private boolean starting = true;
53
54     private volatile boolean stopping;
55
56     private OsgiBundleScanningSchemaService(final BundleContext context) {
57         this.context = Preconditions.checkNotNull(context);
58     }
59
60     public static @Nonnull OsgiBundleScanningSchemaService createInstance(final BundleContext ctx) {
61         final OsgiBundleScanningSchemaService instance = new OsgiBundleScanningSchemaService(ctx);
62         Preconditions.checkState(GLOBAL_INSTANCE.compareAndSet(null, instance));
63         instance.start();
64         return instance;
65     }
66
67     private void start() {
68         checkState(context != null);
69         LOG.debug("start() starting");
70
71         listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, this);
72         bundleTracker = new BundleTracker<>(context,
73                 Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE, scanner);
74
75         synchronized (lock) {
76             bundleTracker.open();
77
78             LOG.debug("BundleTracker.open() complete");
79
80             if (!hasListeners()) {
81                 tryToUpdateSchemaContext();
82             }
83         }
84
85         listenerTracker.open();
86         starting = false;
87
88         LOG.debug("start() complete");
89     }
90
91     public static OsgiBundleScanningSchemaService getInstance() {
92         final OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.get();
93         Preconditions.checkState(instance != null, "Global Instance was not instantiated");
94         return instance;
95     }
96
97     @VisibleForTesting
98     public static void destroyInstance() throws Exception {
99         final OsgiBundleScanningSchemaService instance = GLOBAL_INSTANCE.getAndSet(null);
100         if (instance != null) {
101
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() == FRAMEWORK_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", 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() == FRAMEWORK_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 }