Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ abstract class AbstractSubscriptionConsumer implements AutoCloseable {
private final Map<String, Set<SubscriptionCommitContext>> pendingRedirectAcksByTopicRegion =
new ConcurrentHashMap<>();

private final Map<String, Set<Integer>> terminatedDataNodeIdsByTopic = new ConcurrentHashMap<>();
private final Set<String> autoUnsubscribingTopics = ConcurrentHashMap.newKeySet();
private final Object topicTerminationLock = new Object();

@SuppressWarnings("java:S3077")
protected volatile Map<String, TopicConfig> subscribedTopics = new HashMap<>();

Expand Down Expand Up @@ -409,6 +413,8 @@ public void close() {
// in network I/O. prepareClose() bounds or interrupts those RPCs before providers are detached.
providers.prepareClose();
providers.closeProviders(!isFenced());
clearTerminatedProviderStates();
autoUnsubscribingTopics.clear();
}

boolean isClosed() {
Expand Down Expand Up @@ -456,6 +462,9 @@ private void subscribe(Set<String> topicNames, final boolean needParse)
.collect(Collectors.toSet());
}

topicNames.forEach(terminatedDataNodeIdsByTopic::remove);
topicNames.forEach(autoUnsubscribingTopics::remove);

providers.acquireReadLock();
try {
subscribeWithRedirection(topicNames);
Expand Down Expand Up @@ -492,6 +501,7 @@ private void unsubscribe(Set<String> topicNames, final boolean needParse)
try {
unsubscribeWithRedirection(topicNames);
topicNames.forEach(this::clearPendingRedirectAcks);
topicNames.forEach(terminatedDataNodeIdsByTopic::remove);
} finally {
providers.releaseReadLock();
}
Expand Down Expand Up @@ -773,13 +783,8 @@ private Path getFilePath(
TERMINATION,
(resp, timer) -> {
final SubscriptionCommitContext commitContext = resp.getCommitContext();
final String topicNameToUnsubscribe = commitContext.getTopicName();
LOGGER.info(
SubscriptionMessages
.LOG_TERMINATION_OCCURRED_SUBSCRIPTIONCONSUMER_ARG_POLLING_TOPICS_UNSUBSCRIBE_TOPIC_ARG_AUTOMATICALLY_E9B695FA,
coreReportMessage(),
topicNameToUnsubscribe);
unsubscribe(Collections.singleton(topicNameToUnsubscribe), false);
handleProviderTopicTermination(
commitContext.getDataNodeId(), commitContext.getTopicName());
return Optional.empty();
});
put(
Expand Down Expand Up @@ -811,6 +816,70 @@ protected Set<Integer> getAvailableDataNodeIds() {
}
}

protected Set<Integer> getExpectedDataNodeIds() {
providers.acquireReadLock();
try {
return providers.getExpectedDataNodeIds();
} finally {
providers.releaseReadLock();
}
}

void clearTerminatedProviderStates() {
synchronized (topicTerminationLock) {
terminatedDataNodeIdsByTopic.clear();
}
}

void handleProviderTopicTermination(final int dataNodeId, final String topicName)
throws SubscriptionException {
final TopicConfig topicConfig = subscribedTopics.get(topicName);
if (Objects.nonNull(topicConfig)
&& topicConfig.isSnapshotMode()
&& topicConfig.isProgressRetainedAfterUnsubscribe()) {
final Set<Integer> expectedDataNodeIds = getExpectedDataNodeIds();
synchronized (topicTerminationLock) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 4d3bee9: handleProviderTopicTermination now holds providers.acquireReadLock() across reading providers.getExpectedDataNodeIds() / providers.getTopologyGeneration() and checking topicTerminationLock, and validates that topologyGeneration is unchanged before issuing unsubscribe(); syncInternal also clears termination state and increments topologyGeneration whenever cluster membership changes. Added regression test SubscriptionConsumerMultiProviderPollTest#testRetainedSnapshotTerminationDoesNotUseStaleMembershipAcrossConcurrentSync.

if (!subscribedTopics.containsKey(topicName)) {
terminatedDataNodeIdsByTopic.remove(topicName);
return;
}
final Set<Integer> terminated =
terminatedDataNodeIdsByTopic.computeIfAbsent(
topicName, ignored -> ConcurrentHashMap.newKeySet());
if (dataNodeId >= 0) {
terminated.add(dataNodeId);
}
if (expectedDataNodeIds.isEmpty()
|| !terminated.containsAll(expectedDataNodeIds)
|| !autoUnsubscribingTopics.add(topicName)) {
return;
}
}
try {
LOGGER.info(
SubscriptionMessages
.LOG_TERMINATION_OCCURRED_SUBSCRIPTIONCONSUMER_ARG_POLLING_TOPICS_UNSUBSCRIBE_TOPIC_ARG_AUTOMATICALLY_E9B695FA,
coreReportMessage(),
topicName);
unsubscribe(Collections.singleton(topicName), false);
} finally {
autoUnsubscribingTopics.remove(topicName);
}
return;
}
if (terminatedDataNodeIdsByTopic.remove(topicName) != null
&& !subscribedTopics.containsKey(topicName)) {
return;
}

LOGGER.info(
SubscriptionMessages
.LOG_TERMINATION_OCCURRED_SUBSCRIPTIONCONSUMER_ARG_POLLING_TOPICS_UNSUBSCRIBE_TOPIC_ARG_AUTOMATICALLY_E9B695FA,
coreReportMessage(),
topicName);
unsubscribe(Collections.singleton(topicName), false);
}
Comment thread
jt2594838 marked this conversation as resolved.
Resolved

/**
* Returns the latest watermark timestamp received from the server. This tracks the maximum data
* timestamp observed across all polled regions. Returns {@code Long.MIN_VALUE} if no watermark
Expand Down Expand Up @@ -1507,6 +1576,17 @@ private static void mergeTimeSelectedByTable(
private List<SubscriptionPollResponse> pollInternal(
final Set<String> topicNames, final long timeoutMs) throws SubscriptionException {
checkIfFenced();
if (!terminatedDataNodeIdsByTopic.isEmpty()) {
for (final String topicName : new ArrayList<>(topicNames)) {
final Set<Integer> terminated = terminatedDataNodeIdsByTopic.get(topicName);
if (Objects.nonNull(terminated)) {
final Set<Integer> expectedDataNodeIds = getExpectedDataNodeIds();
if (!expectedDataNodeIds.isEmpty() && terminated.containsAll(expectedDataNodeIds)) {
handleProviderTopicTermination(-1, topicName);
}
}
}
}
boolean syncIfUnavailable = false;
providers.acquireReadLock();
try {
Expand All @@ -1517,10 +1597,30 @@ private List<SubscriptionPollResponse> pollInternal(
}
syncIfUnavailable = true;
} else {
final Set<String> effectiveTopicNames;
if (terminatedDataNodeIdsByTopic.isEmpty()) {
effectiveTopicNames = topicNames;
} else {
effectiveTopicNames = new HashSet<>(topicNames.size());
for (final String topicName : topicNames) {
final Set<Integer> terminated = terminatedDataNodeIdsByTopic.get(topicName);
if (Objects.nonNull(terminated)
&& (!subscribedTopics.containsKey(topicName)
|| terminated.contains(provider.getDataNodeId()))) {
continue;
}
effectiveTopicNames.add(topicName);
}
if (effectiveTopicNames.isEmpty()) {
return Collections.emptyList();
}
}
// ignore SubscriptionConnectionException to improve poll auto retry
try {
return provider.poll(topicNames, timeoutMs, buildCurrentProgressByTopic(topicNames));
return provider.poll(
effectiveTopicNames, timeoutMs, buildCurrentProgressByTopic(effectiveTopicNames));
} catch (final SubscriptionConnectionException ignored) {
clearTerminatedProviderStates();
syncIfUnavailable = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
Expand All @@ -51,6 +52,7 @@ final class AbstractSubscriptionProviders {

private final SortedMap<Integer, AbstractSubscriptionProvider> subscriptionProviders =
new ConcurrentSkipListMap<>();
private final Set<Integer> knownClusterDataNodeIds = ConcurrentHashMap.newKeySet();
private final AtomicBoolean isClosing = new AtomicBoolean(false);
private final AtomicBoolean unavailableSyncInFlight = new AtomicBoolean(false);
private final Set<AbstractSubscriptionProvider> providersWithHeartbeatInFlight =
Expand Down Expand Up @@ -90,6 +92,7 @@ void releaseWriteLock() {
/** Caller should ensure that the method is called in the lock {@link #acquireWriteLock()}. */
void openProviders(final AbstractSubscriptionConsumer consumer) throws SubscriptionException {
// close stale providers
consumer.clearTerminatedProviderStates();
closeProviders(false);

final Map<TEndPoint, String> connectionFailures = new LinkedHashMap<>();
Expand Down Expand Up @@ -126,6 +129,8 @@ void openProviders(final AbstractSubscriptionConsumer consumer) throws Subscript
final Map<Integer, TEndPoint> allEndPoints;
try {
allEndPoints = defaultProvider.heartbeat().getEndPoints();
knownClusterDataNodeIds.clear();
knownClusterDataNodeIds.addAll(allEndPoints.keySet());
} catch (final SubscriptionConsumerFencedException e) {
consumer.fence(e);
throw e;
Expand Down Expand Up @@ -197,6 +202,7 @@ void closeProviders() {
void closeProviders(final boolean closeConsumer) {
final List<AbstractSubscriptionProvider> providers = getAllProviders();
subscriptionProviders.clear();
knownClusterDataNodeIds.clear();
for (final AbstractSubscriptionProvider provider : providers) {
try {
if (closeConsumer) {
Expand Down Expand Up @@ -301,6 +307,13 @@ List<AbstractSubscriptionProvider> getAllAvailableProviders() {
.collect(Collectors.toList());
}

/** Caller should ensure that the method is called in the lock {@link #acquireReadLock()}. */
Set<Integer> getExpectedDataNodeIds() {
final Set<Integer> ids = new HashSet<>(knownClusterDataNodeIds);
ids.addAll(subscriptionProviders.keySet());
return ids;
Comment on lines +322 to +324

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 4d3bee9: AbstractSubscriptionProviders.getExpectedDataNodeIds() now returns Collections.emptySet() when knownClusterDataNodeIds is empty so an unproven cluster topology cannot trigger premature global unsubscribe if initial endpoint discovery fails. Added regression test SubscriptionConsumerMultiProviderPollTest#testRetainedSnapshotTerminationWaitsWhenEndpointDiscoveryFailsDuringOpen.

}

/** Caller should ensure that the method is called in the lock {@link #acquireReadLock()}. */
void updateNextDataNodeId() {
final SortedMap<Integer, AbstractSubscriptionProvider> subProviders =
Expand Down Expand Up @@ -367,19 +380,15 @@ private void heartbeatProvider(
synchronized (heartbeatResponseLock) {
consumer.subscribedTopics = resp.getTopics();
for (final String topicName : resp.getTopicNamesToUnsubscribe()) {
LOGGER.info(
SubscriptionMessages
.LOG_TERMINATION_OCCURRED_SUBSCRIPTIONCONSUMER_ARG_POLLING_TOPICS_UNSUBSCRIBE_TOPIC_ARG_AUTOMATICALLY_E9B695FA,
consumer.coreReportMessage(),
topicName);
consumer.unsubscribe(topicName);
consumer.handleProviderTopicTermination(provider.getDataNodeId(), topicName);
}
}
} catch (final SubscriptionConsumerFencedException e) {
if (containsProvider(provider)) {
consumer.fence(e);
}
provider.setUnavailable();
consumer.clearTerminatedProviderStates();
} catch (final Exception e) {
LOGGER.warn(
SubscriptionMessages
Expand All @@ -389,6 +398,7 @@ private void heartbeatProvider(
e,
e);
provider.setUnavailable();
consumer.clearTerminatedProviderStates();
} finally {
providersWithHeartbeatInFlight.remove(provider);
}
Expand Down Expand Up @@ -472,6 +482,8 @@ private void syncInternal(final AbstractSubscriptionConsumer consumer) {
final Map<Integer, TEndPoint> allEndPoints;
try {
allEndPoints = consumer.fetchAllEndPointsWithRedirection();
knownClusterDataNodeIds.clear();
knownClusterDataNodeIds.addAll(allEndPoints.keySet());
} catch (final SubscriptionConsumerFencedException e) {
consumer.fence(e);
return;
Expand Down Expand Up @@ -509,6 +521,7 @@ private void syncInternal(final AbstractSubscriptionConsumer consumer) {

if (Objects.nonNull(provider) && !provider.isAvailable()) {
// Remove unavailable providers before creating replacements in this same sync round.
consumer.clearTerminatedProviderStates();
try {
closeAndRemoveProvider(entry.getKey());
} catch (final Exception e) {
Expand Down Expand Up @@ -544,6 +557,7 @@ private void syncInternal(final AbstractSubscriptionConsumer consumer) {
e);
continue;
}
consumer.clearTerminatedProviderStates();
addProvider(entry.getKey(), newProvider);
}
}
Expand All @@ -552,6 +566,7 @@ private void syncInternal(final AbstractSubscriptionConsumer consumer) {
for (final AbstractSubscriptionProvider provider : getAllProviders()) {
final int dataNodeId = provider.getDataNodeId();
if (!allEndPoints.containsKey(dataNodeId)) {
consumer.clearTerminatedProviderStates();
try {
closeAndRemoveProvider(dataNodeId);
} catch (final Exception e) {
Expand Down
Loading
Loading