Search in sources :

Example 51 with ServiceEvent

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

the class ZooKeeperClusterBootstrapImpl method cleanInternal.

private BootstrapConfiguration cleanInternal(final BundleContext syscontext, final BootstrapConfiguration bootConfig, RuntimeProperties runtimeProps) throws TimeoutException {
    LOGGER.debug("Begin clean fabric");
    try {
        Configuration zkClientCfg = null;
        Configuration zkServerCfg = null;
        Configuration[] configsSet = configAdmin.get().listConfigurations("(|(service.factoryPid=io.fabric8.zookeeper.server)(service.pid=io.fabric8.zookeeper))");
        if (configsSet != null) {
            for (Configuration cfg : configsSet) {
                // let's explicitly delete client config first
                if ("io.fabric8.zookeeper".equals(cfg.getPid())) {
                    zkClientCfg = cfg;
                }
                if ("io.fabric8.zookeeper.server".equals(cfg.getFactoryPid())) {
                    zkServerCfg = cfg;
                }
            }
        }
        File karafData = new File(data);
        // Setup the listener for unregistration of {@link BootstrapConfiguration}
        final CountDownLatch unregisterLatch = new CountDownLatch(1);
        ServiceListener listener = new ServiceListener() {

            @Override
            public void serviceChanged(ServiceEvent event) {
                if (event.getType() == ServiceEvent.UNREGISTERING) {
                    LOGGER.debug("Unregistering BootstrapConfiguration");
                    bootConfig.getComponentContext().getBundleContext().removeServiceListener(this);
                    unregisterLatch.countDown();
                }
            }
        };
        String filter = "(objectClass=" + BootstrapConfiguration.class.getName() + ")";
        // FABRIC-1052: register listener using the same bundle context that is used for listeners related to SCR
        bootConfig.getComponentContext().getBundleContext().addServiceListener(listener, filter);
        CountDownLatch unregisterLatch2 = null;
        if (syscontext.getServiceReference(CuratorComplete.class) != null) {
            unregisterLatch2 = new CountDownLatch(1);
            final CountDownLatch finalUnregisterLatch = unregisterLatch2;
            listener = new ServiceListener() {

                @Override
                public void serviceChanged(ServiceEvent event) {
                    if (event.getType() == ServiceEvent.UNREGISTERING) {
                        LOGGER.debug("Unregistering CuratorComplete");
                        bootConfig.getComponentContext().getBundleContext().removeServiceListener(this);
                        finalUnregisterLatch.countDown();
                    }
                }
            };
            bootConfig.getComponentContext().getBundleContext().addServiceListener(listener, "(objectClass=" + CuratorComplete.class.getName() + ")");
        }
        // Disable the BootstrapConfiguration component
        // ENTESB-4827: disabling BootstrapConfiguration leads to deactivation of FabricService and ProfileUrlHandler
        // and we have race condition if we're --cleaning after recently created fabric. previous fabric
        // started FabricConfigAdminBridge which scheduled CM updates for tens of PIDs - among others,
        // org.ops4j.pax.web, which leads to an attempt to reconfigure Jetty with "profile:jetty.xml"
        // and if we disable ProfileUrlHandler we may loose Jetty instance
        LOGGER.debug("Disable BootstrapConfiguration");
        ComponentContext componentContext = bootConfig.getComponentContext();
        componentContext.disableComponent(BootstrapConfiguration.COMPONENT_NAME);
        if (!unregisterLatch.await(30, TimeUnit.SECONDS))
            throw new TimeoutException("Timeout for unregistering BootstrapConfiguration service");
        if (unregisterLatch2 != null && !unregisterLatch2.await(30, TimeUnit.SECONDS))
            throw new TimeoutException("Timeout for unregistering CuratorComplete service");
        // Do the cleanup
        runtimeProps.clearRuntimeAttributes();
        cleanConfigurations(syscontext, zkClientCfg, zkServerCfg);
        cleanZookeeperDirectory(karafData);
        cleanGitDirectory(karafData);
        // Setup the registration listener for the new {@link BootstrapConfiguration}
        final CountDownLatch registerLatch = new CountDownLatch(1);
        final AtomicReference<ServiceReference<?>> sref = new AtomicReference<ServiceReference<?>>();
        listener = new ServiceListener() {

            @Override
            public void serviceChanged(ServiceEvent event) {
                if (event.getType() == ServiceEvent.REGISTERED) {
                    LOGGER.debug("Registered BootstrapConfiguration");
                    syscontext.removeServiceListener(this);
                    sref.set(event.getServiceReference());
                    registerLatch.countDown();
                }
            }
        };
        syscontext.addServiceListener(listener, "(objectClass=" + BootstrapConfiguration.class.getName() + ")");
        // Enable the {@link BootstrapConfiguration} component and await the registration of the respective service
        LOGGER.debug("Enable BootstrapConfiguration");
        componentContext.enableComponent(BootstrapConfiguration.COMPONENT_NAME);
        if (!registerLatch.await(30, TimeUnit.SECONDS))
            throw new TimeoutException("Timeout for registering BootstrapConfiguration service");
        return (BootstrapConfiguration) syscontext.getService(sref.get());
    } catch (RuntimeException rte) {
        throw rte;
    } catch (TimeoutException toe) {
        throw toe;
    } catch (Exception ex) {
        throw new FabricException("Unable to delete zookeeper configuration", ex);
    } finally {
        LOGGER.debug("End clean fabric");
    }
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) Configuration(org.osgi.service.cm.Configuration) ComponentContext(org.osgi.service.component.ComponentContext) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) FabricException(io.fabric8.api.FabricException) AtomicReference(java.util.concurrent.atomic.AtomicReference) CuratorComplete(io.fabric8.api.CuratorComplete) CountDownLatch(java.util.concurrent.CountDownLatch) TimeoutException(java.util.concurrent.TimeoutException) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) ServiceReference(org.osgi.framework.ServiceReference) ServiceEvent(org.osgi.framework.ServiceEvent) File(java.io.File) TimeoutException(java.util.concurrent.TimeoutException)

Example 52 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project spring-roo by spring-projects.

the class Activator method start.

public void start(final BundleContext context) throws Exception {
    startLevelServiceReference = context.getServiceReference(StartLevel.class.getName());
    startLevel = (StartLevel) context.getService(startLevelServiceReference);
    for (final Bundle bundle : context.getBundles()) {
        final String value = bundle.getHeaders().get("Service-Component");
        if (value != null) {
            List<String> componentDescriptions = Arrays.asList(value.split("\\s*,\\s*"));
            for (String desc : componentDescriptions) {
                final URL url = bundle.getResource(desc);
                process(url);
            }
        }
    }
    // Ensure I'm notified of other services changes
    final BundleContext myContext = context;
    context.addServiceListener(new ServiceListener() {

        public void serviceChanged(final ServiceEvent event) {
            final ServiceReference sr = event.getServiceReference();
            final String className = getClassName(sr, myContext);
            if (sr != null) {
                myContext.ungetService(sr);
            }
            if (className == null) {
                // Something went wrong
                return;
            }
            if (event.getType() == ServiceEvent.REGISTERED) {
                if (requiredImplementations.keySet().contains(className)) {
                    runningImplementations.add(className);
                    potentiallyChangeStartLevel();
                }
            } else if (event.getType() == ServiceEvent.UNREGISTERING) {
                if (runningImplementations.contains(className)) {
                    runningImplementations.remove(className);
                    potentiallyChangeStartLevel();
                }
            }
        }
    });
    // Now identify if any services I was interested in are already running
    for (final String requiredService : requiredImplementations.keySet()) {
        final String correspondingInterface = requiredImplementations.get(requiredService);
        final ServiceReference[] srs = context.getServiceReferences(correspondingInterface, null);
        if (srs != null) {
            for (final ServiceReference sr : srs) {
                final String className = getClassName(sr, context);
                if (className == null) {
                    // Something went wrong
                    continue;
                }
                if (requiredImplementations.keySet().contains(className)) {
                    runningImplementations.add(className);
                }
            }
        }
    }
    // Potentially change the start level, now that we've added all the
    // known started services
    potentiallyChangeStartLevel();
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) ServiceEvent(org.osgi.framework.ServiceEvent) URL(java.net.URL) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference)

Example 53 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project ecf by eclipse.

the class Activator method start.

/* (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
public void start(final BundleContext context) throws Exception {
    final ServiceReference configAdminServiceRef = context.getServiceReference(ConfigurationAdmin.class.getName());
    if (configAdminServiceRef == null) {
        System.err.println("You don't have config admin deployed. Some tests will fail that require configuration!");
        return;
    }
    final ConfigurationAdmin configAdmin = (ConfigurationAdmin) context.getService(configAdminServiceRef);
    Configuration config = configAdmin.createFactoryConfiguration(DnsSdTestHelper.ECF_DISCOVERY_DNSSD + ".locator", null);
    Dictionary properties = new Hashtable();
    properties.put(IDnsSdDiscoveryConstants.CA_SEARCH_PATH, new String[] { DnsSdTestHelper.DOMAIN });
    properties.put(IDnsSdDiscoveryConstants.CA_RESOLVER, DnsSdTestHelper.DNS_RESOLVER);
    properties.put(IDnsSdDiscoveryConstants.CA_TSIG_KEY, DnsSdTestHelper.TSIG_KEY);
    properties.put(IDnsSdDiscoveryConstants.CA_TSIG_KEY_NAME, DnsSdTestHelper.TSIG_KEY_NAME);
    config.update(properties);
    String filter = "(" + Constants.SERVICE_PID + "=" + config.getPid() + ")";
    // add the service listener
    locListener = new ServiceListener() {

        public void serviceChanged(ServiceEvent event) {
            switch(event.getType()) {
                case ServiceEvent.REGISTERED:
                    ServiceReference serviceReference = event.getServiceReference();
                    discoveryLocator = (IDiscoveryLocator) context.getService(serviceReference);
                    synchronized (locLock) {
                        locLock.notifyAll();
                    }
            }
        }
    };
    context.addServiceListener(locListener, filter);
    // try to get the service initially
    ServiceReference[] references = context.getServiceReferences(IDiscoveryLocator.class.getName(), filter);
    if (references != null) {
        for (int i = 0; i < references.length; ) {
            ServiceReference serviceReference = references[i];
            discoveryLocator = (IDiscoveryLocator) context.getService(serviceReference);
            synchronized (locLock) {
                locLock.notifyAll();
            }
        }
    }
    // advertiser
    config = configAdmin.createFactoryConfiguration(DnsSdTestHelper.ECF_DISCOVERY_DNSSD + ".advertiser", null);
    properties = new Hashtable();
    properties.put(IDnsSdDiscoveryConstants.CA_SEARCH_PATH, new String[] { DnsSdTestHelper.DOMAIN });
    properties.put(IDnsSdDiscoveryConstants.CA_RESOLVER, DnsSdTestHelper.DNS_RESOLVER);
    properties.put(IDnsSdDiscoveryConstants.CA_TSIG_KEY, DnsSdTestHelper.TSIG_KEY);
    properties.put(IDnsSdDiscoveryConstants.CA_TSIG_KEY_NAME, DnsSdTestHelper.TSIG_KEY_NAME);
    config.update(properties);
    filter = "(" + Constants.SERVICE_PID + "=" + config.getPid() + ")";
    // add the service listener
    advListener = new ServiceListener() {

        public void serviceChanged(ServiceEvent event) {
            switch(event.getType()) {
                case ServiceEvent.REGISTERED:
                    ServiceReference serviceReference = event.getServiceReference();
                    discoveryAdvertiser = (IDiscoveryAdvertiser) context.getService(serviceReference);
                    synchronized (advLock) {
                        advLock.notifyAll();
                    }
            }
        }
    };
    context.addServiceListener(advListener, filter);
    // try to get the service initially
    references = context.getServiceReferences(IDiscoveryAdvertiser.class.getName(), filter);
    if (references != null) {
        for (int i = 0; i < references.length; ) {
            ServiceReference serviceReference = references[i];
            discoveryAdvertiser = (IDiscoveryAdvertiser) context.getService(serviceReference);
            synchronized (advLock) {
                advLock.notifyAll();
            }
        }
    }
}
Also used : Dictionary(java.util.Dictionary) ServiceListener(org.osgi.framework.ServiceListener) Configuration(org.osgi.service.cm.Configuration) IDiscoveryAdvertiser(org.eclipse.ecf.discovery.IDiscoveryAdvertiser) Hashtable(java.util.Hashtable) ServiceEvent(org.osgi.framework.ServiceEvent) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) IDiscoveryLocator(org.eclipse.ecf.discovery.IDiscoveryLocator) ServiceReference(org.osgi.framework.ServiceReference)

Example 54 with ServiceEvent

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

the class BundleEventHookTest method testIgnoreUninstalledOriginBundleInAsyncInstalledEvent.

/*
     * Because bundle events are queued for later asynchronous processing while
     * the root subsystem is initializing, it is possible to see an installed
     * event whose origin bundle has been uninstalled (i.e. the origin bundle's
     * revision will be null). These events should result in the installed
     * bundle being associated with the root subsystem.
     */
@Test
public void testIgnoreUninstalledOriginBundleInAsyncInstalledEvent() throws Exception {
    final Bundle core = getSubsystemCoreBundle();
    core.stop();
    final Bundle b = bundleContext.installBundle(BUNDLE_B, new FileInputStream(BUNDLE_B));
    // Ensure bundle B has a context.
    b.start();
    final AtomicReference<Bundle> a = new AtomicReference<Bundle>();
    bundleContext.addServiceListener(new ServiceListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void serviceChanged(ServiceEvent event) {
            if ((event.getType() & (ServiceEvent.REGISTERED | ServiceEvent.MODIFIED)) == 0)
                return;
            if (a.get() != null)
                // We've been here before and already done what needs doing.
                return;
            ServiceReference sr = (ServiceReference) event.getServiceReference();
            bundleContext.getService(sr);
            try {
                // Queue up the installed event for bundle A using B's context.
                a.set(b.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A)));
                // Ensure the origin bundle will be uninstalled before the event is processed.
                b.uninstall();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, "(&(objectClass=org.osgi.service.subsystem.Subsystem)(subsystem.id=0)(subsystem.state=RESOLVED))");
    try {
        // Before the fix, this would fail due to an NPE resulting from a
        // null bundle revision.
        core.start();
    } catch (BundleException e) {
        e.printStackTrace();
        fail("Subsystems failed to handle an asynchronous bundle installed event after the origin bundle was uninstalled");
    }
    assertBundleState(a.get(), Bundle.INSTALLED);
    assertBundleState(b, Bundle.UNINSTALLED);
    Subsystem root = getRootSubsystem();
    assertState(Subsystem.State.ACTIVE, root);
    assertConstituent(root, a.get().getSymbolicName());
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) ServiceEvent(org.osgi.framework.ServiceEvent) Subsystem(org.osgi.service.subsystem.Subsystem) AtomicReference(java.util.concurrent.atomic.AtomicReference) BundleException(org.osgi.framework.BundleException) FileInputStream(java.io.FileInputStream) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BundleException(org.osgi.framework.BundleException) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 55 with ServiceEvent

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

the class BundleEventHookTest method testNoDeadlockWhenSubsystemsInitializing.

/*
     * See https://issues.apache.org/jira/browse/ARIES-982.
     * 
     * When activating, the subsystems bundle must initialize the root subsystem
     * along with any persisted subsystems. Part of the root subsystem 
     * initialization consists of adding all pre-existing bundles as 
     * constituents. In order to ensure that no bundles are missed, a bundle
     * event hook is registered first. The bundle event hook cannot process
     * events until the initialization is complete. Another part of 
     * initialization consists of registering the root subsystem service.
     * Therefore, a potential deadlock exists if something reacts to the
     * service registration by installing an unmanaged bundle.
     */
@Test
public void testNoDeadlockWhenSubsystemsInitializing() throws Exception {
    final Bundle bundle = getSubsystemCoreBundle();
    bundle.stop();
    final AtomicBoolean completed = new AtomicBoolean(false);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    try {
        bundleContext.addServiceListener(new ServiceListener() {

            @Override
            public void serviceChanged(ServiceEvent event) {
                Future<?> future = executor.submit(new Runnable() {

                    public void run() {
                        try {
                            Bundle a = bundle.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
                            completed.set(true);
                            a.uninstall();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                try {
                    future.get();
                    completed.set(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "(&(objectClass=org.osgi.service.subsystem.Subsystem)(subsystem.id=0))");
        Future<?> future = executor.submit(new Runnable() {

            public void run() {
                try {
                    bundle.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        try {
            future.get(3, TimeUnit.SECONDS);
            assertTrue("Deadlock detected", completed.get());
        } catch (TimeoutException e) {
            fail("Deadlock detected");
        }
    } finally {
        executor.shutdownNow();
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) ServiceEvent(org.osgi.framework.ServiceEvent) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) FileInputStream(java.io.FileInputStream) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BundleException(org.osgi.framework.BundleException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Aggregations

ServiceEvent (org.osgi.framework.ServiceEvent)56 ServiceReference (org.osgi.framework.ServiceReference)30 Test (org.junit.Test)24 BundleContext (org.osgi.framework.BundleContext)23 ServiceListener (org.osgi.framework.ServiceListener)20 Bundle (org.osgi.framework.Bundle)18 Hashtable (java.util.Hashtable)14 ServiceRegistration (org.osgi.framework.ServiceRegistration)12 Collection (java.util.Collection)6 IOException (java.io.IOException)5 Dictionary (java.util.Dictionary)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)5 File (java.io.File)4 FileInputStream (java.io.FileInputStream)4 HashMap (java.util.HashMap)4 ServiceRegistrationHolder (org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder)4 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3