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 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;
50 protected AbstractDependentComponentFactoryMetadata(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 dependendencyDesc;
75 public boolean isSatisfied() {
76 return satisfied.get();
79 protected void setFailureMessage(String failureMessage) {
80 setFailure(failureMessage, null);
83 protected void setFailure(String failureMessage, Throwable failureCause) {
84 this.failureMessage = failureMessage;
85 this.failureCause = failureCause;
88 protected void setDependendencyDesc(String dependendencyDesc) {
89 this.dependendencyDesc = dependendencyDesc;
92 protected final ExtendedBlueprintContainer container() {
96 protected void setSatisfied() {
97 if (satisfied.compareAndSet(false, true)) {
98 satisfactionCallback.notifyChanged();
102 protected void retrieveService(String name, Class<?> interfaceClass, Consumer<Object> onServiceRetrieved) {
103 retrieveService(name, interfaceClass.getName(), onServiceRetrieved);
106 protected void retrieveService(String name, String interfaceName, Consumer<Object> onServiceRetrieved) {
107 synchronized (serviceRecipes) {
108 if (stoppedServiceRecipes) {
112 StaticServiceReferenceRecipe recipe = new StaticServiceReferenceRecipe(getId() + "-" + name,
113 container, interfaceName);
114 setDependendencyDesc(recipe.getOsgiFilter());
115 serviceRecipes.add(recipe);
117 recipe.startTracking(onServiceRetrieved);
121 protected final String logName() {
122 return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + " (" + id + ")";
126 public void init(ExtendedBlueprintContainer newContainer) {
127 this.container = newContainer;
129 log.debug("{}: In init", logName());
132 protected void onCreate() throws ComponentDefinitionException {
133 if (failureMessage != null) {
134 throw new ComponentDefinitionException(failureMessage, failureCause);
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.
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
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);
163 Recipe myRecipe = executionContext.getRecipe(id);
164 if (myRecipe instanceof AbstractRecipe) {
165 log.debug("{}: setPrototype to false", logName());
166 ((AbstractRecipe)myRecipe).setPrototype(false);
168 log.warn("{}: Recipe is null or not an AbstractRecipe", logName());
172 protected abstract void startTracking();
175 public final void startTracking(final SatisfactionCallback newSatisfactionCallback) {
176 if (!started.compareAndSet(false, true)) {
180 log.debug("{}: In startTracking", logName());
182 this.satisfactionCallback = newSatisfactionCallback;
188 public void stopTracking() {
189 log.debug("{}: In stopTracking", logName());
191 stopServiceRecipes();
195 public void destroy(Object instance) {
196 log.debug("{}: In destroy", logName());
198 stopServiceRecipes();
201 private void stopServiceRecipes() {
202 synchronized (serviceRecipes) {
203 stoppedServiceRecipes = true;
204 for (StaticServiceReferenceRecipe recipe: serviceRecipes) {
208 serviceRecipes.clear();
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());
222 @SuppressWarnings("unchecked")
224 protected <T> T getOSGiService(Class<T> serviceInterface) {
226 ServiceReference<T> serviceReference =
227 container().getBundleContext().getServiceReference(serviceInterface);
228 if (serviceReference == null) {
229 log.warn("{}: {} reference not found", logName(), serviceInterface.getSimpleName());
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());
240 } catch (IllegalStateException e) {
241 // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we
243 log.debug("{}: Error obtaining {}", logName(), serviceInterface.getSimpleName(), e);