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 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;
31 * Abstract base class for a DependentComponentFactoryMetadata implementation.
33 * @author Thomas Pantelis
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;
52 protected AbstractDependentComponentFactoryMetadata(final String id) {
53 this.id = Preconditions.checkNotNull(id);
57 public String getId() {
62 public int getActivation() {
63 return ACTIVATION_EAGER;
67 public List<String> getDependsOn() {
68 return Collections.emptyList();
72 public String getDependencyDescriptor() {
73 return dependencyDesc;
77 public boolean isSatisfied() {
78 return satisfied.get();
81 protected void setFailureMessage(final String failureMessage) {
82 setFailure(failureMessage, null);
85 @SuppressWarnings("checkstyle:hiddenField")
86 protected void setFailure(final String failureMessage, final Throwable failureCause) {
87 this.failureMessage = failureMessage;
88 this.failureCause = failureCause;
91 protected void setDependencyDesc(final String dependencyDesc) {
92 this.dependencyDesc = dependencyDesc;
95 protected final ExtendedBlueprintContainer container() {
99 protected void setSatisfied() {
100 if (satisfied.compareAndSet(false, true)) {
101 satisfactionCallback.notifyChanged();
105 protected void retrieveService(final String name, final Class<?> interfaceClass,
106 final Consumer<Object> onServiceRetrieved) {
107 retrieveService(name, interfaceClass.getName(), onServiceRetrieved);
110 protected void retrieveService(final String name, final String interfaceName,
111 final Consumer<Object> onServiceRetrieved) {
112 synchronized (serviceRecipes) {
113 if (stoppedServiceRecipes) {
117 StaticServiceReferenceRecipe recipe = new StaticServiceReferenceRecipe(getId() + "-" + name,
118 container, interfaceName);
119 setDependencyDesc(recipe.getOsgiFilter());
120 serviceRecipes.add(recipe);
122 recipe.startTracking(onServiceRetrieved);
126 protected final String logName() {
127 return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + " (" + id + ")";
131 public void init(final ExtendedBlueprintContainer newContainer) {
132 this.container = newContainer;
134 log.debug("{}: In init", logName());
137 protected void onCreate() throws ComponentDefinitionException {
138 if (failureMessage != null) {
139 throw new ComponentDefinitionException(failureMessage, failureCause);
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.
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
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);
168 Recipe myRecipe = executionContext.getRecipe(id);
169 if (myRecipe instanceof AbstractRecipe) {
170 log.debug("{}: setPrototype to false", logName());
171 ((AbstractRecipe)myRecipe).setPrototype(false);
173 log.warn("{}: Recipe is null or not an AbstractRecipe", logName());
177 protected abstract void startTracking();
180 public final void startTracking(final SatisfactionCallback newSatisfactionCallback) {
181 if (!started.compareAndSet(false, true)) {
185 log.debug("{}: In startTracking", logName());
187 this.satisfactionCallback = newSatisfactionCallback;
193 public void stopTracking() {
194 log.debug("{}: In stopTracking", logName());
196 stopServiceRecipes();
200 public void destroy(final Object instance) {
201 log.debug("{}: In destroy", logName());
203 stopServiceRecipes();
206 private void stopServiceRecipes() {
207 synchronized (serviceRecipes) {
208 stoppedServiceRecipes = true;
209 for (StaticServiceReferenceRecipe recipe: serviceRecipes) {
213 serviceRecipes.clear();
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());
227 @SuppressWarnings("unchecked")
229 protected <T> T getOSGiService(final Class<T> serviceInterface) {
231 ServiceReference<T> serviceReference =
232 container().getBundleContext().getServiceReference(serviceInterface);
233 if (serviceReference == null) {
234 log.warn("{}: {} reference not found", logName(), serviceInterface.getSimpleName());
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());
245 } catch (final IllegalStateException e) {
246 // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we
248 log.debug("{}: Error obtaining {}", logName(), serviceInterface.getSimpleName(), e);