Repository navigation
FELIX-6874: Fix DM cache init when bundles start in parallel - #598
Conversation
…ndles 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 apache#236 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
paulrutter
left a comment
There was a problem hiding this comment.
Thanks Pierre, this looks good to me. I reviewed the diff and code only (I did not run the new test locally); CI is green on 17/21/25/27.
Does it fix the exceptions reported in #236? Yes, both stack traces:
- The
ExceptionInInitializerError(NPE inServiceRegistryCacheManager.<clinit>,getBundleContext()returning null) is gone: the static initializer is removed, andgetCache()now starts the DM bundle transiently and waits for its Activator to finish. - The follow-up
NoClassDefFoundErrorinActivator.startis gone too:init(context)uses the context handed to the Activator, so it cannot be null, and the class no longer has a failing static initializer.
Failure mode is also graceful now: getCache() never throws, and a bundle that can't get the cache is simply created without it.
Non-blocking comments:
getCache()can revive a stopped DM bundle. Any newDependencyManagercreated while DM is not ACTIVE callsstart()on it, so a deliberately stopped DM bundle would be restarted by a user bundle creating aDependencyManager. It also runs for everyDependencyManager, so a failing start prints a stack trace each time. Maybe only attempt the start when the state is INSTALLED/RESOLVED/STARTING, or only once.- Re-entrancy is documented but not guarded.
FilterIndexCustomizer.addingServiceandExecutorFactoryCustomizerrun insideActivator.startand callgetServiceon other bundles' services. If such a service factory creates aDependencyManager,getCache()is called on the Activator thread while DM is STARTING. A cheap guard (remember the activating thread ininit) or confirming it is harmless would be nice. - The
START_TRANSIENT_ERRORfallback is not covered by the test. All bundles use the same start level, so the persistent-start branch never runs. A case with DM at a higher start level than the user bundles would cover it. Note that aDependencyManagercreated without the cache never picks it up later; fine as an optimization, just worth knowing. - Test cost. The default of 200 runs x 2 tests x 101 bundles, each on a fresh Felix framework, is heavy for the regular build. Consider a lower default (e.g. 20) and keeping
-Dfelix6874.runsfor stress runs. - Nit:
init()guards onm_context != null, so after a DM stop/start without refresh the old context stays. Same as before, not a regression.
|
Ps. I'm still trying to reproduce the old exception, but haven't been able up until now. Will keep you posted. |
|
Hi Paul, thank you so much for the review, I will address it.
I have attached a reproducer sample in the jira, if you want to use it, see : https://issues.apache.org/jira/browse/FELIX-6874?focusedId=18149855&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-18149855 |
|
Added another reproducer , this time based on dependency manager in parallel mode + a "deployer" thread (similar to file install): |
|
Hi Pierre, This PR fixes the The possible race
Why I suspect itIn a parallel startup with 20 tenant-scoped copies of one adapter component, the application did not finish starting in 1 of about 150 runs. There was no error and no stuck thread. Every component that depends on the service from the shared array stayed unstarted, for all 20 copies at the same time. A shared array explains why all copies fail together. What is proven and what is not
Proposed fixSort a copy in List<MultiPropertyKey> getPermutations(String key, String[] propertyValues) {
List<MultiPropertyKey> results = new ArrayList<>();
// Sort a copy. The array of a service property can be the live array of the registration.
String[] values = propertyValues.clone();
Arrays.sort(values, String.CASE_INSENSITIVE_ORDER);
...The change is 3 lines plus the test. Do you prefer the fix in this PR, or in its own issue and PR? |
|
Thanks, Paul. It looks like you're right, and I think your finding deserves a new Jira ticket and PR. Feel free to go ahead with the PR if you want; I'll review it. Alternatively, I can take care of it myself. Let me know. From my side, I may have found another issue, although it's unrelated to Parallel DM. It's in The code uses I'll create a separate Jira ticket and PR for this. |
|
Alright we're on a spree then, haha. I'll take care of 'my' race then with a separate ticket plus PR. |
…e 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.
|
Thanks for the review! Commit b9f7be4. addresses your first comment: a DM bundle stopped by a management agent is no longer restarted by One edge case is deliberately not handled: a stop which completes between the checks of
I thought about closing it with a /** Set while getCache() starts the DependencyManager bundle (see init()). */
private static final ThreadLocal<Boolean> m_startedByGetCache = new ThreadLocal<>();
public static ServiceRegistryCache getCache(Logger logger) {
try {
Bundle dm = FrameworkUtil.getBundle(ServiceRegistryCacheManager.class);
if (dm != null) {
int state = dm.getState();
if (state == Bundle.STOPPING || m_stopped) {
return null; // shortcut: init() takes the final decision
}
if (state != Bundle.ACTIVE) {
m_startedByGetCache.set(Boolean.TRUE);
try {
startDependencyManager(dm);
} finally {
m_startedByGetCache.remove();
}
}
}
} catch (Exception e) {
if (m_stopped) {
return null; // init() refused to restart the stopped DependencyManager bundle: not an error
}
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;
}
public static void init(BundleContext context) {
// called by our Activator start(), while the framework holds the bundle lock: a stop is either complete or not started
if (m_stopped && m_startedByGetCache.get() != null) {
throw new IllegalStateException("The DependencyManager bundle has been stopped, a user bundle must not restart it");
}
m_stopped = false;
...
}When I didn't apply it, to keep the code simple. The above patch is more complex, it adds a |
…hread
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).
Addressed your feedback in commit 3669425, thank you. |
… 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.
Addressed feedback in commit fe36e47, thank you. |
…rtTest
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.
Addressed your feedback in commit f8c0e4a, thank you. |
… 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 <noreply@anthropic.com>
Thanks! Agreed, this is not a regression, and I'd rather not change it in this PR: a stop/start of the DM bundle without refresh can't be fully supported as is. The components created before the stop keep their interceptors on the old cache, whose listeners were removed by the framework when the DM bundle was stopped, and their bundles are not restarted. The supported way is a refresh: it creates a new wiring of the DM bundle, with a new class loader, so the static state of Commit e1f97f2 adds an integration test for this, Supporting a stop/start without refresh would need a larger change (recreating the cache at each start, closing it at stop, and rebinding the existing components to the new cache), so if we want it, I suggest doing it in a separate PR. |
|
I think I addresses all your comments, let me know if there is something wrong ? or if I can ship this PR ? |
LGTM! good to merge |
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.
getCache(), called by DependencyManager, now 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