Repository navigation
Fix supervisor crash on transient ZK connection loss #9153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jkrauss82
wants to merge
2
commits into
apache:master
Choose a base branch
from
jkrauss82:fix/connection-aware-zk-retry
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
146 changes: 146 additions & 0 deletions
146
storm-client/src/jvm/org/apache/storm/utils/ConnectionAwareRetryPolicy.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| /* | ||
| * 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.storm.utils; | ||
|
|
||
| import java.util.concurrent.ThreadLocalRandom; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.atomic.AtomicReference; | ||
| import java.util.function.Supplier; | ||
| import org.apache.storm.shade.com.google.common.annotations.VisibleForTesting; | ||
| import org.apache.storm.shade.org.apache.curator.RetryPolicy; | ||
| import org.apache.storm.shade.org.apache.curator.RetrySleeper; | ||
| import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework; | ||
| import org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| /** | ||
| * A {@link RetryPolicy} wrapper that makes the Curator retry loop aware of the | ||
| * ZooKeeper connection state. | ||
| * | ||
| * <p>When the connection is {@link ConnectionState#SUSPENDED} or | ||
| * {@link ConnectionState#LOST}, instead of blindly sleeping and retrying (which | ||
| * races against the ZK client's {@code SendThread} reconnection), this policy | ||
| * calls {@link CuratorFramework#blockUntilConnected} to yield to the | ||
| * {@code SendThread} and wait for it to failover to another ensemble member. | ||
| * | ||
| * <p>Once the connection is re-established, the retry loop immediately retries | ||
| * the operation on the new connection. If the connection cannot be | ||
| * re-established within the session timeout, the retry is abandoned. | ||
| * | ||
| * <p>For all other connection states, this policy delegates to the wrapped | ||
| * delegate policy (typically a {@link StormBoundedExponentialBackoffRetry}). | ||
| */ | ||
| public class ConnectionAwareRetryPolicy implements RetryPolicy { | ||
|
|
||
| private static final Logger LOG = LoggerFactory.getLogger(ConnectionAwareRetryPolicy.class); | ||
|
|
||
| /** | ||
| * Maximum jitter (in ms) applied after a successful reconnection to avoid | ||
| * thundering-herd when many suspended clients retry in lockstep. | ||
| */ | ||
| private static final long RECONNECT_JITTER_MS = 100; | ||
|
|
||
| private final RetryPolicy delegate; | ||
| private final Supplier<CuratorFramework> zkSupplier; | ||
| private final int sessionTimeoutMs; | ||
| private final AtomicReference<ConnectionState> connectionState = | ||
| new AtomicReference<>(ConnectionState.CONNECTED); | ||
|
|
||
| /** | ||
| * @param delegate the underlying retry policy to delegate to for normal (connected) retries | ||
| * @param zkSupplier supplier for the {@link CuratorFramework}, used for late binding since | ||
| * the framework does not exist until {@code builder.build()} returns | ||
| * @param sessionTimeoutMs upper bound (in ms) for waiting on reconnection; typically | ||
| * {@code storm.zookeeper.session.timeout} | ||
| */ | ||
| public ConnectionAwareRetryPolicy(RetryPolicy delegate, | ||
| Supplier<CuratorFramework> zkSupplier, | ||
| int sessionTimeoutMs) { | ||
| this.delegate = delegate; | ||
| this.zkSupplier = zkSupplier; | ||
| this.sessionTimeoutMs = sessionTimeoutMs; | ||
| } | ||
|
|
||
| /** | ||
| * Register a {@link org.apache.storm.shade.org.apache.curator.framework.state.ConnectionStateListener} | ||
| * on the given framework to track the current connection state. | ||
| * Must be called after the {@link CuratorFramework} has been built. | ||
| * | ||
| * @param zk the built CuratorFramework | ||
| */ | ||
| public void bind(CuratorFramework zk) { | ||
| zk.getConnectionStateListenable().addListener((client, newState) -> { | ||
| ConnectionState prev = connectionState.getAndSet(newState); | ||
| if (prev != newState) { | ||
| LOG.debug("ZK connection state changed: {} -> {}", prev, newState); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| RetryPolicy getDelegate() { | ||
| return delegate; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleepSleeper) { | ||
| ConnectionState state = connectionState.get(); | ||
|
|
||
| if (state == ConnectionState.SUSPENDED || state == ConnectionState.LOST) { | ||
| // Honour the configured retry budget even while suspended. | ||
| if (!delegate.allowRetry(retryCount, elapsedTimeMs, sleepSleeper)) { | ||
| return false; | ||
| } | ||
|
|
||
| CuratorFramework zk = zkSupplier.get(); | ||
| if (zk == null) { | ||
| // Framework not yet available; delegate already approved the retry | ||
| return true; | ||
| } | ||
|
|
||
| LOG.info("ZK connection is {} on retry {}, waiting for reconnection (timeout {}ms)", | ||
| state, retryCount, sessionTimeoutMs); | ||
| try { | ||
| boolean reconnected = zk.blockUntilConnected(sessionTimeoutMs, TimeUnit.MILLISECONDS); | ||
| if (reconnected) { | ||
| LOG.info("ZK connection re-established (state: {}), retrying operation", | ||
| connectionState.get()); | ||
| // Jitter to avoid thundering-herd on ensemble recovery. | ||
| long jitterMs = ThreadLocalRandom.current().nextLong(RECONNECT_JITTER_MS); | ||
| if (jitterMs > 0) { | ||
| sleepSleeper.sleepFor(jitterMs, TimeUnit.MILLISECONDS); | ||
| } | ||
| return true; | ||
| } | ||
| LOG.warn("ZK connection not re-established within {}ms, abandoning retry", | ||
| sessionTimeoutMs); | ||
| return false; | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| LOG.warn("Interrupted while waiting for ZK reconnection", e); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| // Connection is healthy (CONNECTED, RECONNECTED, or READ_ONLY) — | ||
| // delegate to the existing backoff policy for normal retry behaviour. | ||
| return delegate.allowRetry(retryCount, elapsedTimeMs, sleepSleeper); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
174 changes: 174 additions & 0 deletions
174
storm-client/test/jvm/org/apache/storm/utils/ConnectionAwareRetryPolicyTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| /* | ||
| * 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.storm.utils; | ||
|
|
||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.function.Supplier; | ||
| import org.apache.storm.shade.org.apache.curator.RetryPolicy; | ||
| import org.apache.storm.shade.org.apache.curator.RetrySleeper; | ||
| import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework; | ||
| import org.apache.storm.shade.org.apache.curator.framework.listen.Listenable; | ||
| import org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState; | ||
| import org.apache.storm.shade.org.apache.curator.framework.state.ConnectionStateListener; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.mockito.ArgumentCaptor; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertFalse; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
| import static org.mockito.ArgumentMatchers.any; | ||
| import static org.mockito.ArgumentMatchers.anyInt; | ||
| import static org.mockito.ArgumentMatchers.anyLong; | ||
| import static org.mockito.Mockito.mock; | ||
| import static org.mockito.Mockito.never; | ||
| import static org.mockito.Mockito.verify; | ||
| import static org.mockito.Mockito.when; | ||
|
|
||
| /** | ||
| * Unit tests for {@link ConnectionAwareRetryPolicy}. The ZooKeeper connection state is driven by | ||
| * capturing the {@link ConnectionStateListener} that {@link ConnectionAwareRetryPolicy#bind} registers | ||
| * and firing state transitions at it, so no real ZooKeeper is required. | ||
| */ | ||
| public class ConnectionAwareRetryPolicyTest { | ||
|
|
||
| private static final int SESSION_TIMEOUT_MS = 20_000; | ||
|
|
||
| private final RetryPolicy delegate = mock(RetryPolicy.class); | ||
| private final RetrySleeper sleeper = mock(RetrySleeper.class); | ||
| private final CuratorFramework zk = mock(CuratorFramework.class); | ||
| private ConnectionStateListener listener; | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| private ConnectionAwareRetryPolicy build(Supplier<CuratorFramework> zkSupplier) { | ||
| Listenable<ConnectionStateListener> listenable = mock(Listenable.class); | ||
| when(zk.getConnectionStateListenable()).thenReturn(listenable); | ||
|
|
||
| ConnectionAwareRetryPolicy policy = new ConnectionAwareRetryPolicy(delegate, zkSupplier, SESSION_TIMEOUT_MS); | ||
| policy.bind(zk); | ||
|
|
||
| ArgumentCaptor<ConnectionStateListener> captor = ArgumentCaptor.forClass(ConnectionStateListener.class); | ||
| verify(listenable).addListener(captor.capture()); | ||
| listener = captor.getValue(); | ||
| return policy; | ||
| } | ||
|
|
||
| private void fire(ConnectionState state) { | ||
| listener.stateChanged(zk, state); | ||
| } | ||
|
|
||
| @Test | ||
| public void connectedStateDelegatesToBackoffPolicy() { | ||
| ConnectionAwareRetryPolicy policy = build(() -> zk); | ||
| when(delegate.allowRetry(anyInt(), anyLong(), any())).thenReturn(true); | ||
|
|
||
| // Default state is CONNECTED (no event fired). | ||
| boolean result = policy.allowRetry(0, 0L, sleeper); | ||
|
|
||
| assertTrue(result, "when connected, must propagate the delegate's decision"); | ||
| verify(delegate).allowRetry(0, 0L, sleeper); | ||
| } | ||
|
|
||
| @Test | ||
| public void reconnectedStateDelegatesToBackoffPolicy() { | ||
| ConnectionAwareRetryPolicy policy = build(() -> zk); | ||
| when(delegate.allowRetry(anyInt(), anyLong(), any())).thenReturn(false); | ||
|
|
||
| fire(ConnectionState.RECONNECTED); | ||
| boolean result = policy.allowRetry(2, 100L, sleeper); | ||
|
|
||
| assertFalse(result, "RECONNECTED is a healthy state and must delegate"); | ||
| verify(delegate).allowRetry(2, 100L, sleeper); | ||
| } | ||
|
|
||
| @Test | ||
| public void suspendedBlocksUntilConnectedThenRetriesImmediately() throws Exception { | ||
| ConnectionAwareRetryPolicy policy = build(() -> zk); | ||
| when(delegate.allowRetry(anyInt(), anyLong(), any())).thenReturn(true); | ||
| when(zk.blockUntilConnected(SESSION_TIMEOUT_MS, TimeUnit.MILLISECONDS)).thenReturn(true); | ||
|
|
||
| fire(ConnectionState.SUSPENDED); | ||
| boolean result = policy.allowRetry(0, 0L, sleeper); | ||
|
|
||
| assertTrue(result, "should retry once the SendThread has reconnected"); | ||
| verify(zk).blockUntilConnected(SESSION_TIMEOUT_MS, TimeUnit.MILLISECONDS); | ||
| } | ||
|
|
||
| @Test | ||
| public void lostBlocksUntilConnectedThenRetriesImmediately() throws Exception { | ||
| ConnectionAwareRetryPolicy policy = build(() -> zk); | ||
| when(delegate.allowRetry(anyInt(), anyLong(), any())).thenReturn(true); | ||
| when(zk.blockUntilConnected(SESSION_TIMEOUT_MS, TimeUnit.MILLISECONDS)).thenReturn(true); | ||
|
|
||
| fire(ConnectionState.LOST); | ||
| boolean result = policy.allowRetry(3, 1234L, sleeper); | ||
|
|
||
| assertTrue(result, "LOST should also wait for reconnection then retry"); | ||
| verify(zk).blockUntilConnected(SESSION_TIMEOUT_MS, TimeUnit.MILLISECONDS); | ||
| } | ||
|
|
||
| @Test | ||
| public void suspendedAbandonsRetryWhenReconnectTimesOut() throws Exception { | ||
| ConnectionAwareRetryPolicy policy = build(() -> zk); | ||
| when(delegate.allowRetry(anyInt(), anyLong(), any())).thenReturn(true); | ||
| when(zk.blockUntilConnected(SESSION_TIMEOUT_MS, TimeUnit.MILLISECONDS)).thenReturn(false); | ||
|
|
||
| fire(ConnectionState.SUSPENDED); | ||
| boolean result = policy.allowRetry(0, 0L, sleeper); | ||
|
|
||
| assertFalse(result, "should abandon when not reconnected within the session timeout"); | ||
| } | ||
|
|
||
| @Test | ||
| public void suspendedHonoursDelegateRetryBudget() throws Exception { | ||
| ConnectionAwareRetryPolicy policy = build(() -> zk); | ||
| // Delegate says no more retries allowed (budget exhausted) | ||
| when(delegate.allowRetry(anyInt(), anyLong(), any())).thenReturn(false); | ||
|
|
||
| fire(ConnectionState.SUSPENDED); | ||
| boolean result = policy.allowRetry(100, 99999L, sleeper); | ||
|
|
||
| assertFalse(result, "should abandon when the delegate's retry budget is exhausted"); | ||
| verify(zk, never()).blockUntilConnected(anyInt(), any()); | ||
| } | ||
|
|
||
| @Test | ||
| public void interruptedWhileWaitingReturnsFalseAndPreservesInterruptFlag() throws Exception { | ||
| ConnectionAwareRetryPolicy policy = build(() -> zk); | ||
| when(delegate.allowRetry(anyInt(), anyLong(), any())).thenReturn(true); | ||
| when(zk.blockUntilConnected(anyInt(), any())).thenThrow(new InterruptedException("test")); | ||
|
|
||
| fire(ConnectionState.SUSPENDED); | ||
| boolean result = policy.allowRetry(0, 0L, sleeper); | ||
|
|
||
| assertFalse(result, "an interrupt while waiting should abandon the retry"); | ||
| assertTrue(Thread.interrupted(), "interrupt flag must be preserved (this check also clears it)"); | ||
| } | ||
|
|
||
| @Test | ||
| public void suspendedWithNullFrameworkFallsThroughToDelegate() { | ||
| // zkSupplier returns null (framework not yet available), even though bind() ran on the mock. | ||
| ConnectionAwareRetryPolicy policy = build(() -> null); | ||
| when(delegate.allowRetry(anyInt(), anyLong(), any())).thenReturn(true); | ||
|
|
||
| fire(ConnectionState.SUSPENDED); | ||
| boolean result = policy.allowRetry(1, 50L, sleeper); | ||
|
|
||
| assertTrue(result, "with no framework available yet, must fall through to the delegate"); | ||
| verify(delegate).allowRetry(1, 50L, sleeper); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Core change: replace the budget check that calls the sleeping delegate with a pure retry-count cap, so the suspended path no longer reintroduces the exponential backoff sleep. Depends on the new
maxRetriesfield/constructor arg and theCuratorUtilswiring in the patch above — apply those together or this won't compile.