BUG-7608: Add ActionServiceMetadata and ActionProviderBean
[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     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;
49
50     protected AbstractDependentComponentFactoryMetadata(final 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 dependencyDesc;
72     }
73
74     @Override
75     public boolean isSatisfied() {
76         return satisfied.get();
77     }
78
79     protected void setFailureMessage(final String failureMessage) {
80         setFailure(failureMessage, null);
81     }
82
83     protected void setFailure(final String failureMessage, final Throwable failureCause) {
84         this.failureMessage = failureMessage;
85         this.failureCause = failureCause;
86     }
87
88     protected void setDependencyDesc(final String dependencyDesc) {
89         this.dependencyDesc = dependencyDesc;
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(final String name, final Class<?> interfaceClass,
103             final Consumer<Object> onServiceRetrieved) {
104         retrieveService(name, interfaceClass.getName(), onServiceRetrieved);
105     }
106
107     protected void retrieveService(final String name, final String interfaceName,
108             final Consumer<Object> onServiceRetrieved) {
109         synchronized (serviceRecipes) {
110             if (stoppedServiceRecipes) {
111                 return;
112             }
113
114             StaticServiceReferenceRecipe recipe = new StaticServiceReferenceRecipe(getId() + "-" + name,
115                     container, interfaceName);
116             setDependencyDesc(recipe.getOsgiFilter());
117             serviceRecipes.add(recipe);
118
119             recipe.startTracking(onServiceRetrieved);
120         }
121     }
122
123     protected final String logName() {
124         return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + " (" + id + ")";
125     }
126
127     @Override
128     public void init(final ExtendedBlueprintContainer newContainer) {
129         this.container = newContainer;
130
131         log.debug("{}: In init", logName());
132     }
133
134     protected void onCreate() throws ComponentDefinitionException {
135         if (failureMessage != null) {
136             throw new ComponentDefinitionException(failureMessage, failureCause);
137         }
138
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.
146         //
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
153         // point.
154         //
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);
164
165         Recipe myRecipe = executionContext.getRecipe(id);
166         if (myRecipe instanceof AbstractRecipe) {
167             log.debug("{}: setPrototype to false", logName());
168             ((AbstractRecipe)myRecipe).setPrototype(false);
169         } else {
170             log.warn("{}: Recipe is null or not an AbstractRecipe", logName());
171         }
172     }
173
174     protected abstract void startTracking();
175
176     @Override
177     public final void startTracking(final SatisfactionCallback newSatisfactionCallback) {
178         if (!started.compareAndSet(false, true)) {
179             return;
180         }
181
182         log.debug("{}: In startTracking", logName());
183
184         this.satisfactionCallback = newSatisfactionCallback;
185
186         startTracking();
187     }
188
189     @Override
190     public void stopTracking() {
191         log.debug("{}: In stopTracking", logName());
192
193         stopServiceRecipes();
194     }
195
196     @Override
197     public void destroy(final Object instance) {
198         log.debug("{}: In destroy", logName());
199
200         stopServiceRecipes();
201     }
202
203     private void stopServiceRecipes() {
204         synchronized (serviceRecipes) {
205             stoppedServiceRecipes = true;
206             for (StaticServiceReferenceRecipe recipe: serviceRecipes) {
207                 recipe.stop();
208             }
209
210             serviceRecipes.clear();
211         }
212     }
213
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());
220             }
221         }
222     }
223
224     @SuppressWarnings("unchecked")
225     @Nullable
226     protected <T> T getOSGiService(final Class<T> serviceInterface) {
227         try {
228             ServiceReference<T> serviceReference =
229                     container().getBundleContext().getServiceReference(serviceInterface);
230             if (serviceReference == null) {
231                 log.warn("{}: {} reference not found", logName(), serviceInterface.getSimpleName());
232                 return null;
233             }
234
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());
239             }
240
241             return service;
242         } catch (IllegalStateException e) {
243             // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we
244             // log as debug.
245             log.debug("{}: Error obtaining {}", logName(), serviceInterface.getSimpleName(), e);
246         }
247
248         return null;
249     }
250 }