Fix findbugs warnings
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / ext / AbstractDependentComponentFactoryMetadata.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.ext;
9
10 import com.google.common.base.Preconditions;
11 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.List;
15 import java.util.concurrent.atomic.AtomicBoolean;
16 import java.util.function.Consumer;
17 import javax.annotation.Nullable;
18 import javax.annotation.concurrent.GuardedBy;
19 import org.apache.aries.blueprint.di.AbstractRecipe;
20 import org.apache.aries.blueprint.di.ExecutionContext;
21 import org.apache.aries.blueprint.di.Recipe;
22 import org.apache.aries.blueprint.ext.DependentComponentFactoryMetadata;
23 import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
24 import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
25 import org.osgi.framework.ServiceReference;
26 import org.osgi.service.blueprint.container.ComponentDefinitionException;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * Abstract base class for a DependentComponentFactoryMetadata implementation.
32  *
33  * @author Thomas Pantelis
34  */
35 abstract class AbstractDependentComponentFactoryMetadata implements DependentComponentFactoryMetadata {
36     @SuppressFBWarnings("SLF4J_LOGGER_SHOULD_BE_PRIVATE")
37     final Logger log = LoggerFactory.getLogger(getClass());
38     private final String id;
39     private final AtomicBoolean started = new AtomicBoolean();
40     private final AtomicBoolean satisfied = new AtomicBoolean();
41     private final AtomicBoolean restarting = new AtomicBoolean();
42     @GuardedBy("serviceRecipes")
43     private final List<StaticServiceReferenceRecipe> serviceRecipes = new ArrayList<>();
44     private volatile ExtendedBlueprintContainer container;
45     private volatile SatisfactionCallback satisfactionCallback;
46     private volatile String failureMessage;
47     private volatile Throwable failureCause;
48     private volatile String dependencyDesc;
49     @GuardedBy("serviceRecipes")
50     private boolean stoppedServiceRecipes;
51
52     protected AbstractDependentComponentFactoryMetadata(final String id) {
53         this.id = Preconditions.checkNotNull(id);
54     }
55
56     @Override
57     public String getId() {
58         return id;
59     }
60
61     @Override
62     public int getActivation() {
63         return ACTIVATION_EAGER;
64     }
65
66     @Override
67     public List<String> getDependsOn() {
68         return Collections.emptyList();
69     }
70
71     @Override
72     public String getDependencyDescriptor() {
73         return dependencyDesc;
74     }
75
76     @Override
77     public boolean isSatisfied() {
78         return satisfied.get();
79     }
80
81     protected void setFailureMessage(final String failureMessage) {
82         setFailure(failureMessage, null);
83     }
84
85     @SuppressWarnings("checkstyle:hiddenField")
86     protected void setFailure(final String failureMessage, final Throwable failureCause) {
87         this.failureMessage = failureMessage;
88         this.failureCause = failureCause;
89     }
90
91     protected void setDependencyDesc(final String dependencyDesc) {
92         this.dependencyDesc = dependencyDesc;
93     }
94
95     protected final ExtendedBlueprintContainer container() {
96         return container;
97     }
98
99     protected void setSatisfied() {
100         if (satisfied.compareAndSet(false, true)) {
101             satisfactionCallback.notifyChanged();
102         }
103     }
104
105     protected void retrieveService(final String name, final Class<?> interfaceClass,
106             final Consumer<Object> onServiceRetrieved) {
107         retrieveService(name, interfaceClass.getName(), onServiceRetrieved);
108     }
109
110     protected void retrieveService(final String name, final String interfaceName,
111             final Consumer<Object> onServiceRetrieved) {
112         synchronized (serviceRecipes) {
113             if (stoppedServiceRecipes) {
114                 return;
115             }
116
117             StaticServiceReferenceRecipe recipe = new StaticServiceReferenceRecipe(getId() + "-" + name,
118                     container, interfaceName);
119             setDependencyDesc(recipe.getOsgiFilter());
120             serviceRecipes.add(recipe);
121
122             recipe.startTracking(onServiceRetrieved);
123         }
124     }
125
126     protected final String logName() {
127         return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + " (" + id + ")";
128     }
129
130     @Override
131     public void init(final ExtendedBlueprintContainer newContainer) {
132         this.container = newContainer;
133
134         log.debug("{}: In init", logName());
135     }
136
137     protected void onCreate() throws ComponentDefinitionException {
138         if (failureMessage != null) {
139             throw new ComponentDefinitionException(failureMessage, failureCause);
140         }
141
142         // The following code is a bit odd so requires some explanation. A little background... If a bean
143         // is a prototype then the corresponding Recipe create method does not register the bean as created
144         // with the BlueprintRepository and thus the destroy method isn't called on container destroy. We
145         // rely on destroy being called to close our DTCL registration. Unfortunately the default setting
146         // for the prototype flag in AbstractRecipe is true and the DependentComponentFactoryRecipe, which
147         // is created for DependentComponentFactoryMetadata types of which we are one, doesn't have a way for
148         // us to indicate the prototype state via our metadata.
149         //
150         // The ExecutionContext is actually backed by the BlueprintRepository so we access it here to call
151         // the removePartialObject method which removes any partially created instance, which does not apply
152         // in our case, and also has the side effect of registering our bean as created as if it wasn't a
153         // prototype. We also obtain our corresponding Recipe instance and clear the prototype flag. This
154         // doesn't look to be necessary but is done so for completeness. Better late than never. Note we have
155         // to do this here rather than in startTracking b/c the ExecutionContext is not available yet at that
156         // point.
157         //
158         // Now the stopTracking method is called on container destroy but startTracking/stopTracking can also
159         // be called multiple times during the container creation process for Satisfiable recipes as bean
160         // processors may modify the metadata which could affect how dependencies are satisfied. An example of
161         // this is with service references where the OSGi filter metadata can be modified by bean processors
162         // after the initial service dependency is satisfied. However we don't have any metadata that could
163         // be modified by a bean processor and we don't want to register/unregister our DTCL multiple times
164         // so we only process startTracking once and close the DTCL registration once on container destroy.
165         ExecutionContext executionContext = ExecutionContext.Holder.getContext();
166         executionContext.removePartialObject(id);
167
168         Recipe myRecipe = executionContext.getRecipe(id);
169         if (myRecipe instanceof AbstractRecipe) {
170             log.debug("{}: setPrototype to false", logName());
171             ((AbstractRecipe)myRecipe).setPrototype(false);
172         } else {
173             log.warn("{}: Recipe is null or not an AbstractRecipe", logName());
174         }
175     }
176
177     protected abstract void startTracking();
178
179     @Override
180     public final void startTracking(final SatisfactionCallback newSatisfactionCallback) {
181         if (!started.compareAndSet(false, true)) {
182             return;
183         }
184
185         log.debug("{}: In startTracking", logName());
186
187         this.satisfactionCallback = newSatisfactionCallback;
188
189         startTracking();
190     }
191
192     @Override
193     public void stopTracking() {
194         log.debug("{}: In stopTracking", logName());
195
196         stopServiceRecipes();
197     }
198
199     @Override
200     public void destroy(final Object instance) {
201         log.debug("{}: In destroy", logName());
202
203         stopServiceRecipes();
204     }
205
206     private void stopServiceRecipes() {
207         synchronized (serviceRecipes) {
208             stoppedServiceRecipes = true;
209             for (StaticServiceReferenceRecipe recipe: serviceRecipes) {
210                 recipe.stop();
211             }
212
213             serviceRecipes.clear();
214         }
215     }
216
217     protected void restartContainer() {
218         if (restarting.compareAndSet(false, true)) {
219             BlueprintContainerRestartService restartService = getOSGiService(BlueprintContainerRestartService.class);
220             if (restartService != null) {
221                 log.debug("{}: Restarting container", logName());
222                 restartService.restartContainerAndDependents(container().getBundleContext().getBundle());
223             }
224         }
225     }
226
227     @SuppressWarnings("unchecked")
228     @Nullable
229     protected <T> T getOSGiService(final Class<T> serviceInterface) {
230         try {
231             ServiceReference<T> serviceReference =
232                     container().getBundleContext().getServiceReference(serviceInterface);
233             if (serviceReference == null) {
234                 log.warn("{}: {} reference not found", logName(), serviceInterface.getSimpleName());
235                 return null;
236             }
237
238             T service = (T)container().getService(serviceReference);
239             if (service == null) {
240                 // This could happen on shutdown if the service was already unregistered so we log as debug.
241                 log.debug("{}: {} was not found", logName(), serviceInterface.getSimpleName());
242             }
243
244             return service;
245         } catch (final IllegalStateException e) {
246             // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we
247             // log as debug.
248             log.debug("{}: Error obtaining {}", logName(), serviceInterface.getSimpleName(), e);
249         }
250
251         return null;
252     }
253 }