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