Bug 2970: Fix GlobalBundleScanningSchemaServiceImpl to get RESOLVED bundles correctly
[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 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 org.opendaylight.controller.sal.core.api.model.SchemaService;
21 import org.opendaylight.yangtools.concepts.ListenerRegistration;
22 import org.opendaylight.yangtools.concepts.Registration;
23 import org.opendaylight.yangtools.util.ListenerRegistry;
24 import org.opendaylight.yangtools.yang.model.api.Module;
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.URLSchemaContextResolver;
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 GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, AutoCloseable {
41     private static final Logger LOG = LoggerFactory.getLogger(GlobalBundleScanningSchemaServiceImpl.class);
42
43     private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
44     private final URLSchemaContextResolver contextResolver = URLSchemaContextResolver.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 GlobalBundleScanningSchemaServiceImpl instance;
52
53     private GlobalBundleScanningSchemaServiceImpl(final BundleContext context) {
54         this.context = Preconditions.checkNotNull(context);
55     }
56
57     public synchronized static GlobalBundleScanningSchemaServiceImpl createInstance(final BundleContext ctx) {
58         Preconditions.checkState(instance == null);
59         instance = new GlobalBundleScanningSchemaServiceImpl(ctx);
60         instance.start();
61         return instance;
62     }
63
64     public synchronized static GlobalBundleScanningSchemaServiceImpl 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, GlobalBundleScanningSchemaServiceImpl.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 void addModule(final Module module) {
112         throw new UnsupportedOperationException();
113     }
114
115     @Override
116     public SchemaContext getSessionContext() {
117         throw new UnsupportedOperationException();
118     }
119
120     @Override
121     public void removeModule(final Module module) {
122         throw new UnsupportedOperationException();
123     }
124
125     @Override
126     public synchronized ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
127         Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
128         if(potentialCtx.isPresent()) {
129             listener.onGlobalContextUpdated(potentialCtx.get());
130         }
131         return listeners.register(listener);
132     }
133
134     @Override
135     public void close() {
136         if (bundleTracker != null) {
137             bundleTracker.close();
138         }
139         if (listenerTracker != null) {
140             listenerTracker.close();
141         }
142
143         for (ListenerRegistration<SchemaContextListener> l : listeners.getListeners()) {
144             l.close();
145         }
146     }
147
148     private synchronized void updateContext(final SchemaContext snapshot) {
149         Object[] services = listenerTracker.getServices();
150         for (ListenerRegistration<SchemaContextListener> listener : listeners) {
151             try {
152                 listener.getInstance().onGlobalContextUpdated(snapshot);
153             } catch (Exception e) {
154                 LOG.error("Exception occured during invoking listener", e);
155             }
156         }
157         if (services != null) {
158             for (Object rawListener : services) {
159                 final SchemaContextListener listener = (SchemaContextListener) rawListener;
160                 try {
161                     listener.onGlobalContextUpdated(snapshot);
162                 } catch (Exception e) {
163                     LOG.error("Exception occured during invoking listener {}", listener, e);
164                 }
165             }
166         }
167     }
168
169     private class BundleScanner implements BundleTrackerCustomizer<Iterable<Registration>> {
170         @Override
171         public Iterable<Registration> addingBundle(final Bundle bundle, final BundleEvent event) {
172
173             if (bundle.getBundleId() == 0) {
174                 return Collections.emptyList();
175             }
176
177             final Enumeration<URL> enumeration = bundle.findEntries("META-INF/yang", "*.yang", false);
178             if (enumeration == null) {
179                 return Collections.emptyList();
180             }
181
182             final List<Registration> urls = new ArrayList<>();
183             while (enumeration.hasMoreElements()) {
184                 final URL u = enumeration.nextElement();
185                 try {
186                     urls.add(contextResolver.registerSource(u));
187                     LOG.debug("Registered {}", u);
188                 } catch (Exception e) {
189                     LOG.warn("Failed to register {}, ignoring it", e);
190                 }
191             }
192
193             if (!urls.isEmpty()) {
194                 LOG.debug("Loaded {} new URLs from bundle {}, attempting to rebuild schema context",
195                         urls.size(), bundle.getSymbolicName());
196                 tryToUpdateSchemaContext();
197             }
198
199             return ImmutableList.copyOf(urls);
200         }
201
202         @Override
203         public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> object) {
204         }
205
206         /**
207          * If removing YANG files makes yang store inconsistent, method
208          * {@link #getYangStoreSnapshot()} will throw exception. There is no
209          * rollback.
210          */
211
212         @Override
213         public synchronized void removedBundle(final Bundle bundle, final BundleEvent event, final Iterable<Registration> urls) {
214             for (Registration url : urls) {
215                 try {
216                     url.close();
217                 } catch (Exception e) {
218                     LOG.warn("Failed do unregister URL {}, proceeding", url, e);
219                 }
220             }
221             tryToUpdateSchemaContext();
222         }
223     }
224
225     @Override
226     public synchronized SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
227
228         SchemaContextListener listener = context.getService(reference);
229         SchemaContext _ctxContext = getGlobalContext();
230         if (getContext() != null && _ctxContext != null) {
231             listener.onGlobalContextUpdated(_ctxContext);
232         }
233         return listener;
234     }
235
236     public synchronized void tryToUpdateSchemaContext() {
237         if (starting) {
238             return;
239         }
240         Optional<SchemaContext> schema = contextResolver.getSchemaContext();
241         if(schema.isPresent()) {
242             if(LOG.isDebugEnabled()) {
243                 LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
244             }
245
246             updateContext(schema.get());
247         }
248     }
249
250     @Override
251     public void modifiedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
252         // NOOP
253     }
254
255     @Override
256     public void removedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
257         context.ungetService(reference);
258     }
259 }