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