Search in sources :

Example 6 with FrameworkWiring

use of org.osgi.framework.wiring.FrameworkWiring in project sling by apache.

the class UninstallBundleCommand method execute.

/**
     * @see org.apache.sling.launchpad.base.impl.bootstrapcommands.Command#execute(org.apache.felix.framework.Logger, org.osgi.framework.BundleContext)
     */
@Override
public boolean execute(final Logger logger, final BundleContext ctx) throws Exception {
    final Set<String> refreshBundles = new HashSet<String>();
    // Uninstall all instances of our bundle within our version range
    boolean refreshSystemBundle = false;
    for (final Bundle b : ctx.getBundles()) {
        if (b.getSymbolicName().equals(bundleSymbolicName)) {
            if (versionRange == null || versionRange.isInRange(b.getVersion())) {
                logger.log(Logger.LOG_INFO, this + ": uninstalling bundle version " + b.getVersion());
                final String fragmentHostHeader = getFragmentHostHeader(b);
                if (fragmentHostHeader != null) {
                    if (isSystemBundleFragment(fragmentHostHeader)) {
                        logger.log(Logger.LOG_INFO, this + ": Need to do a system bundle refresh");
                        refreshSystemBundle = true;
                    } else {
                        logger.log(Logger.LOG_INFO, this + ": Need to do a refresh of the bundle's host: " + fragmentHostHeader);
                        refreshBundles.add(fragmentHostHeader);
                    }
                }
                b.uninstall();
            } else {
                logger.log(Logger.LOG_INFO, this + ": bundle version (" + b.getVersion() + " not in range, ignored");
            }
        }
    }
    if (refreshBundles.size() > 0) {
        final List<Bundle> bundles = new ArrayList<Bundle>();
        for (final Bundle b : ctx.getBundles()) {
            if (refreshBundles.contains(b.getSymbolicName())) {
                logger.log(Logger.LOG_INFO, this + ": Found host bundle to refresh " + b.getBundleId());
                bundles.add(b);
            }
        }
        if (bundles.size() > 0) {
            final FrameworkWiring fw = ctx.getBundle().adapt(FrameworkWiring.class);
            fw.refreshBundles(bundles);
        }
    }
    return refreshSystemBundle;
}
Also used : Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) HashSet(java.util.HashSet)

Example 7 with FrameworkWiring

use of org.osgi.framework.wiring.FrameworkWiring in project bnd by bndtools.

the class AgentServer method refresh.

public void refresh(boolean async) throws InterruptedException {
    FrameworkWiring f = context.getBundle(0).adapt(FrameworkWiring.class);
    if (f != null) {
        refresh = new CountDownLatch(1);
        f.refreshBundles(null, new FrameworkListener() {

            @Override
            public void frameworkEvent(FrameworkEvent event) {
                refresh.countDown();
            }
        });
        if (async)
            return;
        refresh.await();
    }
}
Also used : FrameworkEvent(org.osgi.framework.FrameworkEvent) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) CountDownLatch(java.util.concurrent.CountDownLatch) FrameworkListener(org.osgi.framework.FrameworkListener)

Example 8 with FrameworkWiring

use of org.osgi.framework.wiring.FrameworkWiring in project karaf by apache.

the class BundleInstallSupportImpl method resolveBundles.

@Override
public void resolveBundles(Set<Bundle> bundles, final Map<Resource, List<Wire>> wiring, Map<Resource, Bundle> resToBnd) {
    // Make sure it's only used for us
    final Thread thread = Thread.currentThread();
    // Translate wiring
    final Map<Bundle, Resource> bndToRes = new HashMap<>();
    for (Resource res : resToBnd.keySet()) {
        bndToRes.put(resToBnd.get(res), res);
    }
    // Hook
    final ResolverHook hook = new ResolverHook() {

        @Override
        public void filterResolvable(Collection<BundleRevision> candidates) {
        }

        @Override
        public void filterSingletonCollisions(BundleCapability singleton, Collection<BundleCapability> collisionCandidates) {
        }

        @Override
        public void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates) {
            if (Thread.currentThread() == thread) {
                // osgi.ee capabilities are provided by the system bundle, so just ignore those
                if (ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE.equals(requirement.getNamespace())) {
                    return;
                }
                Bundle sourceBundle = requirement.getRevision().getBundle();
                Resource sourceResource = bndToRes.get(sourceBundle);
                List<Wire> wires = wiring.get(sourceResource);
                if (sourceBundle == null || wires == null) {
                    // is being resolve at the same time, so do not interfere
                    return;
                }
                Set<Resource> wired = new HashSet<>();
                // Get a list of allowed wired resources
                wired.add(sourceResource);
                for (Wire wire : wires) {
                    wired.add(wire.getProvider());
                    if (HostNamespace.HOST_NAMESPACE.equals(wire.getRequirement().getNamespace())) {
                        for (Wire hostWire : wiring.get(wire.getProvider())) {
                            wired.add(hostWire.getProvider());
                        }
                    }
                }
                // Remove candidates that are not allowed
                for (Iterator<BundleCapability> candIter = candidates.iterator(); candIter.hasNext(); ) {
                    BundleCapability cand = candIter.next();
                    BundleRevision br = cand.getRevision();
                    if ((br.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) {
                        br = br.getWiring().getRequiredWires(null).get(0).getProvider();
                    }
                    Resource res = bndToRes.get(br.getBundle());
                    if (!wired.contains(br) && !wired.contains(res)) {
                        candIter.remove();
                    }
                }
            }
        }

        @Override
        public void end() {
        }
    };
    hooks.put(Thread.currentThread(), hook);
    try {
        FrameworkWiring frameworkWiring = systemBundleContext.getBundle().adapt(FrameworkWiring.class);
        frameworkWiring.resolveBundles(bundles);
    } finally {
        hooks.remove(Thread.currentThread());
    }
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ResolverHook(org.osgi.framework.hooks.resolver.ResolverHook) Bundle(org.osgi.framework.Bundle) Resource(org.osgi.resource.Resource) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) Wire(org.osgi.resource.Wire) BundleRequirement(org.osgi.framework.wiring.BundleRequirement) BundleRevision(org.osgi.framework.wiring.BundleRevision) Collection(java.util.Collection) BundleCapability(org.osgi.framework.wiring.BundleCapability) HashSet(java.util.HashSet)

Example 9 with FrameworkWiring

use of org.osgi.framework.wiring.FrameworkWiring in project fabric8 by jboss-fuse.

the class ServiceImplTest method testPatch.

@Test
public void testPatch() throws Exception {
    ComponentContext componentContext = createMock(ComponentContext.class);
    BundleContext bundleContext = createMock(BundleContext.class);
    Bundle sysBundle = createMock(Bundle.class);
    BundleContext sysBundleContext = createMock(BundleContext.class);
    Bundle bundle = createMock(Bundle.class);
    Bundle bundle2 = createMock(Bundle.class);
    FrameworkWiring wiring = createMock(FrameworkWiring.class);
    GitPatchRepository repository = createMock(GitPatchRepository.class);
    // 
    // Create a new service, download a patch
    // 
    expect(componentContext.getBundleContext()).andReturn(bundleContext);
    expect(bundleContext.getBundle(0)).andReturn(sysBundle).anyTimes();
    expect(sysBundle.getBundleContext()).andReturn(sysBundleContext).anyTimes();
    expect(sysBundleContext.getProperty(Service.NEW_PATCH_LOCATION)).andReturn(storage.toString()).anyTimes();
    expect(repository.getManagedPatch(anyString())).andReturn(null).anyTimes();
    expect(repository.findOrCreateMainGitRepository()).andReturn(null).anyTimes();
    expect(sysBundleContext.getProperty("karaf.default.repository")).andReturn("system").anyTimes();
    expect(sysBundleContext.getProperty("karaf.home")).andReturn(karaf.getCanonicalPath()).anyTimes();
    expect(sysBundleContext.getProperty("karaf.base")).andReturn(karaf.getCanonicalPath()).anyTimes();
    expect(sysBundleContext.getProperty("karaf.name")).andReturn("root").anyTimes();
    expect(sysBundleContext.getProperty("karaf.instances")).andReturn(karaf.getCanonicalPath() + "/instances").anyTimes();
    expect(sysBundleContext.getProperty("karaf.data")).andReturn(karaf.getCanonicalPath() + "/data").anyTimes();
    replay(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, repository);
    PatchManagement pm = mockManagementService(bundleContext);
    ((GitPatchManagementServiceImpl) pm).setGitPatchRepository(repository);
    ServiceImpl service = new ServiceImpl();
    setField(service, "patchManagement", pm);
    service.activate(componentContext);
    try {
        service.download(new URL("file:" + storage + "/temp/f00.zip"));
        fail("Should have thrown exception on non existent patch file.");
    } catch (Exception e) {
    }
    Iterable<Patch> patches = service.download(patch132.toURI().toURL());
    assertNotNull(patches);
    Iterator<Patch> it = patches.iterator();
    assertTrue(it.hasNext());
    Patch patch = it.next();
    assertNotNull(patch);
    assertEquals("patch-1.3.2", patch.getPatchData().getId());
    assertNotNull(patch.getPatchData().getBundles());
    assertEquals(1, patch.getPatchData().getBundles().size());
    Iterator<String> itb = patch.getPatchData().getBundles().iterator();
    assertEquals("mvn:foo/my-bsn/1.3.2", itb.next());
    assertNull(patch.getResult());
    verify(componentContext, sysBundleContext, sysBundle, bundleContext, bundle);
    // 
    // Simulate the patch
    // 
    reset(componentContext, sysBundleContext, sysBundle, bundleContext, bundle);
    expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle });
    expect(sysBundleContext.getServiceReference("io.fabric8.api.FabricService")).andReturn(null).anyTimes();
    expect(bundle.getSymbolicName()).andReturn("my-bsn").anyTimes();
    expect(bundle.getVersion()).andReturn(new Version("1.3.1")).anyTimes();
    expect(bundle.getLocation()).andReturn("location").anyTimes();
    expect(bundle.getBundleId()).andReturn(123L).anyTimes();
    BundleStartLevel bsl = createMock(BundleStartLevel.class);
    expect(bsl.getStartLevel()).andReturn(30).anyTimes();
    expect(bundle.adapt(BundleStartLevel.class)).andReturn(bsl).anyTimes();
    expect(bundle.getState()).andReturn(1);
    expect(sysBundleContext.getProperty("karaf.default.repository")).andReturn("system").anyTimes();
    replay(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, bsl);
    PatchResult result = service.install(patch, true);
    assertNotNull(result);
    assertNull(patch.getResult());
    assertTrue(result.isSimulation());
    verify(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, bsl);
    // 
    // Recreate a new service and verify the downloaded patch is still available
    // 
    reset(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, repository, bsl);
    expect(componentContext.getBundleContext()).andReturn(bundleContext);
    expect(bundleContext.getBundle(0)).andReturn(sysBundle);
    expect(sysBundle.getBundleContext()).andReturn(sysBundleContext);
    expect(sysBundleContext.getProperty(Service.NEW_PATCH_LOCATION)).andReturn(storage.toString()).anyTimes();
    expect(sysBundleContext.getProperty("karaf.home")).andReturn(karaf.toString()).anyTimes();
    expect(sysBundleContext.getProperty("karaf.base")).andReturn(karaf.getCanonicalPath()).anyTimes();
    expect(sysBundleContext.getProperty("karaf.name")).andReturn("root").anyTimes();
    expect(sysBundleContext.getProperty("karaf.instances")).andReturn(karaf.getCanonicalPath() + "/instances").anyTimes();
    expect(sysBundleContext.getProperty("karaf.default.repository")).andReturn("system").anyTimes();
    expect(repository.getManagedPatch(anyString())).andReturn(null).anyTimes();
    expect(repository.findOrCreateMainGitRepository()).andReturn(null).anyTimes();
    replay(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, repository, bsl);
    service = new ServiceImpl();
    setField(service, "patchManagement", pm);
    service.activate(componentContext);
    patches = service.getPatches();
    assertNotNull(patches);
    it = patches.iterator();
    assertTrue(it.hasNext());
    patch = it.next();
    assertNotNull(patch);
    assertEquals("patch-1.3.2", patch.getPatchData().getId());
    assertNotNull(patch.getPatchData().getBundles());
    assertEquals(1, patch.getPatchData().getBundles().size());
    itb = patch.getPatchData().getBundles().iterator();
    assertEquals("mvn:foo/my-bsn/1.3.2", itb.next());
    assertNull(patch.getResult());
    verify(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, bsl);
    // 
    // Install the patch
    // 
    reset(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, bsl);
    expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle });
    expect(sysBundleContext.getServiceReference("io.fabric8.api.FabricService")).andReturn(null).anyTimes();
    expect(bundle.getSymbolicName()).andReturn("my-bsn").anyTimes();
    expect(bundle.getVersion()).andReturn(new Version("1.3.1")).anyTimes();
    expect(bundle.getLocation()).andReturn("location").anyTimes();
    expect(bundle.getHeaders()).andReturn(new Hashtable<String, String>()).anyTimes();
    expect(bundle.getBundleId()).andReturn(123L).anyTimes();
    bundle.update(EasyMock.<InputStream>anyObject());
    expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle });
    expect(bundle.getState()).andReturn(Bundle.INSTALLED).anyTimes();
    expect(bundle.getRegisteredServices()).andReturn(null);
    expect(bundle.adapt(BundleStartLevel.class)).andReturn(bsl).anyTimes();
    expect(bsl.getStartLevel()).andReturn(30).anyTimes();
    expect(sysBundleContext.getBundle(0)).andReturn(sysBundle);
    expect(sysBundle.adapt(FrameworkWiring.class)).andReturn(wiring);
    expect(sysBundleContext.getProperty("karaf.default.repository")).andReturn("system").anyTimes();
    bundle.start();
    wiring.refreshBundles(eq(asSet(bundle)), anyObject(FrameworkListener[].class));
    expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            ((FrameworkListener) (EasyMock.getCurrentArguments()[1])).frameworkEvent(null);
            return null;
        }
    });
    replay(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, bundle2, wiring, bsl);
    result = service.install(patch, false);
    assertNotNull(result);
    assertSame(result, patch.getResult());
    assertFalse(patch.getResult().isSimulation());
    verify(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, wiring);
    // 
    // Recreate a new service and verify the downloaded patch is still available and installed
    // 
    reset(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, repository);
    expect(componentContext.getBundleContext()).andReturn(bundleContext);
    expect(bundleContext.getBundle(0)).andReturn(sysBundle);
    expect(sysBundle.getBundleContext()).andReturn(sysBundleContext);
    expect(repository.getManagedPatch(anyString())).andReturn(null).anyTimes();
    expect(sysBundleContext.getProperty(Service.NEW_PATCH_LOCATION)).andReturn(storage.toString()).anyTimes();
    expect(sysBundleContext.getProperty("karaf.home")).andReturn(karaf.toString()).anyTimes();
    expect(sysBundleContext.getProperty("karaf.base")).andReturn(karaf.getCanonicalPath()).anyTimes();
    expect(sysBundleContext.getProperty("karaf.name")).andReturn("root").anyTimes();
    expect(sysBundleContext.getProperty("karaf.instances")).andReturn(karaf.getCanonicalPath() + "/instances").anyTimes();
    expect(sysBundleContext.getProperty("karaf.default.repository")).andReturn("system").anyTimes();
    replay(componentContext, sysBundleContext, sysBundle, bundleContext, bundle, repository);
    service = new ServiceImpl();
    setField(service, "patchManagement", pm);
    service.activate(componentContext);
    patches = service.getPatches();
    assertNotNull(patches);
    it = patches.iterator();
    assertTrue(it.hasNext());
    patch = it.next();
    assertNotNull(patch);
    assertEquals("patch-1.3.2", patch.getPatchData().getId());
    assertNotNull(patch.getPatchData().getBundles());
    assertEquals(1, patch.getPatchData().getBundles().size());
    itb = patch.getPatchData().getBundles().iterator();
    assertEquals("mvn:foo/my-bsn/1.3.2", itb.next());
    assertNotNull(patch.getResult());
    verify(componentContext, sysBundleContext, sysBundle, bundleContext, bundle);
}
Also used : BundleStartLevel(org.osgi.framework.startlevel.BundleStartLevel) ComponentContext(org.osgi.service.component.ComponentContext) Bundle(org.osgi.framework.Bundle) GitPatchManagementServiceImpl(io.fabric8.patch.management.impl.GitPatchManagementServiceImpl) Hashtable(java.util.Hashtable) GitPatchRepository(io.fabric8.patch.management.impl.GitPatchRepository) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) URL(java.net.URL) PatchException(io.fabric8.patch.management.PatchException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) GitPatchManagementServiceImpl(io.fabric8.patch.management.impl.GitPatchManagementServiceImpl) Version(org.osgi.framework.Version) PatchManagement(io.fabric8.patch.management.PatchManagement) PatchResult(io.fabric8.patch.management.PatchResult) Patch(io.fabric8.patch.management.Patch) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 10 with FrameworkWiring

use of org.osgi.framework.wiring.FrameworkWiring in project fuse-karaf by jboss-fuse.

the class PatchServiceImpl method applyChanges.

private void applyChanges(Map<Bundle, String> toUpdate) throws BundleException, IOException {
    List<Bundle> toStop = new ArrayList<Bundle>();
    Map<Bundle, String> lessToUpdate = new HashMap<>();
    for (Bundle b : toUpdate.keySet()) {
        if (b.getState() != Bundle.UNINSTALLED) {
            toStop.add(b);
            lessToUpdate.put(b, toUpdate.get(b));
        }
    }
    while (!toStop.isEmpty()) {
        List<Bundle> bs = getBundlesToDestroy(toStop);
        for (Bundle bundle : bs) {
            String hostHeader = bundle.getHeaders().get(Constants.FRAGMENT_HOST);
            if (hostHeader == null && (bundle.getState() == Bundle.ACTIVE || bundle.getState() == Bundle.STARTING)) {
                if (!"org.ops4j.pax.url.mvn".equals(bundle.getSymbolicName())) {
                    bundle.stop();
                }
            }
            toStop.remove(bundle);
        }
    }
    // eagerly load some classes
    try {
        getClass().getClassLoader().loadClass(Parser.class.getName());
        getClass().getClassLoader().loadClass(Clause.class.getName());
        getClass().getClassLoader().loadClass(Attribute.class.getName());
        getClass().getClassLoader().loadClass(Directive.class.getName());
        getClass().getClassLoader().loadClass(RefreshListener.class.getName());
    } catch (Exception ignored) {
    }
    Set<Bundle> toRefresh = new HashSet<Bundle>();
    Set<Bundle> toStart = new HashSet<Bundle>();
    for (Map.Entry<Bundle, String> e : lessToUpdate.entrySet()) {
        Bundle bundle = e.getKey();
        if (!"org.ops4j.pax.url.mvn".equals(bundle.getSymbolicName())) {
            System.out.println("updating: " + bundle.getSymbolicName());
            try {
                update(bundle, new URL(e.getValue()));
            } catch (BundleException ex) {
                System.err.println("Failed to update: " + bundle.getSymbolicName() + ", due to: " + e);
            }
            toStart.add(bundle);
            toRefresh.add(bundle);
        }
    }
    findBundlesWithOptionalPackagesToRefresh(toRefresh);
    findBundlesWithFragmentsToRefresh(toRefresh);
    if (!toRefresh.isEmpty()) {
        final CountDownLatch l = new CountDownLatch(1);
        FrameworkListener listener = new RefreshListener(l);
        FrameworkWiring wiring = bundleContext.getBundle(0).adapt(FrameworkWiring.class);
        wiring.refreshBundles(toRefresh, listener);
        try {
            l.await();
        } catch (InterruptedException e) {
            throw new PatchException("Bundle refresh interrupted", e);
        }
    }
    for (Bundle bundle : toStart) {
        String hostHeader = bundle.getHeaders().get(Constants.FRAGMENT_HOST);
        if (hostHeader == null) {
            try {
                bundle.start();
            } catch (BundleException e) {
                System.err.println("Failed to start: " + bundle.getSymbolicName() + ", due to: " + e);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Attribute(org.apache.felix.utils.manifest.Attribute) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) CountDownLatch(java.util.concurrent.CountDownLatch) URISyntaxException(java.net.URISyntaxException) PatchException(org.jboss.fuse.patch.management.PatchException) BundleException(org.osgi.framework.BundleException) IOException(java.io.IOException) URL(java.net.URL) Parser(org.apache.felix.utils.manifest.Parser) Clause(org.apache.felix.utils.manifest.Clause) BundleException(org.osgi.framework.BundleException) PatchException(org.jboss.fuse.patch.management.PatchException) FrameworkListener(org.osgi.framework.FrameworkListener) Directive(org.apache.felix.utils.manifest.Directive) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

FrameworkWiring (org.osgi.framework.wiring.FrameworkWiring)39 Bundle (org.osgi.framework.Bundle)29 Test (org.junit.Test)12 URL (java.net.URL)10 FrameworkListener (org.osgi.framework.FrameworkListener)10 CountDownLatch (java.util.concurrent.CountDownLatch)8 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 BundleContext (org.osgi.framework.BundleContext)7 HashSet (java.util.HashSet)6 FrameworkEvent (org.osgi.framework.FrameworkEvent)6 Version (org.osgi.framework.Version)6 HashMap (java.util.HashMap)5 ComponentContext (org.osgi.service.component.ComponentContext)5 InputStream (java.io.InputStream)4 BundleStartLevel (org.osgi.framework.startlevel.BundleStartLevel)4 PatchManagement (io.fabric8.patch.management.PatchManagement)3 GitPatchManagementServiceImpl (io.fabric8.patch.management.impl.GitPatchManagementServiceImpl)3 GitPatchRepository (io.fabric8.patch.management.impl.GitPatchRepository)3 FileInputStream (java.io.FileInputStream)3