2 * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.blueprint;
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Collection;
13 import java.util.Collections;
14 import java.util.Dictionary;
15 import java.util.Enumeration;
16 import java.util.HashSet;
17 import java.util.Hashtable;
18 import java.util.List;
19 import javax.annotation.Nullable;
20 import org.apache.aries.blueprint.NamespaceHandler;
21 import org.apache.aries.blueprint.services.BlueprintExtenderService;
22 import org.apache.aries.quiesce.participant.QuiesceParticipant;
23 import org.apache.aries.util.AriesFrameworkUtil;
24 import org.opendaylight.controller.blueprint.ext.OpendaylightNamespaceHandler;
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.BlueprintEvent;
34 import org.osgi.service.blueprint.container.BlueprintListener;
35 import org.osgi.util.tracker.BundleTracker;
36 import org.osgi.util.tracker.BundleTrackerCustomizer;
37 import org.osgi.util.tracker.ServiceTracker;
38 import org.osgi.util.tracker.ServiceTrackerCustomizer;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * This class is created in bundle activation and scans ACTIVE bundles for blueprint XML files located under
44 * the well-known org/opendaylight/blueprint/ path and deploys the XML files via the Aries
45 * BlueprintExtenderService. This path differs from the standard OSGI-INF/blueprint path to allow for
46 * controlled deployment of blueprint containers in an orderly manner.
48 * @author Thomas Pantelis
50 public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCustomizer<Bundle>, BlueprintListener,
51 SynchronousBundleListener {
52 private static final Logger LOG = LoggerFactory.getLogger(BlueprintBundleTracker.class);
53 private static final String BLUEPRINT_FILE_PATH = "org/opendaylight/blueprint/";
54 private static final String BLUEPRINT_FLE_PATTERN = "*.xml";
55 private static final long SYSTEM_BUNDLE_ID = 0;
57 private ServiceTracker<BlueprintExtenderService, BlueprintExtenderService> blueprintExtenderServiceTracker;
58 private ServiceTracker<QuiesceParticipant, QuiesceParticipant> quiesceParticipantTracker;
59 private BundleTracker<Bundle> bundleTracker;
60 private BundleContext bundleContext;
61 private volatile BlueprintExtenderService blueprintExtenderService;
62 private volatile QuiesceParticipant quiesceParticipant;
63 private volatile ServiceRegistration<?> blueprintContainerRestartReg;
64 private volatile BlueprintContainerRestartServiceImpl restartService;
65 private volatile boolean shuttingDown;
66 private ServiceRegistration<?> eventHandlerReg;
67 private ServiceRegistration<?> namespaceReg;
70 * Implemented from BundleActivator.
73 public void start(final BundleContext context) {
74 LOG.info("Starting {}", getClass().getSimpleName());
76 restartService = new BlueprintContainerRestartServiceImpl();
78 bundleContext = context;
80 registerBlueprintEventHandler(context);
82 registerNamespaceHandler(context);
84 bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
86 blueprintExtenderServiceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class.getName(),
87 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
89 public BlueprintExtenderService addingService(
90 final ServiceReference<BlueprintExtenderService> reference) {
91 return onBlueprintExtenderServiceAdded(reference);
95 public void modifiedService(final ServiceReference<BlueprintExtenderService> reference,
96 final BlueprintExtenderService service) {
100 public void removedService(final ServiceReference<BlueprintExtenderService> reference,
101 final BlueprintExtenderService service) {
104 blueprintExtenderServiceTracker.open();
106 quiesceParticipantTracker = new ServiceTracker<>(context, QuiesceParticipant.class.getName(),
107 new ServiceTrackerCustomizer<QuiesceParticipant, QuiesceParticipant>() {
109 public QuiesceParticipant addingService(
110 final ServiceReference<QuiesceParticipant> reference) {
111 return onQuiesceParticipantAdded(reference);
115 public void modifiedService(final ServiceReference<QuiesceParticipant> reference,
116 final QuiesceParticipant service) {
120 public void removedService(final ServiceReference<QuiesceParticipant> reference,
121 final QuiesceParticipant service) {
124 quiesceParticipantTracker.open();
127 private QuiesceParticipant onQuiesceParticipantAdded(final ServiceReference<QuiesceParticipant> reference) {
128 quiesceParticipant = reference.getBundle().getBundleContext().getService(reference);
130 LOG.debug("Got QuiesceParticipant");
132 restartService.setQuiesceParticipant(quiesceParticipant);
134 return quiesceParticipant;
137 private BlueprintExtenderService onBlueprintExtenderServiceAdded(
138 final ServiceReference<BlueprintExtenderService> reference) {
139 blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
140 bundleTracker.open();
142 bundleContext.addBundleListener(BlueprintBundleTracker.this);
144 LOG.debug("Got BlueprintExtenderService");
146 restartService.setBlueprintExtenderService(blueprintExtenderService);
148 blueprintContainerRestartReg = bundleContext.registerService(
149 BlueprintContainerRestartService.class, restartService, new Hashtable<>());
151 return blueprintExtenderService;
154 private void registerNamespaceHandler(final BundleContext context) {
155 Dictionary<String, Object> props = new Hashtable<>();
156 props.put("osgi.service.blueprint.namespace", OpendaylightNamespaceHandler.NAMESPACE_1_0_0);
157 namespaceReg = context.registerService(NamespaceHandler.class, new OpendaylightNamespaceHandler(), props);
160 private void registerBlueprintEventHandler(final BundleContext context) {
161 eventHandlerReg = context.registerService(BlueprintListener.class, this, new Hashtable<>());
165 * Implemented from BundleActivator.
168 public void stop(final BundleContext context) {
169 bundleTracker.close();
170 blueprintExtenderServiceTracker.close();
171 quiesceParticipantTracker.close();
173 AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
174 AriesFrameworkUtil.safeUnregisterService(namespaceReg);
175 AriesFrameworkUtil.safeUnregisterService(blueprintContainerRestartReg);
179 * Implemented from SynchronousBundleListener.
182 public void bundleChanged(final BundleEvent event) {
183 // If the system bundle (id 0) is stopping, do an orderly shutdown of all blueprint containers. On
184 // shutdown the system bundle is stopped first.
185 if (event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
186 shutdownAllContainers();
191 * Implemented from BundleActivator.
194 public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
195 modifiedBundle(bundle, event, bundle);
200 * Implemented from BundleTrackerCustomizer.
203 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
208 if (bundle.getState() == Bundle.ACTIVE) {
209 List<Object> paths = findBlueprintPaths(bundle);
211 if (!paths.isEmpty()) {
212 LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
214 blueprintExtenderService.createContainer(bundle, paths);
220 * Implemented from BundleTrackerCustomizer.
223 public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
224 // BlueprintExtenderService will handle this.
228 * Implemented from BlueprintListener to listen for blueprint events.
230 * @param event the event to handle
233 public void blueprintEvent(BlueprintEvent event) {
234 if (event.getType() == BlueprintEvent.CREATED) {
235 LOG.info("Blueprint container for bundle {} was successfully created", event.getBundle());
239 // If the container timed out waiting for dependencies, we'll destroy it and start it again. This
240 // is indicated via a non-null DEPENDENCIES property containing the missing dependencies. The
241 // default timeout is 5 min and ideally we would set this to infinite but the timeout can only
242 // be set at the bundle level in the manifest - there's no way to set it globally.
243 if (event.getType() == BlueprintEvent.FAILURE && event.getDependencies() != null) {
244 Bundle bundle = event.getBundle();
246 List<Object> paths = findBlueprintPaths(bundle);
247 if (!paths.isEmpty()) {
248 LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
251 restartService.restartContainer(bundle, paths);
256 @SuppressWarnings({ "rawtypes", "unchecked" })
257 static List<Object> findBlueprintPaths(final Bundle bundle) {
258 Enumeration<?> rntries = bundle.findEntries(BLUEPRINT_FILE_PATH, BLUEPRINT_FLE_PATTERN, false);
259 if (rntries == null) {
260 return Collections.emptyList();
262 return Collections.list((Enumeration)rntries);
266 private void shutdownAllContainers() {
269 restartService.close();
271 LOG.info("Shutting down all blueprint containers...");
273 Collection<Bundle> containerBundles = new HashSet<>(Arrays.asList(bundleContext.getBundles()));
274 while (!containerBundles.isEmpty()) {
275 // For each iteration of getBundlesToDestroy, as containers are destroyed, other containers become
276 // eligible to be destroyed. We loop until we've destroyed them all.
277 for (Bundle bundle : getBundlesToDestroy(containerBundles)) {
278 containerBundles.remove(bundle);
279 BlueprintContainer container = blueprintExtenderService.getContainer(bundle);
280 if (container != null) {
281 blueprintExtenderService.destroyContainer(bundle, container);
286 LOG.info("Shutdown of blueprint containers complete");
289 private List<Bundle> getBundlesToDestroy(final Collection<Bundle> containerBundles) {
290 List<Bundle> bundlesToDestroy = new ArrayList<>();
292 // Find all container bundles that either have no registered services or whose services are no
294 for (Bundle bundle : containerBundles) {
295 ServiceReference<?>[] references = bundle.getRegisteredServices();
297 if (references != null) {
298 for (ServiceReference<?> reference : references) {
299 usage += getServiceUsage(reference);
303 LOG.debug("Usage for bundle {} is {}", bundle, usage);
305 bundlesToDestroy.add(bundle);
309 if (!bundlesToDestroy.isEmpty()) {
310 bundlesToDestroy.sort((b1, b2) -> (int) (b2.getLastModified() - b1.getLastModified()));
312 LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy);
314 // There's either no more container bundles or they all have services being used. For
315 // the latter it means there's either circular service usage or a service is being used
316 // by a non-container bundle. But we need to make progress so we pick the bundle with a
317 // used service with the highest service ID. Each service is assigned a monotonically
318 // increasing ID as they are registered. By picking the bundle with the highest service
319 // ID, we're picking the bundle that was (likely) started after all the others and thus
320 // is likely the safest to destroy at this point.
322 Bundle bundle = findBundleWithHighestUsedServiceId(containerBundles);
323 if (bundle != null) {
324 bundlesToDestroy.add(bundle);
327 LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
331 return bundlesToDestroy;
335 private Bundle findBundleWithHighestUsedServiceId(final Collection<Bundle> containerBundles) {
336 ServiceReference<?> highestServiceRef = null;
337 for (Bundle bundle : containerBundles) {
338 ServiceReference<?>[] references = bundle.getRegisteredServices();
339 if (references == null) {
343 for (ServiceReference<?> reference : references) {
344 // We did check the service usage previously but it's possible the usage has changed since then.
345 if (getServiceUsage(reference) == 0) {
349 // Choose 'reference' if it has a lower service ranking or, if the rankings are equal
350 // which is usually the case, if it has a higher service ID. For the latter the < 0
351 // check looks backwards but that's how ServiceReference#compareTo is documented to work.
352 if (highestServiceRef == null || reference.compareTo(highestServiceRef) < 0) {
353 LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference);
354 highestServiceRef = reference;
359 return highestServiceRef == null ? null : highestServiceRef.getBundle();
362 private static int getServiceUsage(final ServiceReference<?> ref) {
363 Bundle[] usingBundles = ref.getUsingBundles();
364 return usingBundles != null ? usingBundles.length : 0;