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