Search in sources :

Example 6 with FrameworkListener

use of org.osgi.framework.FrameworkListener in project aries by apache.

the class BundleFrameworkImpl method increaseStartLevel.

private void increaseStartLevel(BundleContext context) {
    /*
       * Algorithm for doing this
       * 
       * 1. Set up a framework listener that will tell us when the start level has been set.
       * 
       * 2. Change the start level. This is asynchronous so by the time the method returned the event 
       *    could have been sent. This is why we set up the listener in step 1.
       * 
       * 3. Wait until the start level has been set appropriately. At this stage all the bundles are startable
       *    and some have been started (most notably lazy activated bundles it appears). Other bundles are still
       *    in resolved state.
       */
    ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
    if (ref != null) {
        StartLevel sl = (StartLevel) context.getService(ref);
        if (sl != null) {
            final Semaphore waitForStartLevelChangedEventToOccur = new Semaphore(0);
            // step 1
            FrameworkListener listener = new FrameworkListener() {

                public void frameworkEvent(FrameworkEvent event) {
                    if (event.getType() == FrameworkEvent.STARTLEVEL_CHANGED) {
                        waitForStartLevelChangedEventToOccur.release();
                    }
                }
            };
            context.addFrameworkListener(listener);
            // step 2
            sl.setStartLevel(sl.getStartLevel() + 1);
            // step 3
            try {
                if (!!!waitForStartLevelChangedEventToOccur.tryAcquire(60, TimeUnit.SECONDS)) {
                    LOGGER.debug("Starting CBA child bundles took longer than 60 seconds");
                }
            } catch (InterruptedException e) {
                // restore the interrupted status
                Thread.currentThread().interrupt();
            }
            context.removeFrameworkListener(listener);
        }
        context.ungetService(ref);
    }
}
Also used : FrameworkEvent(org.osgi.framework.FrameworkEvent) StartLevel(org.osgi.service.startlevel.StartLevel) Semaphore(java.util.concurrent.Semaphore) FrameworkListener(org.osgi.framework.FrameworkListener) ServiceReference(org.osgi.framework.ServiceReference)

Example 7 with FrameworkListener

use of org.osgi.framework.FrameworkListener in project aries by apache.

the class BundleFrameworkManagerImpl method uninstallBundle.

public void uninstallBundle(Bundle b) throws BundleException {
    synchronized (BundleFrameworkManager.SHARED_FRAMEWORK_LOCK) {
        BundleFramework framework = getBundleFramework(b);
        if (framework != null) {
            for (Bundle bundle : new ArrayList<Bundle>(framework.getBundles())) {
                framework.uninstall(bundle);
            }
            BundleContext ctx = framework.getIsolatedBundleContext();
            ServiceReference ref = ctx.getServiceReference(PackageAdmin.class.getName());
            if (ref != null) {
                try {
                    PackageAdmin pa = (PackageAdmin) ctx.getService(ref);
                    if (pa != null) {
                        final Semaphore sem = new Semaphore(0);
                        FrameworkListener listener = new FrameworkListener() {

                            public void frameworkEvent(FrameworkEvent event) {
                                if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
                                    sem.release();
                                }
                            }
                        };
                        ctx.addFrameworkListener(listener);
                        pa.refreshPackages(null);
                        try {
                            sem.tryAcquire(60, TimeUnit.SECONDS);
                        } catch (InterruptedException ie) {
                        }
                        ctx.removeFrameworkListener(listener);
                    }
                } finally {
                    ctx.ungetService(ref);
                }
            }
            framework.close();
            // clean up our maps so we don't leak memory
            _frameworks.remove(b);
            Iterator<BundleFramework> it = _frameworksByAppScope.values().iterator();
            while (it.hasNext()) {
                if (it.next().equals(framework))
                    it.remove();
            }
        }
    }
}
Also used : PackageAdmin(org.osgi.service.packageadmin.PackageAdmin) FrameworkEvent(org.osgi.framework.FrameworkEvent) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) BundleFramework(org.apache.aries.application.management.spi.framework.BundleFramework) Semaphore(java.util.concurrent.Semaphore) FrameworkListener(org.osgi.framework.FrameworkListener) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference)

Example 8 with FrameworkListener

use of org.osgi.framework.FrameworkListener in project aries by apache.

the class Framework method refreshBundlesAndWait.

private void refreshBundlesAndWait(long[] bundleIdentifiers, Bundle[] bundles) throws IOException {
    final CountDownLatch latch = new CountDownLatch(1);
    FrameworkListener listener = new FrameworkListener() {

        public void frameworkEvent(FrameworkEvent event) {
            if (FrameworkEvent.PACKAGES_REFRESHED == event.getType()) {
                latch.countDown();
            }
        }
    };
    try {
        context.addFrameworkListener(listener);
        try {
            if (bundles != null) {
                for (int i = 0; i < bundleIdentifiers.length; i++) {
                    bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]);
                }
            }
            packageAdmin.refreshPackages(bundles);
            if (latch.await(30, TimeUnit.SECONDS))
                return;
            else
                throw new IOException("Refresh operation timed out");
        } catch (InterruptedException e) {
            IOException ex = new IOException();
            ex.initCause(e);
            throw ex;
        }
    } finally {
        context.removeFrameworkListener(listener);
    }
}
Also used : FrameworkEvent(org.osgi.framework.FrameworkEvent) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) FrameworkListener(org.osgi.framework.FrameworkListener)

Example 9 with FrameworkListener

use of org.osgi.framework.FrameworkListener in project karaf by apache.

the class BundleInstallSupportImpl method refreshPackages.

/* (non-Javadoc)
     * @see org.apache.karaf.features.internal.service.Regions#refreshPackages(java.util.Collection)
     */
@Override
public void refreshPackages(Collection<Bundle> bundles) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    FrameworkWiring fw = systemBundleContext.getBundle().adapt(FrameworkWiring.class);
    fw.refreshBundles(bundles, (FrameworkListener) event -> {
        if (event.getType() == FrameworkEvent.ERROR) {
            LOGGER.error("Framework error", event.getThrowable());
        }
        latch.countDown();
    });
    latch.await();
}
Also used : DigraphHelper(org.apache.karaf.features.internal.region.DigraphHelper) ResolverHookFactory(org.osgi.framework.hooks.resolver.ResolverHookFactory) Region(org.eclipse.equinox.region.Region) RegionFilterBuilder(org.eclipse.equinox.region.RegionFilterBuilder) ExecutionEnvironmentNamespace(org.osgi.framework.namespace.ExecutionEnvironmentNamespace) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) FeaturesService(org.apache.karaf.features.FeaturesService) FrameworkListener(org.osgi.framework.FrameworkListener) HashSet(java.util.HashSet) BundleCapability(org.osgi.framework.wiring.BundleCapability) Map(java.util.Map) Bundle(org.osgi.framework.Bundle) BundleRevision(org.osgi.framework.wiring.BundleRevision) BundleException(org.osgi.framework.BundleException) ServiceRegistration(org.osgi.framework.ServiceRegistration) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Resource(org.osgi.resource.Resource) Collection(java.util.Collection) FrameworkStartLevel(org.osgi.framework.startlevel.FrameworkStartLevel) Feature(org.apache.karaf.features.Feature) FrameworkEvent(org.osgi.framework.FrameworkEvent) BundleRequirement(org.osgi.framework.wiring.BundleRequirement) Set(java.util.Set) IOException(java.io.IOException) ResolverHook(org.osgi.framework.hooks.resolver.ResolverHook) FileInputStream(java.io.FileInputStream) File(java.io.File) BundleContext(org.osgi.framework.BundleContext) BundleStartLevel(org.osgi.framework.startlevel.BundleStartLevel) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) RegionDigraph(org.eclipse.equinox.region.RegionDigraph) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) Wire(org.osgi.resource.Wire) BundleUtils(org.apache.karaf.util.bundles.BundleUtils) HostNamespace(org.osgi.framework.namespace.HostNamespace) InputStream(java.io.InputStream) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 10 with FrameworkListener

use of org.osgi.framework.FrameworkListener in project karaf by apache.

the class LoadTest method execute.

@Override
public Object execute() throws Exception {
    if (!confirm(session)) {
        return null;
    }
    final BundleContext bundleContext = this.bundleContext.getBundle(0).getBundleContext();
    final FrameworkWiring wiring = bundleContext.getBundle().adapt(FrameworkWiring.class);
    final CountDownLatch latch = new CountDownLatch(threads);
    final Bundle[] bundles = bundleContext.getBundles();
    final AtomicBoolean[] locks = new AtomicBoolean[bundles.length];
    for (int b = 0; b < locks.length; b++) {
        locks[b] = new AtomicBoolean(true);
        // Avoid touching excluded bundles
        if (excludes.contains(Long.toString(bundles[b].getBundleId())) || excludes.contains(bundles[b].getSymbolicName())) {
            continue;
        }
        // Only touch active bundles
        if (bundles[b].getState() != Bundle.ACTIVE) {
            continue;
        }
        // Now set the lock to available
        locks[b].set(false);
    }
    for (int i = 0; i < threads; i++) {
        new Thread(() -> {
            try {
                Random rand = new Random();
                for (int j = 0; j < iterations; j++) {
                    for (; ; ) {
                        int b = rand.nextInt(bundles.length);
                        if (locks[b].compareAndSet(false, true)) {
                            try {
                                // Only touch active bundles
                                if (bundles[b].getState() != Bundle.ACTIVE) {
                                    continue;
                                }
                                if (rand.nextInt(100) < refresh) {
                                    try {
                                        bundles[b].update();
                                        final CountDownLatch latch1 = new CountDownLatch(1);
                                        wiring.refreshBundles(Collections.singletonList(bundles[b]), (FrameworkListener) event -> latch1.countDown());
                                        latch1.await();
                                    } finally {
                                        while (true) {
                                            try {
                                                bundles[b].start(Bundle.START_TRANSIENT);
                                                break;
                                            } catch (Exception e) {
                                                Thread.sleep(1);
                                            }
                                        }
                                    }
                                } else {
                                    try {
                                        bundles[b].stop(Bundle.STOP_TRANSIENT);
                                    } finally {
                                        while (true) {
                                            try {
                                                bundles[b].start(Bundle.START_TRANSIENT);
                                                break;
                                            } catch (Exception e) {
                                                Thread.sleep(1);
                                            }
                                        }
                                    }
                                }
                                Thread.sleep(rand.nextInt(delay));
                            } catch (Exception e) {
                                boolean ignore = false;
                                if (e instanceof BundleException && e.getMessage() != null) {
                                    String msg = e.getMessage();
                                    if ("Cannot acquire global lock to update the bundle.".equals(msg) || "Unable to acquire global lock for resolve.".equals(msg) || msg.matches("Bundle .* cannot be update, since it is either starting or stopping.")) {
                                        ignore = true;
                                    }
                                }
                                if (!ignore) {
                                    e.printStackTrace();
                                }
                            } finally {
                                locks[b].set(false);
                            }
                        }
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                latch.countDown();
            }
        }).start();
    }
    new Thread(() -> {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.err.println("Load test finished");
    }).start();
    return null;
}
Also used : Bundle(org.osgi.framework.Bundle) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) BundleException(org.osgi.framework.BundleException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Random(java.util.Random) BundleException(org.osgi.framework.BundleException) FrameworkListener(org.osgi.framework.FrameworkListener) BundleContext(org.osgi.framework.BundleContext)

Aggregations

FrameworkListener (org.osgi.framework.FrameworkListener)12 FrameworkEvent (org.osgi.framework.FrameworkEvent)11 IOException (java.io.IOException)5 Bundle (org.osgi.framework.Bundle)5 FrameworkWiring (org.osgi.framework.wiring.FrameworkWiring)5 CountDownLatch (java.util.concurrent.CountDownLatch)4 BundleContext (org.osgi.framework.BundleContext)4 BundleException (org.osgi.framework.BundleException)4 Semaphore (java.util.concurrent.Semaphore)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 File (java.io.File)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ServiceReference (org.osgi.framework.ServiceReference)2 Framework (org.osgi.framework.launch.Framework)2 FrameworkFactory (org.osgi.framework.launch.FrameworkFactory)2 MiniFramework (aQute.launcher.minifw.MiniFramework)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1