diff --git a/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/pom.xml b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/pom.xml new file mode 100644 index 0000000000..8777f85603 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/pom.xml @@ -0,0 +1,72 @@ + + + + 4.0.0 + + + org.apache.felix + dependencymanager-parent + 1.0.1-SNAPSHOT + ../pom.xml + + + org.apache.felix.dependencymanager.index.itest.refresh.bundle + bundle + + Apache Felix Dependency Manager FilterIndex refresh test bundle + Internal test bundle used by the Apache Felix Dependency Manager FilterIndex refresh tests + + + + true + true + + + + + org.osgi + osgi.core + 8.0.0 + + + org.apache.felix + org.apache.felix.dependencymanager + 5.0.1-SNAPSHOT + + + + + src + + + org.apache.felix + maven-bundle-plugin + + + test + org.apache.felix.dm.index.itest.refresh.bundle + + org.apache.felix.dm.index.itest.refresh.bundle.Activator + + + + + + diff --git a/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/src/org/apache/felix/dm/index/itest/refresh/bundle/Activator.java b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/src/org/apache/felix/dm/index/itest/refresh/bundle/Activator.java new file mode 100644 index 0000000000..345664deb0 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/src/org/apache/felix/dm/index/itest/refresh/bundle/Activator.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.felix.dm.index.itest.refresh.bundle; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; + +/** + * Creates a component with a service dependency on the Runnable services having the + * "dm.refresh.test" property. The dependency filter only uses objectClass and this property, so it + * goes through the "objectClass,dm.refresh.test" index configured in the test.bndrun of the refresh + * tests (with the "org.apache.felix.dependencymanager.filterindex" property). + * + * The service type comes from the JDK, so that the test bundle doesn't need to import any package + * of this bundle (which is refreshed with the DependencyManager bundle). The property is needed + * because other bundles register Runnable services (the bnd tester registers itself as a Runnable, + * to run the tests). + * + * @author Felix Project Team + */ +public class Activator extends DependencyActivatorBase { + + @Override + public void init(BundleContext context, DependencyManager dm) throws Exception { + dm.add(createComponent() + .setImplementation(RunnableConsumer.class) + .add(createServiceDependency() + .setService(Runnable.class, "(dm.refresh.test=true)") + .setRequired(false) + .setCallbacks("add", "change", null))); + } + +} diff --git a/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/src/org/apache/felix/dm/index/itest/refresh/bundle/RunnableConsumer.java b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/src/org/apache/felix/dm/index/itest/refresh/bundle/RunnableConsumer.java new file mode 100644 index 0000000000..3ee68e6888 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/src/org/apache/felix/dm/index/itest/refresh/bundle/RunnableConsumer.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.felix.dm.index.itest.refresh.bundle; + +/** + * Runs each Runnable service injected by the DependencyManager, and each time the properties of + * such a service are updated: this is how the test sees that the dependency works, and that the + * service events are propagated. + * + * @author Felix Project Team + */ +public class RunnableConsumer { + + void add(Runnable runnable) { + runnable.run(); + } + + void change(Runnable runnable) { + runnable.run(); + } + +} diff --git a/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/pom.xml b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/pom.xml new file mode 100644 index 0000000000..91f568b983 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/pom.xml @@ -0,0 +1,131 @@ + + + + 4.0.0 + + + org.apache.felix + dependencymanager-parent + 1.0.1-SNAPSHOT + ../pom.xml + + + org.apache.felix.dependencymanager.index.itest.refresh.tests + bundle + + Apache Felix Dependency Manager FilterIndex refresh tests + Integration tests for the filter indices of Apache Felix Dependency Manager, when the DependencyManager bundle is refreshed + + + + true + true + + + + + + org.osgi + osgi.core + 8.0.0 + + + junit + junit + provided + + + org.apache.felix + org.apache.felix.dependencymanager + 5.0.1-SNAPSHOT + runtime + + + org.apache.felix + org.apache.felix.dependencymanager.index.itest.refresh.bundle + ${project.version} + runtime + + + org.apache.felix + org.apache.felix.configadmin + ${configadmin.version} + runtime + + + org.apache.felix + org.apache.felix.log + ${log.version} + runtime + + + org.apache.felix + org.apache.felix.metatype + ${metatype.version} + runtime + + + org.apache.felix + org.apache.felix.framework + ${framework.version} + runtime + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.junit + ${servicemix.junit.version} + runtime + + + + + src + + + org.apache.felix + maven-bundle-plugin + + + test + org.apache.felix.dm.index.itest.refresh.tests + + $[classes;CONCRETE;EXTENDS;junit.framework.TestCase] + + + + + biz.aQute.bnd + bnd-testing-maven-plugin + + + ${project.build.directory}/${project.build.finalName}.jar + + + test.bndrun + + + + + + diff --git a/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/src/org/apache/felix/dm/index/itest/refresh/tests/FELIX6874_DependencyManagerRefreshTest.java b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/src/org/apache/felix/dm/index/itest/refresh/tests/FELIX6874_DependencyManagerRefreshTest.java new file mode 100644 index 0000000000..2037acc488 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/src/org/apache/felix/dm/index/itest/refresh/tests/FELIX6874_DependencyManagerRefreshTest.java @@ -0,0 +1,161 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.felix.dm.index.itest.refresh.tests; + +import java.util.Collections; +import java.util.Dictionary; +import java.util.Hashtable; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkEvent; +import org.osgi.framework.FrameworkListener; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceRegistration; +import org.osgi.framework.wiring.BundleWiring; +import org.osgi.framework.wiring.FrameworkWiring; + +import junit.framework.TestCase; + +/** + * Checks that the service registry cache works after a refresh of the DependencyManager bundle. + * + * The cache is kept in static fields of the DependencyManager bundle. A refresh creates a new + * wiring of the bundle, with a new class loader, so these fields start from scratch: the cache is + * created again with the new DependencyManager bundle context, and the bundles which use the + * DependencyManager are refreshed too (stopped and started again), so their components use the new + * cache. + * + * The cache is enabled with an "objectClass,dm.refresh.test" index (see the test.bndrun). The + * refresh test bundle creates a component with a service dependency on the Runnable services having + * the "dm.refresh.test" property, which goes through this index, and runs each Runnable it gets, and + * each time its properties are updated. We check that a Runnable registered before the refresh, then + * one registered after the refresh, are injected, and that the update of their service properties + * is propagated. + * + * This test bundle doesn't import any package of the DependencyManager bundle (or of the refresh + * test bundle), so it is not refreshed with it: it only uses the OSGi and JDK APIs. + * + * @author Felix Project Team + */ +public class FELIX6874_DependencyManagerRefreshTest extends TestCase { + + private final static String DM_BSN = "org.apache.felix.dependencymanager"; + + private final static String REFRESH_BUNDLE_BSN = "org.apache.felix.dependencymanager.index.itest.refresh.bundle"; + + private final static long TIMEOUT = 10000; // ms + + private BundleContext m_context; + + /** The framework errors reported during the test. */ + private final List m_errors = new CopyOnWriteArrayList<>(); + + private final FrameworkListener m_errorListener = event -> { + if (event.getType() == FrameworkEvent.ERROR) { + m_errors.add(event); + } + }; + + @Override + public void setUp() throws Exception { + m_context = FrameworkUtil.getBundle(getClass()).getBundleContext(); + m_context.addFrameworkListener(m_errorListener); + } + + @Override + public void tearDown() throws Exception { + m_context.removeFrameworkListener(m_errorListener); + } + + public void testCacheWorksAfterDependencyManagerRefresh() throws Exception { + Bundle dm = getBundle(DM_BSN); + Bundle refreshBundle = getBundle(REFRESH_BUNDLE_BSN); + assertEquals(Bundle.ACTIVE, dm.getState()); + assertEquals(Bundle.ACTIVE, refreshBundle.getState()); + + // before the refresh + checkRunnableInjected("before the refresh"); + + // refresh the DependencyManager bundle, and wait until the refresh is complete (the refreshed + // bundles have been started again) + BundleWiring dmWiring = dm.adapt(BundleWiring.class); + BundleWiring refreshBundleWiring = refreshBundle.adapt(BundleWiring.class); + CountDownLatch refreshed = new CountDownLatch(1); + FrameworkWiring wiring = m_context.getBundle(0).adapt(FrameworkWiring.class); + wiring.refreshBundles(Collections.singleton(dm), event -> { + if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { + refreshed.countDown(); + } + }); + assertTrue("refresh not complete", refreshed.await(TIMEOUT, TimeUnit.MILLISECONDS)); + + // both bundles have a new wiring (with a new class loader), and have been started again + assertNotSame("DependencyManager bundle not refreshed", dmWiring, dm.adapt(BundleWiring.class)); + assertNotSame("refresh test bundle not refreshed", refreshBundleWiring, refreshBundle.adapt(BundleWiring.class)); + assertNotSame("DependencyManager class loader not recreated", dmWiring.getClassLoader(), + dm.adapt(BundleWiring.class).getClassLoader()); + assertEquals(Bundle.ACTIVE, dm.getState()); + assertEquals(Bundle.ACTIVE, refreshBundle.getState()); + + // after the refresh: the Runnable is registered (then updated) after the refresh, so it is only + // seen if the index receives the service events of the new DependencyManager bundle context + checkRunnableInjected("after the refresh"); + + assertTrue("framework errors: " + m_errors, m_errors.isEmpty()); + } + + /** + * Registers a Runnable, and checks that the component of the refresh test bundle runs it (the + * service is injected), then updates the service properties, and checks that the component + * runs it again (the service event is propagated to the dependency). + */ + private void checkRunnableInjected(String when) throws InterruptedException { + Semaphore runs = new Semaphore(0); + Runnable runnable = runs::release; + Dictionary props = new Hashtable<>(); + props.put("dm.refresh.test", "true"); + ServiceRegistration registration = m_context.registerService(Runnable.class, runnable, props); + try { + assertTrue("Runnable not injected " + when, runs.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)); + + // update the service properties: the dependency must be called back + props.put("version", "2"); + registration.setProperties(props); + assertTrue("service update not propagated " + when, runs.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)); + } finally { + registration.unregister(); + } + } + + private Bundle getBundle(String symbolicName) { + for (Bundle b : m_context.getBundles()) { + if (symbolicName.equals(b.getSymbolicName())) { + return b; + } + } + throw new IllegalStateException("bundle " + symbolicName + " not found"); + } + +} diff --git a/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/test.bndrun b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/test.bndrun new file mode 100644 index 0000000000..e4d4c350fd --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/test.bndrun @@ -0,0 +1,33 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +-runfw: org.apache.felix.framework;version='[8.0.0,9)' +-runee: JavaSE-11 +-runvm: -ea +-runsystempackages: sun.reflect +-runproperties: \ + org.apache.felix.dependencymanager.loglevel=2,\ + org.apache.felix.log.maxSize=100000,\ + org.apache.felix.log.storeDebug=true,\ + org.apache.felix.dependencymanager.filterindex=objectClass,dm.refresh.test +-runrequires: \ + osgi.identity;filter:='(osgi.identity=org.apache.felix.dependencymanager.index.itest.refresh.tests)',\ + osgi.identity;filter:='(osgi.identity=org.apache.felix.dependencymanager.index.itest.refresh.bundle)',\ + osgi.identity;filter:='(osgi.identity=org.apache.felix.dependencymanager)',\ + osgi.identity;filter:='(osgi.identity=org.apache.felix.configadmin)',\ + osgi.identity;filter:='(osgi.identity=org.apache.felix.log)',\ + osgi.identity;filter:='(osgi.identity=org.apache.felix.metatype)',\ + osgi.identity;filter:='(osgi.identity=org.apache.servicemix.bundles.junit)' diff --git a/dependencymanager/org.apache.felix.dependencymanager/pom.xml b/dependencymanager/org.apache.felix.dependencymanager/pom.xml index 2e9a1c9a18..1d63fe14fe 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/pom.xml +++ b/dependencymanager/org.apache.felix.dependencymanager/pom.xml @@ -42,6 +42,13 @@ + + + org.apache.felix + org.apache.felix.framework + ${framework.version} + test + org.osgi osgi.core diff --git a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/DependencyManager.java b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/DependencyManager.java index f2c0435613..d10eb89ab0 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/DependencyManager.java +++ b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/DependencyManager.java @@ -85,7 +85,7 @@ public DependencyManager(BundleContext context) { } DependencyManager(BundleContext context, Logger logger) { - m_context = createContext(context); + m_context = createContext(context, logger); m_logger = logger; synchronized (m_dependencyManagers) { m_dependencyManagers.add(new WeakReference(this)); @@ -310,8 +310,8 @@ public PropertyMetaData createPropertyMetaData() { return new PropertyMetaDataImpl(); } - private BundleContext createContext(BundleContext context) { - ServiceRegistryCache cache = ServiceRegistryCacheManager.getCache(); + private BundleContext createContext(BundleContext context, Logger logger) { + ServiceRegistryCache cache = ServiceRegistryCacheManager.getCache(logger); if (cache != null) { return cache.createBundleContextInterceptor(context); } diff --git a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/Activator.java b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/Activator.java index 8d6ec9a2ac..9784648ae4 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/Activator.java +++ b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/Activator.java @@ -42,21 +42,31 @@ public class Activator implements BundleActivator { @Override public void start(BundleContext context) throws Exception { - // make sure the backdoor is set in system properties (needed by tests) - ServiceRegistryCacheManager.init(); + try { + // create the service registry cache, if configured (and set the backdoor in system + // properties, needed by tests) + ServiceRegistryCacheManager.init(context); - m_context = context; - Filter execFilter = context.createFilter("(objectClass=" + ComponentExecutorFactory.class.getName() + ")"); - m_execTracker = new ServiceTracker<>(context, execFilter, new ExecutorFactoryCustomizer()); - m_execTracker.open(); + m_context = context; + Filter execFilter = context.createFilter("(objectClass=" + ComponentExecutorFactory.class.getName() + ")"); + m_execTracker = new ServiceTracker<>(context, execFilter, new ExecutorFactoryCustomizer()); + m_execTracker.open(); - Filter indexFilter = context.createFilter("(objectClass=" + FilterIndex.class.getName() + ")"); - m_indexTracker = new ServiceTracker<>(context, indexFilter, new FilterIndexCustomizer()); - m_indexTracker.open(); + Filter indexFilter = context.createFilter("(objectClass=" + FilterIndex.class.getName() + ")"); + m_indexTracker = new ServiceTracker<>(context, indexFilter, new FilterIndexCustomizer()); + m_indexTracker.open(); + } finally { + // getCache() may be called by user bundles from now on (it returns null while we are + // starting, on this thread) + ServiceRegistryCacheManager.activated(); + } } @Override public void stop(BundleContext context) throws Exception { + // from now on, user bundles must neither restart us nor use the cache + ServiceRegistryCacheManager.stopped(); + if (m_execTracker != null) { m_execTracker.close(); } diff --git a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/index/ServiceRegistryCacheManager.java b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/index/ServiceRegistryCacheManager.java index 87ca2efa26..37b889883e 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/index/ServiceRegistryCacheManager.java +++ b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/index/ServiceRegistryCacheManager.java @@ -19,10 +19,12 @@ package org.apache.felix.dm.impl.index; import java.lang.reflect.Constructor; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import org.apache.felix.dm.DependencyManager; import org.apache.felix.dm.FilterIndex; +import org.apache.felix.dm.Logger; import org.apache.felix.dm.impl.index.multiproperty.MultiPropertyFilterIndex; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; @@ -50,27 +52,124 @@ public class ServiceRegistryCacheManager { * the DependendencyManager bundle context used by the ServiceRegistryCache. */ private static volatile BundleContext m_context; - + /** - * Boolean used to check if we are already initialized + * True when the DependencyManager bundle has been stopped after having been started + * (deliberately, or because the framework is shutting down). Reset by init() when the bundle is + * started again. */ - private static volatile boolean m_init = false; - + private static volatile boolean m_stopped; + /** - * Static initializer: we create the registry cache in case "org.apache.felix.dependencymanager.filterindex" system property is configured. + * The thread currently running the DependencyManager Activator start method, or null. The + * Activator calls getService on other bundles' services (see its tracker customizers): if a + * service factory creates a DependencyManager, getCache() is called back on this thread while + * the bundle is STARTING, and must not try to start it. */ - static { - init(); - } - + private static volatile Thread m_activatingThread; + /** - * Gets the service registry cache, if enabled. + * Set once a failure to start the DependencyManager bundle has been logged: getCache() is + * called each time a DependencyManager is created, and the failures usually have the same + * cause, so we log only once, even if getCache() is called concurrently. + */ + private static final AtomicBoolean m_startFailureLogged = new AtomicBoolean(); + + /** + * Gets the service registry cache, if enabled. Before returning the cache, we try to make sure + * the DependencyManager bundle is started, because the cache is initialized by the + * DependencyManager bundle Activator. + * + * The cache is only an optimization: this method never throws. If the DependencyManager bundle + * can't be started, null is returned, and the error is logged only once. + * + * If the DependencyManager bundle has been stopped after having been started, we don't restart + * it, and we return null: the cache was opened with the DependencyManager bundle context, which + * is no longer valid, so the cache doesn't receive service events anymore. We read the bundle + * state before m_stopped, so a stop which is in progress (STOPPING) or complete (m_stopped is + * set before the state becomes RESOLVED) is detected. Only a stop which happens between our + * checks and the start of the bundle is not detected: the DependencyManager bundle may then be + * restarted (transiently). + * + * If called back from the DependencyManager Activator thread while the Activator is starting + * (for example from a service factory called by one of the Activator trackers), null is + * returned: the cache is not ready yet, and the bundle is already being started by this thread. + * + * @param logger the logger used to report a failure to start the DependencyManager bundle * @return the service registry cache, if enabled, or null */ - public static ServiceRegistryCache getCache() { + public static ServiceRegistryCache getCache(Logger logger) { + if (Thread.currentThread() == m_activatingThread) { + return null; // re-entrant call from the Activator start method + } + try { + Bundle dm = FrameworkUtil.getBundle(ServiceRegistryCacheManager.class); + if (dm != null) { // null outside OSGi: there's no bundle to start + int state = dm.getState(); // read before m_stopped (see javadoc) + if (state == Bundle.STOPPING || m_stopped) { + return null; // stopped after having been started: don't restart it + } + if (state != Bundle.ACTIVE) { + startDependencyManager(dm); + } + } + } catch (Exception e) { + // we can't start the DependencyManager bundle: never prevent the user bundle from + // starting, just don't use the indices (don't return m_cache: it may be bound to the + // bundle context of a failed or previous activation, which is no longer valid) + if (m_startFailureLogged.compareAndSet(false, true)) { + logger.log(Logger.LOG_ERROR, + "Could not start the DependencyManager bundle, the service registry cache won't be used", e); + } + return null; + } return m_cache; } - + + /** + * Starts the DependencyManager bundle, so that its Activator has initialized the cache when we + * return it. + * + * We first try a transient start, because while the framework is raising its start level, a + * transient start is much more likely to activate the bundle immediately than a persistent + * start (this describes the Felix framework): + *
    + *
  • the framework raises its active start level one level at a time, and its start level + * thread starts the bundles from a queue, in start level order;
  • + *
  • a persistent start called from another thread is queued if the bundle start level is + * greater than or equal to the active start level: it returns without starting the bundle;
  • + *
  • a transient start is never queued: if the bundle start level is lower than or equal to + * the active start level, it activates the bundle immediately (or waits until the thread that + * is already starting it has completed), else it fails with START_TRANSIENT_ERROR.
  • + *
+ * For example, if all bundles have the start level 2, the active start level is 2 during almost + * the whole startup: a transient start activates the DependencyManager bundle immediately, + * whereas a persistent start only queues it, so the cache would not be initialized yet (this + * was the cause of FELIX-6874). + * + * If the transient start fails with START_TRANSIENT_ERROR, we fall back to a persistent start: + * it still activates the bundle immediately if the framework has just begun to raise its start + * level (no bundle is queued yet, and the active start level is still 0). Else, the bundle is + * started later, and our caller does not use the cache. + * + * @param dm the DependencyManager bundle + * @throws BundleException if the DependencyManager bundle can't be started + */ + private static void startDependencyManager(Bundle dm) throws BundleException { + try { + dm.start(Bundle.START_TRANSIENT); + } catch (BundleException e) { + if (dm.getState() == Bundle.ACTIVE) { + return; // started meanwhile by another thread + } + if (e.getType() != BundleException.START_TRANSIENT_ERROR) { + throw e; + } + // start level not met yet: fall back to a persistent start (see javadoc) + dm.start(); + } + } + /** * Registers a FilterIndex into the service registry cache. The cache is created if necessary. * @param index a new FilterIndex to be registered in the cache @@ -86,7 +185,7 @@ public static void registerFilterIndex(FilterIndex index, BundleContext context) * @param index the FilterIndex to unregister */ public static void unregisterFilterIndex(FilterIndex index) { - ServiceRegistryCache cache = ServiceRegistryCacheManager.getCache(); + ServiceRegistryCache cache = m_cache; if (cache != null) { cache.removeFilterIndex(index); boolean close = false; @@ -124,33 +223,42 @@ private static ServiceRegistryCache createCache(BundleContext context) { } /** - * Initialize the service registry cache. + * Initialize the service registry cache. Called by the DependencyManager Activator, with the + * DependencyManager bundle context (the framework serializes the Activator start, so we don't + * need to synchronize). Initialization is only done once, even if the DependencyManager bundle + * is restarted (except m_stopped, which is reset at each start). + * @param context the DependencyManager bundle context */ - public static void init() { - try { - if (m_init) { - return; - } - Bundle bundle = FrameworkUtil.getBundle(ServiceRegistryCacheManager.class); - if (bundle != null) { - if (bundle.getState() != Bundle.STARTING && bundle.getState() != Bundle.ACTIVE) { - bundle.start(); // take care: may callback our registerFilterIndex method - } - m_context = bundle.getBundleContext(); - String index = m_context.getProperty(DependencyManager.SERVICEREGISTRY_CACHE_INDICES); - if (index != null) { - resetIndices(index); - } - } - Consumer reset = ServiceRegistryCacheManager::reset; - System.getProperties().put(RESET, reset); - m_init = true; + public static void init(BundleContext context) { + m_activatingThread = Thread.currentThread(); // cleared by activated() + m_stopped = false; + if (m_context != null) { + return; + } + m_context = context; + String index = m_context.getProperty(DependencyManager.SERVICEREGISTRY_CACHE_INDICES); + if (index != null) { + resetIndices(index); } + Consumer reset = ServiceRegistryCacheManager::reset; + System.getProperties().put(RESET, reset); + } + + /** + * Called by the DependencyManager Activator when its start method has completed (successfully + * or not): getCache() is no longer re-entrant for the Activator thread. + */ + public static void activated() { + m_activatingThread = null; + } - catch (BundleException e) { - // if we cannot start ourselves, we cannot use the indices - e.printStackTrace(); - } + /** + * Called by the DependencyManager Activator when the DependencyManager bundle is stopped: from + * now on, getCache() neither restarts the DependencyManager bundle nor returns the cache, until + * the bundle is started again. + */ + public static void stopped() { + m_stopped = true; } private static void resetIndices(String index) { diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java new file mode 100644 index 0000000000..67d2077336 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java @@ -0,0 +1,473 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.stream.Stream; + +import org.apache.felix.dm.DependencyManager; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.framework.FrameworkEvent; +import org.osgi.framework.launch.Framework; +import org.osgi.framework.launch.FrameworkFactory; +import org.osgi.framework.startlevel.BundleStartLevel; +import org.osgi.framework.startlevel.FrameworkStartLevel; + +import test.felix6874.ReentrantActivator; +import test.felix6874.UserActivator; + +/** + * FELIX-6874: user bundles started in parallel with the DependencyManager bundle, like the + * AutoProcessor of Felix PR #236 does: a pool of 8 threads calls start() once on every bundle, + * while the framework starts. + * + * All bundles use the default start level (1). If a pool thread starts a user bundle before the DM + * bundle is started, the service registry cache initialization must not fail (in DM 5.0.0, + * ServiceRegistryCacheManager. throws a NullPointerException, and the class becomes + * unusable). + * + * This is a race: the scenario is run again with a new embedded Felix framework, at most + * "felix6874.runs" times (system property, default 20; use a higher value, e.g. -Dfelix6874.runs=200, for stress runs). + * + * This class also checks that a DependencyManager bundle stopped by a management agent is not + * restarted by the user bundles started afterwards, that a re-entrant call to the service + * registry cache from the DependencyManager Activator thread is harmless, and that the + * DependencyManager bundle is still started when its transient start fails with + * START_TRANSIENT_ERROR. + */ +public class FELIX6874_ParallelStartTest { + + private static final int RUNS = Integer.getInteger("felix6874.runs", 20); + private static final int USER_BUNDLES = 100; + + @Rule + public TemporaryFolder m_tmp = new TemporaryFolder(); + + @Test + public void testUserBundlesStartedInParallelWithDependencyManager() throws Exception { + test(null); + } + + @Test + public void testUserBundlesStartedInParallelWithDependencyManagerAndFilterIndex() throws Exception { + test("objectClass,user.bundle"); + } + + /** + * A DependencyManager bundle stopped by a management agent must not be restarted by a user + * bundle creating a DependencyManager, and this user bundle must not use the service registry + * cache of the stopped DependencyManager bundle. The management agent can still restart the + * DependencyManager bundle. + */ + @Test + public void testStoppedDependencyManagerIsNotRestartedByUserBundles() throws Exception { + File dmJar = createDependencyManagerBundle(m_tmp.newFile("dependencymanager.jar")); + File userJar = createUserBundle(m_tmp.newFile("user-bundle.jar")); + + Map config = new HashMap<>(); + config.put(DependencyManager.SERVICEREGISTRY_CACHE_INDICES, "objectClass,user.bundle"); + config.put(Constants.FRAMEWORK_STORAGE, m_tmp.newFolder("felix-cache").getAbsolutePath()); + config.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); + config.put(Constants.FRAMEWORK_BSNVERSION, Constants.FRAMEWORK_BSNVERSION_MULTIPLE); + config.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.service.cm,org.osgi.service.metatype"); + Framework framework = ServiceLoader.load(FrameworkFactory.class).iterator().next().newFramework(config); + framework.start(); + try { + BundleContext context = framework.getBundleContext(); + Bundle dm = install(context, dmJar, "dependencymanager"); + Bundle user1 = install(context, userJar, "user-bundle-1"); + Bundle user2 = install(context, userJar, "user-bundle-2"); + + dm.start(); + user1.start(); + Assert.assertTrue("user bundle 1 must use the service registry cache", cacheUsed(user1)); + + dm.stop(); // like a management agent + user2.start(); // creates a DependencyManager + Assert.assertEquals("user bundle 2 not active", Bundle.ACTIVE, user2.getState()); + Assert.assertEquals("the stopped DependencyManager bundle has been restarted", Bundle.RESOLVED, dm.getState()); + Assert.assertFalse("user bundle 2 must not use the cache of the stopped DependencyManager bundle", cacheUsed(user2)); + + dm.start(); // the management agent can still restart it + Assert.assertEquals("the DependencyManager bundle can't be restarted", Bundle.ACTIVE, dm.getState()); + } finally { + framework.stop(); + framework.waitForStop(30000); + } + } + + /** + * The DependencyManager Activator calls getService() on other bundles' services when it starts: + * a ServiceFactory may then create a DependencyManager on the Activator thread, while the + * DependencyManager bundle is STARTING. This re-entrant call to the service registry cache must + * neither try to start the DependencyManager bundle (which fails, since it is already being + * started by this thread), nor log a start failure; the DependencyManager just doesn't use the + * cache. Once the Activator has completed, the cache is used again, even on the same thread. + */ + @Test + public void testReentrantCallFromDependencyManagerActivator() throws Exception { + File dmJar = createDependencyManagerBundle(m_tmp.newFile("dependencymanager.jar")); + File factoryJar = createUserBundle(m_tmp.newFile("factory-bundle.jar"), ReentrantActivator.class); + File userJar = createUserBundle(m_tmp.newFile("user-bundle.jar")); + + Map config = new HashMap<>(); + config.put(DependencyManager.SERVICEREGISTRY_CACHE_INDICES, "objectClass,user.bundle"); + config.put(Constants.FRAMEWORK_STORAGE, m_tmp.newFolder("felix-cache").getAbsolutePath()); + config.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); + config.put(Constants.FRAMEWORK_BSNVERSION, Constants.FRAMEWORK_BSNVERSION_MULTIPLE); + config.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.service.cm,org.osgi.service.metatype"); + Framework framework = ServiceLoader.load(FrameworkFactory.class).iterator().next().newFramework(config); + framework.start(); + try { + BundleContext context = framework.getBundleContext(); + Bundle dm = install(context, dmJar, "dependencymanager"); + Bundle factory = install(context, factoryJar, "factory-bundle"); + Bundle user = install(context, userJar, "user-bundle"); + + factory.start(); // registers its ServiceFactory, nothing calls it yet + dm.start(); // the Activator gets the ServiceFactory service, on this thread + + Class activator = factory.loadClass(ReentrantActivator.class.getName()); + Assert.assertEquals("the ServiceFactory has not been called by the DependencyManager Activator", + true, activator.getField("s_called").get(null)); + Assert.assertEquals("the ServiceFactory must be called while the DependencyManager bundle is starting", + Bundle.STARTING, activator.getField("s_dmState").get(null)); + Assert.assertNull("the ServiceFactory could not create its DependencyManager", + activator.getField("s_failure").get(null)); + Assert.assertEquals("the DependencyManager created during the Activator start must not use the cache", + false, activator.getField("s_cacheUsed").get(null)); + Assert.assertEquals("DependencyManager bundle not active", Bundle.ACTIVE, dm.getState()); + Assert.assertFalse("a failure to start the DependencyManager bundle has been logged", startFailureLogged(dm)); + + user.start(); // same thread as the DependencyManager activation, which has completed + Assert.assertTrue("the user bundle must use the service registry cache", cacheUsed(user)); + } finally { + framework.stop(); + framework.waitForStop(30000); + } + } + + /** + * START_TRANSIENT_ERROR fallback. While the framework raises its start level, the start level + * thread sets the target start level before queuing the bundles to start: in between, a + * persistent start called from another thread activates the bundle immediately, although the + * active start level is still lower than the bundle start level. The DependencyManager created + * by the user bundle then fails to start the DependencyManager bundle (same start level as the + * user bundle) with a transient start (START_TRANSIENT_ERROR), and the persistent start + * fallback must activate it immediately, so that the user bundle uses the cache. + * + * To open this window deterministically, the test thread holds the Felix global lock (internal + * API, called by reflection) while the framework raises its start level from 1 to 2: the start + * level thread sets its target start level, then waits for the global lock before queuing the + * bundles, while the test thread, which owns the global lock, can still start bundles. + */ + @Test + public void testTransientStartFailureFallsBackToPersistentStart() throws Exception { + File dmJar = createDependencyManagerBundle(m_tmp.newFile("dependencymanager.jar")); + File userJar = createUserBundle(m_tmp.newFile("user-bundle.jar")); + + Map config = new HashMap<>(); + config.put(DependencyManager.SERVICEREGISTRY_CACHE_INDICES, "objectClass,user.bundle"); + config.put(Constants.FRAMEWORK_STORAGE, m_tmp.newFolder("felix-cache").getAbsolutePath()); + config.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); + config.put(Constants.FRAMEWORK_BSNVERSION, Constants.FRAMEWORK_BSNVERSION_MULTIPLE); + config.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.service.cm,org.osgi.service.metatype"); + config.put(Constants.FRAMEWORK_BEGINNING_STARTLEVEL, "1"); + Framework framework = ServiceLoader.load(FrameworkFactory.class).iterator().next().newFramework(config); + framework.start(); + try { + BundleContext context = framework.getBundleContext(); + FrameworkStartLevel frameworkStartLevel = framework.adapt(FrameworkStartLevel.class); + // same start level for the DependencyManager bundle and the user bundle + frameworkStartLevel.setInitialBundleStartLevel(2); + Bundle dm = install(context, dmJar, "dependencymanager"); + Bundle user = install(context, userJar, "user-bundle"); + + Method acquireGlobalLock = framework.getClass().getDeclaredMethod("acquireGlobalLock"); + Method releaseGlobalLock = framework.getClass().getDeclaredMethod("releaseGlobalLock"); + Field targetStartLevel = framework.getClass().getDeclaredField("m_targetStartLevel"); + acquireGlobalLock.setAccessible(true); + releaseGlobalLock.setAccessible(true); + targetStartLevel.setAccessible(true); + + CountDownLatch startLevelChanged = new CountDownLatch(1); + Assert.assertTrue("could not acquire the framework global lock", (Boolean) acquireGlobalLock.invoke(framework)); + try { + frameworkStartLevel.setStartLevel(2, event -> startLevelChanged.countDown()); + long deadline = System.currentTimeMillis() + 30000; + while (targetStartLevel.getInt(framework) != 2) { + if (System.currentTimeMillis() > deadline) { + Assert.fail("the start level thread did not set its target start level"); + } + Thread.sleep(10); + } + Assert.assertEquals("the active start level must still be 1", 1, frameworkStartLevel.getStartLevel()); + + user.start(); // activated immediately, on this thread + } finally { + releaseGlobalLock.invoke(framework); + } + + Assert.assertEquals("user bundle not active", Bundle.ACTIVE, user.getState()); + Assert.assertEquals("DependencyManager bundle not active", Bundle.ACTIVE, dm.getState()); + // a transient start doesn't mark the bundle as persistently started + Assert.assertTrue("the DependencyManager bundle has not been started by the persistent start fallback", + dm.adapt(BundleStartLevel.class).isPersistentlyStarted()); + Assert.assertTrue("the user bundle must use the service registry cache", cacheUsed(user)); + Assert.assertFalse("a failure to start the DependencyManager bundle has been logged", startFailureLogged(dm)); + Assert.assertTrue("the framework start level has not been raised", startLevelChanged.await(30, TimeUnit.SECONDS)); + } finally { + framework.stop(); + framework.waitForStop(30000); + } + } + + /** + * Returns true if ServiceRegistryCacheManager has logged a failure to start the + * DependencyManager bundle. + */ + private static boolean startFailureLogged(Bundle dm) throws Exception { + Field field = dm.loadClass("org.apache.felix.dm.impl.index.ServiceRegistryCacheManager").getDeclaredField("m_startFailureLogged"); + field.setAccessible(true); + return ((AtomicBoolean) field.get(null)).get(); + } + + /** + * Returns true if the DependencyManager of the given user bundle uses the service registry + * cache. + */ + private static boolean cacheUsed(Bundle userBundle) throws Exception { + return (Boolean) userBundle.loadClass(UserActivator.class.getName()).getField("s_cacheUsed").get(null); + } + + /** + * Runs the scenario RUNS times. + * @param indices the filter indices (org.apache.felix.dependencymanager.filterindex property), + * or null for no service registry cache + */ + private void test(String indices) throws Exception { + File dmJar = createDependencyManagerBundle(m_tmp.newFile("dependencymanager.jar")); + File userJar = createUserBundle(m_tmp.newFile("user-bundle.jar")); + File storage = m_tmp.newFolder("felix-cache"); + + for (int run = 1; run <= RUNS; run++) { + Throwable failure = runOnce(run, dmJar, userJar, storage, indices); + if (failure != null) { + Assert.fail("FELIX-6874 reproduced (run " + run + "):\n" + toString(failure)); + } + } + } + + /** + * Starts a new framework once. Returns the FELIX-6874 exception thrown by a bundle start, or + * null. + */ + private Throwable runOnce(int run, File dmJar, File userJar, File storage, String indices) throws Exception { + Map config = new HashMap<>(); + if (indices != null) { + config.put(DependencyManager.SERVICEREGISTRY_CACHE_INDICES, indices); + // the user bundles add components using the filter index (without index, keep the user + // activators as light as possible, the race is easier to reproduce) + config.put(UserActivator.COMPONENTS, "true"); + } + config.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath()); + config.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); + // allow several copies of the user bundle (same symbolic name and version) + config.put(Constants.FRAMEWORK_BSNVERSION, Constants.FRAMEWORK_BSNVERSION_MULTIPLE); + // packages imported by DM, provided by the test classpath (osgi.cmpn) + config.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.service.cm,org.osgi.service.metatype"); + // errors are collected by the framework listener below + config.put("felix.log.level", "0"); + Framework framework = ServiceLoader.load(FrameworkFactory.class).iterator().next().newFramework(config); + AtomicReference failure = new AtomicReference<>(); + ExecutorService pool = null; + FrameworkEvent stopped; + try { + framework.init(); + BundleContext context = framework.getBundleContext(); + + // the bundles started by the FelixStartLevel thread report their start errors as + // framework events + context.addFrameworkListener(event -> { + if (event.getType() == FrameworkEvent.ERROR && event.getThrowable() != null) { + record(failure, event.getThrowable()); + } + }); + + List bundles = new ArrayList<>(); + for (int i = 1; i <= USER_BUNDLES; i++) { + bundles.add(install(context, userJar, "user-bundle-" + i)); + } + bundles.add(install(context, dmJar, "dependencymanager")); + + // AutoProcessor of PR #236: a pool of 8 threads starts the bundles, the launcher does + // not wait. + pool = Executors.newFixedThreadPool(8); + for (Bundle bundle : bundles) { + pool.execute(() -> { + try { + bundle.start(); + } catch (Throwable e) { + record(failure, e); // other start errors are ignored, like PR #236 does + } + }); + } + pool.shutdown(); + + framework.start(); + + if (!pool.awaitTermination(30, TimeUnit.SECONDS)) { + Assert.fail("run " + run + ": the bundle starts did not complete"); + } + if (failure.get() == null) { + // make sure the scenario really ran: all bundles must be started + for (Bundle bundle : bundles) { + Assert.assertEquals("run " + run + ": bundle " + bundle.getLocation() + " not active", + Bundle.ACTIVE, bundle.getState()); + } + // each user bundle must use the service registry cache (if enabled), and its client + // component must be started + for (Bundle bundle : bundles.subList(0, USER_BUNDLES)) { + Class activator = bundle.loadClass(UserActivator.class.getName()); + Assert.assertEquals("run " + run + ": bundle " + bundle.getLocation() + ": service registry cache usage", + indices != null, activator.getField("s_cacheUsed").get(null)); + if (indices != null) { + Assert.assertEquals("run " + run + ": bundle " + bundle.getLocation() + ": client component not started", + true, activator.getField("s_clientStarted").get(null)); + } + } + } + } finally { + if (pool != null) { + pool.shutdownNow(); + } + framework.stop(); + stopped = framework.waitForStop(30000); + } + // checked after the finally block, so that it does not hide an exception thrown by the try + // block + Assert.assertNotEquals("run " + run + ": the framework did not stop", FrameworkEvent.WAIT_TIMEDOUT, stopped.getType()); + return failure.get(); + } + + private static void record(AtomicReference failure, Throwable e) { + if (toString(e).contains("ServiceRegistryCacheManager")) { + failure.compareAndSet(null, e); + } + } + + private static Bundle install(BundleContext context, File jar, String location) throws Exception { + try (FileInputStream in = new FileInputStream(jar)) { + return context.installBundle(location, in); + } + } + + /** Creates the DependencyManager bundle from the compiled classes of this module. */ + private static File createDependencyManagerBundle(File jar) throws Exception { + Manifest manifest = new Manifest(); + Attributes attrs = manifest.getMainAttributes(); + attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); + attrs.putValue(Constants.BUNDLE_MANIFESTVERSION, "2"); + attrs.putValue(Constants.BUNDLE_SYMBOLICNAME, "org.apache.felix.dependencymanager"); + attrs.putValue(Constants.BUNDLE_ACTIVATOR, "org.apache.felix.dm.impl.Activator"); + attrs.putValue(Constants.EXPORT_PACKAGE, "org.apache.felix.dm,org.apache.felix.dm.compat,org.apache.felix.dm.context," + + "org.apache.felix.dm.diagnostics,org.apache.felix.dm.tracker"); + attrs.putValue(Constants.IMPORT_PACKAGE, "org.osgi.framework,org.osgi.util.tracker,org.osgi.service.cm,org.osgi.service.metatype"); + Path classes = classesDir(DependencyManager.class); + return createBundle(jar, manifest, classes, classes.resolve("org/apache/felix/dm")); + } + + /** Creates a user bundle, with the UserActivator class as activator. */ + private static File createUserBundle(File jar) throws Exception { + return createUserBundle(jar, UserActivator.class); + } + + /** + * Creates a user bundle, which contains the classes of the test.felix6874 package, with the + * given activator. + */ + private static File createUserBundle(File jar, Class activator) throws Exception { + Manifest manifest = new Manifest(); + Attributes attrs = manifest.getMainAttributes(); + attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); + attrs.putValue(Constants.BUNDLE_MANIFESTVERSION, "2"); + attrs.putValue(Constants.BUNDLE_SYMBOLICNAME, "felix6874.user"); + attrs.putValue(Constants.BUNDLE_ACTIVATOR, activator.getName()); + attrs.putValue(Constants.IMPORT_PACKAGE, "org.apache.felix.dm,org.osgi.framework"); + Path classes = classesDir(UserActivator.class); + return createBundle(jar, manifest, classes, classes.resolve("test/felix6874")); + } + + /** + * Returns the classes directory (target/classes or target/test-classes) containing the given + * class. + */ + private static Path classesDir(Class clazz) throws Exception { + return new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI()).toPath(); + } + + /** Creates a jar with the given manifest, and all the files found under root/dir. */ + private static File createBundle(File jar, Manifest manifest, Path root, Path dir) throws IOException { + try (JarOutputStream out = new JarOutputStream(new FileOutputStream(jar), manifest); + Stream files = Files.walk(dir)) { + for (Path file : (Iterable) files.filter(Files::isRegularFile)::iterator) { + out.putNextEntry(new JarEntry(root.relativize(file).toString().replace(File.separatorChar, '/'))); + Files.copy(file, out); + out.closeEntry(); + } + } + return jar; + } + + private static String toString(Throwable e) { + StringWriter out = new StringWriter(); + e.printStackTrace(new PrintWriter(out)); + return out.toString(); + } +} diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/ReentrantActivator.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/ReentrantActivator.java new file mode 100644 index 0000000000..ad4ada15ff --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/ReentrantActivator.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package test.felix6874; + +import org.apache.felix.dm.ComponentExecutorFactory; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceFactory; +import org.osgi.framework.ServiceRegistration; + +/** + * Activator of the bundle generated by FELIX6874_ParallelStartTest to test a re-entrant call to the + * service registry cache: it registers a ComponentExecutorFactory as a ServiceFactory, whose + * getService() method creates a DependencyManager. + * + * When the DependencyManager bundle is started afterwards, its Activator tracks the + * ComponentExecutorFactory services and calls getService() from its start method: our getService() + * is then called on the Activator thread, while the DependencyManager bundle is STARTING, and the + * DependencyManager it creates calls back the service registry cache. + * + * Each bundle has its own copy of this class (own class loader): the test reads the static fields + * below using Bundle.loadClass(). + */ +public class ReentrantActivator implements BundleActivator { + + /** true once our ServiceFactory has created its DependencyManager */ + public static volatile boolean s_called; + + /** the state of the DependencyManager bundle when our ServiceFactory has been called */ + public static volatile int s_dmState; + + /** + * true if the DependencyManager created by our ServiceFactory uses the service registry cache + */ + public static volatile boolean s_cacheUsed; + + /** the exception thrown when our ServiceFactory has created its DependencyManager, or null */ + public static volatile Throwable s_failure; + + @Override + public void start(BundleContext context) throws Exception { + context.registerService(ComponentExecutorFactory.class.getName(), new ServiceFactory() { + @Override + public Object getService(Bundle bundle, ServiceRegistration registration) { + try { + // bundle is the DependencyManager bundle, which gets the service + s_dmState = bundle.getState(); + DependencyManager manager = new DependencyManager(context); + s_cacheUsed = manager.getBundleContext() != context; + } catch (Throwable e) { + s_failure = e; + } + s_called = true; + // no executor: components are handled as usual + ComponentExecutorFactory factory = component -> null; + return factory; + } + + @Override + public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) { + } + }, null); + } + + @Override + public void stop(BundleContext context) throws Exception { + } +} diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/UserActivator.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/UserActivator.java new file mode 100644 index 0000000000..72e01819da --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/UserActivator.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package test.felix6874; + +import java.util.Hashtable; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; + +/** + * Activator of the user bundles generated by FELIX6874_ParallelStartTest. + * DependencyActivatorBase.start() creates a DependencyManager, which initializes the service + * registry cache. + * + * If the "felix6874.components" framework property is "true", the activator registers a Runnable + * service with a "user.bundle" property, and a client component depending on it with a + * "(user.bundle=)" filter, which is served by the "objectClass,user.bundle" filter index + * (when enabled). Else, it only creates its DependencyManager. + * + * Each user bundle has its own copy of this class (own class loader): the test reads the static + * fields below using Bundle.loadClass(). + */ +public class UserActivator extends DependencyActivatorBase { + + /** framework property: "true" if the activator must add its components */ + public static final String COMPONENTS = "felix6874.components"; + + /** + * true if our DependencyManager uses the service registry cache (its bundle context is an + * interceptor) + */ + public static volatile boolean s_cacheUsed; + + /** + * true if the client component has been started, meaning its service dependency has been + * injected + */ + public static volatile boolean s_clientStarted; + + @Override + public void init(BundleContext context, DependencyManager manager) throws Exception { + s_cacheUsed = manager.getBundleContext() != context; + if (!Boolean.parseBoolean(context.getProperty(COMPONENTS))) { + return; + } + + long id = context.getBundle().getBundleId(); + Hashtable props = new Hashtable<>(); + props.put("user.bundle", id); + Runnable service = () -> {}; + manager.add(createComponent() + .setInterface(Runnable.class.getName(), props) + .setImplementation(service)); + + manager.add(createComponent() + .setImplementation(new Client()) + .add(createServiceDependency().setService(Runnable.class, "(user.bundle=" + id + ")").setRequired(true))); + } + + public static class Client { + volatile Runnable m_service; // injected + + void start() { + s_clientStarted = m_service != null; + } + } +} diff --git a/dependencymanager/pom.xml b/dependencymanager/pom.xml index 11ce9f12cd..1a22927f56 100644 --- a/dependencymanager/pom.xml +++ b/dependencymanager/pom.xml @@ -54,6 +54,8 @@ org.apache.felix.dependencymanager.index.itest.dynamic.customindex org.apache.felix.dependencymanager.index.itest.static.customindex org.apache.felix.dependencymanager.index.itest.tests + org.apache.felix.dependencymanager.index.itest.refresh.bundle + org.apache.felix.dependencymanager.index.itest.refresh.tests org.apache.felix.dependencymanager.lambda.itest.lifecycle org.apache.felix.dependencymanager.lambda.itest.tests org.apache.felix.dependencymanager.runtime.itest