Ensure CSS modules are closed before blueprint containers on shutdown
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / BlueprintBundleTracker.java
1 /*
2  * Copyright (c) 2016 Brocade Communications 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.blueprint;
9
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Collection;
13 import java.util.Collections;
14 import java.util.Comparator;
15 import java.util.Dictionary;
16 import java.util.Enumeration;
17 import java.util.HashSet;
18 import java.util.Hashtable;
19 import java.util.List;
20 import org.apache.aries.blueprint.NamespaceHandler;
21 import org.apache.aries.blueprint.services.BlueprintExtenderService;
22 import org.apache.aries.util.AriesFrameworkUtil;
23 import org.opendaylight.controller.blueprint.ext.OpendaylightNamespaceHandler;
24 import org.opendaylight.controller.config.api.ConfigSystemService;
25 import org.osgi.framework.Bundle;
26 import org.osgi.framework.BundleActivator;
27 import org.osgi.framework.BundleContext;
28 import org.osgi.framework.BundleEvent;
29 import org.osgi.framework.ServiceReference;
30 import org.osgi.framework.ServiceRegistration;
31 import org.osgi.framework.SynchronousBundleListener;
32 import org.osgi.service.blueprint.container.BlueprintContainer;
33 import org.osgi.service.blueprint.container.EventConstants;
34 import org.osgi.service.event.Event;
35 import org.osgi.service.event.EventHandler;
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 /**
44  * This class is created in bundle activation and scans ACTIVE bundles for blueprint XML files located under
45  * the well-known org/opendaylight/blueprint/ path and deploys the XML files via the Aries
46  * BlueprintExtenderService. This path differs from the standard OSGI-INF/blueprint path to allow for
47  * controlled deployment of blueprint containers in an orderly manner.
48  *
49  * @author Thomas Pantelis
50  */
51 public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCustomizer<Bundle>, EventHandler,
52         SynchronousBundleListener {
53     private static final Logger LOG = LoggerFactory.getLogger(BlueprintBundleTracker.class);
54     private static final String BLUEPRINT_FILE_PATH = "org/opendaylight/blueprint/";
55     private static final String BLUEPRINT_FLE_PATTERN = "*.xml";
56     private static final long SYSTEM_BUNDLE_ID = 0;
57
58     private ServiceTracker<BlueprintExtenderService, BlueprintExtenderService> serviceTracker;
59     private BundleTracker<Bundle> bundleTracker;
60     private BundleContext bundleContext;
61     private volatile BlueprintExtenderService blueprintExtenderService;
62     private volatile ServiceRegistration<?> blueprintContainerRestartReg;
63     private volatile BlueprintContainerRestartServiceImpl restartService;
64     private volatile boolean shuttingDown;
65     private ServiceRegistration<?> eventHandlerReg;
66     private ServiceRegistration<?> namespaceReg;
67
68     /**
69      * Implemented from BundleActivator.
70      */
71     @Override
72     public void start(BundleContext context) {
73         LOG.info("Starting {}", getClass().getSimpleName());
74
75         bundleContext = context;
76
77         registerBlueprintEventHandler(context);
78
79         registerNamespaceHandler(context);
80
81         bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
82
83         serviceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class.getName(),
84                 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
85                     @Override
86                     public BlueprintExtenderService addingService(
87                             ServiceReference<BlueprintExtenderService> reference) {
88                         blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
89                         bundleTracker.open();
90
91                         context.addBundleListener(BlueprintBundleTracker.this);
92
93                         LOG.debug("Got BlueprintExtenderService");
94
95                         restartService = new BlueprintContainerRestartServiceImpl(blueprintExtenderService);
96                         blueprintContainerRestartReg = context.registerService(
97                                 BlueprintContainerRestartService.class.getName(), restartService, new Hashtable<>());
98
99                         return blueprintExtenderService;
100                     }
101
102                     @Override
103                     public void modifiedService(ServiceReference<BlueprintExtenderService> reference,
104                             BlueprintExtenderService service) {
105                     }
106
107                     @Override
108                     public void removedService(ServiceReference<BlueprintExtenderService> reference,
109                             BlueprintExtenderService service) {
110                     }
111                 });
112         serviceTracker.open();
113     }
114
115     private void registerNamespaceHandler(BundleContext context) {
116         Dictionary<String, Object> props = new Hashtable<>();
117         props.put("osgi.service.blueprint.namespace", OpendaylightNamespaceHandler.NAMESPACE_1_0_0);
118         namespaceReg = context.registerService(NamespaceHandler.class.getName(),
119                 new OpendaylightNamespaceHandler(), props);
120     }
121
122     private void registerBlueprintEventHandler(BundleContext context) {
123         Dictionary<String, Object> props = new Hashtable<>();
124         props.put(org.osgi.service.event.EventConstants.EVENT_TOPIC, EventConstants.TOPIC_CREATED);
125         eventHandlerReg = context.registerService(EventHandler.class.getName(), this, props);
126     }
127
128     /**
129      * Implemented from BundleActivator.
130      */
131     @Override
132     public void stop(BundleContext context) {
133         bundleTracker.close();
134         serviceTracker.close();
135
136         AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
137         AriesFrameworkUtil.safeUnregisterService(namespaceReg);
138         AriesFrameworkUtil.safeUnregisterService(blueprintContainerRestartReg);
139     }
140
141     /**
142      * Implemented from SynchronousBundleListener.
143      */
144     @Override
145     public void bundleChanged(BundleEvent event) {
146         // If the system bundle (id 0) is stopping, do an orderly shutdown of all blueprint containers. On
147         // shutdown the system bundle is stopped first.
148         if(event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
149             shutdownAllContainers();
150         }
151     }
152
153     /**
154      * Implemented from BundleActivator.
155      */
156     @Override
157     public Bundle addingBundle(Bundle bundle, BundleEvent event) {
158         modifiedBundle(bundle, event, bundle);
159         return bundle;
160     }
161
162     /**
163      * Implemented from BundleActivator.
164      */
165     @Override
166     public void modifiedBundle(Bundle bundle, BundleEvent event, Bundle object) {
167         if(shuttingDown) {
168             return;
169         }
170
171         if(bundle.getState() == Bundle.ACTIVE) {
172             List<Object> paths = findBlueprintPaths(bundle);
173
174             if(!paths.isEmpty()) {
175                 LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
176
177                 blueprintExtenderService.createContainer(bundle, paths);
178             }
179         }
180     }
181
182     /**
183      * Implemented from BundleActivator.
184      */
185     @Override
186     public void removedBundle(Bundle bundle, BundleEvent event, Bundle object) {
187         // BlueprintExtenderService will handle this.
188     }
189
190     /**
191      * Implemented from EventHandler to listen for blueprint events.
192      *
193      * @param event
194      */
195     @Override
196     public void handleEvent(Event event) {
197         if(EventConstants.TOPIC_CREATED.equals(event.getTopic())) {
198             LOG.info("Blueprint container for bundle {} was successfully created",
199                     event.getProperty(EventConstants.BUNDLE));
200         }
201     }
202
203     @SuppressWarnings({ "rawtypes", "unchecked" })
204     static List<Object> findBlueprintPaths(Bundle bundle) {
205         Enumeration<?> e = bundle.findEntries(BLUEPRINT_FILE_PATH, BLUEPRINT_FLE_PATTERN, false);
206         if(e == null) {
207             return Collections.emptyList();
208         } else {
209             return Collections.list((Enumeration)e);
210         }
211     }
212
213     private void shutdownAllContainers() {
214         shuttingDown = true;
215
216         restartService.close();
217
218         // Close all CSS modules first.
219         ConfigSystemService configSystem = getOSGiService(ConfigSystemService.class);
220         if(configSystem != null) {
221             configSystem.closeAllConfigModules();
222         }
223
224         LOG.info("Shutting down all blueprint containers...");
225
226         Collection<Bundle> containerBundles = new HashSet<>(Arrays.asList(bundleContext.getBundles()));
227         while(!containerBundles.isEmpty()) {
228             // For each iteration of getBundlesToDestroy, as containers are destroyed, other containers become
229             // eligible to be destroyed. We loop until we've destroyed them all.
230             for(Bundle bundle : getBundlesToDestroy(containerBundles)) {
231                 containerBundles.remove(bundle);
232                 BlueprintContainer container = blueprintExtenderService.getContainer(bundle);
233                 if(container != null) {
234                     blueprintExtenderService.destroyContainer(bundle, container);
235                 }
236             }
237         }
238
239         LOG.info("Shutdown of blueprint containers complete");
240     }
241
242     private List<Bundle> getBundlesToDestroy(Collection<Bundle> containerBundles) {
243         List<Bundle> bundlesToDestroy = new ArrayList<Bundle>();
244
245         // Find all container bundles that either have no registered services or whose services are no
246         // longer in use.
247         for(Bundle bundle : containerBundles) {
248             ServiceReference<?>[] references = bundle.getRegisteredServices();
249             int usage = 0;
250             if(references != null) {
251                 for(ServiceReference<?> reference : references) {
252                     usage += getServiceUsage(reference);
253                 }
254             }
255
256             LOG.debug("Usage for bundle {} is {}", bundle, usage);
257             if(usage == 0) {
258                 bundlesToDestroy.add(bundle);
259             }
260         }
261
262         if(!bundlesToDestroy.isEmpty()) {
263             Collections.sort(bundlesToDestroy, new Comparator<Bundle>() {
264                 @Override
265                 public int compare(Bundle b1, Bundle b2) {
266                     return (int) (b2.getLastModified() - b1.getLastModified());
267                 }
268             });
269
270             LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy);
271         } else {
272             // There's either no more container bundles or they all have services being used. For
273             // the latter it means there's either circular service usage or a service is being used
274             // by a non-container bundle. But we need to make progress so we pick the bundle with a
275             // used service with the highest service ID. Each service is assigned a monotonically
276             // increasing ID as they are registered. By picking the bundle with the highest service
277             // ID, we're picking the bundle that was (likely) started after all the others and thus
278             // is likely the safest to destroy at this point.
279
280             ServiceReference<?> ref = null;
281             for(Bundle bundle : containerBundles) {
282                 ServiceReference<?>[] references = bundle.getRegisteredServices();
283                 if(references == null) {
284                     continue;
285                 }
286
287                 for(ServiceReference<?> reference : references) {
288                     // We did check the service usage above but it's possible the usage has changed since
289                     // then,
290                     if(getServiceUsage(reference) == 0) {
291                         continue;
292                     }
293
294                     // Choose 'reference' if it has a lower service ranking or, if the rankings are equal
295                     // which is usually the case, if it has a higher service ID. For the latter the < 0
296                     // check looks backwards but that's how ServiceReference#compareTo is documented to work.
297                     if(ref == null || reference.compareTo(ref) < 0) {
298                         LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference);
299                         ref = reference;
300                     }
301                 }
302             }
303
304             if(ref != null) {
305                 bundlesToDestroy.add(ref.getBundle());
306             }
307
308             LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
309                     bundlesToDestroy);
310         }
311
312         return bundlesToDestroy;
313     }
314
315     private static int getServiceUsage(ServiceReference<?> ref) {
316         Bundle[] usingBundles = ref.getUsingBundles();
317         return usingBundles != null ? usingBundles.length : 0;
318     }
319
320     private <T> T getOSGiService(Class<T> serviceInterface) {
321         try {
322             ServiceReference<T> serviceReference = bundleContext.getServiceReference(serviceInterface);
323             if(serviceReference == null) {
324                 LOG.warn("{} service reference not found", serviceInterface.getSimpleName());
325                 return null;
326             }
327
328             T service = bundleContext.getService(serviceReference);
329             if(service == null) {
330                 // This could happen on shutdown if the service was already unregistered so we log as debug.
331                 LOG.debug("{} service instance was not found", serviceInterface.getSimpleName());
332             }
333
334             return service;
335         } catch(IllegalStateException e) {
336             // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we
337             // log as debug.
338             LOG.debug("Error obtaining OSGi service {}", serviceInterface.getSimpleName(), e);
339         }
340
341         return null;
342     }
343 }