]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.support.osgi/src/main/java/org/argeo/slc/osgi/BundlesManager.java
Introduce bundle register
[gpl/argeo-slc.git] / runtime / org.argeo.slc.support.osgi / src / main / java / org / argeo / slc / osgi / BundlesManager.java
1 /*
2 * Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org>
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 package org.argeo.slc.osgi;
18
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;
44
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);
49
50 private BundleContext bundleContext;
51
52 private Long defaultTimeout = 10000l;
53 private Long pollingPeriod = 100l;
54
55 // Refresh sync objects
56 private final Object refreshedPackageSem = new Object();
57 private Boolean packagesRefreshed = false;
58
59 /**
60 * Stop the module, update it, refresh it and restart it. All synchronously.
61 */
62 public void upgradeSynchronous(OsgiBundle osgiBundle) {
63 try {
64 Bundle bundle = findRelatedBundle(osgiBundle);
65
66 long begin = System.currentTimeMillis();
67
68 long bStop = begin;
69 stopSynchronous(bundle);
70
71 long bUpdate = System.currentTimeMillis();
72 updateSynchronous(bundle);
73
74 // Refresh in case there are fragments
75 long bRefresh = System.currentTimeMillis();
76 refreshSynchronous(bundle);
77
78 long bStart = System.currentTimeMillis();
79 startSynchronous(bundle);
80
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");
90 }
91
92 long bAppContext = System.currentTimeMillis();
93 String filter = "(Bundle-SymbolicName=" + bundle.getSymbolicName()
94 + ")";
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;
102
103 if (log.isTraceEnabled()) {
104 log.debug("Application context refresh performed in "
105 + (aAppContext - bAppContext) + "ms for bundle "
106 + osgiBundle);
107 }
108
109 if (log.isDebugEnabled())
110 log.debug("Bundle '" + bundle.getSymbolicName()
111 + "' upgraded and ready " + " (upgrade performed in "
112 + (end - begin) + "ms).");
113
114 if (log.isTraceEnabled()) {
115 ApplicationContext applicationContext = (ApplicationContext) bundleContext
116 .getService(sr);
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");
122 }
123
124 bundleContext.ungetService(sr);
125
126 } catch (Exception e) {
127 throw new SlcException("Cannot update bundle " + osgiBundle, e);
128 }
129 }
130
131 /** Updates bundle synchronously. */
132 protected void updateSynchronous(Bundle bundle) throws BundleException {
133 bundle.update();
134 boolean waiting = true;
135
136 long begin = System.currentTimeMillis();
137 do {
138 int state = bundle.getState();
139 if (state == Bundle.INSTALLED || state == Bundle.ACTIVE
140 || state == Bundle.RESOLVED)
141 waiting = false;
142
143 sleepWhenPolling();
144 checkTimeout(begin, "Update of bundle " + bundle.getSymbolicName()
145 + " timed out. Bundle state = " + bundle.getState());
146 } while (waiting);
147
148 if (log.isTraceEnabled())
149 log.debug("Bundle " + bundle.getSymbolicName() + " updated.");
150 }
151
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)
156 return;
157
158 bundle.start();
159 boolean waiting = true;
160
161 long begin = System.currentTimeMillis();
162 do {
163 if (bundle.getState() == Bundle.ACTIVE)
164 waiting = false;
165
166 sleepWhenPolling();
167 checkTimeout(begin, "Start of bundle " + bundle.getSymbolicName()
168 + " timed out. Bundle state = " + bundle.getState());
169 } while (waiting);
170
171 if (log.isTraceEnabled())
172 log.debug("Bundle " + bundle.getSymbolicName() + " started.");
173 }
174
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)
179 return;
180
181 bundle.stop();
182 boolean waiting = true;
183
184 long begin = System.currentTimeMillis();
185 do {
186 if (bundle.getState() != Bundle.ACTIVE
187 && bundle.getState() != Bundle.STOPPING)
188 waiting = false;
189
190 sleepWhenPolling();
191 checkTimeout(begin, "Stop of bundle " + bundle.getSymbolicName()
192 + " timed out. Bundle state = " + bundle.getState());
193 } while (waiting);
194
195 if (log.isTraceEnabled())
196 log.debug("Bundle " + bundle.getSymbolicName() + " stopped.");
197 }
198
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 };
206
207 long begin = System.currentTimeMillis();
208 synchronized (refreshedPackageSem) {
209 packagesRefreshed = false;
210 packageAdmin.refreshPackages(bundles);
211 try {
212 refreshedPackageSem.wait(defaultTimeout);
213 } catch (InterruptedException e) {
214 // silent
215 }
216 if (!packagesRefreshed) {
217 long now = System.currentTimeMillis();
218 throw new SlcException("Packages not refreshed after "
219 + (now - begin) + "ms");
220 } else {
221 packagesRefreshed = false;
222 }
223 }
224
225 if (log.isTraceEnabled())
226 log.debug("Bundle " + bundle.getSymbolicName() + " refreshed.");
227 }
228
229 public void frameworkEvent(FrameworkEvent event) {
230 if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
231 synchronized (refreshedPackageSem) {
232 packagesRefreshed = true;
233 refreshedPackageSem.notifyAll();
234 }
235 }
236 }
237
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();
245 do {
246 sfs = bundleContext.getServiceReferences(clss, filter);
247
248 if (sfs != null)
249 waiting = false;
250
251 sleepWhenPolling();
252 checkTimeout(begin, "Search of services " + clss + " with filter "
253 + filter + " timed out.");
254 } while (waiting);
255
256 return sfs;
257 }
258
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)
263 + "ms)");
264
265 }
266
267 protected void sleepWhenPolling() {
268 try {
269 Thread.sleep(pollingPeriod);
270 } catch (InterruptedException e) {
271 // silent
272 }
273 }
274
275 /** Creates and open a new service tracker. */
276 public ServiceTracker newTracker(Class<?> clss) {
277 ServiceTracker st = new ServiceTracker(bundleContext, clss.getName(),
278 null);
279 st.open();
280 return st;
281 }
282
283 @SuppressWarnings(value = { "unchecked" })
284 public <T> T getSingleService(Class<T> clss, String filter) {
285 Assert.isTrue(OsgiFilterUtils.isValidFilter(filter), "valid filter");
286 ServiceReference[] sfs;
287 try {
288 sfs = bundleContext.getServiceReferences(clss.getName(), filter);
289 } catch (InvalidSyntaxException e) {
290 throw new SlcException("Cannot retrieve service reference for "
291 + filter, e);
292 }
293
294 if (sfs == null || sfs.length == 0)
295 return null;
296 else if (sfs.length > 1)
297 throw new SlcException("More than one execution flow found for "
298 + filter);
299 return (T) bundleContext.getService(sfs[0]);
300 }
301
302 public <T> T getSingleServiceStrict(Class<T> clss, String filter) {
303 T service = getSingleService(clss, filter);
304 if (service == null)
305 throw new SlcException("No execution flow found for " + filter);
306 else
307 return service;
308 }
309
310 /** @return the related bundle or null if not found */
311 public Bundle findRelatedBundle(OsgiBundle osgiBundle) {
312 Bundle bundle = null;
313 if (osgiBundle.getInternalBundleId() != null) {
314 bundle = bundleContext.getBundle(osgiBundle.getInternalBundleId());
315 Assert.isTrue(
316 osgiBundle.getName().equals(bundle.getSymbolicName()),
317 "symbolic name consistent");
318 if (osgiBundle.getVersion() != null)
319 Assert.isTrue(osgiBundle.getVersion().equals(
320 bundle.getHeaders().get(Constants.BUNDLE_VERSION)),
321 "version consistent");
322 } else if (osgiBundle.getVersion() == null) {
323 bundle = OsgiBundleUtils.findBundleBySymbolicName(bundleContext,
324 osgiBundle.getName());
325 } else {// scan all bundles
326 bundles: for (Bundle b : bundleContext.getBundles()) {
327 if (b.getSymbolicName() == null) {
328 log.warn("Bundle " + b + " has no symbolic name defined.");
329 continue bundles;
330 }
331
332 if (b.getSymbolicName().equals(osgiBundle.getName())) {
333 if (osgiBundle.getVersion() == null) {
334 bundle = b;
335 break bundles;
336 }
337
338 if (b.getHeaders().get(Constants.BUNDLE_VERSION).equals(
339 osgiBundle.getVersion())) {
340 bundle = b;
341 osgiBundle.setInternalBundleId(b.getBundleId());
342 break bundles;
343 }
344 }
345 }
346 }
347 return bundle;
348 }
349
350 /** Find a single bundle based on a symbolic name pattern. */
351 public OsgiBundle findFromPattern(String pattern) {
352 OsgiBundle osgiBundle = null;
353 for (Bundle b : bundleContext.getBundles()) {
354 if (b.getSymbolicName().contains(pattern)) {
355 osgiBundle = new OsgiBundle(b);
356 break;
357 }
358 }
359 return osgiBundle;
360 }
361
362 public OsgiBundle getBundle(Long bundleId) {
363 Bundle bundle = bundleContext.getBundle(bundleId);
364 return new OsgiBundle(bundle);
365 }
366
367 public void setBundleContext(BundleContext bundleContext) {
368 this.bundleContext = bundleContext;
369 }
370
371 public void afterPropertiesSet() throws Exception {
372 bundleContext.addFrameworkListener(this);
373 }
374
375 public void destroy() throws Exception {
376 bundleContext.removeFrameworkListener(this);
377 }
378
379 public void setDefaultTimeout(Long defaultTimeout) {
380 this.defaultTimeout = defaultTimeout;
381 }
382
383 /** Temporary internal access for {@link OsgiExecutionModulesManager} */
384 BundleContext getBundleContext() {
385 return bundleContext;
386 }
387
388 public void setPollingPeriod(Long pollingPeriod) {
389 this.pollingPeriod = pollingPeriod;
390 }
391
392 public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event) {
393 if (event instanceof OsgiBundleContextRefreshedEvent) {
394 log.debug("App context refreshed: " + event);
395 } else if (event instanceof OsgiBundleContextFailedEvent) {
396 log.debug("App context failed: " + event);
397 }
398 if (event instanceof OsgiBundleContextClosedEvent) {
399 log.debug("App context closed: " + event);
400 }
401
402 }
403
404 }