Force UntrustedXML to be initialized from activator
[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 BLUEPRINT_FILE_PATH = "org/opendaylight/blueprint/";
55     private static final String BLUEPRINT_FLE_PATTERN = "*.xml";
56     private static final long SYSTEM_BUNDLE_ID = 0;
57
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;
69
70     /**
71      * Implemented from BundleActivator.
72      */
73     @Override
74     public void start(final BundleContext context) {
75         LOG.info("Starting {}", getClass().getSimpleName());
76
77         // CONTROLLER-1867: force UntrustedXML initialization, so that it uses our TCCL to initialize
78         UntrustedXML.newDocumentBuilder();
79
80         restartService = new BlueprintContainerRestartServiceImpl();
81
82         bundleContext = context;
83
84         registerBlueprintEventHandler(context);
85
86         registerNamespaceHandler(context);
87
88         bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
89
90         blueprintExtenderServiceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class.getName(),
91                 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
92                     @Override
93                     public BlueprintExtenderService addingService(
94                             final ServiceReference<BlueprintExtenderService> reference) {
95                         return onBlueprintExtenderServiceAdded(reference);
96                     }
97
98                     @Override
99                     public void modifiedService(final ServiceReference<BlueprintExtenderService> reference,
100                             final BlueprintExtenderService service) {
101                     }
102
103                     @Override
104                     public void removedService(final ServiceReference<BlueprintExtenderService> reference,
105                             final BlueprintExtenderService service) {
106                     }
107                 });
108         blueprintExtenderServiceTracker.open();
109
110         quiesceParticipantTracker = new ServiceTracker<>(context, QuiesceParticipant.class.getName(),
111                 new ServiceTrackerCustomizer<QuiesceParticipant, QuiesceParticipant>() {
112                     @Override
113                     public QuiesceParticipant addingService(
114                             final ServiceReference<QuiesceParticipant> reference) {
115                         return onQuiesceParticipantAdded(reference);
116                     }
117
118                     @Override
119                     public void modifiedService(final ServiceReference<QuiesceParticipant> reference,
120                                                 final QuiesceParticipant service) {
121                     }
122
123                     @Override
124                     public void removedService(final ServiceReference<QuiesceParticipant> reference,
125                                                final QuiesceParticipant service) {
126                     }
127                 });
128         quiesceParticipantTracker.open();
129     }
130
131     private QuiesceParticipant onQuiesceParticipantAdded(final ServiceReference<QuiesceParticipant> reference) {
132         quiesceParticipant = reference.getBundle().getBundleContext().getService(reference);
133
134         LOG.debug("Got QuiesceParticipant");
135
136         restartService.setQuiesceParticipant(quiesceParticipant);
137
138         return quiesceParticipant;
139     }
140
141     private BlueprintExtenderService onBlueprintExtenderServiceAdded(
142             final ServiceReference<BlueprintExtenderService> reference) {
143         blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
144         bundleTracker.open();
145
146         bundleContext.addBundleListener(BlueprintBundleTracker.this);
147
148         LOG.debug("Got BlueprintExtenderService");
149
150         restartService.setBlueprintExtenderService(blueprintExtenderService);
151
152         blueprintContainerRestartReg = bundleContext.registerService(
153                 BlueprintContainerRestartService.class.getName(), restartService, new Hashtable<>());
154
155         return blueprintExtenderService;
156     }
157
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);
163     }
164
165     private void registerBlueprintEventHandler(final BundleContext context) {
166         eventHandlerReg = context.registerService(BlueprintListener.class.getName(), this, new Hashtable<>());
167     }
168
169     /**
170      * Implemented from BundleActivator.
171      */
172     @Override
173     public void stop(final BundleContext context) {
174         bundleTracker.close();
175         blueprintExtenderServiceTracker.close();
176         quiesceParticipantTracker.close();
177
178         AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
179         AriesFrameworkUtil.safeUnregisterService(namespaceReg);
180         AriesFrameworkUtil.safeUnregisterService(blueprintContainerRestartReg);
181     }
182
183     /**
184      * Implemented from SynchronousBundleListener.
185      */
186     @Override
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();
192         }
193     }
194
195     /**
196      * Implemented from BundleActivator.
197      */
198     @Override
199     public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
200         modifiedBundle(bundle, event, bundle);
201         return bundle;
202     }
203
204     /**
205      * Implemented from BundleTrackerCustomizer.
206      */
207     @Override
208     public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
209         if (shuttingDown) {
210             return;
211         }
212
213         if (bundle.getState() == Bundle.ACTIVE) {
214             List<Object> paths = findBlueprintPaths(bundle);
215
216             if (!paths.isEmpty()) {
217                 LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
218
219                 blueprintExtenderService.createContainer(bundle, paths);
220             }
221         }
222     }
223
224     /**
225      * Implemented from BundleTrackerCustomizer.
226      */
227     @Override
228     public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
229         // BlueprintExtenderService will handle this.
230     }
231
232     /**
233      * Implemented from BlueprintListener to listen for blueprint events.
234      *
235      * @param event the event to handle
236      */
237     @Override
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());
241             return;
242         }
243
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();
250
251             List<Object> paths = findBlueprintPaths(bundle);
252             if (!paths.isEmpty()) {
253                 LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
254                         bundle);
255
256                 restartService.restartContainer(bundle, paths);
257             }
258         }
259     }
260
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();
266         } else {
267             return Collections.list((Enumeration)rntries);
268         }
269     }
270
271     private void shutdownAllContainers() {
272         shuttingDown = true;
273
274         restartService.close();
275
276         LOG.info("Shutting down all blueprint containers...");
277
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);
287                 }
288             }
289         }
290
291         LOG.info("Shutdown of blueprint containers complete");
292     }
293
294     private List<Bundle> getBundlesToDestroy(final Collection<Bundle> containerBundles) {
295         List<Bundle> bundlesToDestroy = new ArrayList<>();
296
297         // Find all container bundles that either have no registered services or whose services are no
298         // longer in use.
299         for (Bundle bundle : containerBundles) {
300             ServiceReference<?>[] references = bundle.getRegisteredServices();
301             int usage = 0;
302             if (references != null) {
303                 for (ServiceReference<?> reference : references) {
304                     usage += getServiceUsage(reference);
305                 }
306             }
307
308             LOG.debug("Usage for bundle {} is {}", bundle, usage);
309             if (usage == 0) {
310                 bundlesToDestroy.add(bundle);
311             }
312         }
313
314         if (!bundlesToDestroy.isEmpty()) {
315             bundlesToDestroy.sort((b1, b2) -> (int) (b2.getLastModified() - b1.getLastModified()));
316
317             LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy);
318         } else {
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.
326
327             Bundle bundle = findBundleWithHighestUsedServiceId(containerBundles);
328             if (bundle != null) {
329                 bundlesToDestroy.add(bundle);
330             }
331
332             LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
333                     bundlesToDestroy);
334         }
335
336         return bundlesToDestroy;
337     }
338
339     @Nullable
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) {
345                 continue;
346             }
347
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) {
351                     continue;
352                 }
353
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;
360                 }
361             }
362         }
363
364         return highestServiceRef == null ? null : highestServiceRef.getBundle();
365     }
366
367     private static int getServiceUsage(final ServiceReference<?> ref) {
368         Bundle[] usingBundles = ref.getUsingBundles();
369         return usingBundles != null ? usingBundles.length : 0;
370     }
371 }