2 * Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org>
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org
.argeo
.slc
.osgi
;
19 import org
.apache
.commons
.logging
.Log
;
20 import org
.apache
.commons
.logging
.LogFactory
;
21 import org
.argeo
.slc
.SlcException
;
22 import org
.osgi
.framework
.Bundle
;
23 import org
.osgi
.framework
.BundleContext
;
24 import org
.osgi
.framework
.BundleException
;
25 import org
.osgi
.framework
.Constants
;
26 import org
.osgi
.framework
.FrameworkEvent
;
27 import org
.osgi
.framework
.FrameworkListener
;
28 import org
.osgi
.framework
.InvalidSyntaxException
;
29 import org
.osgi
.framework
.ServiceReference
;
30 import org
.osgi
.service
.packageadmin
.PackageAdmin
;
31 import org
.osgi
.util
.tracker
.ServiceTracker
;
32 import org
.springframework
.beans
.factory
.DisposableBean
;
33 import org
.springframework
.beans
.factory
.InitializingBean
;
34 import org
.springframework
.context
.ApplicationContext
;
35 import org
.springframework
.osgi
.context
.BundleContextAware
;
36 import org
.springframework
.osgi
.context
.event
.OsgiBundleApplicationContextEvent
;
37 import org
.springframework
.osgi
.context
.event
.OsgiBundleApplicationContextListener
;
38 import org
.springframework
.osgi
.context
.event
.OsgiBundleContextClosedEvent
;
39 import org
.springframework
.osgi
.context
.event
.OsgiBundleContextFailedEvent
;
40 import org
.springframework
.osgi
.context
.event
.OsgiBundleContextRefreshedEvent
;
41 import org
.springframework
.osgi
.util
.OsgiBundleUtils
;
42 import org
.springframework
.osgi
.util
.OsgiFilterUtils
;
43 import org
.springframework
.util
.Assert
;
45 /** Wraps low-level access to a {@link BundleContext} */
46 public class BundlesManager
implements BundleContextAware
, FrameworkListener
,
47 InitializingBean
, DisposableBean
, OsgiBundleApplicationContextListener
{
48 private final static Log log
= LogFactory
.getLog(BundlesManager
.class);
50 private BundleContext bundleContext
;
52 private Long defaultTimeout
= 30 * 1000l;
53 private Long pollingPeriod
= 200l;
55 // Refresh sync objects
56 private final Object refreshedPackageSem
= new Object();
57 private Boolean packagesRefreshed
= false;
60 * Stop the module, update it, refresh it and restart it. All synchronously.
62 public void upgradeSynchronous(OsgiBundle osgiBundle
) {
64 Bundle bundle
= findRelatedBundle(osgiBundle
);
66 long begin
= System
.currentTimeMillis();
69 stopSynchronous(bundle
);
71 long bUpdate
= System
.currentTimeMillis();
72 updateSynchronous(bundle
);
74 // Refresh in case there are fragments
75 long bRefresh
= System
.currentTimeMillis();
76 refreshSynchronous(bundle
);
78 long bStart
= System
.currentTimeMillis();
79 startSynchronous(bundle
);
81 long aStart
= System
.currentTimeMillis();
82 if (log
.isTraceEnabled()) {
83 log
.debug("OSGi upgrade performed in " + (aStart
- begin
)
84 + "ms for bundle " + osgiBundle
);
85 log
.debug(" stop \t: " + (bUpdate
- bStop
) + "ms");
86 log
.debug(" update\t: " + (bRefresh
- bUpdate
) + "ms");
87 log
.debug(" refresh\t: " + (bStart
- bRefresh
) + "ms");
88 log
.debug(" start\t: " + (aStart
- bStart
) + "ms");
89 log
.debug(" TOTAL\t: " + (aStart
- begin
) + "ms");
92 long bAppContext
= System
.currentTimeMillis();
93 String filter
= "(Bundle-SymbolicName=" + bundle
.getSymbolicName()
95 // Wait for application context to be ready
96 // TODO: use service tracker
97 ServiceReference
[] srs
= getServiceRefSynchronous(
98 ApplicationContext
.class.getName(), filter
);
99 ServiceReference sr
= srs
[0];
100 long aAppContext
= System
.currentTimeMillis();
101 long end
= aAppContext
;
103 if (log
.isTraceEnabled()) {
104 log
.debug("Application context refresh performed in "
105 + (aAppContext
- bAppContext
) + "ms for bundle "
109 if (log
.isDebugEnabled())
110 log
.debug("Bundle '" + bundle
.getSymbolicName()
111 + "' upgraded and ready " + " (upgrade performed in "
112 + (end
- begin
) + "ms).");
114 if (log
.isTraceEnabled()) {
115 ApplicationContext applicationContext
= (ApplicationContext
) bundleContext
117 int beanDefCount
= applicationContext
.getBeanDefinitionCount();
118 log
.debug(" " + beanDefCount
+ " beans in app context of "
119 + bundle
.getSymbolicName()
120 + ", average init time per bean=" + (end
- begin
)
121 / beanDefCount
+ "ms");
124 bundleContext
.ungetService(sr
);
126 } catch (Exception e
) {
127 throw new SlcException("Cannot update bundle " + osgiBundle
, e
);
131 /** Updates bundle synchronously. */
132 protected void updateSynchronous(Bundle bundle
) throws BundleException
{
134 boolean waiting
= true;
136 long begin
= System
.currentTimeMillis();
138 int state
= bundle
.getState();
139 if (state
== Bundle
.INSTALLED
|| state
== Bundle
.ACTIVE
140 || state
== Bundle
.RESOLVED
)
144 checkTimeout(begin
, "Update of bundle " + bundle
.getSymbolicName()
145 + " timed out. Bundle state = " + bundle
.getState());
148 if (log
.isTraceEnabled())
149 log
.debug("Bundle " + bundle
.getSymbolicName() + " updated.");
152 /** Starts bundle synchronously. Does nothing if already started. */
153 protected void startSynchronous(Bundle bundle
) throws BundleException
{
154 int originalState
= bundle
.getState();
155 if (originalState
== Bundle
.ACTIVE
)
159 boolean waiting
= true;
161 long begin
= System
.currentTimeMillis();
163 if (bundle
.getState() == Bundle
.ACTIVE
)
167 checkTimeout(begin
, "Start of bundle " + bundle
.getSymbolicName()
168 + " timed out. Bundle state = " + bundle
.getState());
171 if (log
.isTraceEnabled())
172 log
.debug("Bundle " + bundle
.getSymbolicName() + " started.");
175 /** Stops bundle synchronously. Does nothing if already started. */
176 protected void stopSynchronous(Bundle bundle
) throws BundleException
{
177 int originalState
= bundle
.getState();
178 if (originalState
!= Bundle
.ACTIVE
)
182 boolean waiting
= true;
184 long begin
= System
.currentTimeMillis();
186 if (bundle
.getState() != Bundle
.ACTIVE
187 && bundle
.getState() != Bundle
.STOPPING
)
191 checkTimeout(begin
, "Stop of bundle " + bundle
.getSymbolicName()
192 + " timed out. Bundle state = " + bundle
.getState());
195 if (log
.isTraceEnabled())
196 log
.debug("Bundle " + bundle
.getSymbolicName() + " stopped.");
199 /** Refresh bundle synchronously. Does nothing if already started. */
200 protected void refreshSynchronous(Bundle bundle
) throws BundleException
{
201 ServiceReference packageAdminRef
= bundleContext
202 .getServiceReference(PackageAdmin
.class.getName());
203 PackageAdmin packageAdmin
= (PackageAdmin
) bundleContext
204 .getService(packageAdminRef
);
205 Bundle
[] bundles
= { bundle
};
207 long begin
= System
.currentTimeMillis();
208 synchronized (refreshedPackageSem
) {
209 packagesRefreshed
= false;
210 packageAdmin
.refreshPackages(bundles
);
212 refreshedPackageSem
.wait(defaultTimeout
);
213 } catch (InterruptedException e
) {
216 if (!packagesRefreshed
) {
217 long now
= System
.currentTimeMillis();
218 throw new SlcException("Packages not refreshed after "
219 + (now
- begin
) + "ms");
221 packagesRefreshed
= false;
225 if (log
.isTraceEnabled())
226 log
.debug("Bundle " + bundle
.getSymbolicName() + " refreshed.");
229 public void frameworkEvent(FrameworkEvent event
) {
230 if (event
.getType() == FrameworkEvent
.PACKAGES_REFRESHED
) {
231 synchronized (refreshedPackageSem
) {
232 packagesRefreshed
= true;
233 refreshedPackageSem
.notifyAll();
238 public ServiceReference
[] getServiceRefSynchronous(String clss
,
239 String filter
) throws InvalidSyntaxException
{
240 if (log
.isTraceEnabled())
241 log
.debug("Filter: '" + filter
+ "'");
242 ServiceReference
[] sfs
= null;
243 boolean waiting
= true;
244 long begin
= System
.currentTimeMillis();
246 sfs
= bundleContext
.getServiceReferences(clss
, filter
);
252 checkTimeout(begin
, "Search of services " + clss
+ " with filter "
253 + filter
+ " timed out.");
259 protected void checkTimeout(long begin
, String msg
) {
260 long now
= System
.currentTimeMillis();
261 if (now
- begin
> defaultTimeout
)
262 throw new SlcException(msg
+ " (timeout after " + (now
- begin
)
267 protected void sleepWhenPolling() {
269 Thread
.sleep(pollingPeriod
);
270 } catch (InterruptedException e
) {
275 /** Creates and open a new service tracker. */
276 public ServiceTracker
newTracker(Class
<?
> clss
) {
277 ServiceTracker st
= new ServiceTracker(bundleContext
, clss
.getName(),
283 @SuppressWarnings(value
= { "unchecked" })
284 public <T
> T
getSingleService(Class
<T
> clss
, String filter
,
285 Boolean synchronous
) {
286 Assert
.isTrue(OsgiFilterUtils
.isValidFilter(filter
), "valid filter");
287 ServiceReference
[] sfs
;
290 sfs
= getServiceRefSynchronous(clss
.getName(), filter
);
293 .getServiceReferences(clss
.getName(), filter
);
294 } catch (InvalidSyntaxException e
) {
295 throw new SlcException("Cannot retrieve service reference for "
299 if (sfs
== null || sfs
.length
== 0)
301 else if (sfs
.length
> 1)
302 throw new SlcException("More than one execution flow found for "
304 return (T
) bundleContext
.getService(sfs
[0]);
307 public <T
> T
getSingleServiceStrict(Class
<T
> clss
, String filter
,
308 Boolean synchronous
) {
309 T service
= getSingleService(clss
, filter
, synchronous
);
311 throw new SlcException("No execution flow found for " + filter
);
319 * @return the related bundle or null if not found
321 public Bundle
findRelatedBundle(OsgiBundle osgiBundle
) {
322 Bundle bundle
= null;
323 if (osgiBundle
.getInternalBundleId() != null) {
324 bundle
= bundleContext
.getBundle(osgiBundle
.getInternalBundleId());
326 osgiBundle
.getName().equals(bundle
.getSymbolicName()),
327 "symbolic name consistent");
328 if (osgiBundle
.getVersion() != null)
330 osgiBundle
.getVersion().equals(
331 bundle
.getHeaders().get(
332 Constants
.BUNDLE_VERSION
)),
333 "version consistent");
334 } else if (osgiBundle
.getVersion() == null) {
335 bundle
= OsgiBundleUtils
.findBundleBySymbolicName(bundleContext
,
336 osgiBundle
.getName());
337 } else {// scan all bundles
338 bundles
: for (Bundle b
: bundleContext
.getBundles()) {
339 if (b
.getSymbolicName() == null) {
340 log
.warn("Bundle " + b
+ " has no symbolic name defined.");
344 if (b
.getSymbolicName().equals(osgiBundle
.getName())) {
345 if (osgiBundle
.getVersion() == null) {
350 if (b
.getHeaders().get(Constants
.BUNDLE_VERSION
)
351 .equals(osgiBundle
.getVersion())) {
353 osgiBundle
.setInternalBundleId(b
.getBundleId());
362 /** Find a single bundle based on a symbolic name pattern. */
363 public OsgiBundle
findFromPattern(String pattern
) {
364 OsgiBundle osgiBundle
= null;
365 for (Bundle b
: bundleContext
.getBundles()) {
366 if (b
.getSymbolicName().contains(pattern
)) {
367 osgiBundle
= new OsgiBundle(b
);
374 public OsgiBundle
getBundle(Long bundleId
) {
375 Bundle bundle
= bundleContext
.getBundle(bundleId
);
376 return new OsgiBundle(bundle
);
379 public void setBundleContext(BundleContext bundleContext
) {
380 this.bundleContext
= bundleContext
;
383 public void afterPropertiesSet() throws Exception
{
384 bundleContext
.addFrameworkListener(this);
387 public void destroy() throws Exception
{
388 bundleContext
.removeFrameworkListener(this);
391 public void setDefaultTimeout(Long defaultTimeout
) {
392 this.defaultTimeout
= defaultTimeout
;
396 * Use with caution since it may interfer with some cached information
399 public BundleContext
getBundleContext() {
400 return bundleContext
;
403 public void setPollingPeriod(Long pollingPeriod
) {
404 this.pollingPeriod
= pollingPeriod
;
407 public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event
) {
408 if (event
instanceof OsgiBundleContextRefreshedEvent
) {
409 log
.debug("App context refreshed: " + event
);
410 } else if (event
instanceof OsgiBundleContextFailedEvent
) {
411 log
.debug("App context failed: " + event
);
413 if (event
instanceof OsgiBundleContextClosedEvent
) {
414 log
.debug("App context closed: " + event
);