From 53ba1621a5913dcd8d40dd3292c8fb1b6f3af9c3 Mon Sep 17 00:00:00 2001 From: Pierre De Rop Date: Sun, 22 Nov 2026 18:56:57 -0600 Subject: [PATCH 1/6] FELIX-6874: Fix DM ServiceRegistryCacheManager initialization when bundles are started in parallel Motivation: ServiceRegistryCacheManager initialized itself from a static initializer, which called start() on the DM bundle in order to get its BundleContext. When a user bundle is started before the DM bundle, the framework may not start the DM bundle synchronously, so getBundleContext() returned null. The static initializer then failed with a NullPointerException, and ServiceRegistryCacheManager became unusable for every DM bundle (NoClassDefFoundError: Could not initialize class ...). This can happen when threads that start bundles in parallel are launched while the framework is still starting and raising its start levels: a user bundle may then be started before the DM bundle, which is still waiting to be started by the framework start level thread. Until now, DM in parallel mode has only been tested after the FrameworkStarted event, once the framework is fully started and all the start levels are reached. This is why the problem was never seen. Modification: The cache is now initialized by the DM bundle Activator, using its own BundleContext, and the static initializer is removed: - Activator.start() calls ServiceRegistryCacheManager.init(context), which creates the configured filter indices once. The framework serializes the Activator start, so no extra locking is needed. - DependencyManager now calls getCache(), which locates the DM bundle with FrameworkUtil and starts it transiently if it is not active. If another thread is already starting the DM bundle, the framework blocks the caller until the DM Activator has completed, so the cache is ready when the DependencyManager is created. - While the framework is raising its start level, it may refuse a transient start because the DM bundle start level is not met yet. In this case, the DM bundle is started with a persistent start, which lets the framework start it now if it can, else later (the caller then does not use the cache). The service registry cache is only an optimization: getCache never throws. If the DM bundle cannot be started, the error is reported and the DependencyManager is created without cache, so that bundles can still start. A new unit test, FELIX6874_ParallelStartTest, starts 100 user bundles and the DM bundle from a pool of threads, on an embedded Felix framework, with and without a filter index. The Felix framework is added as a test dependency for it. Result: Starting bundles in parallel no longer breaks ServiceRegistryCacheManager. The new test fails with the previous code and passes with this fix. Ref #236 Co-Authored-By: Claude Sonnet 5.5 --- .../pom.xml | 7 + .../org/apache/felix/dm/impl/Activator.java | 4 +- .../index/ServiceRegistryCacheManager.java | 115 +++++--- .../test/FELIX6874_ParallelStartTest.java | 252 ++++++++++++++++++ .../test/test/felix6874/UserActivator.java | 76 ++++++ 5 files changed, 411 insertions(+), 43 deletions(-) create mode 100644 dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java create mode 100644 dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/UserActivator.java 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/impl/Activator.java b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/Activator.java index 8d6ec9a2ac..96164e7fc0 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,8 +42,8 @@ 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(); + // 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() + ")"); 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..036a160169 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 @@ -50,27 +50,71 @@ 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 - */ - private static volatile boolean m_init = false; - - /** - * Static initializer: we create the registry cache in case "org.apache.felix.dependencymanager.filterindex" system property is configured. - */ - static { - init(); - } - + /** - * Gets the service registry cache, if enabled. + * 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, and if the DependencyManager bundle can't be started, + * the error is reported and the cache (possibly null) is returned. + * + * Never call this method from the DependencyManager Activator. + * * @return the service registry cache, if enabled, or null */ public static ServiceRegistryCache getCache() { + try { + Bundle dm = FrameworkUtil.getBundle(ServiceRegistryCacheManager.class); + if (dm != null && dm.getState() != 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 + e.printStackTrace(); + } 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 +130,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 +168,22 @@ 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. + * @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) { + if (m_context != null) { + return; } - - catch (BundleException e) { - // if we cannot start ourselves, we cannot use the indices - e.printStackTrace(); - } + 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); } 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..7c3dc2ef45 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java @@ -0,0 +1,252 @@ +/* + * 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.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.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +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 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 200). + */ +public class FELIX6874_ParallelStartTest { + + private static final int RUNS = Integer.getInteger("felix6874.runs", 200); + 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"); + } + + /** + * 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, which only contains the UserActivator class. */ + private static File createUserBundle(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, "felix6874.user"); + attrs.putValue(Constants.BUNDLE_ACTIVATOR, UserActivator.class.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/UserActivator.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/UserActivator.java new file mode 100644 index 0000000000..7f218631a1 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/UserActivator.java @@ -0,0 +1,76 @@ +/* + * 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; + } + } +} From b9f7be47441392f399e20bbf37b081c83a01dbcd Mon Sep 17 00:00:00 2001 From: Pierre De Rop Date: Tue, 24 Nov 2026 21:43:05 -0600 Subject: [PATCH 2/6] FELIX-6874: Don't restart a stopped DM bundle, and log a start failure only once Motivation: ServiceRegistryCacheManager.getCache() starts the DM bundle each time a DependencyManager is created, if the DM bundle is not active (PR review): - a DM bundle deliberately stopped was restarted by any user bundle; and the cache, opened with the bundle context of the stopped DM bundle, no longer receives service events; - a failure to start the DM bundle printed a stack trace for each user bundle. Modification: - The DM Activator stop() calls ServiceRegistryCacheManager.stopped(), which sets a volatile flag, reset by init() at the next start. When the flag is set, or the DM bundle is STOPPING, getCache() returns null without starting the DM bundle. The bundle state is read before the flag, so that a concurrent stop is detected (see javadoc). - The start failure is logged once (AtomicBoolean, getCache() may be called concurrently), at ERROR level with the DependencyManager Logger, and getCache() then returns null instead of a cache which may be bound to an invalid bundle context. The Logger is passed to getCache(). - The start is still attempted for each DependencyManager, not only once: when user bundles are started in parallel, each of them must call start() to wait for the DM activation in progress, so that it gets the cache. - A new test in FELIX6874_ParallelStartTest stops the DM bundle, then starts a user bundle: the DM bundle must stay RESOLVED, the user bundle must not use the cache, and the DM bundle can still be restarted. Known limitation (not changed here): restarting the DM bundle without refreshing it, with the cache enabled, leaves the cache bound to the bundle context of the previous activation. --- .../apache/felix/dm/DependencyManager.java | 6 +- .../org/apache/felix/dm/impl/Activator.java | 3 + .../index/ServiceRegistryCacheManager.java | 58 ++++++++++++++++--- .../test/FELIX6874_ParallelStartTest.java | 50 ++++++++++++++++ 4 files changed, 107 insertions(+), 10 deletions(-) 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 96164e7fc0..5719106fb0 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 @@ -57,6 +57,9 @@ public void start(BundleContext context) throws Exception { @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 036a160169..6d5e15409a 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; @@ -51,26 +53,58 @@ public class ServiceRegistryCacheManager { */ private static volatile BundleContext m_context; + /** + * 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_stopped; + + /** + * 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, and if the DependencyManager bundle can't be started, - * the error is reported and the cache (possibly null) is returned. + * 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). * * Never call this method from the DependencyManager Activator. * + * @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) { try { Bundle dm = FrameworkUtil.getBundle(ServiceRegistryCacheManager.class); - if (dm != null && dm.getState() != Bundle.ACTIVE) { - startDependencyManager(dm); + 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 - e.printStackTrace(); + // (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; } @@ -170,10 +204,12 @@ private static ServiceRegistryCache createCache(BundleContext context) { /** * 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. + * 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(BundleContext context) { + m_stopped = false; if (m_context != null) { return; } @@ -186,6 +222,14 @@ public static void init(BundleContext context) { System.getProperties().put(RESET, reset); } + /** + * 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) { try { if (index != null) { diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java index 7c3dc2ef45..464130cf85 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java @@ -65,6 +65,9 @@ * * This is a race: the scenario is run again with a new embedded Felix framework, at most "felix6874.runs" times * (system property, default 200). + * + * This class also checks that a DependencyManager bundle stopped by a management agent is not restarted by the user + * bundles started afterwards. */ public class FELIX6874_ParallelStartTest { @@ -84,6 +87,53 @@ public void testUserBundlesStartedInParallelWithDependencyManagerAndFilterIndex( 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); + } + } + + /** 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 From 36694257994c577f11937a60f5c8032e01dcf92b Mon Sep 17 00:00:00 2001 From: Pierre De Rop Date: Wed, 25 Nov 2026 09:17:55 -0600 Subject: [PATCH 3/6] FELIX-6874: Guard re-entrant getCache() calls from the DM Activator thread Motivation: The DM Activator start() opens two ServiceTrackers, whose customizers call getService() on other bundles' services (PR review). If such a service is a ServiceFactory creating a DependencyManager, getCache() is called back on the Activator thread, while the DM bundle is STARTING. This was only documented ("Never call this method from the DependencyManager Activator"): - getCache() saw a bundle which is not ACTIVE, and started it: Felix rejects the start of a bundle being started by the same thread ("cannot be started, since it is starting"); - the error was logged as a failure to start the DM bundle, and consumed the "log once" flag, hiding a real start failure afterwards. Modification: - ServiceRegistryCacheManager.init() remembers the activating thread, and a new activated() method clears it. The Activator start() calls activated() in a finally block, so the thread is cleared even if the start fails. - getCache() returns null at once when called by the activating thread: the DM bundle is not started again, and nothing is logged. The DependencyManager created by the ServiceFactory doesn't use the cache, which is only an optimization. Other threads are not affected. - A new test in FELIX6874_ParallelStartTest starts a bundle registering a ComponentExecutorFactory ServiceFactory which creates a DependencyManager, then starts the DM bundle: the ServiceFactory must be called while the DM bundle is STARTING, the DM bundle must become ACTIVE, no start failure must be logged, and a user bundle started afterwards on the same thread must use the cache. - The comments written for FELIX-6874 are wrapped at 100 columns (original Felix comments are unchanged). --- .../org/apache/felix/dm/impl/Activator.java | 25 ++-- .../index/ServiceRegistryCacheManager.java | 111 +++++++++----- .../test/FELIX6874_ParallelStartTest.java | 138 +++++++++++++++--- .../test/felix6874/ReentrantActivator.java | 86 +++++++++++ .../test/test/felix6874/UserActivator.java | 26 ++-- 5 files changed, 304 insertions(+), 82 deletions(-) create mode 100644 dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/ReentrantActivator.java 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 5719106fb0..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,17 +42,24 @@ public class Activator implements BundleActivator { @Override public void start(BundleContext context) throws Exception { - // create the service registry cache, if configured (and set the backdoor in system properties, needed by tests) - ServiceRegistryCacheManager.init(context); + 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 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 6d5e15409a..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 @@ -54,37 +54,54 @@ public class ServiceRegistryCacheManager { private static volatile BundleContext m_context; /** - * 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. + * 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_stopped; /** - * 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. + * 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. + */ + private static volatile Thread m_activatingThread; + + /** + * 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. + * 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. + * 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 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). * - * Never call this method from the DependencyManager Activator. + * 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(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 @@ -97,9 +114,9 @@ public static ServiceRegistryCache getCache(Logger logger) { } } } 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) + // 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); @@ -110,26 +127,30 @@ public static ServiceRegistryCache getCache(Logger logger) { } /** - * Starts the DependencyManager bundle, so that its Activator has initialized the cache when we return it. + * 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): + * 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.
  • + *
  • 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). + * 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. + * 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 @@ -202,13 +223,14 @@ private static ServiceRegistryCache createCache(BundleContext context) { } /** - * 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). + * 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(BundleContext context) { + m_activatingThread = Thread.currentThread(); // cleared by activated() m_stopped = false; if (m_context != null) { return; @@ -223,8 +245,17 @@ public static void init(BundleContext context) { } /** - * 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. + * 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; + } + + /** + * 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; diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java index 464130cf85..4b2c100a89 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java @@ -24,6 +24,7 @@ import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; +import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -34,6 +35,7 @@ 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; @@ -53,21 +55,25 @@ import org.osgi.framework.launch.Framework; import org.osgi.framework.launch.FrameworkFactory; +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. + * 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). + * 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 200). + * This is a race: the scenario is run again with a new embedded Felix framework, at most + * "felix6874.runs" times (system property, default 200). * - * This class also checks that a DependencyManager bundle stopped by a management agent is not restarted by the user - * bundles started afterwards. + * This class also checks that a DependencyManager bundle stopped by a management agent is not + * restarted by the user bundles started afterwards, and that a re-entrant call to the service + * registry cache from the DependencyManager Activator thread is harmless. */ public class FELIX6874_ParallelStartTest { @@ -88,9 +94,10 @@ public void testUserBundlesStartedInParallelWithDependencyManagerAndFilterIndex( } /** - * 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. + * 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 { @@ -129,14 +136,79 @@ public void testStoppedDependencyManagerIsNotRestartedByUserBundles() throws Exc } } - /** Returns true if the DependencyManager of the given user bundle uses the service registry cache. */ + /** + * 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); + } + } + + /** + * 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 + * @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")); @@ -151,13 +223,16 @@ private void test(String indices) throws Exception { } } - /** Starts a new framework once. Returns the FELIX-6874 exception thrown by a bundle start, or null. */ + /** + * 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) + // 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()); @@ -176,7 +251,8 @@ private Throwable runOnce(int run, File dmJar, File userJar, File storage, Strin framework.init(); BundleContext context = framework.getBundleContext(); - // the bundles started by the FelixStartLevel thread report their start errors as framework events + // 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()); @@ -189,7 +265,8 @@ private Throwable runOnce(int run, File dmJar, File userJar, File storage, Strin } bundles.add(install(context, dmJar, "dependencymanager")); - // AutoProcessor of PR #236: a pool of 8 threads starts the bundles, the launcher does not wait. + // 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(() -> { @@ -213,7 +290,8 @@ private Throwable runOnce(int run, File dmJar, File userJar, File storage, Strin 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 + // 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", @@ -231,7 +309,8 @@ private Throwable runOnce(int run, File dmJar, File userJar, File storage, Strin framework.stop(); stopped = framework.waitForStop(30000); } - // checked after the finally block, so that it does not hide an exception thrown by the try block + // 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(); } @@ -263,20 +342,31 @@ private static File createDependencyManagerBundle(File jar) throws Exception { return createBundle(jar, manifest, classes, classes.resolve("org/apache/felix/dm")); } - /** Creates a user bundle, which only contains the UserActivator class. */ + /** 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, UserActivator.class.getName()); + 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. */ + /** + * 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(); } 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 index 7f218631a1..72e01819da 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/UserActivator.java +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/felix6874/UserActivator.java @@ -25,25 +25,33 @@ 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. + * 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. + * 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(). + * 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) */ + /** + * 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 */ + /** + * true if the client component has been started, meaning its service dependency has been + * injected + */ public static volatile boolean s_clientStarted; @Override From fe36e47ff9dcceb7e59c124443962bc321df9a0c Mon Sep 17 00:00:00 2001 From: Pierre De Rop Date: Wed, 25 Nov 2026 10:17:48 -0600 Subject: [PATCH 4/6] FELIX-6874: Cover the START_TRANSIENT_ERROR fallback of getCache() in a test Motivation: The START_TRANSIENT_ERROR fallback of ServiceRegistryCacheManager.getCache() was not covered by the tests (PR review). getCache() starts the DM bundle with START_TRANSIENT, and falls back to a persistent start if Felix rejects the transient start with START_TRANSIENT_ERROR. In the existing tests, all bundles use the same start level and the framework is stable, so the transient start never fails and the persistent start branch never runs. Modification: - A new test in FELIX6874_ParallelStartTest, testTransientStartFailureFallsBackToPersistentStart, covers this branch. The DM bundle and the user bundle have the same start level (2), and the framework raises its start level from 1 to 2. The start level thread sets its target start level, then waits for the Felix global lock before queuing the bundles to start: in between, the active start level is still 1, and a persistent start called from another thread activates the bundle immediately. The DependencyManager created by the user bundle then fails to start the DM bundle with a transient start (START_TRANSIENT_ERROR). - 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, waits for the target start level to be set, then starts the user bundle. - The test verifies that the user and DM bundles are ACTIVE, that the DM bundle has been started by the persistent start fallback (a transient start doesn't mark the bundle as persistently started), that the user bundle uses the service registry cache, that no start failure is logged, and that the framework start level is finally raised. --- .../test/FELIX6874_ParallelStartTest.java | 85 ++++++++++++++++++- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java index 4b2c100a89..f0d9a346b8 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java @@ -25,6 +25,7 @@ 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; @@ -32,6 +33,7 @@ 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; @@ -54,6 +56,8 @@ 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; @@ -72,8 +76,10 @@ * "felix6874.runs" times (system property, default 200). * * This class also checks that a DependencyManager bundle stopped by a management agent is not - * restarted by the user bundles started afterwards, and that a re-entrant call to the service - * registry cache from the DependencyManager Activator thread is harmless. + * 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 { @@ -187,6 +193,81 @@ public void testReentrantCallFromDependencyManagerActivator() throws Exception { } } + /** + * 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. From f8c0e4a6917b8fb966a4e6ee1aea6ef24df07801 Mon Sep 17 00:00:00 2001 From: Pierre De Rop Date: Wed, 25 Nov 2026 10:25:23 -0600 Subject: [PATCH 5/6] FELIX-6874: Lower the default number of runs of FELIX6874_ParallelStartTest Motivation: FELIX6874_ParallelStartTest repeats its race scenario 200 times by default ("felix6874.runs"), with 2 tests and 101 bundles per run, each on a fresh embedded Felix framework. This is heavy for the regular build (PR review). Modification: - The default value of the "felix6874.runs" system property is lowered from 200 to 20. - The class comment says that a higher value can be used for stress runs, for example -Dfelix6874.runs=200. --- .../test/test/FELIX6874_ParallelStartTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java index f0d9a346b8..67d2077336 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java +++ b/dependencymanager/org.apache.felix.dependencymanager/test/test/FELIX6874_ParallelStartTest.java @@ -73,7 +73,7 @@ * unusable). * * This is a race: the scenario is run again with a new embedded Felix framework, at most - * "felix6874.runs" times (system property, default 200). + * "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 @@ -83,7 +83,7 @@ */ public class FELIX6874_ParallelStartTest { - private static final int RUNS = Integer.getInteger("felix6874.runs", 200); + private static final int RUNS = Integer.getInteger("felix6874.runs", 20); private static final int USER_BUNDLES = 100; @Rule From e1f97f2e51c5c65f795f4821beec12134d6a0564 Mon Sep 17 00:00:00 2001 From: Pierre De Rop Date: Wed, 25 Nov 2026 12:42:48 -0600 Subject: [PATCH 6/6] FELIX-6874: Test the service registry cache after a refresh of the DM bundle Motivation: A stop/start of the DependencyManager bundle without refresh keeps the static state of ServiceRegistryCacheManager (PR review), and is not supported: the components created before the stop keep their interceptors on the old cache, whose listeners were removed by the framework, and their bundles are not restarted. The supported way is a refresh of the DependencyManager bundle. Modification: - A refresh creates a new wiring of the DependencyManager bundle, with a new class loader, so the static state of ServiceRegistryCacheManager starts from scratch (new context, new cache), and the bundles using DependencyManager are refreshed too, so their components use the new cache. - New integration test, FELIX6874_DependencyManagerRefreshTest, in the new module index.itest.refresh.tests: with an "objectClass,dm.refresh.test" index configured by the system property, it refreshes the DependencyManager bundle and checks that a service dependency works before the refresh, and for a service registered after the refresh. For each of them, it also updates the service properties, and checks that the service event is propagated to the dependency. This test bundle must not import org.apache.felix.dm, else it would be refreshed in the middle of the test. - New module index.itest.refresh.bundle: the bundle using DependencyManager which is refreshed with it. Its component depends on the Runnable services having the "dm.refresh.test" property (the bnd tester registers itself as a Runnable), and runs them when they are added or changed. Co-Authored-By: Claude Sonnet 5.5 --- .../pom.xml | 72 ++++++++ .../index/itest/refresh/bundle/Activator.java | 50 ++++++ .../refresh/bundle/RunnableConsumer.java | 38 +++++ .../pom.xml | 131 ++++++++++++++ ...ELIX6874_DependencyManagerRefreshTest.java | 161 ++++++++++++++++++ .../test.bndrun | 33 ++++ dependencymanager/pom.xml | 2 + 7 files changed, 487 insertions(+) create mode 100644 dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/pom.xml create mode 100644 dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/src/org/apache/felix/dm/index/itest/refresh/bundle/Activator.java create mode 100644 dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.bundle/src/org/apache/felix/dm/index/itest/refresh/bundle/RunnableConsumer.java create mode 100644 dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/pom.xml create mode 100644 dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/src/org/apache/felix/dm/index/itest/refresh/tests/FELIX6874_DependencyManagerRefreshTest.java create mode 100644 dependencymanager/org.apache.felix.dependencymanager.index.itest.refresh.tests/test.bndrun 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/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