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