Bump upstream SNAPSHOTS
[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 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;
43
44 /**
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.
49  *
50  * @author Thomas Pantelis
51  */
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;
59
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;
71
72     /**
73      * Implemented from BundleActivator.
74      */
75     @Override
76     public void start(final BundleContext context) {
77         LOG.info("Starting {}", getClass().getSimpleName());
78
79         // CONTROLLER-1867: force UntrustedXML initialization, so that it uses our TCCL to initialize
80         UntrustedXML.newDocumentBuilder();
81
82         restartService = new BlueprintContainerRestartServiceImpl();
83
84         bundleContext = context;
85
86         registerBlueprintEventHandler(context);
87
88         registerNamespaceHandler(context);
89
90         bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
91
92         blueprintExtenderServiceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class,
93                 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
94                     @Override
95                     public BlueprintExtenderService addingService(
96                             final ServiceReference<BlueprintExtenderService> reference) {
97                         return onBlueprintExtenderServiceAdded(reference);
98                     }
99
100                     @Override
101                     public void modifiedService(final ServiceReference<BlueprintExtenderService> reference,
102                             final BlueprintExtenderService service) {
103                     }
104
105                     @Override
106                     public void removedService(final ServiceReference<BlueprintExtenderService> reference,
107                             final BlueprintExtenderService service) {
108                     }
109                 });
110         blueprintExtenderServiceTracker.open();
111
112         quiesceParticipantTracker = new ServiceTracker<>(context, QuiesceParticipant.class,
113                 new ServiceTrackerCustomizer<QuiesceParticipant, QuiesceParticipant>() {
114                     @Override
115                     public QuiesceParticipant addingService(
116                             final ServiceReference<QuiesceParticipant> reference) {
117                         return onQuiesceParticipantAdded(reference);
118                     }
119
120                     @Override
121                     public void modifiedService(final ServiceReference<QuiesceParticipant> reference,
122                                                 final QuiesceParticipant service) {
123                     }
124
125                     @Override
126                     public void removedService(final ServiceReference<QuiesceParticipant> reference,
127                                                final QuiesceParticipant service) {
128                     }
129                 });
130         quiesceParticipantTracker.open();
131     }
132
133     private QuiesceParticipant onQuiesceParticipantAdded(final ServiceReference<QuiesceParticipant> reference) {
134         quiesceParticipant = reference.getBundle().getBundleContext().getService(reference);
135
136         LOG.debug("Got QuiesceParticipant");
137
138         restartService.setQuiesceParticipant(quiesceParticipant);
139
140         return quiesceParticipant;
141     }
142
143     private BlueprintExtenderService onBlueprintExtenderServiceAdded(
144             final ServiceReference<BlueprintExtenderService> reference) {
145         blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
146         bundleTracker.open();
147
148         bundleContext.addBundleListener(BlueprintBundleTracker.this);
149
150         LOG.debug("Got BlueprintExtenderService");
151
152         restartService.setBlueprintExtenderService(blueprintExtenderService);
153
154         blueprintContainerRestartReg = bundleContext.registerService(BlueprintContainerRestartService.class,
155             restartService, null);
156
157         return blueprintExtenderService;
158     }
159
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);
164     }
165
166     private void registerBlueprintEventHandler(final BundleContext context) {
167         eventHandlerReg = context.registerService(BlueprintListener.class, this, null);
168     }
169
170     @SuppressModernizer
171     private static Dictionary<String, Object> emptyDict() {
172         return new Hashtable<>();
173     }
174
175     /**
176      * Implemented from BundleActivator.
177      */
178     @Override
179     public void stop(final BundleContext context) {
180         bundleTracker.close();
181         blueprintExtenderServiceTracker.close();
182         quiesceParticipantTracker.close();
183
184         AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
185         AriesFrameworkUtil.safeUnregisterService(namespaceReg);
186         AriesFrameworkUtil.safeUnregisterService(blueprintContainerRestartReg);
187     }
188
189     /**
190      * Implemented from SynchronousBundleListener.
191      */
192     @Override
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();
198         }
199     }
200
201     /**
202      * Implemented from BundleActivator.
203      */
204     @Override
205     public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
206         modifiedBundle(bundle, event, bundle);
207         return bundle;
208     }
209
210     /**
211      * Implemented from BundleTrackerCustomizer.
212      */
213     @Override
214     public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
215         if (shuttingDown) {
216             return;
217         }
218
219         if (bundle.getState() == Bundle.ACTIVE) {
220             List<Object> paths = findBlueprintPaths(bundle, ODL_CUSTOM_BLUEPRINT_FILE_PATH);
221
222             if (!paths.isEmpty()) {
223                 LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
224
225                 blueprintExtenderService.createContainer(bundle, paths);
226             }
227         }
228     }
229
230     /**
231      * Implemented from BundleTrackerCustomizer.
232      */
233     @Override
234     public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
235         // BlueprintExtenderService will handle this.
236     }
237
238     /**
239      * Implemented from BlueprintListener to listen for blueprint events.
240      *
241      * @param event the event to handle
242      */
243     @Override
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());
247             return;
248         }
249
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();
256
257             List<Object> paths = findBlueprintPaths(bundle);
258             if (!paths.isEmpty()) {
259                 LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
260                         bundle);
261
262                 restartService.restartContainer(bundle, paths);
263             }
264         }
265     }
266
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);
270     }
271
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) {
275             return List.of();
276         } else {
277             return List.copyOf(Collections.list(rntries));
278         }
279     }
280
281     private void shutdownAllContainers() {
282         shuttingDown = true;
283
284         restartService.close();
285
286         LOG.info("Shutting down all blueprint containers...");
287
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);
297                 }
298             }
299         }
300
301         LOG.info("Shutdown of blueprint containers complete");
302     }
303
304     private static List<Bundle> getBundlesToDestroy(final Collection<Bundle> containerBundles) {
305         List<Bundle> bundlesToDestroy = new ArrayList<>();
306
307         // Find all container bundles that either have no registered services or whose services are no
308         // longer in use.
309         for (Bundle bundle : containerBundles) {
310             ServiceReference<?>[] references = bundle.getRegisteredServices();
311             int usage = 0;
312             if (references != null) {
313                 for (ServiceReference<?> reference : references) {
314                     usage += getServiceUsage(reference);
315                 }
316             }
317
318             LOG.debug("Usage for bundle {} is {}", bundle, usage);
319             if (usage == 0) {
320                 bundlesToDestroy.add(bundle);
321             }
322         }
323
324         if (!bundlesToDestroy.isEmpty()) {
325             bundlesToDestroy.sort((b1, b2) -> (int) (b2.getLastModified() - b1.getLastModified()));
326
327             LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy);
328         } else {
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.
336
337             Bundle bundle = findBundleWithHighestUsedServiceId(containerBundles);
338             if (bundle != null) {
339                 bundlesToDestroy.add(bundle);
340             }
341
342             LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
343                     bundlesToDestroy);
344         }
345
346         return bundlesToDestroy;
347     }
348
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) {
354                 continue;
355             }
356
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) {
360                     continue;
361                 }
362
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;
369                 }
370             }
371         }
372
373         return highestServiceRef == null ? null : highestServiceRef.getBundle();
374     }
375
376     private static int getServiceUsage(final ServiceReference<?> ref) {
377         Bundle[] usingBundles = ref.getUsingBundles();
378         return usingBundles != null ? usingBundles.length : 0;
379     }
380 }