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.opendaylight.yangtools.util.xml.UntrustedXML;
26 import org.osgi.framework.Bundle;
27 import org.osgi.framework.BundleActivator;
28 import org.osgi.framework.BundleContext;
29 import org.osgi.framework.BundleEvent;
30 import org.osgi.framework.ServiceReference;
31 import org.osgi.framework.ServiceRegistration;
32 import org.osgi.framework.SynchronousBundleListener;
33 import org.osgi.service.blueprint.container.BlueprintContainer;
34 import org.osgi.service.blueprint.container.BlueprintEvent;
35 import org.osgi.service.blueprint.container.BlueprintListener;
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;
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.
49 * @author Thomas Pantelis
51 public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCustomizer<Bundle>, BlueprintListener,
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;
58 private ServiceTracker<BlueprintExtenderService, BlueprintExtenderService> blueprintExtenderServiceTracker;
59 private ServiceTracker<QuiesceParticipant, QuiesceParticipant> quiesceParticipantTracker;
60 private BundleTracker<Bundle> bundleTracker;
61 private BundleContext bundleContext;
62 private volatile BlueprintExtenderService blueprintExtenderService;
63 private volatile QuiesceParticipant quiesceParticipant;
64 private volatile ServiceRegistration<?> blueprintContainerRestartReg;
65 private volatile BlueprintContainerRestartServiceImpl restartService;
66 private volatile boolean shuttingDown;
67 private ServiceRegistration<?> eventHandlerReg;
68 private ServiceRegistration<?> namespaceReg;
71 * Implemented from BundleActivator.
74 public void start(final BundleContext context) {
75 LOG.info("Starting {}", getClass().getSimpleName());
77 // CONTROLLER-1867: force UntrustedXML initialization, so that it uses our TCCL to initialize
78 UntrustedXML.newDocumentBuilder();
80 restartService = new BlueprintContainerRestartServiceImpl();
82 bundleContext = context;
84 registerBlueprintEventHandler(context);
86 registerNamespaceHandler(context);
88 bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
90 blueprintExtenderServiceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class.getName(),
91 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
93 public BlueprintExtenderService addingService(
94 final ServiceReference<BlueprintExtenderService> reference) {
95 return onBlueprintExtenderServiceAdded(reference);
99 public void modifiedService(final ServiceReference<BlueprintExtenderService> reference,
100 final BlueprintExtenderService service) {
104 public void removedService(final ServiceReference<BlueprintExtenderService> reference,
105 final BlueprintExtenderService service) {
108 blueprintExtenderServiceTracker.open();
110 quiesceParticipantTracker = new ServiceTracker<>(context, QuiesceParticipant.class.getName(),
111 new ServiceTrackerCustomizer<QuiesceParticipant, QuiesceParticipant>() {
113 public QuiesceParticipant addingService(
114 final ServiceReference<QuiesceParticipant> reference) {
115 return onQuiesceParticipantAdded(reference);
119 public void modifiedService(final ServiceReference<QuiesceParticipant> reference,
120 final QuiesceParticipant service) {
124 public void removedService(final ServiceReference<QuiesceParticipant> reference,
125 final QuiesceParticipant service) {
128 quiesceParticipantTracker.open();
131 private QuiesceParticipant onQuiesceParticipantAdded(final ServiceReference<QuiesceParticipant> reference) {
132 quiesceParticipant = reference.getBundle().getBundleContext().getService(reference);
134 LOG.debug("Got QuiesceParticipant");
136 restartService.setQuiesceParticipant(quiesceParticipant);
138 return quiesceParticipant;
141 private BlueprintExtenderService onBlueprintExtenderServiceAdded(
142 final ServiceReference<BlueprintExtenderService> reference) {
143 blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
144 bundleTracker.open();
146 bundleContext.addBundleListener(BlueprintBundleTracker.this);
148 LOG.debug("Got BlueprintExtenderService");
150 restartService.setBlueprintExtenderService(blueprintExtenderService);
152 blueprintContainerRestartReg = bundleContext.registerService(
153 BlueprintContainerRestartService.class.getName(), restartService, new Hashtable<>());
155 return blueprintExtenderService;
158 private void registerNamespaceHandler(final BundleContext context) {
159 Dictionary<String, Object> props = new Hashtable<>();
160 props.put("osgi.service.blueprint.namespace", OpendaylightNamespaceHandler.NAMESPACE_1_0_0);
161 namespaceReg = context.registerService(NamespaceHandler.class.getName(),
162 new OpendaylightNamespaceHandler(), props);
165 private void registerBlueprintEventHandler(final BundleContext context) {
166 eventHandlerReg = context.registerService(BlueprintListener.class.getName(), this, new Hashtable<>());
170 * Implemented from BundleActivator.
173 public void stop(final BundleContext context) {
174 bundleTracker.close();
175 blueprintExtenderServiceTracker.close();
176 quiesceParticipantTracker.close();
178 AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
179 AriesFrameworkUtil.safeUnregisterService(namespaceReg);
180 AriesFrameworkUtil.safeUnregisterService(blueprintContainerRestartReg);
184 * Implemented from SynchronousBundleListener.
187 public void bundleChanged(final BundleEvent event) {
188 // If the system bundle (id 0) is stopping, do an orderly shutdown of all blueprint containers. On
189 // shutdown the system bundle is stopped first.
190 if (event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
191 shutdownAllContainers();
196 * Implemented from BundleActivator.
199 public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
200 modifiedBundle(bundle, event, bundle);
205 * Implemented from BundleTrackerCustomizer.
208 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
213 if (bundle.getState() == Bundle.ACTIVE) {
214 List<Object> paths = findBlueprintPaths(bundle);
216 if (!paths.isEmpty()) {
217 LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
219 blueprintExtenderService.createContainer(bundle, paths);
225 * Implemented from BundleTrackerCustomizer.
228 public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
229 // BlueprintExtenderService will handle this.
233 * Implemented from BlueprintListener to listen for blueprint events.
235 * @param event the event to handle
238 public void blueprintEvent(final BlueprintEvent event) {
239 if (event.getType() == BlueprintEvent.CREATED) {
240 LOG.info("Blueprint container for bundle {} was successfully created", event.getBundle());
244 // If the container timed out waiting for dependencies, we'll destroy it and start it again. This
245 // is indicated via a non-null DEPENDENCIES property containing the missing dependencies. The
246 // default timeout is 5 min and ideally we would set this to infinite but the timeout can only
247 // be set at the bundle level in the manifest - there's no way to set it globally.
248 if (event.getType() == BlueprintEvent.FAILURE && event.getDependencies() != null) {
249 Bundle bundle = event.getBundle();
251 List<Object> paths = findBlueprintPaths(bundle);
252 if (!paths.isEmpty()) {
253 LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
256 restartService.restartContainer(bundle, paths);
261 @SuppressWarnings({ "rawtypes", "unchecked" })
262 static List<Object> findBlueprintPaths(final Bundle bundle) {
263 Enumeration<?> rntries = bundle.findEntries(BLUEPRINT_FILE_PATH, BLUEPRINT_FLE_PATTERN, false);
264 if (rntries == null) {
265 return Collections.emptyList();
267 return Collections.list((Enumeration)rntries);
271 private void shutdownAllContainers() {
274 restartService.close();
276 LOG.info("Shutting down all blueprint containers...");
278 Collection<Bundle> containerBundles = new HashSet<>(Arrays.asList(bundleContext.getBundles()));
279 while (!containerBundles.isEmpty()) {
280 // For each iteration of getBundlesToDestroy, as containers are destroyed, other containers become
281 // eligible to be destroyed. We loop until we've destroyed them all.
282 for (Bundle bundle : getBundlesToDestroy(containerBundles)) {
283 containerBundles.remove(bundle);
284 BlueprintContainer container = blueprintExtenderService.getContainer(bundle);
285 if (container != null) {
286 blueprintExtenderService.destroyContainer(bundle, container);
291 LOG.info("Shutdown of blueprint containers complete");
294 private List<Bundle> getBundlesToDestroy(final Collection<Bundle> containerBundles) {
295 List<Bundle> bundlesToDestroy = new ArrayList<>();
297 // Find all container bundles that either have no registered services or whose services are no
299 for (Bundle bundle : containerBundles) {
300 ServiceReference<?>[] references = bundle.getRegisteredServices();
302 if (references != null) {
303 for (ServiceReference<?> reference : references) {
304 usage += getServiceUsage(reference);
308 LOG.debug("Usage for bundle {} is {}", bundle, usage);
310 bundlesToDestroy.add(bundle);
314 if (!bundlesToDestroy.isEmpty()) {
315 bundlesToDestroy.sort((b1, b2) -> (int) (b2.getLastModified() - b1.getLastModified()));
317 LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy);
319 // There's either no more container bundles or they all have services being used. For
320 // the latter it means there's either circular service usage or a service is being used
321 // by a non-container bundle. But we need to make progress so we pick the bundle with a
322 // used service with the highest service ID. Each service is assigned a monotonically
323 // increasing ID as they are registered. By picking the bundle with the highest service
324 // ID, we're picking the bundle that was (likely) started after all the others and thus
325 // is likely the safest to destroy at this point.
327 Bundle bundle = findBundleWithHighestUsedServiceId(containerBundles);
328 if (bundle != null) {
329 bundlesToDestroy.add(bundle);
332 LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
336 return bundlesToDestroy;
340 private Bundle findBundleWithHighestUsedServiceId(final Collection<Bundle> containerBundles) {
341 ServiceReference<?> highestServiceRef = null;
342 for (Bundle bundle : containerBundles) {
343 ServiceReference<?>[] references = bundle.getRegisteredServices();
344 if (references == null) {
348 for (ServiceReference<?> reference : references) {
349 // We did check the service usage previously but it's possible the usage has changed since then.
350 if (getServiceUsage(reference) == 0) {
354 // Choose 'reference' if it has a lower service ranking or, if the rankings are equal
355 // which is usually the case, if it has a higher service ID. For the latter the < 0
356 // check looks backwards but that's how ServiceReference#compareTo is documented to work.
357 if (highestServiceRef == null || reference.compareTo(highestServiceRef) < 0) {
358 LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference);
359 highestServiceRef = reference;
364 return highestServiceRef == null ? null : highestServiceRef.getBundle();
367 private static int getServiceUsage(final ServiceReference<?> ref) {
368 Bundle[] usingBundles = ref.getUsingBundles();
369 return usingBundles != null ? usingBundles.length : 0;