88a829ba0464ab7c57e2c0d320666df78d2a7175
[controller.git] / opendaylight / sal / api / src / main / java / org / opendaylight / controller / sal / core / ComponentActivatorAbstractBase.java
1
2 /*
3  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 package org.opendaylight.controller.sal.core;
11
12 /**
13  * @file   ComponentActivatorAbstractBase.java
14  *
15  * @brief  Abstract class which need to be subclassed in order to
16  * track and register dependencies per-container
17  *
18  * Abstract class which need to be subclassed in order to
19  * track and register dependencies per-container
20  *
21  */
22
23 import java.util.Dictionary;
24 import java.util.Hashtable;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ConcurrentMap;
27
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.apache.felix.dm.Component;
30 import org.apache.felix.dm.ComponentStateListener;
31 import org.apache.felix.dm.DependencyManager;
32 import org.apache.felix.dm.ServiceDependency;
33 import org.osgi.framework.BundleActivator;
34 import org.osgi.framework.BundleContext;
35 import org.osgi.framework.ServiceRegistration;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * Abstract class which need to be subclassed in order to track and
41  * register dependencies per-container
42  *
43  */
44 abstract public class ComponentActivatorAbstractBase implements
45         BundleActivator, IContainerAware {
46     Logger logger = LoggerFactory
47             .getLogger(ComponentActivatorAbstractBase.class);
48     private ServiceRegistration containerAwareRegistration;
49     private DependencyManager dm;
50     private ConcurrentMap<ImmutablePair<String, Object>, Component> dbInstances = (ConcurrentMap<ImmutablePair<String, Object>, Component>) new ConcurrentHashMap<ImmutablePair<String, Object>, Component>();
51     private ConcurrentMap<Object, Component> dbGlobalInstances = (ConcurrentMap<Object, Component>) new ConcurrentHashMap<Object, Component>();
52
53     /**
54      * Abstract method that MUST be implemented by the derived class
55      * that wants to activate the Component bundle in a container. Here
56      * customization for the component are expected
57      */
58     abstract protected void init();
59
60     /**
61      * Abstract method that MUST be implemented by the derived class
62      * that wants to DE-activate the Component bundle in a container. Here
63      * customization for the component are expected
64      */
65     abstract protected void destroy();
66
67     /**
68      * Method which tells how many implementations are supported by
69      * the bundle. This way we can tune the number of components
70      * created.
71      *
72      *
73      * @return The list of implementations the bundle will support,
74      * this will be used to decide how many components need to be
75      * created per-container
76      */
77     protected Object[] getImplementations() {
78         return null;
79     }
80
81     /**
82      * Method which tells how many Global implementations are
83      * supported by the bundle. This way we can tune the number of
84      * components created. This components will be created ONLY at the
85      * time of bundle startup and will be destroyed only at time of
86      * bundle destruction, this is the major difference with the
87      * implementation retrieved via getImplementations where all of
88      * them are assumed to be in a container!
89      *
90      *
91      * @return The list of implementations the bundle will support,
92      * in Global version
93      */
94     protected Object[] getGlobalImplementations() {
95         return null;
96     }
97
98     /**
99      * Configure the dependency for a given instance inside a container
100      *
101      * @param c Component assigned for this instance, this will be
102      * what will be used for configuration
103      * @param imp implementation to be configured
104      * @param containerName container on which the configuration happens
105      */
106     protected void configureInstance(Component c, Object imp,
107             String containerName) {
108         // do nothing by default
109     }
110
111     /**
112      * Configure the dependency for a given instance Global
113      *
114      * @param c Component assigned for this instance, this will be
115      * what will be used for configuration
116      * @param imp implementation to be configured
117      * @param containerName container on which the configuration happens
118      */
119     protected void configureGlobalInstance(Component c, Object imp) {
120         // Do nothing by default
121     }
122
123     // Private class used to listen to state transition so we can
124     // implement the necessary logic to call "started" and "stopping"
125     // methods on the component. Right now the framework natively
126     // support only the call of:
127     // - "init": Called after dependency are satisfied
128     // - "start": Called after init but before services are registered
129     // - "stop": Called after services are unregistered but before the
130     // component is going to be destroyed
131     // - "destroy": Called to destroy the component.
132     // There is still a need for two notifications:
133     // - "started" method to be called after "start" and after the
134     // services has been registered in the OSGi service registry
135     // - "stopping" method to be called before "stop" method and
136     // before the services of the component are removed from OSGi
137     // service registry
138     class ListenerComponentStates implements ComponentStateListener {
139         @Override
140         public void starting(Component component) {
141             // do nothing
142         }
143
144         @Override
145         public void started(Component component) {
146             if (component == null) {
147                 return;
148             }
149             component.invokeCallbackMethod(new Object[] { component
150                     .getService() }, "started", new Class[][] {
151                     { Component.class }, {} }, new Object[][] { { component },
152                     {} });
153         }
154
155         @Override
156         public void stopped(Component component) {
157             if (component == null) {
158                 return;
159             }
160             component.invokeCallbackMethod(new Object[] { component
161                     .getService() }, "stopping", new Class[][] {
162                     { Component.class }, {} }, new Object[][] { { component },
163                     {} });
164         }
165
166         @Override
167         public void stopping(Component component) {
168             // do nothing
169         }
170     }
171
172     /**
173      * Method of IContainerAware called when a new container is available
174      *
175      * @param containerName Container being created
176      */
177     @Override
178     public void containerCreate(String containerName) {
179         try {
180             Object[] imps = getImplementations();
181             logger.trace("Creating instance {}", containerName);
182             if (imps != null) {
183                 for (int i = 0; i < imps.length; i++) {
184                     ImmutablePair<String, Object> key = new ImmutablePair<String, Object>(
185                             containerName, imps[i]);
186                     Component c = this.dbInstances.get(key);
187                     if (c == null) {
188                         c = this.dm.createComponent();
189                         c.addStateListener(new ListenerComponentStates());
190                         // Now let the derived class to configure the
191                         // dependencies it wants
192                         configureInstance(c, imps[i], containerName);
193                         // Set the implementation so the component can manage
194                         // its lifecycle
195                         if (c.getService() == null) {
196                             logger.trace("Setting implementation to: {}",
197                                           imps[i]);
198                             c.setImplementation(imps[i]);
199                         }
200
201                         //Set the service properties to include the containerName
202                         //in the service, that is fundamental for supporting
203                         //multiple services just distinguished via a container
204                         Dictionary<String, String> serviceProps = c
205                                 .getServiceProperties();
206                         if (serviceProps != null) {
207                             logger.trace("Adding new property for container");
208                             serviceProps.put("containerName", containerName);
209                         } else {
210                             logger
211                                     .trace("Create a new properties for the service");
212                             serviceProps = new Hashtable<String, String>();
213                             serviceProps.put("containerName", containerName);
214                         }
215                         c.setServiceProperties(serviceProps);
216
217                         // Now add the component to the dependency Manager
218                         // which will immediately start tracking the dependencies
219                         this.dm.add(c);
220
221                         //Now lets keep track in our shadow database of the
222                         //association
223                         this.dbInstances.put(key, c);
224                     } else {
225                         logger
226                                 .error("I have been asked again to create an instance "
227                                         + "on: "
228                                         + containerName
229                                         + "for object: "
230                                         + imps[i]
231                                         + "when i already have it!!");
232                     }
233                 }
234             }
235         } catch (Exception ex) {
236             logger
237                     .error("During containerDestroy invocation caught exception: "
238                             + ex
239                             + "\nStacktrace:"
240                             + stackToString(ex.getStackTrace()));
241         }
242     }
243
244     @Override
245     public void containerDestroy(String containerName) {
246         try {
247             Object[] imps = getImplementations();
248             logger.trace("Destroying instance {}", containerName);
249             if (imps != null) {
250                 for (int i = 0; i < imps.length; i++) {
251                     ImmutablePair<String, Object> key = new ImmutablePair<String, Object>(
252                             containerName, imps[i]);
253                     Component c = this.dbInstances.get(key);
254                     if (c != null) {
255                         // Now remove the component from dependency manager,
256                         // which will implicitely stop it first
257                         this.dm.remove(c);
258                     } else {
259                         logger
260                                 .error("I have been asked again to remove an instance "
261                                         + "on: "
262                                         + containerName
263                                         + "for object: "
264                                         + imps[i]
265                                         + "when i already have cleared it!!");
266                     }
267
268                     //Now lets remove the association from our shadow
269                     //database so the component can be recycled, this is done
270                     //unconditionally in case of spurious conditions
271                     this.dbInstances.remove(key);
272                 }
273             }
274         } catch (Exception ex) {
275             logger
276                     .error("During containerDestroy invocation caught exception: "
277                             + ex
278                             + "\nStacktrace:"
279                             + stackToString(ex.getStackTrace()));
280         }
281     }
282
283     private String stackToString(StackTraceElement[] stack) {
284         if (stack == null) {
285             return "<EmptyStack>";
286         }
287         StringBuffer buffer = new StringBuffer();
288
289         for (int i = 0; i < stack.length; i++) {
290             buffer.append("\n\t" + stack[i].toString());
291         }
292         return buffer.toString();
293     }
294
295     /**
296      * Method called by the OSGi framework when the OSGi bundle
297      * starts. The functionality we want to perform here are:
298      *
299      * 1) Register with the OSGi framework, that we are a provider of
300      * IContainerAware service and so in case of startup of a container we
301      * want to be called
302      *
303      * 2) Create data structures that allow to keep track of all the
304      * instances created per-container given the derived class of
305      * ComponentActivatorAbstractBase will act as a Factory manager
306      *
307      * @param context OSGi bundle context to interact with OSGi framework
308      */
309     @Override
310     public void start(BundleContext context) {
311         try {
312             this.dm = new DependencyManager(context);
313
314             logger.trace("Activating");
315
316             // Now create Global components
317             Object[] imps = getGlobalImplementations();
318             if (imps != null) {
319                 for (int i = 0; i < imps.length; i++) {
320                     Object key = imps[i];
321                     Component c = this.dbGlobalInstances.get(key);
322                     if (c == null) {
323                         try {
324                             c = this.dm.createComponent();
325                             c.addStateListener(new ListenerComponentStates());
326                             // Now let the derived class to configure the
327                             // dependencies it wants
328                             configureGlobalInstance(c, imps[i]);
329                             // Set the implementation so the component
330                             // can manage its lifesycle
331                             if (c.getService() == null) {
332                                 logger.trace("Setting implementation to: {}",
333                                         imps[i]);
334                                 c.setImplementation(imps[i]);
335                             }
336
337                             // Now add the component to the dependency
338                             // Manager which will immediately start
339                             // tracking the dependencies
340                             this.dm.add(c);
341                         } catch (Exception nex) {
342                             logger.error("During creation of a Global "
343                                     + "instance caught exception: " + nex
344                                     + "\nStacktrace:"
345                                     + stackToString(nex.getStackTrace()));
346                         }
347
348                         //Now lets keep track in our shadow database of the
349                         //association
350                         if (c != null)
351                             this.dbGlobalInstances.put(key, c);
352                     } else {
353                         logger.error("I have been asked again to create an "
354                                 + "instance " + " Global for object: "
355                                 + imps[i] + "when i already have it!!");
356                     }
357                 }
358             }
359
360             // Register with OSGi the provider for the service IContainerAware
361             this.containerAwareRegistration = context.registerService(
362                     IContainerAware.class.getName(), this, null);
363
364             // Now call the derived class init function
365             this.init();
366
367             logger.trace("Activation DONE!");
368         } catch (Exception ex) {
369             logger.error("During Activator start caught exception: " + ex
370                     + "\nStacktrace:" + stackToString(ex.getStackTrace()));
371         }
372     }
373
374     /**
375      * Method called by the OSGi framework when the OSGi bundle
376      * stops. The functionality we want to perform here are:
377      *
378      * 1) Force all the instances to stop and do cleanup and
379      * unreference them so garbage collection can clean them up
380      *
381      * NOTE: UN-Register with the OSGi framework,is not needed because
382      * the framework will automatically do it
383      *
384      * @param context OSGi bundle context to interact with OSGi framework
385      */
386     @Override
387     public void stop(BundleContext context) {
388         try {
389             logger.trace("DE-Activating");
390
391             // Now call the derived class destroy function
392             this.destroy();
393
394             // Now remove all the components tracked for container components
395             for (ImmutablePair<String, Object> key : this.dbInstances.keySet()) {
396                 try {
397                     Component c = this.dbInstances.get(key);
398                     if (c != null) {
399                         logger.trace("Remove component on container: {} Object: {}",
400                                 key.getLeft(), key.getRight());
401                         this.dm.remove(c);
402                     }
403                 } catch (Exception nex) {
404                     logger.error("During removal of a container component "
405                             + "instance caught exception: " + nex
406                             + "\nStacktrace:"
407                             + stackToString(nex.getStackTrace()));
408                 }
409                 this.dbInstances.remove(key);
410             }
411
412             // Now remove all the components tracked for Global Components
413             for (Object key : this.dbGlobalInstances.keySet()) {
414                 try {
415                     Component c = this.dbGlobalInstances.get(key);
416                     if (c != null) {
417                         logger.trace("Remove component for Object: {}" , key);
418                         this.dm.remove(c);
419                     }
420                 } catch (Exception nex) {
421                     logger.error("During removal of a Global "
422                             + "instance caught exception: " + nex
423                             + "\nStacktrace:"
424                             + stackToString(nex.getStackTrace()));
425                 }
426
427                 this.dbGlobalInstances.remove(key);
428             }
429
430             // Detach Dependency Manager
431             this.dm = null;
432
433             logger.trace("Deactivation DONE!");
434         } catch (Exception ex) {
435             logger.error("During Activator stop caught exception: " + ex
436                     + "\nStacktrace:" + stackToString(ex.getStackTrace()));
437         }
438     }
439
440     /**
441      * Return a ServiceDependency customized ad hoc for slicing, this
442      * essentially the same org.apache.felix.dm.ServiceDependency just
443      * with some filters pre-set
444      *
445      * @param containerName containerName for which we want to create the dependency
446      *
447      * @return a ServiceDependency
448      */
449     protected ServiceDependency createContainerServiceDependency(
450             String containerName) {
451         return (new ContainerServiceDependency(this.dm, containerName));
452     }
453
454     /**
455      * Return a ServiceDependency as provided by Dependency Manager as it's
456      *
457      *
458      * @return a ServiceDependency
459      */
460     protected ServiceDependency createServiceDependency() {
461         return this.dm.createServiceDependency();
462     }
463 }