Search in sources :

Example 11 with ConfigurationEvent

use of org.osgi.service.cm.ConfigurationEvent in project felix by apache.

the class ConfigurationManagerTest method testEventsStartingBundle.

@Test
public void testEventsStartingBundle() throws Exception {
    final Set<String> result = new HashSet<>();
    SynchronousConfigurationListener syncListener1 = new SynchronousConfigurationListener() {

        @Override
        public void configurationEvent(ConfigurationEvent event) {
            result.add("L1");
        }
    };
    SynchronousConfigurationListener syncListener2 = new SynchronousConfigurationListener() {

        @Override
        public void configurationEvent(ConfigurationEvent event) {
            result.add("L2");
        }
    };
    SynchronousConfigurationListener syncListener3 = new SynchronousConfigurationListener() {

        @Override
        public void configurationEvent(ConfigurationEvent event) {
            result.add("L3");
        }
    };
    ServiceReference mockRef = Mockito.mock(ServiceReference.class);
    ServiceRegistration mockReg = Mockito.mock(ServiceRegistration.class);
    Mockito.when(mockReg.getReference()).thenReturn(mockRef);
    ConfigurationManager configMgr = new ConfigurationManager(new PersistenceManagerProxy(new MockPersistenceManager()), null);
    setServiceTrackerField(configMgr, "configurationListenerTracker");
    ServiceReference[] refs = setServiceTrackerField(configMgr, "syncConfigurationListenerTracker", syncListener1, syncListener2, syncListener3);
    for (int i = 0; i < refs.length; i++) {
        Bundle mockBundle = Mockito.mock(Bundle.class);
        switch(i) {
            case 0:
                Mockito.when(mockBundle.getState()).thenReturn(Bundle.ACTIVE);
                break;
            case 1:
                Mockito.when(mockBundle.getState()).thenReturn(Bundle.STARTING);
                break;
            case 2:
                Mockito.when(mockBundle.getState()).thenReturn(Bundle.STOPPING);
                break;
        }
        Mockito.when(refs[i].getBundle()).thenReturn(mockBundle);
    }
    Field srField = configMgr.getClass().getDeclaredField("configurationAdminRegistration");
    srField.setAccessible(true);
    srField.set(configMgr, mockReg);
    Field utField = configMgr.getClass().getDeclaredField("updateThread");
    utField.setAccessible(true);
    utField.set(configMgr, new UpdateThread(null, "Test updater"));
    Dictionary<String, Object> props = new Hashtable<>();
    props.put(Constants.SERVICE_PID, "org.acme.testpid");
    ConfigurationImpl config = new ConfigurationImpl(configMgr, new MockPersistenceManager(), props);
    configMgr.updated(config, true);
    assertEquals("Both listeners should have been called, both in the STARTING and ACTIVE state, but not in the STOPPING state", 2, result.size());
}
Also used : ConfigurationEvent(org.osgi.service.cm.ConfigurationEvent) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) PersistenceManagerProxy(org.apache.felix.cm.impl.persistence.PersistenceManagerProxy) CachingPersistenceManagerProxy(org.apache.felix.cm.impl.persistence.CachingPersistenceManagerProxy) SynchronousConfigurationListener(org.osgi.service.cm.SynchronousConfigurationListener) ServiceReference(org.osgi.framework.ServiceReference) Field(java.lang.reflect.Field) MockPersistenceManager(org.apache.felix.cm.MockPersistenceManager) HashSet(java.util.HashSet) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Example 12 with ConfigurationEvent

use of org.osgi.service.cm.ConfigurationEvent in project fabric8 by jboss-fuse.

the class ZooKeeperClusterBootstrapImpl method create.

@Override
public void create(CreateEnsembleOptions options) {
    assertValid();
    try {
        // Wait for bootstrap to be complete
        ServiceLocator.awaitService(BootstrapComplete.class);
        LOGGER.info("Create fabric with: {}", options);
        stopBundles();
        BundleContext syscontext = bundleContext.getBundle(0).getBundleContext();
        long bootstrapTimeout = options.getBootstrapTimeout();
        RuntimeProperties runtimeProps = runtimeProperties.get();
        BootstrapConfiguration bootConfig = bootstrapConfiguration.get();
        if (options.isClean()) {
            bootConfig = cleanInternal(syscontext, bootConfig, runtimeProps);
        }
        // before we start fabric, register CM listener that'll mark end of work of FabricConfigAdminBridge
        final CountDownLatch fcabLatch = new CountDownLatch(1);
        final ServiceRegistration<ConfigurationListener> registration = bundleContext.registerService(ConfigurationListener.class, new ConfigurationListener() {

            @Override
            public void configurationEvent(ConfigurationEvent event) {
                if (event.getType() == ConfigurationEvent.CM_UPDATED && event.getPid() != null && event.getPid().equals(Constants.CONFIGADMIN_BRIDGE_PID)) {
                    fcabLatch.countDown();
                }
            }
        }, null);
        BootstrapCreateHandler createHandler = new BootstrapCreateHandler(syscontext, bootConfig, runtimeProps);
        createHandler.bootstrapFabric(name, homeDir, options);
        startBundles(options);
        long startTime = System.currentTimeMillis();
        ServiceLocator.awaitService(FabricComplete.class, bootstrapTimeout, TimeUnit.MILLISECONDS);
        // FabricComplete is registered somewhere in the middle of registering CuratorFramework (SCR activates
        // it when CuratorFramework is registered), but CuratorFramework leads to activation of >100 SCR
        // components, so let's wait for new CuratorComplete service - it is registered after registration
        // of CuratorFramework finishes
        ServiceLocator.awaitService(CuratorComplete.class, bootstrapTimeout, TimeUnit.MILLISECONDS);
        CuratorFramework curatorFramework = ServiceLocator.getService(CuratorFramework.class);
        Map<String, String> dataStoreProperties = options.getDataStoreProperties();
        if (ZooKeeperUtils.exists(curatorFramework, ZkPath.CONFIG_GIT_EXTERNAL.getPath()) == null)
            ZooKeeperUtils.create(curatorFramework, ZkPath.CONFIG_GIT_EXTERNAL.getPath());
        if (dataStoreProperties != null) {
            String remoteUrl = dataStoreProperties.get(Constants.GIT_REMOTE_URL);
            if (remoteUrl != null) {
                ZooKeeperUtils.create(curatorFramework, ZkPath.CONFIG_GIT_EXTERNAL_URL.getPath());
                ZooKeeperUtils.add(curatorFramework, ZkPath.CONFIG_GIT_EXTERNAL_URL.getPath(), remoteUrl);
            }
            String remoteUser = dataStoreProperties.get("gitRemoteUser");
            if (remoteUser != null) {
                ZooKeeperUtils.create(curatorFramework, ZkPath.CONFIG_GIT_EXTERNAL_USER.getPath());
                ZooKeeperUtils.add(curatorFramework, ZkPath.CONFIG_GIT_EXTERNAL_USER.getPath(), remoteUser);
            }
            String remotePassword = dataStoreProperties.get("gitRemotePassword");
            if (remotePassword != null) {
                ZooKeeperUtils.create(curatorFramework, ZkPath.CONFIG_GIT_EXTERNAL_PASSWORD.getPath());
                ZooKeeperUtils.add(curatorFramework, ZkPath.CONFIG_GIT_EXTERNAL_PASSWORD.getPath(), remotePassword);
            }
        }
        // HttpService is registered differently. not as SCR component activation, but after
        // FabricConfigAdminBridge updates (or doesn't touch) org.ops4j.pax.web CM configuration
        // however in fabric, this PID contains URL to jetty configuration in the form "profile:jetty.xml"
        // so we have to have FabricService and ProfileUrlHandler active
        // some ARQ (single container instance) tests failed because tests ended without http service running
        // of course we have to think if all fabric instances need http service
        ServiceLocator.awaitService("org.osgi.service.http.HttpService", bootstrapTimeout, TimeUnit.MILLISECONDS);
        // and last wait - too much synchronization never hurts
        fcabLatch.await(bootstrapTimeout, TimeUnit.MILLISECONDS);
        registration.unregister();
        long timeDiff = System.currentTimeMillis() - startTime;
        createHandler.waitForContainerAlive(name, syscontext, bootstrapTimeout);
        if (options.isWaitForProvision() && options.isAgentEnabled()) {
            long currentTime = System.currentTimeMillis();
            createHandler.waitForSuccessfulDeploymentOf(name, syscontext, bootstrapTimeout - (currentTime - startTime));
        }
    } catch (RuntimeException rte) {
        throw rte;
    } catch (Exception ex) {
        throw new FabricException("Unable to create zookeeper server configuration", ex);
    }
}
Also used : ConfigurationEvent(org.osgi.service.cm.ConfigurationEvent) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) FabricException(io.fabric8.api.FabricException) 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) ConfigurationListener(org.osgi.service.cm.ConfigurationListener) CuratorFramework(org.apache.curator.framework.CuratorFramework) RuntimeProperties(io.fabric8.api.RuntimeProperties) BundleContext(org.osgi.framework.BundleContext)

Example 13 with ConfigurationEvent

use of org.osgi.service.cm.ConfigurationEvent in project fabric8 by jboss-fuse.

the class OsgiUtils method updateCmFactoryConfigurationAndWait.

/**
 * Updates CM configuration and waits for CM_UPDATE event to be send
 * @param bundleContext
 * @param config
 * @param properties
 * @param timeout
 * @param unit
 * @return
 */
public static boolean updateCmFactoryConfigurationAndWait(BundleContext bundleContext, final Configuration config, Dictionary<String, Object> properties, long timeout, TimeUnit unit) throws IOException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final ServiceRegistration<ConfigurationListener> registration = bundleContext.registerService(ConfigurationListener.class, new ConfigurationListener() {

        @Override
        public void configurationEvent(ConfigurationEvent event) {
            if (event.getType() == ConfigurationEvent.CM_UPDATED && event.getFactoryPid() != null && event.getFactoryPid().startsWith(config.getFactoryPid())) {
                latch.countDown();
            }
        }
    }, null);
    config.update(properties);
    try {
        return latch.await(timeout, unit);
    } finally {
        registration.unregister();
    }
}
Also used : ConfigurationListener(org.osgi.service.cm.ConfigurationListener) ConfigurationEvent(org.osgi.service.cm.ConfigurationEvent) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 14 with ConfigurationEvent

use of org.osgi.service.cm.ConfigurationEvent in project fabric8 by jboss-fuse.

the class OsgiUtils method deleteCmFactoryConfigurationAndWait.

/**
 * Deletes CM factory configuration and waits for CM_DELETE event to be send
 * @param bundleContext
 * @param config
 * @param timeout
 * @param unit
 * @return
 */
public static boolean deleteCmFactoryConfigurationAndWait(BundleContext bundleContext, final Configuration config, final String pid, long timeout, TimeUnit unit) throws IOException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final ServiceRegistration<ConfigurationListener> registration = bundleContext.registerService(ConfigurationListener.class, new ConfigurationListener() {

        @Override
        public void configurationEvent(ConfigurationEvent event) {
            if (event.getType() == ConfigurationEvent.CM_DELETED && event.getFactoryPid() != null && event.getFactoryPid().startsWith(pid)) {
                latch.countDown();
            }
        }
    }, null);
    config.delete();
    try {
        return latch.await(timeout, unit);
    } finally {
        registration.unregister();
    }
}
Also used : ConfigurationListener(org.osgi.service.cm.ConfigurationListener) ConfigurationEvent(org.osgi.service.cm.ConfigurationEvent) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 15 with ConfigurationEvent

use of org.osgi.service.cm.ConfigurationEvent in project feature-flags-for-osgi by amitjoy.

the class FeatureManagerProviderTest method testConfigurationEventUpdated.

@Test
public void testConfigurationEventUpdated() throws Exception {
    final FeatureManagerProvider manager = new FeatureManagerProvider();
    manager.setConfigurationAdmin(configurationAdmin);
    manager.setMetaTypeService(metaTypeService);
    manager.activate(bundleContext1);
    final MetaTypeExtender extender = manager.getExtender();
    final String[] pids = new String[] { "a" };
    final BundleEvent bundleEvent = new BundleEvent(BundleEvent.STARTED, bundle);
    when(metaTypeService.getMetaTypeInformation(bundle)).thenReturn(metaTypeInfo);
    when(metaTypeInfo.getPids()).thenReturn(pids);
    when(metaTypeInfo.getObjectClassDefinition("a", null)).thenReturn(ocd);
    when(ocd.getAttributeDefinitions(ALL)).thenReturn(new AttributeDefinition[] { ad });
    mockADWithoutDefaultValue();
    when(bundleContext1.getBundle(0)).thenReturn(systemBundle);
    when(bundle.getState()).thenReturn(ACTIVE);
    when(bundle.getBundleContext()).thenReturn(bundleContext1);
    extender.addingBundle(bundle, bundleEvent);
    Thread.sleep(1000);
    FeatureDTO feature = manager.getFeatures().collect(Collectors.toList()).get(0);
    assertEquals(FEATURE_ID, feature.id);
    assertEquals(FEATURE_DESC, feature.description);
    assertFalse(feature.isEnabled);
    feature = manager.getFeatures(FEATURE_ID).findFirst().get();
    assertEquals(FEATURE_ID, feature.id);
    assertEquals(FEATURE_DESC, feature.description);
    assertFalse(feature.isEnabled);
    feature = manager.getFeatures(FEATURE_ID).findAny().get();
    assertEquals(FEATURE_DESC, feature.description);
    assertFalse(feature.isEnabled);
    final Map<String, Object> properties = ImmutableMap.<String, Object>builder().put("osgi.feature.myfeature", true).build();
    when(configurationAdmin.getConfiguration("a", "?")).thenReturn(configuration);
    when(configuration.getProperties()).thenReturn(new MapToDictionary(properties));
    final ConfigurationEvent configEvent = new ConfigurationEvent(reference, 1, null, "a");
    manager.configurationEvent(configEvent);
    final FeatureDTO updatedFeature = manager.getFeatures(FEATURE_ID).findAny().get();
    assertTrue(updatedFeature.isEnabled);
}
Also used : ConfigurationEvent(org.osgi.service.cm.ConfigurationEvent) BundleEvent(org.osgi.framework.BundleEvent) MapToDictionary(org.apache.felix.utils.collections.MapToDictionary) FeatureDTO(com.amitinside.featureflags.dto.FeatureDTO) Test(org.junit.Test)

Aggregations

ConfigurationEvent (org.osgi.service.cm.ConfigurationEvent)16 ConfigurationListener (org.osgi.service.cm.ConfigurationListener)8 Test (org.junit.Test)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 Hashtable (java.util.Hashtable)4 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)4 FeatureDTO (com.amitinside.featureflags.dto.FeatureDTO)3 Dictionary (java.util.Dictionary)3 Capture (org.easymock.Capture)3 Bundle (org.osgi.framework.Bundle)3 BundleEvent (org.osgi.framework.BundleEvent)3 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 OutputStream (java.io.OutputStream)2 Configuration (org.osgi.service.cm.Configuration)2 FabricException (io.fabric8.api.FabricException)1 RuntimeProperties (io.fabric8.api.RuntimeProperties)1 BootstrapConfiguration (io.fabric8.zookeeper.bootstrap.BootstrapConfiguration)1 IOException (java.io.IOException)1 Field (java.lang.reflect.Field)1