2 * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.blueprint.ext;
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;
30 * Abstract base class for a DependentComponentFactoryMetadata implementation.
32 * @author Thomas Pantelis
34 abstract class AbstractDependentComponentFactoryMetadata implements DependentComponentFactoryMetadata {
35 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 dependencyDesc;
47 @GuardedBy("serviceRecipes")
48 private boolean stoppedServiceRecipes;
50 protected AbstractDependentComponentFactoryMetadata(final String id) {
51 this.id = Preconditions.checkNotNull(id);
55 public String getId() {
60 public int getActivation() {
61 return ACTIVATION_EAGER;
65 public List<String> getDependsOn() {
66 return Collections.emptyList();
70 public String getDependencyDescriptor() {
71 return dependencyDesc;
75 public boolean isSatisfied() {
76 return satisfied.get();
79 protected void setFailureMessage(final String failureMessage) {
80 setFailure(failureMessage, null);
83 protected void setFailure(final String failureMessage, final Throwable failureCause) {
84 this.failureMessage = failureMessage;
85 this.failureCause = failureCause;
88 protected void setDependencyDesc(final String dependencyDesc) {
89 this.dependencyDesc = dependencyDesc;
92 protected final ExtendedBlueprintContainer container() {
96 protected void setSatisfied() {
97 if (satisfied.compareAndSet(false, true)) {
98 satisfactionCallback.notifyChanged();
102 protected void retrieveService(final String name, final Class<?> interfaceClass,
103 final Consumer<Object> onServiceRetrieved) {
104 retrieveService(name, interfaceClass.getName(), onServiceRetrieved);
107 protected void retrieveService(final String name, final String interfaceName,
108 final Consumer<Object> onServiceRetrieved) {
109 synchronized (serviceRecipes) {
110 if (stoppedServiceRecipes) {
114 StaticServiceReferenceRecipe recipe = new StaticServiceReferenceRecipe(getId() + "-" + name,
115 container, interfaceName);
116 setDependencyDesc(recipe.getOsgiFilter());
117 serviceRecipes.add(recipe);
119 recipe.startTracking(onServiceRetrieved);
123 protected final String logName() {
124 return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + " (" + id + ")";
128 public void init(final ExtendedBlueprintContainer newContainer) {
129 this.container = newContainer;
131 log.debug("{}: In init", logName());
134 protected void onCreate() throws ComponentDefinitionException {
135 if (failureMessage != null) {
136 throw new ComponentDefinitionException(failureMessage, failureCause);
139 // The following code is a bit odd so requires some explanation. A little background... If a bean
140 // is a prototype then the corresponding Recipe create method does not register the bean as created
141 // with the BlueprintRepository and thus the destroy method isn't called on container destroy. We
142 // rely on destroy being called to close our DTCL registration. Unfortunately the default setting
143 // for the prototype flag in AbstractRecipe is true and the DependentComponentFactoryRecipe, which
144 // is created for DependentComponentFactoryMetadata types of which we are one, doesn't have a way for
145 // us to indicate the prototype state via our metadata.
147 // The ExecutionContext is actually backed by the BlueprintRepository so we access it here to call
148 // the removePartialObject method which removes any partially created instance, which does not apply
149 // in our case, and also has the side effect of registering our bean as created as if it wasn't a
150 // prototype. We also obtain our corresponding Recipe instance and clear the prototype flag. This
151 // doesn't look to be necessary but is done so for completeness. Better late than never. Note we have
152 // to do this here rather than in startTracking b/c the ExecutionContext is not available yet at that
155 // Now the stopTracking method is called on container destroy but startTracking/stopTracking can also
156 // be called multiple times during the container creation process for Satisfiable recipes as bean
157 // processors may modify the metadata which could affect how dependencies are satisfied. An example of
158 // this is with service references where the OSGi filter metadata can be modified by bean processors
159 // after the initial service dependency is satisfied. However we don't have any metadata that could
160 // be modified by a bean processor and we don't want to register/unregister our DTCL multiple times
161 // so we only process startTracking once and close the DTCL registration once on container destroy.
162 ExecutionContext executionContext = ExecutionContext.Holder.getContext();
163 executionContext.removePartialObject(id);
165 Recipe myRecipe = executionContext.getRecipe(id);
166 if (myRecipe instanceof AbstractRecipe) {
167 log.debug("{}: setPrototype to false", logName());
168 ((AbstractRecipe)myRecipe).setPrototype(false);
170 log.warn("{}: Recipe is null or not an AbstractRecipe", logName());
174 protected abstract void startTracking();
177 public final void startTracking(final SatisfactionCallback newSatisfactionCallback) {
178 if (!started.compareAndSet(false, true)) {
182 log.debug("{}: In startTracking", logName());
184 this.satisfactionCallback = newSatisfactionCallback;
190 public void stopTracking() {
191 log.debug("{}: In stopTracking", logName());
193 stopServiceRecipes();
197 public void destroy(final Object instance) {
198 log.debug("{}: In destroy", logName());
200 stopServiceRecipes();
203 private void stopServiceRecipes() {
204 synchronized (serviceRecipes) {
205 stoppedServiceRecipes = true;
206 for (StaticServiceReferenceRecipe recipe: serviceRecipes) {
210 serviceRecipes.clear();
214 protected void restartContainer() {
215 if (restarting.compareAndSet(false, true)) {
216 BlueprintContainerRestartService restartService = getOSGiService(BlueprintContainerRestartService.class);
217 if (restartService != null) {
218 log.debug("{}: Restarting container", logName());
219 restartService.restartContainerAndDependents(container().getBundleContext().getBundle());
224 @SuppressWarnings("unchecked")
226 protected <T> T getOSGiService(final Class<T> serviceInterface) {
228 ServiceReference<T> serviceReference =
229 container().getBundleContext().getServiceReference(serviceInterface);
230 if (serviceReference == null) {
231 log.warn("{}: {} reference not found", logName(), serviceInterface.getSimpleName());
235 T service = (T)container().getService(serviceReference);
236 if (service == null) {
237 // This could happen on shutdown if the service was already unregistered so we log as debug.
238 log.debug("{}: {} was not found", logName(), serviceInterface.getSimpleName());
242 } catch (IllegalStateException e) {
243 // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we
245 log.debug("{}: Error obtaining {}", logName(), serviceInterface.getSimpleName(), e);