Search in sources :

Example 1 with BundleListener

use of org.osgi.framework.BundleListener in project atlas by alibaba.

the class Framework method notifyBundleListeners.

/**
     * notify all bundle listeners.
     *
     * @param state the new state.
     * @param bundle the bundle.
     */
static void notifyBundleListeners(final int state, final Bundle bundle) {
    if (syncBundleListeners.isEmpty() && bundleListeners.isEmpty()) {
        return;
    }
    final BundleEvent event = new BundleEvent(state, bundle);
    // inform the synchrounous bundle listeners first ...
    final BundleListener[] syncs = (BundleListener[]) syncBundleListeners.toArray(new BundleListener[syncBundleListeners.size()]);
    for (int i = 0; i < syncs.length; i++) {
        syncs[i].bundleChanged(event);
    }
    if (bundleListeners.isEmpty()) {
        return;
    }
    final BundleListener[] asyncs = (BundleListener[]) bundleListeners.toArray(new BundleListener[bundleListeners.size()]);
    for (int i = 0; i < asyncs.length; i++) {
        asyncs[i].bundleChanged(event);
    }
}
Also used : BundleEvent(org.osgi.framework.BundleEvent) BundleListener(org.osgi.framework.BundleListener)

Example 2 with BundleListener

use of org.osgi.framework.BundleListener in project rt.equinox.framework by eclipse.

the class SystemBundleTests method testSystemBundleListener.

public void testSystemBundleListener() throws BundleException, InterruptedException {
    File config = OSGiTestsActivator.getContext().getDataFile(getName());
    config.mkdirs();
    Map<String, Object> configuration = new HashMap<String, Object>();
    configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath());
    Equinox equinox = new Equinox(configuration);
    equinox.start();
    BundleContext systemContext = equinox.getBundleContext();
    final AtomicInteger stoppingEvent = new AtomicInteger();
    final AtomicInteger stoppedEvent = new AtomicInteger();
    BundleListener systemBundleListener = new SynchronousBundleListener() {

        @Override
        public void bundleChanged(BundleEvent event) {
            if (event.getBundle().getBundleId() == 0) {
                switch(event.getType()) {
                    case BundleEvent.STOPPING:
                        stoppingEvent.incrementAndGet();
                        break;
                    case BundleEvent.STOPPED:
                        stoppedEvent.incrementAndGet();
                    default:
                        break;
                }
            }
        }
    };
    systemContext.addBundleListener(systemBundleListener);
    equinox.stop();
    equinox.waitForStop(5000);
    assertEquals("Wrong number of STOPPING events", 1, stoppingEvent.get());
    assertEquals("Wrong number of STOPPED events", 1, stoppedEvent.get());
}
Also used : Equinox(org.eclipse.osgi.launch.Equinox) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BundleEvent(org.osgi.framework.BundleEvent) BundleListener(org.osgi.framework.BundleListener) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) File(java.io.File) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) BundleContext(org.osgi.framework.BundleContext)

Example 3 with BundleListener

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

the class GitPatchManagementServiceImpl method checkPendingPatches.

@Override
public void checkPendingPatches() {
    File[] pendingPatches = patchesDir.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return pathname.exists() && pathname.getName().endsWith(".pending");
        }
    });
    if (pendingPatches == null || pendingPatches.length == 0) {
        return;
    }
    final String dataCache = systemContext.getProperty("org.osgi.framework.storage");
    for (File pending : pendingPatches) {
        try {
            Pending what = Pending.valueOf(FileUtils.readFileToString(pending));
            final String prefix = what == Pending.ROLLUP_INSTALLATION ? "install" : "rollback";
            String name = pending.getName().replaceFirst("\\.pending$", "");
            if (isStandaloneChild()) {
                if (name.endsWith("." + System.getProperty("karaf.name") + ".patch")) {
                    name = name.replaceFirst("\\." + System.getProperty("karaf.name"), "");
                } else {
                    continue;
                }
            }
            File patchFile = new File(pending.getParentFile(), name);
            if (!patchFile.isFile()) {
                Activator.log(LogService.LOG_INFO, "Ignoring patch result file: " + patchFile.getName());
                continue;
            }
            PatchData patchData = PatchData.load(new FileInputStream(patchFile));
            Patch patch = loadPatch(new PatchDetailsRequest(patchData.getId()));
            String dataFilesName = patchData.getId() + ".datafiles";
            if (isStandaloneChild()) {
                dataFilesName = patchData.getId() + "." + System.getProperty("karaf.name") + ".datafiles";
            }
            final File dataFilesBackupDir = new File(pending.getParentFile(), dataFilesName);
            final Properties backupProperties = new Properties();
            FileInputStream inStream = new FileInputStream(new File(dataFilesBackupDir, "backup-" + prefix + ".properties"));
            backupProperties.load(inStream);
            IOUtils.closeQuietly(inStream);
            // maybe one of those bundles has data directory to restore?
            for (Bundle b : systemContext.getBundles()) {
                if (b.getSymbolicName() != null) {
                    String key = String.format("%s$$%s", stripSymbolicName(b.getSymbolicName()), b.getVersion().toString());
                    if (backupProperties.containsKey(key)) {
                        String backupDirName = backupProperties.getProperty(key);
                        File backupDir = new File(dataFilesBackupDir, prefix + "/" + backupDirName + "/data");
                        restoreDataDirectory(dataCache, b, backupDir);
                        // we no longer want to restore this dir
                        backupProperties.remove(key);
                    }
                }
            }
            // 2. We can however have more bundle data backups - we'll restore them after each bundle
            // is INSTALLED and we'll use listener for this
            BundleListener bundleListener = new SynchronousBundleListener() {

                @Override
                public void bundleChanged(BundleEvent event) {
                    Bundle b = event.getBundle();
                    if (event.getType() == BundleEvent.INSTALLED && b.getSymbolicName() != null) {
                        String key = String.format("%s$$%s", stripSymbolicName(b.getSymbolicName()), b.getVersion().toString());
                        if (backupProperties.containsKey(key)) {
                            String backupDirName = backupProperties.getProperty(key);
                            File backupDir = new File(dataFilesBackupDir, prefix + "/" + backupDirName + "/data");
                            restoreDataDirectory(dataCache, b, backupDir);
                        }
                    }
                }
            };
            systemContext.addBundleListener(bundleListener);
            pendingPatchesListeners.put(patchData.getId(), bundleListener);
        } catch (Exception e) {
            Activator.log(LogService.LOG_ERROR, null, e.getMessage(), e, true);
        }
    }
}
Also used : PatchData(io.fabric8.patch.management.PatchData) Bundle(org.osgi.framework.Bundle) Properties(java.util.Properties) PatchDetailsRequest(io.fabric8.patch.management.PatchDetailsRequest) FileInputStream(java.io.FileInputStream) PatchException(io.fabric8.patch.management.PatchException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BundleEvent(org.osgi.framework.BundleEvent) BundleListener(org.osgi.framework.BundleListener) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) FileFilter(java.io.FileFilter) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) ManagedPatch(io.fabric8.patch.management.ManagedPatch) Patch(io.fabric8.patch.management.Patch) Pending(io.fabric8.patch.management.Pending) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener)

Example 4 with BundleListener

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

the class GitPatchManagementServiceImpl method ensurePatchManagementInitialized.

/**
 * Check if Fuse/Fabric8 installation is correctly managed by patch mechanism. Check if main git repository
 * is created and is intialized with correct content, there are no conflicts and no pending updates in main Karaf
 * directory. After this method is invoked, we're basically ready to perform rollup patches backed up by git
 * repository.
 */
@Override
public void ensurePatchManagementInitialized() {
    Activator.log(LogService.LOG_INFO, "Configuring patch management system");
    Git fork = null;
    try {
        Git mainRepository = gitPatchRepository.findOrCreateMainGitRepository();
        ensuringLock.lock();
        if (env.isFabric()) {
            // let's fetch from origin to check if someone else already does fabric patch management
            fetchFabricPatchData(mainRepository);
            if (env == EnvType.FABRIC_FUSE || env == EnvType.FABRIC_AMQ) {
                // I think it's enough to compare the main HEADs. if there are no remote branches
                // for patch management or their HEADs are the same, we are the MAIN container that performs
                // git patch management
                ObjectId ours = mainRepository.getRepository().resolve("refs/heads/" + gitPatchRepository.getFuseRootContainerPatchBranchName());
                ObjectId theirs = mainRepository.getRepository().resolve("refs/remotes/origin/" + gitPatchRepository.getFuseRootContainerPatchBranchName());
                if (theirs == null || theirs.equals(ours)) {
                    // if ours is null, then we've just started git patch management
                    // but there's little chance that we're just doing fabric:join... there's only one
                    // way to test it
                    boolean hasZookeeperUrlSetInSystemProperties = false;
                    Properties systemProperties = new Properties();
                    try (FileInputStream fis = new FileInputStream(new File(karafBase, "etc/system.properties"))) {
                        systemProperties.load(fis);
                        String zookeeperUrl = systemProperties.getProperty("zookeeper.url");
                        hasZookeeperUrlSetInSystemProperties = zookeeperUrl != null && !zookeeperUrl.trim().equals("");
                    }
                    master = !hasZookeeperUrlSetInSystemProperties;
                    gitPatchRepository.setMaster(master);
                }
            }
        }
        // prepare single fork for all the below operations - switch to different branches later, as needed
        fork = gitPatchRepository.cloneRepository(mainRepository, true);
        if (env.isFabric() && master) {
            // track baselines for future - when containers are upgraded and their static resources
            // have to be rebased on new baselines
            // new baselines will be added when patches are installed
            trackBaselinesForRootContainer(fork);
            trackBaselinesForChildContainers(fork);
            trackBaselinesForSSHContainers(fork);
        }
        if (env == EnvType.STANDALONE) {
            boolean possiblyInFabric8KarafDistro = new File(karafHome, "bin/fabric8").isFile() || new File(karafHome, "bin/fabric8.bat").isFile();
            if (!possiblyInFabric8KarafDistro) {
                // ENTESB-5761: let's skip the initialization in fabric8-karaf distro - probably we're in SSH container
                // that's just being created
                // do standalone history initialization. We're in root Fuse/AMQ container
                String currentFuseVersion = determineVersion(karafHome, "fuse");
                // one of the steps may return a commit that has to be tagged as first baseline
                RevCommit baselineCommit = null;
                if (!gitPatchRepository.containsTag(fork, String.format(env.getBaselineTagFormat(), currentFuseVersion))) {
                    baselineCommit = trackBaselineRepository(fork);
                    RevCommit c2 = installPatchManagementBundle(fork);
                    if (c2 != null) {
                        baselineCommit = c2;
                    }
                }
                // because patch management is already installed, we have to add consecutive (post patch-management installation) changes
                applyUserChanges(fork);
                if (baselineCommit != null) {
                    // and we'll tag the baseline *after* steps related to first baseline
                    fork.tag().setName(String.format(env.getBaselineTagFormat(), currentFuseVersion)).setObjectId(baselineCommit).call();
                    gitPatchRepository.push(fork);
                }
                // now we have to do the same for existing/future admin:create based child containers
                // it's the root container that takes care of this
                trackBaselinesForChildContainers(fork);
                // repository of patch data - already installed patches
                migrateOldPatchData();
            }
        } else if (env == EnvType.STANDALONE_CHILD) {
            // we're in admin:create based child container. we share patch management git repository
            // with the container that created us
            String currentKarafVersion = determineVersion(karafBase, "karaf");
            String tagName = String.format(env.getBaselineTagFormat(), currentKarafVersion);
            handleNonCurrentBaseline(fork, currentKarafVersion, tagName, true, true);
        } else {
            // do fabric history branch initialization
            // each container has to make sure their private history branch is created and that it contains
            // tag related to the "version" of container (child: karaf, ssh: fabric8 or fuse, root: fuse or amq)
            String currentKarafVersion = determineVersion(karafBase, env.getProductId());
            String tagName = String.format(env.getBaselineTagFormat(), currentKarafVersion);
            handleNonCurrentBaseline(fork, currentKarafVersion, tagName, true, false);
        }
        // remove pending patches listeners
        for (BundleListener bl : pendingPatchesListeners.values()) {
            systemContext.removeBundleListener(bl);
        }
    } catch (GitAPIException | IOException e) {
        Activator.log(LogService.LOG_ERROR, null, e.getMessage(), e, true);
    } finally {
        ensuringLock.unlock();
        initialized.countDown();
        if (fork != null) {
            gitPatchRepository.closeRepository(fork, true);
        }
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) ObjectId(org.eclipse.jgit.lib.ObjectId) BundleListener(org.osgi.framework.BundleListener) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) IOException(java.io.IOException) Properties(java.util.Properties) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) FileInputStream(java.io.FileInputStream) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 5 with BundleListener

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

the class GitPatchManagementServiceImpl method ensurePatchManagementInitialized.

/**
 * Check if Fuse/Karaf installation is correctly managed by patch mechanism. Check if main git repository
 * is created and is intialized with correct content, there are no conflicts and no pending updates in main Karaf
 * directory. After this method is invoked, we're basically ready to perform rollup patches backed up by git
 * repository.
 */
@Override
public void ensurePatchManagementInitialized() {
    Activator.log(LogService.LOG_INFO, "Configuring patch management system");
    Git fork = null;
    try {
        Git mainRepository = gitPatchRepository.findOrCreateMainGitRepository();
        ensuringLock.lock();
        // prepare single fork for all the below operations - switch to different branches later, as needed
        fork = gitPatchRepository.cloneRepository(mainRepository, true);
        if (env == EnvType.STANDALONE) {
            // do standalone history initialization. We're in root Fuse/AMQ container
            String currentFuseVersion = determineVersion(karafHome);
            // one of the steps may return a commit that has to be tagged as first baseline
            RevCommit baselineCommit = null;
            if (!gitPatchRepository.containsTag(fork, String.format(env.getBaselineTagFormat(), currentFuseVersion))) {
                baselineCommit = trackBaselineRepository(fork);
                RevCommit c2 = installPatchManagementBundle(fork);
                if (c2 != null) {
                    baselineCommit = c2;
                }
            }
            // because patch management is already installed, we have to add consecutive (post patch-management installation) changes
            applyUserChanges(fork);
            if (baselineCommit != null) {
                // and we'll tag the baseline *after* steps related to first baseline
                fork.tag().setName(String.format(env.getBaselineTagFormat(), currentFuseVersion)).setObjectId(baselineCommit).call();
                gitPatchRepository.push(fork);
            }
            // now we have to do the same for existing/future instance:create based child containers
            // it's the root container that takes care of this
            trackBaselinesForChildContainers(fork);
        } else if (env == EnvType.STANDALONE_CHILD) {
            // we're in instance:create based child container. we share patch management git repository
            // with the container that created us
            String currentKarafVersion = determineVersion(karafBase);
            String tagName = String.format(env.getBaselineTagFormat(), currentKarafVersion);
            handleNonCurrentBaseline(fork, currentKarafVersion, tagName, true, true);
        }
        // remove pending patches listeners
        for (BundleListener bl : pendingPatchesListeners.values()) {
            systemContext.removeBundleListener(bl);
        }
    } catch (GitAPIException | IOException e) {
        Activator.log(LogService.LOG_ERROR, null, e.getMessage(), e, true);
    } finally {
        ensuringLock.unlock();
        initialized.countDown();
        if (fork != null) {
            gitPatchRepository.closeRepository(fork, true);
        }
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) BundleListener(org.osgi.framework.BundleListener) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) IOException(java.io.IOException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

BundleListener (org.osgi.framework.BundleListener)18 BundleEvent (org.osgi.framework.BundleEvent)14 SynchronousBundleListener (org.osgi.framework.SynchronousBundleListener)9 Bundle (org.osgi.framework.Bundle)8 File (java.io.File)5 BundleContext (org.osgi.framework.BundleContext)5 IOException (java.io.IOException)4 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)4 FileInputStream (java.io.FileInputStream)3 Properties (java.util.Properties)3 ZipFile (org.apache.commons.compress.archivers.zip.ZipFile)3 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 ExecutorService (java.util.concurrent.ExecutorService)2 MBeanServer (javax.management.MBeanServer)2 ObjectName (javax.management.ObjectName)2 Logger (org.apache.aries.jmx.Logger)2 Git (org.eclipse.jgit.api.Git)2