allthingssecurity opened a new pull request, #30919: URL: https://github.com/apache/camel/pull/30919
# Description [CAMEL-27592](https://issues.apache.org/jira/browse/CAMEL-27592) Two bugs in `ClusteredRoutePolicy` (camel-cluster), plus a small third one in the same code. **1. A route added while the leadership is lost keeps running on a node that is not the leader.** When a route is added to a running CamelContext, `onInit` reads `isLeader()` without the policy lock. On the leader it records the route as started and leaves its auto startup on, so the route controller starts it as part of `addRoutes`. If the leadership is lost after `onInit` but before the route has started, the policy thread applies the loss while the route cannot be stopped yet: either the policy is not started yet (it is added as a service right after `onInit`, so `doStopManagedRoutes` returns at once), or the route status is still null, Initialized or Starting. The pass skips the route, the route controller then starts it, and nothing stops it afterwards. The node that is now the leader runs the route as well. **2. After `CamelContext.stop()` and `start()`, the leader never starts the routes of the policy.** A policy set on a route definition is used again by the routes created at the restart. The stop shut the policy down: the executor of the policy thread (created once, in `setCamelContext`) got `shutdownNow`, the event notifier was removed and `retryScheduled` was left true. Nothing undid that, so every later leadership change was rejected by the dead executor and the started event of the restart never reached the policy. The view and the policy both said "leader" while the routes stayed stopped on every node. **3.** A route start or stop that throws an `Error` (for example a `NoClassDefFoundError` from a consumer) ended the pass and was never tried again, because only `Exception` was caught. Change (`ClusteredRoutePolicy` only): - New `onStart`: when a route that the policy recorded as started begins to run on a node that is no longer the leader, the policy thread applies the leadership again (`reapply`, as for a route added or a failed start). In `doStopManagedRoutes`, a route that is still `Starting` is not skipped any more: the stop is tried again after `retryDelay` (the retry already used for a failed stop). `onStart` runs while the route is still `Starting` (`BaseService` sets `Started` after `doStart`), so the pass it queues usually finds the route starting and stops it on that retry: a route added while the leadership is lost runs on the node that is not the leader for about one `retryDelay` (5 s by default) before it is stopped, instead of forever as on main. A follow-up could react to `RouteStartedEvent` to make this window shorter. The fast path stays as it is: on the leader, `addRoutes` still returns with the route started, which `ClusteredRoutePolicyTest.testClusteredRoutePolicyAddRouteAlready Leader` and `ClusteredEdgeCasesTest.testInitialDelayForRouteAddedAfterStartOnLeader` check. - `onInit` makes a shut down policy usable again before it retains the view: a new executor for the policy thread, the event notifier added back, `leadershipChangePending`, `reapply`, `retryScheduled`, `contextStarted`, `contextResumed` and `initialDelayElapsed` reset, and `startManagedRoutesEarly` set, so the routes start once the CamelContext has started, as at the first start (the routes are created while the CamelContext initializes). The shutdown now clears the executor field, which is how `onInit` knows. The initial delay applies again after a restart. - An `Error` from `startRoute` or `stopRoute` is a failed start or stop and is tried again. A `VirtualMachineError` (also one found as a cause, `ObjectHelper.getVirtualMachineError`) is not: the retry is scheduled and the error is rethrown, without going to the exception handler of the policy (as on main, which caught only `Exception`). `applyLeadershipChange` catches `Throwable`, logs a `VirtualMachineError` once at ERROR with its stack trace and rethrows it (as in CAMEL-27515), and logs any other reason at WARN, as before. - `scheduleRetry` sets its flag before it creates the timer thread. If that fails with something other than a `RejectedExecutionException` (for example an `OutOfMemoryError` when no native thread can be created), the flag is now reset and the error rethrown, so a later failure schedules a retry again. Before, the flag stayed set and no retry ran until a restart. The `VirtualMachineError` path above is the first to call `scheduleRetry` in that situation. The analysis suggested another way to fix 1: always register the route as stopped with auto startup off in `onInit`, and let the policy thread start it. I did not do that, because `addRoutes` on the leader would then return before the route has started (two existing tests check that it is started), and the initial delay of a new policy would then also apply to a route added on the leader. The `onStart` check keeps both. One small difference is visible: a route that the policy recorded as started, then stopped by hand on the leader, and started by hand again after this node lost the leadership, is now stopped by the policy (before, nothing stopped it). No upgrade guide entry: these are bug fixes, and nothing changes for a node whose leadership does not change while a route is being added, or for a CamelContext that is not stopped and started again. Not changed here (follow-up JIRAs offered): - A CamelContext suspend between the check and `startRoute` or `stopRoute` (the start or stop then does nothing, but the policy records it as done). This needs the passes to reconcile against the real route status, a larger change. - A route removed and added again with the same id while a pass holds the old instance (found only in the model). - `ZooKeeperClusterView` gives up the leadership on stop without firing an event (found only in the model). The sibling policies (`HazelcastRoutePolicy`, `MasterRoutePolicy` in camel-zookeeper-master) create their executors in `doStart`, so they work after a restart already, and they have no leader fast path in `onInit`. Tests: new `ClusteredRoutePolicyLateStartAndRestartTest` in camel-core (package-private, a `DefaultCamelContext` with a stand-in cluster service, latches and Awaitility, no sleeps): - `routeAddedWhileLeadershipIsLostIsStopped`: a second policy of the route, whose `onInit` runs right after the clustered one, takes the leadership away and waits until the policy thread has looked at the route (a route controller that counts down a latch when the policy thread reads its status). - `routeStartingWhileLeadershipIsLostIsStoppedOnceStarted`: the same, from the `onStart` of a second policy, so the policy thread sees the route `Starting`. - `leaderStartsRoutesAfterCamelContextRestart`: after a stop and start the leader starts the route, keeps a route with `autoStartup(false)` stopped, and applies a later leadership loss. - `leadershipTakenAfterCamelContextRestartStartsRoute`: leadership taken after the restart. - `routeStartThrowingErrorIsTriedAgain`: one `NoClassDefFoundError` on start, the route is started on the retry. - `retryTimerThatCannotBeCreatedIsCreatedOnTheNextFailure`: the first retry timer cannot be created (an `ExecutorServiceManager` that throws once when the timer is created), the leadership is lost and taken again, the next failed start schedules its retry, and the route is started on it. The test throws an `IllegalStateException`, not an `OutOfMemoryError`: both take the same path in `scheduleRetry`, and an `OutOfMemoryError` would escape the policy thread and fail the tests that run at the same time in camel-core. Results: with main's `ClusteredRoutePolicy`, all 6 tests fail in each of 3 runs. Removing only the `onStart` check fails only the first test; removing only the retry for a `Starting` route fails only the second; without the reset in `scheduleRetry` only `retryTimerThatCannotBeCreatedIsCreatedOnTheNextFailure` fails (3 runs of 3, the route stays `Stopped`). With the change, the first five tests and the existing `ClusteredRoutePolicyTest`, `ClusteredEdgeCasesTest`, `ClusteredRoutePolicyLeaderChangeTest` and `ClusteredRoutePolicyFactoryTest` passed 20 runs out of 20 in one JVM (640 of 640 tests), and the new class with all 6 tests passed 10 runs out of 10 (60 of 60). The cluster and route policy tests of camel-core (53 classes, 159 tests: `org.apache.camel.cluster`, the file lock cluster tests and every `*RoutePolicy*Test`) and the 16 tests of camel-cluster pass. Found with a TLA+ model of the policy (the hand-off to the policy thread, the start and stop passes, the retry timer, route add and remove, and the CamelContext suspend, resume, stop and start), and reproduced against the real class. In the model, "a node that is not the leader eventually runs no managed route" fails on main and holds with the `onStart` change (also when a route is removed and added again). "The leader eventually runs every route" holds after a restart with the restart change. What the model still finds with these changes is the suspend window listed above, which main has too. # Target - [x] I checked that the commit is targeting the correct branch (Camel 4 uses the `main` branch) # Tracking - [x] If this is a large change, bug fix, or code improvement, I checked there is a [JIRA issue](https://issues.apache.org/jira/browse/CAMEL) filed for the change (usually before you start working on it): [CAMEL-27592](https://issues.apache.org/jira/browse/CAMEL-27592). # Apache Camel coding standards and style - [x] I checked that each commit in the pull request has a meaningful subject line and body. - [ ] I have run `mvn clean install -DskipTests` locally from root folder and I have committed all auto-generated changes. (I built camel-cluster and camel-core offline with the formatter and import-sort plugins and ran the tests listed above. I did not run the full root build. No option or generated file changed.) # AI-assisted contributions - [x] If this PR includes AI-generated code, commits have proper co-authorship attribution (e.g., `Co-authored-by` trailers) and the PR description identifies the AI tool used. This PR was prepared with Claude Code (Claude Opus 5.5). The commit carries a `Co-Authored-By` trailer. _Claude Code on behalf of allthingssecurity_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
