]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.support.osgi/src/main/java/org/argeo/slc/osgi/BundlesManager.java
Revert explicit security context propagation
[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 = 30 * 1000l;
53 private Long pollingPeriod = 200l;
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 Boolean synchronous) {
286 Assert.isTrue(OsgiFilterUtils.isValidFilter(filter), "valid filter");
287 ServiceReference[] sfs;
288 try {
289 if (synchronous)
290 sfs = getServiceRefSynchronous(clss.getName(), filter);
291 else
292 sfs = bundleContext
293 .getServiceReferences(clss.getName(), filter);
294 } catch (InvalidSyntaxException e) {
295 throw new SlcException("Cannot retrieve service reference for "
296 + filter, e);
297 }
298
299 if (sfs == null || sfs.length == 0)
300 return null;
301 else if (sfs.length > 1)
302 throw new SlcException("More than one execution flow found for "
303 + filter);
304 return (T) bundleContext.getService(sfs[0]);
305 }
306
307 public <T> T getSingleServiceStrict(Class<T> clss, String filter,
308 Boolean synchronous) {
309 T service = getSingleService(clss, filter, synchronous);
310 if (service == null)
311 throw new SlcException("No execution flow found for " + filter);
312 else
313 return service;
314 }
315
316 /**
317 * @param osgiBundle
318 * cannot be null
319 * @return the related bundle or null if not found
320 */
321 public Bundle findRelatedBundle(OsgiBundle osgiBundle) {
322 Bundle bundle = null;
323 if (osgiBundle.getInternalBundleId() != null) {
324 bundle = bundleContext.getBundle(osgiBundle.getInternalBundleId());
325 Assert.isTrue(
326 osgiBundle.getName().equals(bundle.getSymbolicName()),
327 "symbolic name consistent");
328 if (osgiBundle.getVersion() != null)
329 Assert.isTrue(
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.");
341 continue bundles;
342 }
343
344 if (b.getSymbolicName().equals(osgiBundle.getName())) {
345 if (osgiBundle.getVersion() == null) {
346 bundle = b;
347 break bundles;
348 }
349
350 if (b.getHeaders().get(Constants.BUNDLE_VERSION)
351 .equals(osgiBundle.getVersion())) {
352 bundle = b;
353 osgiBundle.setInternalBundleId(b.getBundleId());
354 break bundles;
355 }
356 }
357 }
358 }
359 return bundle;
360 }
361
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);
368 break;
369 }
370 }
371 return osgiBundle;
372 }
373
374 public OsgiBundle getBundle(Long bundleId) {
375 Bundle bundle = bundleContext.getBundle(bundleId);
376 return new OsgiBundle(bundle);
377 }
378
379 public void setBundleContext(BundleContext bundleContext) {
380 this.bundleContext = bundleContext;
381 }
382
383 public void afterPropertiesSet() throws Exception {
384 bundleContext.addFrameworkListener(this);
385 }
386
387 public void destroy() throws Exception {
388 bundleContext.removeFrameworkListener(this);
389 }
390
391 public void setDefaultTimeout(Long defaultTimeout) {
392 this.defaultTimeout = defaultTimeout;
393 }
394
395 /**
396 * Use with caution since it may interfer with some cached information
397 * within this object
398 */
399 public BundleContext getBundleContext() {
400 return bundleContext;
401 }
402
403 public void setPollingPeriod(Long pollingPeriod) {
404 this.pollingPeriod = pollingPeriod;
405 }
406
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);
412 }
413 if (event instanceof OsgiBundleContextClosedEvent) {
414 log.debug("App context closed: " + event);
415 }
416
417 }
418
419 }