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 org.apache.aries.blueprint.NamespaceHandler;
20 import org.apache.aries.blueprint.services.BlueprintExtenderService;
21 import org.apache.aries.quiesce.participant.QuiesceParticipant;
22 import org.apache.aries.util.AriesFrameworkUtil;
23 import org.eclipse.jdt.annotation.Nullable;
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 ODL_CUSTOM_BLUEPRINT_FILE_PATH = "org/opendaylight/blueprint/";
55 private static final String STANDARD_BLUEPRINT_FILE_PATH = "OSGI-INF/blueprint/";
56 private static final String BLUEPRINT_FLE_PATTERN = "*.xml";
57 private static final long SYSTEM_BUNDLE_ID = 0;
59 private ServiceTracker<BlueprintExtenderService, BlueprintExtenderService> blueprintExtenderServiceTracker;
60 private ServiceTracker<QuiesceParticipant, QuiesceParticipant> quiesceParticipantTracker;
61 private BundleTracker<Bundle> bundleTracker;
62 private BundleContext bundleContext;
63 private volatile BlueprintExtenderService blueprintExtenderService;
64 private volatile QuiesceParticipant quiesceParticipant;
65 private volatile ServiceRegistration<?> blueprintContainerRestartReg;
66 private volatile BlueprintContainerRestartServiceImpl restartService;
67 private volatile boolean shuttingDown;
68 private ServiceRegistration<?> eventHandlerReg;
69 private ServiceRegistration<?> namespaceReg;
72 * Implemented from BundleActivator.
75 public void start(final BundleContext context) {
76 LOG.info("Starting {}", getClass().getSimpleName());
78 // CONTROLLER-1867: force UntrustedXML initialization, so that it uses our TCCL to initialize
79 UntrustedXML.newDocumentBuilder();
81 restartService = new BlueprintContainerRestartServiceImpl();
83 bundleContext = context;
85 registerBlueprintEventHandler(context);
87 registerNamespaceHandler(context);
89 bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
91 blueprintExtenderServiceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class.getName(),
92 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
94 public BlueprintExtenderService addingService(
95 final ServiceReference<BlueprintExtenderService> reference) {
96 return onBlueprintExtenderServiceAdded(reference);
100 public void modifiedService(final ServiceReference<BlueprintExtenderService> reference,
101 final BlueprintExtenderService service) {
105 public void removedService(final ServiceReference<BlueprintExtenderService> reference,
106 final BlueprintExtenderService service) {
109 blueprintExtenderServiceTracker.open();
111 quiesceParticipantTracker = new ServiceTracker<>(context, QuiesceParticipant.class.getName(),
112 new ServiceTrackerCustomizer<QuiesceParticipant, QuiesceParticipant>() {
114 public QuiesceParticipant addingService(
115 final ServiceReference<QuiesceParticipant> reference) {
116 return onQuiesceParticipantAdded(reference);
120 public void modifiedService(final ServiceReference<QuiesceParticipant> reference,
121 final QuiesceParticipant service) {
125 public void removedService(final ServiceReference<QuiesceParticipant> reference,
126 final QuiesceParticipant service) {
129 quiesceParticipantTracker.open();
132 private QuiesceParticipant onQuiesceParticipantAdded(final ServiceReference<QuiesceParticipant> reference) {
133 quiesceParticipant = reference.getBundle().getBundleContext().getService(reference);
135 LOG.debug("Got QuiesceParticipant");
137 restartService.setQuiesceParticipant(quiesceParticipant);
139 return quiesceParticipant;
142 private BlueprintExtenderService onBlueprintExtenderServiceAdded(
143 final ServiceReference<BlueprintExtenderService> reference) {
144 blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
145 bundleTracker.open();
147 bundleContext.addBundleListener(BlueprintBundleTracker.this);
149 LOG.debug("Got BlueprintExtenderService");
151 restartService.setBlueprintExtenderService(blueprintExtenderService);
153 blueprintContainerRestartReg = bundleContext.registerService(
154 BlueprintContainerRestartService.class.getName(), restartService, new Hashtable<>());
156 return blueprintExtenderService;
159 private void registerNamespaceHandler(final BundleContext context) {
160 Dictionary<String, Object> props = new Hashtable<>();
161 props.put("osgi.service.blueprint.namespace", OpendaylightNamespaceHandler.NAMESPACE_1_0_0);
162 namespaceReg = context.registerService(NamespaceHandler.class.getName(),
163 new OpendaylightNamespaceHandler(), props);
166 private void registerBlueprintEventHandler(final BundleContext context) {
167 eventHandlerReg = context.registerService(BlueprintListener.class.getName(), this, new Hashtable<>());
171 * Implemented from BundleActivator.
174 public void stop(final BundleContext context) {
175 bundleTracker.close();
176 blueprintExtenderServiceTracker.close();
177 quiesceParticipantTracker.close();
179 AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
180 AriesFrameworkUtil.safeUnregisterService(namespaceReg);
181 AriesFrameworkUtil.safeUnregisterService(blueprintContainerRestartReg);
185 * Implemented from SynchronousBundleListener.
188 public void bundleChanged(final BundleEvent event) {
189 // If the system bundle (id 0) is stopping, do an orderly shutdown of all blueprint containers. On
190 // shutdown the system bundle is stopped first.
191 if (event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
192 shutdownAllContainers();
197 * Implemented from BundleActivator.
200 public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
201 modifiedBundle(bundle, event, bundle);
206 * Implemented from BundleTrackerCustomizer.
209 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
214 if (bundle.getState() == Bundle.ACTIVE) {
215 List<Object> paths = findBlueprintPaths(bundle, ODL_CUSTOM_BLUEPRINT_FILE_PATH);
217 if (!paths.isEmpty()) {
218 LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
220 blueprintExtenderService.createContainer(bundle, paths);
226 * Implemented from BundleTrackerCustomizer.
229 public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
230 // BlueprintExtenderService will handle this.
234 * Implemented from BlueprintListener to listen for blueprint events.
236 * @param event the event to handle
239 public void blueprintEvent(final BlueprintEvent event) {
240 if (event.getType() == BlueprintEvent.CREATED) {
241 LOG.info("Blueprint container for bundle {} was successfully created", event.getBundle());
245 // If the container timed out waiting for dependencies, we'll destroy it and start it again. This
246 // is indicated via a non-null DEPENDENCIES property containing the missing dependencies. The
247 // default timeout is 5 min and ideally we would set this to infinite but the timeout can only
248 // be set at the bundle level in the manifest - there's no way to set it globally.
249 if (event.getType() == BlueprintEvent.FAILURE && event.getDependencies() != null) {
250 Bundle bundle = event.getBundle();
252 List<Object> paths = findBlueprintPaths(bundle);
253 if (!paths.isEmpty()) {
254 LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
257 restartService.restartContainer(bundle, paths);
262 static List<Object> findBlueprintPaths(final Bundle bundle) {
263 List<Object> paths = findBlueprintPaths(bundle, STANDARD_BLUEPRINT_FILE_PATH);
264 return !paths.isEmpty() ? paths : findBlueprintPaths(bundle, ODL_CUSTOM_BLUEPRINT_FILE_PATH);
267 @SuppressWarnings({ "rawtypes", "unchecked" })
268 private static List<Object> findBlueprintPaths(final Bundle bundle, final String path) {
269 Enumeration<?> rntries = bundle.findEntries(path, BLUEPRINT_FLE_PATTERN, false);
270 if (rntries == null) {
271 return Collections.emptyList();
273 return Collections.list((Enumeration)rntries);
277 private void shutdownAllContainers() {
280 restartService.close();
282 LOG.info("Shutting down all blueprint containers...");
284 Collection<Bundle> containerBundles = new HashSet<>(Arrays.asList(bundleContext.getBundles()));
285 while (!containerBundles.isEmpty()) {
286 // For each iteration of getBundlesToDestroy, as containers are destroyed, other containers become
287 // eligible to be destroyed. We loop until we've destroyed them all.
288 for (Bundle bundle : getBundlesToDestroy(containerBundles)) {
289 containerBundles.remove(bundle);
290 BlueprintContainer container = blueprintExtenderService.getContainer(bundle);
291 if (container != null) {
292 blueprintExtenderService.destroyContainer(bundle, container);
297 LOG.info("Shutdown of blueprint containers complete");
300 private List<Bundle> getBundlesToDestroy(final Collection<Bundle> containerBundles) {
301 List<Bundle> bundlesToDestroy = new ArrayList<>();
303 // Find all container bundles that either have no registered services or whose services are no
305 for (Bundle bundle : containerBundles) {
306 ServiceReference<?>[] references = bundle.getRegisteredServices();
308 if (references != null) {
309 for (ServiceReference<?> reference : references) {
310 usage += getServiceUsage(reference);
314 LOG.debug("Usage for bundle {} is {}", bundle, usage);
316 bundlesToDestroy.add(bundle);
320 if (!bundlesToDestroy.isEmpty()) {
321 bundlesToDestroy.sort((b1, b2) -> (int) (b2.getLastModified() - b1.getLastModified()));
323 LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy);
325 // There's either no more container bundles or they all have services being used. For
326 // the latter it means there's either circular service usage or a service is being used
327 // by a non-container bundle. But we need to make progress so we pick the bundle with a
328 // used service with the highest service ID. Each service is assigned a monotonically
329 // increasing ID as they are registered. By picking the bundle with the highest service
330 // ID, we're picking the bundle that was (likely) started after all the others and thus
331 // is likely the safest to destroy at this point.
333 Bundle bundle = findBundleWithHighestUsedServiceId(containerBundles);
334 if (bundle != null) {
335 bundlesToDestroy.add(bundle);
338 LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
342 return bundlesToDestroy;
345 private @Nullable Bundle findBundleWithHighestUsedServiceId(final Collection<Bundle> containerBundles) {
346 ServiceReference<?> highestServiceRef = null;
347 for (Bundle bundle : containerBundles) {
348 ServiceReference<?>[] references = bundle.getRegisteredServices();
349 if (references == null) {
353 for (ServiceReference<?> reference : references) {
354 // We did check the service usage previously but it's possible the usage has changed since then.
355 if (getServiceUsage(reference) == 0) {
359 // Choose 'reference' if it has a lower service ranking or, if the rankings are equal
360 // which is usually the case, if it has a higher service ID. For the latter the < 0
361 // check looks backwards but that's how ServiceReference#compareTo is documented to work.
362 if (highestServiceRef == null || reference.compareTo(highestServiceRef) < 0) {
363 LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference);
364 highestServiceRef = reference;
369 return highestServiceRef == null ? null : highestServiceRef.getBundle();
372 private static int getServiceUsage(final ServiceReference<?> ref) {
373 Bundle[] usingBundles = ref.getUsingBundles();
374 return usingBundles != null ? usingBundles.length : 0;