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");
}
}
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();
}
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();
}
}
}
}
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());
}
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();
}
}
Aggregations