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.gaul.modernizer_maven_annotations.SuppressModernizer;
25 import org.opendaylight.controller.blueprint.ext.OpendaylightNamespaceHandler;
26 import org.opendaylight.yangtools.util.xml.UntrustedXML;
27 import org.osgi.framework.Bundle;
28 import org.osgi.framework.BundleActivator;
29 import org.osgi.framework.BundleContext;
30 import org.osgi.framework.BundleEvent;
31 import org.osgi.framework.ServiceReference;
32 import org.osgi.framework.ServiceRegistration;
33 import org.osgi.framework.SynchronousBundleListener;
34 import org.osgi.service.blueprint.container.BlueprintContainer;
35 import org.osgi.service.blueprint.container.BlueprintEvent;
36 import org.osgi.service.blueprint.container.BlueprintListener;
37 import org.osgi.util.tracker.BundleTracker;
38 import org.osgi.util.tracker.BundleTrackerCustomizer;
39 import org.osgi.util.tracker.ServiceTracker;
40 import org.osgi.util.tracker.ServiceTrackerCustomizer;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * This class is created in bundle activation and scans ACTIVE bundles for blueprint XML files located under
46 * the well-known org/opendaylight/blueprint/ path and deploys the XML files via the Aries
47 * BlueprintExtenderService. This path differs from the standard OSGI-INF/blueprint path to allow for
48 * controlled deployment of blueprint containers in an orderly manner.
50 * @author Thomas Pantelis
52 public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCustomizer<Bundle>, BlueprintListener,
53 SynchronousBundleListener {
54 private static final Logger LOG = LoggerFactory.getLogger(BlueprintBundleTracker.class);
55 private static final String ODL_CUSTOM_BLUEPRINT_FILE_PATH = "org/opendaylight/blueprint/";
56 private static final String STANDARD_BLUEPRINT_FILE_PATH = "OSGI-INF/blueprint/";
57 private static final String BLUEPRINT_FLE_PATTERN = "*.xml";
58 private static final long SYSTEM_BUNDLE_ID = 0;
60 private ServiceTracker<BlueprintExtenderService, BlueprintExtenderService> blueprintExtenderServiceTracker;
61 private ServiceTracker<QuiesceParticipant, QuiesceParticipant> quiesceParticipantTracker;
62 private BundleTracker<Bundle> bundleTracker;
63 private BundleContext bundleContext;
64 private volatile BlueprintExtenderService blueprintExtenderService;
65 private volatile QuiesceParticipant quiesceParticipant;
66 private volatile ServiceRegistration<?> blueprintContainerRestartReg;
67 private volatile BlueprintContainerRestartServiceImpl restartService;
68 private volatile boolean shuttingDown;
69 private ServiceRegistration<?> eventHandlerReg;
70 private ServiceRegistration<?> namespaceReg;
73 * Implemented from BundleActivator.
76 public void start(final BundleContext context) {
77 LOG.info("Starting {}", getClass().getSimpleName());
79 // CONTROLLER-1867: force UntrustedXML initialization, so that it uses our TCCL to initialize
80 UntrustedXML.newDocumentBuilder();
82 restartService = new BlueprintContainerRestartServiceImpl();
84 bundleContext = context;
86 registerBlueprintEventHandler(context);
88 registerNamespaceHandler(context);
90 bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
92 blueprintExtenderServiceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class,
93 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
95 public BlueprintExtenderService addingService(
96 final ServiceReference<BlueprintExtenderService> reference) {
97 return onBlueprintExtenderServiceAdded(reference);
101 public void modifiedService(final ServiceReference<BlueprintExtenderService> reference,
102 final BlueprintExtenderService service) {
106 public void removedService(final ServiceReference<BlueprintExtenderService> reference,
107 final BlueprintExtenderService service) {
110 blueprintExtenderServiceTracker.open();
112 quiesceParticipantTracker = new ServiceTracker<>(context, QuiesceParticipant.class,
113 new ServiceTrackerCustomizer<QuiesceParticipant, QuiesceParticipant>() {
115 public QuiesceParticipant addingService(
116 final ServiceReference<QuiesceParticipant> reference) {
117 return onQuiesceParticipantAdded(reference);
121 public void modifiedService(final ServiceReference<QuiesceParticipant> reference,
122 final QuiesceParticipant service) {
126 public void removedService(final ServiceReference<QuiesceParticipant> reference,
127 final QuiesceParticipant service) {
130 quiesceParticipantTracker.open();
133 private QuiesceParticipant onQuiesceParticipantAdded(final ServiceReference<QuiesceParticipant> reference) {
134 quiesceParticipant = reference.getBundle().getBundleContext().getService(reference);
136 LOG.debug("Got QuiesceParticipant");
138 restartService.setQuiesceParticipant(quiesceParticipant);
140 return quiesceParticipant;
143 private BlueprintExtenderService onBlueprintExtenderServiceAdded(
144 final ServiceReference<BlueprintExtenderService> reference) {
145 blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
146 bundleTracker.open();
148 bundleContext.addBundleListener(BlueprintBundleTracker.this);
150 LOG.debug("Got BlueprintExtenderService");
152 restartService.setBlueprintExtenderService(blueprintExtenderService);
154 blueprintContainerRestartReg = bundleContext.registerService(BlueprintContainerRestartService.class,
155 restartService, null);
157 return blueprintExtenderService;
160 private void registerNamespaceHandler(final BundleContext context) {
161 Dictionary<String, Object> props = emptyDict();
162 props.put("osgi.service.blueprint.namespace", OpendaylightNamespaceHandler.NAMESPACE_1_0_0);
163 namespaceReg = context.registerService(NamespaceHandler.class, new OpendaylightNamespaceHandler(), props);
166 private void registerBlueprintEventHandler(final BundleContext context) {
167 eventHandlerReg = context.registerService(BlueprintListener.class, this, null);
171 private static Dictionary<String, Object> emptyDict() {
172 return new Hashtable<>();
176 * Implemented from BundleActivator.
179 public void stop(final BundleContext context) {
180 bundleTracker.close();
181 blueprintExtenderServiceTracker.close();
182 quiesceParticipantTracker.close();
184 AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
185 AriesFrameworkUtil.safeUnregisterService(namespaceReg);
186 AriesFrameworkUtil.safeUnregisterService(blueprintContainerRestartReg);
190 * Implemented from SynchronousBundleListener.
193 public void bundleChanged(final BundleEvent event) {
194 // If the system bundle (id 0) is stopping, do an orderly shutdown of all blueprint containers. On
195 // shutdown the system bundle is stopped first.
196 if (event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
197 shutdownAllContainers();
202 * Implemented from BundleActivator.
205 public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
206 modifiedBundle(bundle, event, bundle);
211 * Implemented from BundleTrackerCustomizer.
214 public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
219 if (bundle.getState() == Bundle.ACTIVE) {
220 List<Object> paths = findBlueprintPaths(bundle, ODL_CUSTOM_BLUEPRINT_FILE_PATH);
222 if (!paths.isEmpty()) {
223 LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
225 blueprintExtenderService.createContainer(bundle, paths);
231 * Implemented from BundleTrackerCustomizer.
234 public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
235 // BlueprintExtenderService will handle this.
239 * Implemented from BlueprintListener to listen for blueprint events.
241 * @param event the event to handle
244 public void blueprintEvent(final BlueprintEvent event) {
245 if (event.getType() == BlueprintEvent.CREATED) {
246 LOG.info("Blueprint container for bundle {} was successfully created", event.getBundle());
250 // If the container timed out waiting for dependencies, we'll destroy it and start it again. This
251 // is indicated via a non-null DEPENDENCIES property containing the missing dependencies. The
252 // default timeout is 5 min and ideally we would set this to infinite but the timeout can only
253 // be set at the bundle level in the manifest - there's no way to set it globally.
254 if (event.getType() == BlueprintEvent.FAILURE && event.getDependencies() != null) {
255 Bundle bundle = event.getBundle();
257 List<Object> paths = findBlueprintPaths(bundle);
258 if (!paths.isEmpty()) {
259 LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
262 restartService.restartContainer(bundle, paths);
267 static List<Object> findBlueprintPaths(final Bundle bundle) {
268 List<Object> paths = findBlueprintPaths(bundle, STANDARD_BLUEPRINT_FILE_PATH);
269 return !paths.isEmpty() ? paths : findBlueprintPaths(bundle, ODL_CUSTOM_BLUEPRINT_FILE_PATH);
272 private static List<Object> findBlueprintPaths(final Bundle bundle, final String path) {
273 Enumeration<?> rntries = bundle.findEntries(path, BLUEPRINT_FLE_PATTERN, false);
274 if (rntries == null) {
277 return List.copyOf(Collections.list(rntries));
281 private void shutdownAllContainers() {
284 restartService.close();
286 LOG.info("Shutting down all blueprint containers...");
288 Collection<Bundle> containerBundles = new HashSet<>(Arrays.asList(bundleContext.getBundles()));
289 while (!containerBundles.isEmpty()) {
290 // For each iteration of getBundlesToDestroy, as containers are destroyed, other containers become
291 // eligible to be destroyed. We loop until we've destroyed them all.
292 for (Bundle bundle : getBundlesToDestroy(containerBundles)) {
293 containerBundles.remove(bundle);
294 BlueprintContainer container = blueprintExtenderService.getContainer(bundle);
295 if (container != null) {
296 blueprintExtenderService.destroyContainer(bundle, container);
301 LOG.info("Shutdown of blueprint containers complete");
304 private static List<Bundle> getBundlesToDestroy(final Collection<Bundle> containerBundles) {
305 List<Bundle> bundlesToDestroy = new ArrayList<>();
307 // Find all container bundles that either have no registered services or whose services are no
309 for (Bundle bundle : containerBundles) {
310 ServiceReference<?>[] references = bundle.getRegisteredServices();
312 if (references != null) {
313 for (ServiceReference<?> reference : references) {
314 usage += getServiceUsage(reference);
318 LOG.debug("Usage for bundle {} is {}", bundle, usage);
320 bundlesToDestroy.add(bundle);
324 if (!bundlesToDestroy.isEmpty()) {
325 bundlesToDestroy.sort((b1, b2) -> (int) (b2.getLastModified() - b1.getLastModified()));
327 LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy);
329 // There's either no more container bundles or they all have services being used. For
330 // the latter it means there's either circular service usage or a service is being used
331 // by a non-container bundle. But we need to make progress so we pick the bundle with a
332 // used service with the highest service ID. Each service is assigned a monotonically
333 // increasing ID as they are registered. By picking the bundle with the highest service
334 // ID, we're picking the bundle that was (likely) started after all the others and thus
335 // is likely the safest to destroy at this point.
337 Bundle bundle = findBundleWithHighestUsedServiceId(containerBundles);
338 if (bundle != null) {
339 bundlesToDestroy.add(bundle);
342 LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
346 return bundlesToDestroy;
349 private static @Nullable Bundle findBundleWithHighestUsedServiceId(final Collection<Bundle> containerBundles) {
350 ServiceReference<?> highestServiceRef = null;
351 for (Bundle bundle : containerBundles) {
352 ServiceReference<?>[] references = bundle.getRegisteredServices();
353 if (references == null) {
357 for (ServiceReference<?> reference : references) {
358 // We did check the service usage previously but it's possible the usage has changed since then.
359 if (getServiceUsage(reference) == 0) {
363 // Choose 'reference' if it has a lower service ranking or, if the rankings are equal
364 // which is usually the case, if it has a higher service ID. For the latter the < 0
365 // check looks backwards but that's how ServiceReference#compareTo is documented to work.
366 if (highestServiceRef == null || reference.compareTo(highestServiceRef) < 0) {
367 LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference);
368 highestServiceRef = reference;
373 return highestServiceRef == null ? null : highestServiceRef.getBundle();
376 private static int getServiceUsage(final ServiceReference<?> ref) {
377 Bundle[] usingBundles = ref.getUsingBundles();
378 return usingBundles != null ? usingBundles.length : 0;