Fix sonar warnings in blueprint bundle
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / BlueprintBundleTracker.java
index 6c267ac5fe62494793d29270420eccfe1685912d..5119c90363794b2b71334e3fc4ac17d1e2d8ae29 100644 (file)
@@ -16,8 +16,10 @@ import java.util.Enumeration;
 import java.util.HashSet;
 import java.util.Hashtable;
 import java.util.List;
+import javax.annotation.Nullable;
 import org.apache.aries.blueprint.NamespaceHandler;
 import org.apache.aries.blueprint.services.BlueprintExtenderService;
+import org.apache.aries.quiesce.participant.QuiesceParticipant;
 import org.apache.aries.util.AriesFrameworkUtil;
 import org.opendaylight.controller.blueprint.ext.OpendaylightNamespaceHandler;
 import org.opendaylight.controller.config.api.ConfigSystemService;
@@ -54,10 +56,12 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
     private static final String BLUEPRINT_FLE_PATTERN = "*.xml";
     private static final long SYSTEM_BUNDLE_ID = 0;
 
-    private ServiceTracker<BlueprintExtenderService, BlueprintExtenderService> serviceTracker;
+    private ServiceTracker<BlueprintExtenderService, BlueprintExtenderService> blueprintExtenderServiceTracker;
+    private ServiceTracker<QuiesceParticipant, QuiesceParticipant> quiesceParticipantTracker;
     private BundleTracker<Bundle> bundleTracker;
     private BundleContext bundleContext;
     private volatile BlueprintExtenderService blueprintExtenderService;
+    private volatile QuiesceParticipant quiesceParticipant;
     private volatile ServiceRegistration<?> blueprintContainerRestartReg;
     private volatile BlueprintContainerRestartServiceImpl restartService;
     private volatile boolean shuttingDown;
@@ -68,9 +72,11 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
      * Implemented from BundleActivator.
      */
     @Override
-    public void start(BundleContext context) {
+    public void start(final BundleContext context) {
         LOG.info("Starting {}", getClass().getSimpleName());
 
+        restartService = new BlueprintContainerRestartServiceImpl();
+
         bundleContext = context;
 
         registerBlueprintEventHandler(context);
@@ -79,46 +85,82 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
 
         bundleTracker = new BundleTracker<>(context, Bundle.ACTIVE, this);
 
-        serviceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class.getName(),
+        blueprintExtenderServiceTracker = new ServiceTracker<>(context, BlueprintExtenderService.class.getName(),
                 new ServiceTrackerCustomizer<BlueprintExtenderService, BlueprintExtenderService>() {
                     @Override
                     public BlueprintExtenderService addingService(
-                            ServiceReference<BlueprintExtenderService> reference) {
-                        blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
-                        bundleTracker.open();
-
-                        context.addBundleListener(BlueprintBundleTracker.this);
+                            final ServiceReference<BlueprintExtenderService> reference) {
+                        return onBlueprintExtenderServiceAdded(reference);
+                    }
 
-                        LOG.debug("Got BlueprintExtenderService");
+                    @Override
+                    public void modifiedService(final ServiceReference<BlueprintExtenderService> reference,
+                            final BlueprintExtenderService service) {
+                    }
 
-                        restartService = new BlueprintContainerRestartServiceImpl(blueprintExtenderService);
-                        blueprintContainerRestartReg = context.registerService(
-                                BlueprintContainerRestartService.class.getName(), restartService, new Hashtable<>());
+                    @Override
+                    public void removedService(final ServiceReference<BlueprintExtenderService> reference,
+                            final BlueprintExtenderService service) {
+                    }
+                });
+        blueprintExtenderServiceTracker.open();
 
-                        return blueprintExtenderService;
+        quiesceParticipantTracker = new ServiceTracker<>(context, QuiesceParticipant.class.getName(),
+                new ServiceTrackerCustomizer<QuiesceParticipant, QuiesceParticipant>() {
+                    @Override
+                    public QuiesceParticipant addingService(
+                            final ServiceReference<QuiesceParticipant> reference) {
+                        return onQuiesceParticipantAdded(reference);
                     }
 
                     @Override
-                    public void modifiedService(ServiceReference<BlueprintExtenderService> reference,
-                            BlueprintExtenderService service) {
+                    public void modifiedService(final ServiceReference<QuiesceParticipant> reference,
+                                                final QuiesceParticipant service) {
                     }
 
                     @Override
-                    public void removedService(ServiceReference<BlueprintExtenderService> reference,
-                            BlueprintExtenderService service) {
+                    public void removedService(final ServiceReference<QuiesceParticipant> reference,
+                                               final QuiesceParticipant service) {
                     }
                 });
-        serviceTracker.open();
+        quiesceParticipantTracker.open();
+    }
+
+    private QuiesceParticipant onQuiesceParticipantAdded(final ServiceReference<QuiesceParticipant> reference) {
+        quiesceParticipant = reference.getBundle().getBundleContext().getService(reference);
+
+        LOG.debug("Got QuiesceParticipant");
+
+        restartService.setQuiesceParticipant(quiesceParticipant);
+
+        return quiesceParticipant;
     }
 
-    private void registerNamespaceHandler(BundleContext context) {
+    private BlueprintExtenderService onBlueprintExtenderServiceAdded(
+            final ServiceReference<BlueprintExtenderService> reference) {
+        blueprintExtenderService = reference.getBundle().getBundleContext().getService(reference);
+        bundleTracker.open();
+
+        bundleContext.addBundleListener(BlueprintBundleTracker.this);
+
+        LOG.debug("Got BlueprintExtenderService");
+
+        restartService.setBlueprintExtenderService(blueprintExtenderService);
+
+        blueprintContainerRestartReg = bundleContext.registerService(
+                BlueprintContainerRestartService.class.getName(), restartService, new Hashtable<>());
+
+        return blueprintExtenderService;
+    }
+
+    private void registerNamespaceHandler(final BundleContext context) {
         Dictionary<String, Object> props = new Hashtable<>();
         props.put("osgi.service.blueprint.namespace", OpendaylightNamespaceHandler.NAMESPACE_1_0_0);
         namespaceReg = context.registerService(NamespaceHandler.class.getName(),
                 new OpendaylightNamespaceHandler(), props);
     }
 
-    private void registerBlueprintEventHandler(BundleContext context) {
+    private void registerBlueprintEventHandler(final BundleContext context) {
         Dictionary<String, Object> props = new Hashtable<>();
         props.put(org.osgi.service.event.EventConstants.EVENT_TOPIC,
                 new String[]{EventConstants.TOPIC_CREATED, EventConstants.TOPIC_FAILURE});
@@ -129,9 +171,10 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
      * Implemented from BundleActivator.
      */
     @Override
-    public void stop(BundleContext context) {
+    public void stop(final BundleContext context) {
         bundleTracker.close();
-        serviceTracker.close();
+        blueprintExtenderServiceTracker.close();
+        quiesceParticipantTracker.close();
 
         AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
         AriesFrameworkUtil.safeUnregisterService(namespaceReg);
@@ -142,7 +185,7 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
      * Implemented from SynchronousBundleListener.
      */
     @Override
-    public void bundleChanged(BundleEvent event) {
+    public void bundleChanged(final BundleEvent event) {
         // If the system bundle (id 0) is stopping, do an orderly shutdown of all blueprint containers. On
         // shutdown the system bundle is stopped first.
         if (event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
@@ -154,16 +197,16 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
      * Implemented from BundleActivator.
      */
     @Override
-    public Bundle addingBundle(Bundle bundle, BundleEvent event) {
+    public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
         modifiedBundle(bundle, event, bundle);
         return bundle;
     }
 
     /**
-     * Implemented from BundleActivator.
+     * Implemented from BundleTrackerCustomizer.
      */
     @Override
-    public void modifiedBundle(Bundle bundle, BundleEvent event, Bundle object) {
+    public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
         if (shuttingDown) {
             return;
         }
@@ -180,10 +223,10 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
     }
 
     /**
-     * Implemented from BundleActivator.
+     * Implemented from BundleTrackerCustomizer.
      */
     @Override
-    public void removedBundle(Bundle bundle, BundleEvent event, Bundle object) {
+    public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
         // BlueprintExtenderService will handle this.
     }
 
@@ -193,31 +236,33 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
      * @param event the event to handle
      */
     @Override
-    public void handleEvent(Event event) {
+    public void handleEvent(final Event event) {
         if (EventConstants.TOPIC_CREATED.equals(event.getTopic())) {
             LOG.info("Blueprint container for bundle {} was successfully created",
                     event.getProperty(EventConstants.BUNDLE));
-        } else if (EventConstants.TOPIC_FAILURE.equals(event.getTopic())) {
-            // If the container timed out waiting for dependencies, we'll destroy it and start it again. This
-            // is indicated via a non-null DEPENDENCIES property containing the missing dependencies. The
-            // default timeout is 5 min and ideally we would set this to infinite but the timeout can only
-            // be set at the bundle level in the manifest - there's no way to set it globally.
-            if (event.getProperty(EventConstants.DEPENDENCIES) != null) {
-                Bundle bundle = (Bundle) event.getProperty(EventConstants.BUNDLE);
-
-                List<Object> paths = findBlueprintPaths(bundle);
-                if (!paths.isEmpty()) {
-                    LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
-                            event.getProperty(EventConstants.BUNDLE));
-
-                    restartService.restartContainer(bundle, paths);
-                }
+            return;
+        }
+
+        // If the container timed out waiting for dependencies, we'll destroy it and start it again. This
+        // is indicated via a non-null DEPENDENCIES property containing the missing dependencies. The
+        // default timeout is 5 min and ideally we would set this to infinite but the timeout can only
+        // be set at the bundle level in the manifest - there's no way to set it globally.
+        if (EventConstants.TOPIC_FAILURE.equals(event.getTopic())
+                && event.getProperty(EventConstants.DEPENDENCIES) != null) {
+            Bundle bundle = (Bundle) event.getProperty(EventConstants.BUNDLE);
+
+            List<Object> paths = findBlueprintPaths(bundle);
+            if (!paths.isEmpty()) {
+                LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it",
+                        event.getProperty(EventConstants.BUNDLE));
+
+                restartService.restartContainer(bundle, paths);
             }
         }
     }
 
     @SuppressWarnings({ "rawtypes", "unchecked" })
-    static List<Object> findBlueprintPaths(Bundle bundle) {
+    static List<Object> findBlueprintPaths(final Bundle bundle) {
         Enumeration<?> rntries = bundle.findEntries(BLUEPRINT_FILE_PATH, BLUEPRINT_FLE_PATTERN, false);
         if (rntries == null) {
             return Collections.emptyList();
@@ -255,7 +300,7 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
         LOG.info("Shutdown of blueprint containers complete");
     }
 
-    private List<Bundle> getBundlesToDestroy(Collection<Bundle> containerBundles) {
+    private List<Bundle> getBundlesToDestroy(final Collection<Bundle> containerBundles) {
         List<Bundle> bundlesToDestroy = new ArrayList<>();
 
         // Find all container bundles that either have no registered services or whose services are no
@@ -288,32 +333,9 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
             // ID, we're picking the bundle that was (likely) started after all the others and thus
             // is likely the safest to destroy at this point.
 
-            ServiceReference<?> ref = null;
-            for (Bundle bundle : containerBundles) {
-                ServiceReference<?>[] references = bundle.getRegisteredServices();
-                if (references == null) {
-                    continue;
-                }
-
-                for (ServiceReference<?> reference : references) {
-                    // We did check the service usage above but it's possible the usage has changed since
-                    // then,
-                    if (getServiceUsage(reference) == 0) {
-                        continue;
-                    }
-
-                    // Choose 'reference' if it has a lower service ranking or, if the rankings are equal
-                    // which is usually the case, if it has a higher service ID. For the latter the < 0
-                    // check looks backwards but that's how ServiceReference#compareTo is documented to work.
-                    if (ref == null || reference.compareTo(ref) < 0) {
-                        LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference);
-                        ref = reference;
-                    }
-                }
-            }
-
-            if (ref != null) {
-                bundlesToDestroy.add(ref.getBundle());
+            Bundle bundle = findBundleWithHighestUsedServiceId(containerBundles);
+            if (bundle != null) {
+                bundlesToDestroy.add(bundle);
             }
 
             LOG.debug("Selected bundle {} for destroy (lowest ranking service or highest service ID)",
@@ -323,12 +345,40 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
         return bundlesToDestroy;
     }
 
-    private static int getServiceUsage(ServiceReference<?> ref) {
+    @Nullable
+    private Bundle findBundleWithHighestUsedServiceId(final Collection<Bundle> containerBundles) {
+        ServiceReference<?> highestServiceRef = null;
+        for (Bundle bundle : containerBundles) {
+            ServiceReference<?>[] references = bundle.getRegisteredServices();
+            if (references == null) {
+                continue;
+            }
+
+            for (ServiceReference<?> reference : references) {
+                // We did check the service usage previously but it's possible the usage has changed since then.
+                if (getServiceUsage(reference) == 0) {
+                    continue;
+                }
+
+                // Choose 'reference' if it has a lower service ranking or, if the rankings are equal
+                // which is usually the case, if it has a higher service ID. For the latter the < 0
+                // check looks backwards but that's how ServiceReference#compareTo is documented to work.
+                if (highestServiceRef == null || reference.compareTo(highestServiceRef) < 0) {
+                    LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference);
+                    highestServiceRef = reference;
+                }
+            }
+        }
+
+        return highestServiceRef == null ? null : highestServiceRef.getBundle();
+    }
+
+    private static int getServiceUsage(final ServiceReference<?> ref) {
         Bundle[] usingBundles = ref.getUsingBundles();
         return usingBundles != null ? usingBundles.length : 0;
     }
 
-    private <T> T getOSGiService(Class<T> serviceInterface) {
+    private <T> T getOSGiService(final Class<T> serviceInterface) {
         try {
             ServiceReference<T> serviceReference = bundleContext.getServiceReference(serviceInterface);
             if (serviceReference == null) {
@@ -343,7 +393,7 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus
             }
 
             return service;
-        } catch (IllegalStateException e) {
+        } catch (final IllegalStateException e) {
             // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we
             // log as debug.
             LOG.debug("Error obtaining OSGi service {}", serviceInterface.getSimpleName(), e);