Search in sources :

Example 81 with BundleException

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

the class AssemblyDeployCallback method installBundle.

@Override
public Bundle installBundle(String region, String uri, InputStream is) throws BundleException {
    // Check blacklist
    if (Blacklist.isBundleBlacklisted(builder.getBlacklistedBundles(), uri)) {
        if (builder.getBlacklistPolicy() == Builder.BlacklistPolicy.Fail) {
            throw new RuntimeException("Bundle " + uri + " is blacklisted");
        }
    }
    // Install
    LOGGER.info("      adding maven artifact: " + uri);
    try {
        String regUri;
        String path;
        if (uri.startsWith("mvn:")) {
            regUri = uri;
            path = Parser.pathFromMaven(uri);
        } else {
            uri = uri.replaceAll("[^0-9a-zA-Z.\\-_]+", "_");
            if (uri.length() > 256) {
                //to avoid the File name too long exception
                uri = uri.substring(0, 255);
            }
            path = "generated/" + uri;
            regUri = "file:" + path;
        }
        final Path bundleSystemFile = systemDirectory.resolve(path);
        Files.createDirectories(bundleSystemFile.getParent());
        Files.copy(is, bundleSystemFile, StandardCopyOption.REPLACE_EXISTING);
        Hashtable<String, String> headers = new Hashtable<>();
        try (JarFile jar = new JarFile(bundleSystemFile.toFile())) {
            Attributes attributes = jar.getManifest().getMainAttributes();
            for (Map.Entry<Object, Object> attr : attributes.entrySet()) {
                headers.put(attr.getKey().toString(), attr.getValue().toString());
            }
        }
        BundleRevision revision = new FakeBundleRevision(headers, uri, nextBundleId.incrementAndGet());
        Bundle bundle = revision.getBundle();
        MapUtils.addToMapSet(dstate.bundlesPerRegion, region, bundle.getBundleId());
        dstate.bundles.put(bundle.getBundleId(), bundle);
        bundles.put(regUri, bundle);
        return bundle;
    } catch (IOException e) {
        throw new BundleException("Unable to install bundle", e);
    }
}
Also used : Path(java.nio.file.Path) Hashtable(java.util.Hashtable) Bundle(org.osgi.framework.Bundle) Attributes(java.util.jar.Attributes) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) BundleRevision(org.osgi.framework.wiring.BundleRevision) BundleException(org.osgi.framework.BundleException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 82 with BundleException

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

the class Install method execute.

@Override
public Object execute() throws Exception {
    if (level != null) {
        int sbsl = bundleService.getSystemBundleThreshold();
        if (level < sbsl) {
            if (!JaasHelper.currentUserHasRole(BundleService.SYSTEM_BUNDLES_ROLE)) {
                throw new IllegalArgumentException("Insufficient privileges");
            }
        }
    }
    // install the bundles
    boolean r3warned = false;
    List<Exception> exceptions = new ArrayList<>();
    List<Bundle> bundles = new ArrayList<>();
    for (URI url : urls) {
        try {
            Bundle bundle = bundleContext.installBundle(url.toString(), null);
            if (!"2".equals(bundle.getHeaders().get(Constants.BUNDLE_MANIFESTVERSION))) {
                if (allowR3) {
                    if (!r3warned) {
                        System.err.println("WARNING: use of OSGi r3 bundles is discouraged");
                        r3warned = true;
                    }
                } else {
                    bundle.uninstall();
                    throw new BundleException("OSGi R3 bundle not supported");
                }
            }
            bundles.add(bundle);
        } catch (Exception e) {
            exceptions.add(new Exception("Unable to install bundle " + url + ": " + e.toString(), e));
        }
    }
    // optionally set start level
    if (level != null) {
        for (Bundle bundle : bundles) {
            try {
                bundle.adapt(BundleStartLevel.class).setStartLevel(level);
            } catch (Exception e) {
                exceptions.add(new Exception("Unable to set bundle start level " + bundle.getLocation() + ": " + e.toString(), e));
            }
        }
    }
    // optionally start the bundles
    if (start) {
        for (Bundle bundle : bundles) {
            try {
                bundle.start();
            } catch (Exception e) {
                exceptions.add(new Exception("Unable to start bundle " + bundle.getLocation() + ": " + e.toString(), e));
            }
        }
    }
    // print the installed bundles
    if (bundles.size() == 1) {
        System.out.println("Bundle ID: " + bundles.get(0).getBundleId());
    } else {
        String msg = bundles.stream().map(b -> Long.toString(b.getBundleId())).collect(Collectors.joining(", ", "Bundle IDs: ", ""));
        System.out.println(msg);
    }
    MultiException.throwIf("Error installing bundles", exceptions);
    return null;
}
Also used : MultiException(org.apache.karaf.shell.support.MultiException) Session(org.apache.karaf.shell.api.console.Session) Constants(org.osgi.framework.Constants) BundleService(org.apache.karaf.bundle.core.BundleService) Argument(org.apache.karaf.shell.api.action.Argument) Collectors(java.util.stream.Collectors) BundleContext(org.osgi.framework.BundleContext) ArrayList(java.util.ArrayList) Command(org.apache.karaf.shell.api.action.Command) Action(org.apache.karaf.shell.api.action.Action) BundleStartLevel(org.osgi.framework.startlevel.BundleStartLevel) Reference(org.apache.karaf.shell.api.action.lifecycle.Reference) List(java.util.List) JaasHelper(org.apache.karaf.util.jaas.JaasHelper) Service(org.apache.karaf.shell.api.action.lifecycle.Service) URI(java.net.URI) Option(org.apache.karaf.shell.api.action.Option) Bundle(org.osgi.framework.Bundle) BundleException(org.osgi.framework.BundleException) BundleStartLevel(org.osgi.framework.startlevel.BundleStartLevel) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) URI(java.net.URI) MultiException(org.apache.karaf.shell.support.MultiException) BundleException(org.osgi.framework.BundleException) BundleException(org.osgi.framework.BundleException)

Example 83 with BundleException

use of org.osgi.framework.BundleException 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)

Example 84 with BundleException

use of org.osgi.framework.BundleException in project sling by apache.

the class HeartbeatHandler method issueClusterLocalHeartbeat.

/** Issue a cluster local heartbeat (into the repository) **/
protected void issueClusterLocalHeartbeat() {
    if (logger.isDebugEnabled()) {
        logger.debug("issueClusterLocalHeartbeat: storing cluster-local heartbeat to repository for " + slingId);
    }
    ResourceResolver resourceResolver = null;
    final String myClusterNodePath = getLocalClusterNodePath();
    final Calendar currentTime = Calendar.getInstance();
    try {
        resourceResolver = getResourceResolver();
        if (resourceResolver == null) {
            logger.error("issueClusterLocalHeartbeat: no resourceresolver available!");
            return;
        }
        final Resource resource = ResourceHelper.getOrCreateResource(resourceResolver, myClusterNodePath);
        final ModifiableValueMap resourceMap = resource.adaptTo(ModifiableValueMap.class);
        if (firstHeartbeatWritten != -1 && lastHeartbeatWritten != null) {
            // SLING-2892: additional paranoia check
            // after the first heartbeat, check if there's someone else using
            // the same sling.id in this cluster
            final long timeSinceFirstHeartbeat = System.currentTimeMillis() - firstHeartbeatWritten;
            if (timeSinceFirstHeartbeat > 2 * config.getHeartbeatInterval()) {
                // but wait at least 2 heartbeat intervals to handle the situation
                // where a bundle is refreshed, and startup cases.
                final Calendar lastHeartbeat = resourceMap.get(PROPERTY_ID_LAST_HEARTBEAT, Calendar.class);
                if (lastHeartbeat != null) {
                    // the last time
                    if (!lastHeartbeatWritten.getTime().equals(lastHeartbeat.getTime())) {
                        // then we've likely hit the situation where there is another
                        // sling instance accessing the same repository (ie in the same cluster)
                        // using the same sling.id - hence writing to the same
                        // resource
                        invalidateCurrentEstablishedView();
                        discoveryServiceImpl.handleTopologyChanging();
                        logger.error("issueClusterLocalHeartbeat: SLING-2892: Detected unexpected, concurrent update of: " + myClusterNodePath + " 'lastHeartbeat'. If not done manually, " + "this likely indicates that there is more than 1 instance running in this cluster" + " with the same sling.id. My sling.id is " + slingId + "." + " Check for sling.id.file in your installation of all instances in this cluster " + "to verify this! Duplicate sling.ids are not allowed within a cluster!");
                    }
                }
            }
            // SLING-2901 : robust paranoia check: on first heartbeat write, the
            //              'runtimeId' is set as a property (ignoring any former value).
            //              If in subsequent calls the value of 'runtimeId' changes, then
            //              there is someone else around with the same slingId.
            final String readRuntimeId = resourceMap.get(PROPERTY_ID_RUNTIME, String.class);
            if (readRuntimeId == null) {
                // SLING-3977
                // someone deleted the resource property
                firstHeartbeatWritten = -1;
            } else if (!runtimeId.equals(readRuntimeId)) {
                invalidateCurrentEstablishedView();
                discoveryServiceImpl.handleTopologyChanging();
                final String slingHomePath = slingSettingsService == null ? "n/a" : slingSettingsService.getSlingHomePath();
                final String endpointsAsString = getEndpointsAsString();
                final String readEndpoints = resourceMap.get(PROPERTY_ID_ENDPOINTS, String.class);
                final String readSlingHomePath = resourceMap.get(PROPERTY_ID_SLING_HOME_PATH, String.class);
                logger.error("issueClusterLocalHeartbeat: SLING-2901: Detected more than 1 instance running in this cluster " + " with the same sling.id. " + "My sling.id: " + slingId + ", my runtimeId: " + runtimeId + ", my endpoints: " + endpointsAsString + ", my slingHomePath: " + slingHomePath + ", other runtimeId: " + readRuntimeId + ", other endpoints: " + readEndpoints + ", other slingHomePath:" + readSlingHomePath + " Check for sling.id.file in your installation of all instances in this cluster " + "to verify this! Duplicate sling.ids are not allowed within a cluster!");
                logger.error("issueClusterLocalHeartbeat: sending TOPOLOGY_CHANGING before self-disabling.");
                discoveryServiceImpl.forcedShutdown();
                logger.error("issueClusterLocalHeartbeat: disabling discovery.impl");
                activated = false;
                if (context != null) {
                    // disable all components
                    try {
                        context.getBundleContext().getBundle().stop();
                    } catch (BundleException e) {
                        logger.warn("issueClusterLocalHeartbeat: could not stop bundle: " + e, e);
                        // then disable all compnoents instead
                        context.disableComponent(null);
                    }
                }
                return;
            }
        }
        resourceMap.put(PROPERTY_ID_LAST_HEARTBEAT, currentTime);
        if (firstHeartbeatWritten == -1) {
            resourceMap.put(PROPERTY_ID_RUNTIME, runtimeId);
            // SLING-4765 : store more infos to be able to be more verbose on duplicate slingId/ghost detection
            final String slingHomePath = slingSettingsService == null ? "n/a" : slingSettingsService.getSlingHomePath();
            resourceMap.put(PROPERTY_ID_SLING_HOME_PATH, slingHomePath);
            final String endpointsAsString = getEndpointsAsString();
            resourceMap.put(PROPERTY_ID_ENDPOINTS, endpointsAsString);
            logger.info("issueClusterLocalHeartbeat: storing my runtimeId: {}, endpoints: {} and sling home path: {}", new Object[] { runtimeId, endpointsAsString, slingHomePath });
        }
        if (resetLeaderElectionId || !resourceMap.containsKey("leaderElectionId")) {
            // the new leaderElectionId might have been 'pre set' in the field 'newLeaderElectionId'
            // if that's the case, use that one, otherwise calculate a new one now
            final String newLeaderElectionId = this.newLeaderElectionId != null ? this.newLeaderElectionId : newLeaderElectionId(resourceResolver);
            this.newLeaderElectionId = null;
            resourceMap.put("leaderElectionId", newLeaderElectionId);
            resourceMap.put("leaderElectionIdCreatedAt", new Date());
            logger.info("issueClusterLocalHeartbeat: set leaderElectionId to " + newLeaderElectionId + " (resetLeaderElectionId: " + resetLeaderElectionId + ")");
            if (votingHandler != null) {
                votingHandler.setLeaderElectionId(newLeaderElectionId);
            }
            resetLeaderElectionId = false;
        }
        logger.debug("issueClusterLocalHeartbeat: committing cluster-local heartbeat to repository for {}", slingId);
        resourceResolver.commit();
        logger.debug("issueClusterLocalHeartbeat: committed cluster-local heartbeat to repository for {}", slingId);
        // SLING-2892: only in success case: remember the last heartbeat value written
        lastHeartbeatWritten = currentTime;
        // and set the first heartbeat written value - if it is not already set
        if (firstHeartbeatWritten == -1) {
            firstHeartbeatWritten = System.currentTimeMillis();
        }
    } catch (LoginException e) {
        logger.error("issueHeartbeat: could not log in administratively: " + e, e);
    } catch (PersistenceException e) {
        logger.error("issueHeartbeat: Got a PersistenceException: " + myClusterNodePath + " " + e, e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}
Also used : Calendar(java.util.Calendar) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) BundleException(org.osgi.framework.BundleException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Date(java.util.Date)

Example 85 with BundleException

use of org.osgi.framework.BundleException in project sling by apache.

the class LogSupportTest method testFrameworkEventError.

@Test
public void testFrameworkEventError() throws Exception {
    BundleException bundleException = new BundleException("my bundle exception", BundleException.ACTIVATOR_ERROR);
    FrameworkEvent frameworkEvent = new FrameworkEvent(FrameworkEvent.ERROR, bundle, bundleException);
    logSupport.frameworkEvent(frameworkEvent);
    Mockito.verify(testLogger).error("FrameworkEvent ERROR (org.osgi.framework.BundleException: my bundle exception)", bundleException);
}
Also used : FrameworkEvent(org.osgi.framework.FrameworkEvent) BundleException(org.osgi.framework.BundleException) Test(org.junit.Test)

Aggregations

BundleException (org.osgi.framework.BundleException)99 Bundle (org.osgi.framework.Bundle)54 IOException (java.io.IOException)31 Test (org.junit.Test)19 File (java.io.File)15 ArrayList (java.util.ArrayList)13 InputStream (java.io.InputStream)10 FileInputStream (java.io.FileInputStream)9 BundleContext (org.osgi.framework.BundleContext)9 HashMap (java.util.HashMap)8 Map (java.util.Map)7 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)7 Hashtable (java.util.Hashtable)5 Manifest (java.util.jar.Manifest)5 ServiceReference (org.osgi.framework.ServiceReference)5 Version (org.osgi.framework.Version)5 BundleStartLevel (org.osgi.framework.startlevel.BundleStartLevel)5 LowDiskException (android.taobao.atlas.runtime.LowDiskException)4 TimeoutException (java.util.concurrent.TimeoutException)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4