b79d3662f966b36aca51fd6fee3ba106cb951bd4
[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.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;
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>, 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;
58
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;
70
71     /**
72      * Implemented from BundleActivator.
73      */
74     @Override
75     public void start(final BundleContext context) {
76         LOG.info("Starting {}", getClass().getSimpleName());
77
78         // CONTROLLER-1867: force UntrustedXML initialization, so that it uses our TCCL to initialize
79         UntrustedXML.newDocumentBuilder();
80
81         restartService = new BlueprintContainerRestartServiceImpl();
82
83         bundleContext = context;
84
85         registerBlueprintEventHandler(context);
86
87         registerNamespaceHandler(context);
88
89         bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
90
91         blueprintExtenderServiceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class.getName(),
92                 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
93                     @Override
94                     public BlueprintExtenderService addingService(
95                             final ServiceReference<BlueprintExtenderService> reference) {
96                         return onBlueprintExtenderServiceAdded(reference);
97                     }
98
99                     @Override
100                     public void modifiedService(final ServiceReference<BlueprintExtenderService> reference,
101                             final BlueprintExtenderService service) {
102                     }
103
104                     @Override
105                     public void removedService(final ServiceReference<BlueprintExtenderService> reference,
106                             final BlueprintExtenderService service) {
107                     }
108                 });
109         blueprintExtenderServiceTracker.open();
110
111         quiesceParticipantTracker = new ServiceTracker<>(context, QuiesceParticipant.class.getName(),
112                 new ServiceTrackerCustomizer<QuiesceParticipant, QuiesceParticipant>() {
113                     @Override
114                     public QuiesceParticipant addingService(
115                             final ServiceReference<QuiesceParticipant> reference) {
116                         return onQuiesceParticipantAdded(reference);
117                     }
118
119                     @Override
120                     public void modifiedService(final ServiceReference<QuiesceParticipant> reference,
121                                                 final QuiesceParticipant service) {
122                     }
123
124                     @Override
125                     public void removedService(final ServiceReference<QuiesceParticipant> reference,
126                                                final QuiesceParticipant service) {
127                     }
128                 });
129         quiesceParticipantTracker.open();
130     }
131
132     private QuiesceParticipant onQuiesceParticipantAdded(final ServiceReference<QuiesceParticipant> reference) {
133         quiesceParticipant = reference.getBundle().getBundleContext().getService(reference);
134
135         LOG.debug("Got QuiesceParticipant");
136
137         restartService.setQuiesceParticipant(quiesceParticipant);
138
139         return quiesceParticipant;
140     }
141
142     private BlueprintExtenderService onBlueprintExtenderServiceAdded(
143             final ServiceReference<BlueprintExtenderService> reference) {
144         blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
145         bundleTracker.open();
146
147         bundleContext.addBundleListener(BlueprintBundleTracker.this);
148
149         LOG.debug("Got BlueprintExtenderService");
150
151         restartService.setBlueprintExtenderService(blueprintExtenderService);
152
153         blueprintContainerRestartReg = bundleContext.registerService(
154                 BlueprintContainerRestartService.class.getName(), restartService, new Hashtable<>());
155
156         return blueprintExtenderService;
157     }
158
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);
164     }
165
166     private void registerBlueprintEventHandler(final BundleContext context) {
167         eventHandlerReg = context.registerService(BlueprintListener.class.getName(), this, new Hashtable<>());
168     }
169
170     /**
171      * Implemented from BundleActivator.
172      */
173     @Override
174     public void stop(final BundleContext context) {
175         bundleTracker.close();
176         blueprintExtenderServiceTracker.close();
177         quiesceParticipantTracker.close();
178
179         AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
180         AriesFrameworkUtil.safeUnregisterService(namespaceReg);
181         AriesFrameworkUtil.safeUnregisterService(blueprintContainerRestartReg);
182     }
183
184     /**
185      * Implemented from SynchronousBundleListener.
186      */
187     @Override
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();
193         }
194     }
195
196     /**
197      * Implemented from BundleActivator.
198      */
199     @Override
200     public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
201         modifiedBundle(bundle, event, bundle);
202         return bundle;
203     }
204
205     /**
206      * Implemented from BundleTrackerCustomizer.
207      */
208     @Override
209     public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
210         if (shuttingDown) {
211             return;
212         }
213
214         if (bundle.getState() == Bundle.ACTIVE) {
215             List<Object> paths = findBlueprintPaths(bundle, ODL_CUSTOM_BLUEPRINT_FILE_PATH);
216
217             if (!paths.isEmpty()) {
218                 LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
219
220                 blueprintExtenderService.createContainer(bundle, paths);
221             }
222         }
223     }
224
225     /**
226      * Implemented from BundleTrackerCustomizer.
227      */
228     @Override
229     public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
230         // BlueprintExtenderService will handle this.
231     }
232
233     /**
234      * Implemented from BlueprintListener to listen for blueprint events.
235      *
236      * @param event the event to handle
237      */
238     @Override
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());
242             return;
243         }
244
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();
251
252             List<Object> paths = findBlueprintPaths(bundle);
253             if (!paths.isEmpty()) {
254                 LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
255                         bundle);
256
257                 restartService.restartContainer(bundle, paths);
258             }
259         }
260     }
261
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);
265     }
266
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();
272         } else {
273             return Collections.list((Enumeration)rntries);
274         }
275     }
276
277     private void shutdownAllContainers() {
278         shuttingDown = true;
279
280         restartService.close();
281
282         LOG.info("Shutting down all blueprint containers...");
283
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);
293                 }
294             }
295         }
296
297         LOG.info("Shutdown of blueprint containers complete");
298     }
299
300     private List<Bundle> getBundlesToDestroy(final Collection<Bundle> containerBundles) {
301         List<Bundle> bundlesToDestroy = new ArrayList<>();
302
303         // Find all container bundles that either have no registered services or whose services are no
304         // longer in use.
305         for (Bundle bundle : containerBundles) {
306             ServiceReference<?>[] references = bundle.getRegisteredServices();
307             int usage = 0;
308             if (references != null) {
309                 for (ServiceReference<?> reference : references) {
310                     usage += getServiceUsage(reference);
311                 }
312             }
313
314             LOG.debug("Usage for bundle {} is {}", bundle, usage);
315             if (usage == 0) {
316                 bundlesToDestroy.add(bundle);
317             }
318         }
319
320         if (!bundlesToDestroy.isEmpty()) {
321             bundlesToDestroy.sort((b1, b2) -> (int) (b2.getLastModified() - b1.getLastModified()));
322
323             LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy);
324         } else {
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.
332
333             Bundle bundle = findBundleWithHighestUsedServiceId(containerBundles);
334             if (bundle != null) {
335                 bundlesToDestroy.add(bundle);
336             }
337
338             LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
339                     bundlesToDestroy);
340         }
341
342         return bundlesToDestroy;
343     }
344
345     @Nullable
346     private Bundle findBundleWithHighestUsedServiceId(final Collection<Bundle> containerBundles) {
347         ServiceReference<?> highestServiceRef = null;
348         for (Bundle bundle : containerBundles) {
349             ServiceReference<?>[] references = bundle.getRegisteredServices();
350             if (references == null) {
351                 continue;
352             }
353
354             for (ServiceReference<?> reference : references) {
355                 // We did check the service usage previously but it's possible the usage has changed since then.
356                 if (getServiceUsage(reference) == 0) {
357                     continue;
358                 }
359
360                 // Choose 'reference' if it has a lower service ranking or, if the rankings are equal
361                 // which is usually the case, if it has a higher service ID. For the latter the < 0
362                 // check looks backwards but that's how ServiceReference#compareTo is documented to work.
363                 if (highestServiceRef == null || reference.compareTo(highestServiceRef) < 0) {
364                     LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference);
365                     highestServiceRef = reference;
366                 }
367             }
368         }
369
370         return highestServiceRef == null ? null : highestServiceRef.getBundle();
371     }
372
373     private static int getServiceUsage(final ServiceReference<?> ref) {
374         Bundle[] usingBundles = ref.getUsingBundles();
375         return usingBundles != null ? usingBundles.length : 0;
376     }
377 }