Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -115,15 +115,15 @@ public static class TopicMetadataAndConfig {
private final int replicationFactor;
private final Config config;

TopicMetadataAndConfig(Uuid topicId, int numPartitions, int replicationFactor, Config config) {
public TopicMetadataAndConfig(Uuid topicId, int numPartitions, int replicationFactor, Config config) {
this.exception = null;
this.topicId = topicId;
this.numPartitions = numPartitions;
this.replicationFactor = replicationFactor;
this.config = config;
}

TopicMetadataAndConfig(ApiException exception) {
public TopicMetadataAndConfig(ApiException exception) {
this.exception = exception;
this.topicId = Uuid.ZERO_UUID;
this.numPartitions = UNKNOWN;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
public class DeleteTopicsResult {
final Map<String, KafkaFuture<Void>> futures;

DeleteTopicsResult(Map<String, KafkaFuture<Void>> futures) {
protected DeleteTopicsResult(Map<String, KafkaFuture<Void>> futures) {
this.futures = futures;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.apache.kafka.clients.admin.Config;
import org.apache.kafka.clients.admin.ConfigEntry;
import org.apache.kafka.clients.admin.CreateTopicsResult;
import org.apache.kafka.clients.admin.DeleteTopicsResult;
import org.apache.kafka.clients.admin.DescribeConfigsResult;
import org.apache.kafka.clients.admin.DescribeTopicsResult;
import org.apache.kafka.clients.admin.NewTopic;
Expand All @@ -44,6 +45,8 @@
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
Expand Down Expand Up @@ -186,14 +189,23 @@ public ValidationResult validate(final Map<String, InternalTopicConfig> topicCon
);
}

maybeThrowTimeoutException(topicDescriptionsStillToValidate, topicConfigsStillToValidate, deadline);
maybeThrowTimeoutException(
Arrays.asList(topicDescriptionsStillToValidate, topicConfigsStillToValidate),
deadline,
String.format("Could not validate internal topics within %d milliseconds. " +
"This can happen if the Kafka cluster is temporarily not available.", retryTimeoutMs)
);

if (!descriptionsForTopic.isEmpty() || !configsForTopic.isEmpty()) {
Utils.sleep(100);
}
}

maybeSleep(topicDescriptionsStillToValidate, topicConfigsStillToValidate, deadline);
maybeSleep(
Arrays.asList(topicDescriptionsStillToValidate, topicConfigsStillToValidate),
deadline,
"validated"
);
}

log.info("Completed validation of internal topics {}.", topicConfigs.keySet());
Expand All @@ -205,16 +217,16 @@ private <V> void doValidateTopic(final ValidationResult validationResult,
final Map<String, InternalTopicConfig> topicsConfigs,
final Set<String> topicsStillToValidate,
final BiConsumer<InternalTopicConfig, V> validator) {
for (final InternalTopicConfig topicConfig : topicsConfigs.values()) {
final String topicName = topicConfig.name();
for (final String topicName : new HashSet<>(topicsStillToValidate)) {
if (!futuresForTopic.containsKey(topicName)) {
throw new IllegalStateException("Description results do not contain topics to validate. " + BUG_ERROR_MESSAGE);
}
final KafkaFuture<V> future = futuresForTopic.get(topicName);
if (future.isDone()) {
try {
final V brokerSideTopicConfig = future.get();
validator.accept(topicConfig, brokerSideTopicConfig);
final InternalTopicConfig streamsSideTopicConfig = topicsConfigs.get(topicName);
validator.accept(streamsSideTopicConfig, brokerSideTopicConfig);
topicsStillToValidate.remove(topicName);
} catch (final ExecutionException executionException) {
final Throwable cause = executionException.getCause();
Expand Down Expand Up @@ -242,35 +254,6 @@ private <V> void doValidateTopic(final ValidationResult validationResult,
}
}

private void maybeThrowTimeoutException(final Set<String> topicDescriptionsStillToValidate,
final Set<String> topicConfigsStillToValidate,
final long deadline) {
if (!topicDescriptionsStillToValidate.isEmpty() || !topicConfigsStillToValidate.isEmpty()) {
final long now = time.milliseconds();
if (now >= deadline) {
final String timeoutError = String.format("Could not validate internal topics within %d milliseconds. " +
"This can happen if the Kafka cluster is temporarily not available.", retryTimeoutMs);
log.error(timeoutError);
throw new TimeoutException(timeoutError);
}
}
}

private void maybeSleep(final Set<String> topicDescriptionsStillToValidate,
final Set<String> topicConfigsStillToValidate,
final long deadline) {
if (!topicDescriptionsStillToValidate.isEmpty() || !topicConfigsStillToValidate.isEmpty()) {
final long now = time.milliseconds();
log.info(
"Internal topics {} could not be validated. Will retry in {} milliseconds. Remaining time in milliseconds: {}",
new HashSet<>(topicDescriptionsStillToValidate).addAll(topicConfigsStillToValidate),
retryBackOffMs,
deadline - now
);
Utils.sleep(retryBackOffMs);
}
}

private void validatePartitionCount(final ValidationResult validationResult,
final InternalTopicConfig topicConfig,
final TopicDescription topicDescription) {
Expand Down Expand Up @@ -580,4 +563,219 @@ private Set<String> validateTopics(final Set<String> topicsToValidate,

return topicsToCreate;
}

/**
* Sets up internal topics.
*
* Either the given topic are all created or the method fails with an exception.
*
* @param topicConfigs internal topics to setup
*/
public void setup(final Map<String, InternalTopicConfig> topicConfigs) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should we make an effort to clean up created topics on failure? currently this method is not retriable

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, I agree that cleaning up would be a good idea.

log.info("Starting to setup internal topics {}.", topicConfigs.keySet());

final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;

final Map<String, Map<String, String>> streamsSideTopicConfigs = topicConfigs.values().stream()
.collect(Collectors.toMap(
InternalTopicConfig::name,
topicConfig -> topicConfig.getProperties(defaultTopicConfigs, windowChangeLogAdditionalRetention)
));
final Set<String> createdTopics = new HashSet<>();
final Set<String> topicStillToCreate = new HashSet<>(topicConfigs.keySet());
while (!topicStillToCreate.isEmpty()) {
final Set<NewTopic> newTopics = topicStillToCreate.stream()
.map(topicName -> new NewTopic(
topicName,
topicConfigs.get(topicName).numberOfPartitions(),
Optional.of(replicationFactor)
).configs(streamsSideTopicConfigs.get(topicName))
).collect(Collectors.toSet());

log.info("Going to create internal topics: " + newTopics);
final CreateTopicsResult createTopicsResult = adminClient.createTopics(newTopics);

processCreateTopicResults(createTopicsResult, topicStillToCreate, createdTopics, deadline);

maybeSleep(Collections.singletonList(topicStillToCreate), deadline, "created");
}

log.info("Completed setup of internal topics {}.", topicConfigs.keySet());
}

private void processCreateTopicResults(final CreateTopicsResult createTopicsResult,
final Set<String> topicStillToCreate,
final Set<String> createdTopics,
final long deadline) {
final Map<String, Throwable> lastErrorsSeenForTopic = new HashMap<>();
final Map<String, KafkaFuture<Void>> createResultForTopic = createTopicsResult.values();
while (!createResultForTopic.isEmpty()) {
for (final String topicName : new HashSet<>(topicStillToCreate)) {
if (!createResultForTopic.containsKey(topicName)) {
cleanUpCreatedTopics(createdTopics);
throw new IllegalStateException("Create topic results do not contain internal topic " + topicName
+ " to setup. " + BUG_ERROR_MESSAGE);
}
final KafkaFuture<Void> createResult = createResultForTopic.get(topicName);
if (createResult.isDone()) {
try {
createResult.get();
createdTopics.add(topicName);
topicStillToCreate.remove(topicName);
} catch (final ExecutionException executionException) {
final Throwable cause = executionException.getCause();
if (cause instanceof TopicExistsException) {
lastErrorsSeenForTopic.put(topicName, cause);
log.info("Internal topic {} already exists. Topic is probably marked for deletion. " +
"Will retry to create this topic later (to let broker complete async delete operation first)",
topicName);
} else if (cause instanceof TimeoutException) {
lastErrorsSeenForTopic.put(topicName, cause);
log.info("Creating internal topic {} timed out.", topicName);
} else {
cleanUpCreatedTopics(createdTopics);
log.error("Unexpected error during creation of internal topic: ", cause);
throw new StreamsException(
String.format("Could not create internal topic %s for the following reason: ", topicName),
cause
);
}
} catch (final InterruptedException interruptedException) {
throw new InterruptException(interruptedException);
} finally {
createResultForTopic.remove(topicName);
}
}
}

maybeThrowTimeoutExceptionDuringSetup(
topicStillToCreate,
createdTopics,
lastErrorsSeenForTopic,
deadline
);

if (!createResultForTopic.isEmpty()) {
Utils.sleep(100);
}
}
}

private void cleanUpCreatedTopics(final Set<String> topicsToCleanUp) {
log.info("Starting to clean up internal topics {}.", topicsToCleanUp);

final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;

final Set<String> topicsStillToCleanup = new HashSet<>(topicsToCleanUp);
while (!topicsStillToCleanup.isEmpty()) {
log.info("Going to cleanup internal topics: " + topicsStillToCleanup);
final DeleteTopicsResult deleteTopicsResult = adminClient.deleteTopics(topicsStillToCleanup);
final Map<String, KafkaFuture<Void>> deleteResultForTopic = deleteTopicsResult.values();
while (!deleteResultForTopic.isEmpty()) {
for (final String topicName : new HashSet<>(topicsStillToCleanup)) {
if (!deleteResultForTopic.containsKey(topicName)) {
throw new IllegalStateException("Delete topic results do not contain internal topic " + topicName
+ " to clean up. " + BUG_ERROR_MESSAGE);
}
final KafkaFuture<Void> deleteResult = deleteResultForTopic.get(topicName);
if (deleteResult.isDone()) {
try {
deleteResult.get();
topicsStillToCleanup.remove(topicName);
} catch (final ExecutionException executionException) {
final Throwable cause = executionException.getCause();
if (cause instanceof UnknownTopicOrPartitionException) {
log.info("Internal topic {} to clean up is missing", topicName);
} else if (cause instanceof LeaderNotAvailableException) {
log.info("The leader of internal topic {} to clean up is not available.", topicName);
} else if (cause instanceof TimeoutException) {
log.info("Cleaning up internal topic {} timed out.", topicName);
} else {
log.error("Unexpected error during cleanup of internal topics: ", cause);
throw new StreamsException(
String.format("Could not clean up internal topics %s, because during the cleanup " +
"of topic %s the following error occurred: ",
topicsStillToCleanup, topicName),
cause
);
}
} catch (final InterruptedException interruptedException) {
throw new InterruptException(interruptedException);
} finally {
deleteResultForTopic.remove(topicName);
}
}
}

maybeThrowTimeoutException(
Collections.singletonList(topicsStillToCleanup),
deadline,
String.format("Could not cleanup internal topics within %d milliseconds. This can happen if the " +
"Kafka cluster is temporarily not available or the broker did not complete topic creation " +
"before the cleanup. The following internal topics could not be cleaned up: %s",
retryTimeoutMs, topicsStillToCleanup)
);

if (!deleteResultForTopic.isEmpty()) {
Utils.sleep(100);
}
}

maybeSleep(
Collections.singletonList(topicsStillToCleanup),
deadline,
"validated"
);
}

log.info("Completed cleanup of internal topics {}.", topicsToCleanUp);
}

private void maybeThrowTimeoutException(final List<Set<String>> topicStillToProcess,
final long deadline,
final String errorMessage) {
if (topicStillToProcess.stream().anyMatch(resultSet -> !resultSet.isEmpty())) {
final long now = time.milliseconds();
if (now >= deadline) {
log.error(errorMessage);
throw new TimeoutException(errorMessage);
}
}
}

private void maybeThrowTimeoutExceptionDuringSetup(final Set<String> topicStillToProcess,
final Set<String> createdTopics,
final Map<String, Throwable> lastErrorsSeenForTopic,
final long deadline) {
if (topicStillToProcess.stream().anyMatch(resultSet -> !resultSet.isEmpty())) {
final long now = time.milliseconds();
if (now >= deadline) {
cleanUpCreatedTopics(createdTopics);
final String errorMessage = String.format("Could not create internal topics within %d milliseconds. This can happen if the " +
"Kafka cluster is temporarily not available or a topic is marked for deletion and the broker " +
"did not complete its deletion within the timeout. The last errors seen per topic are: %s",
retryTimeoutMs, lastErrorsSeenForTopic);
log.error(errorMessage);
throw new TimeoutException(errorMessage);
}
}
}

private void maybeSleep(final List<Set<String>> resultSetsStillToValidate,
final long deadline,
final String action) {
if (resultSetsStillToValidate.stream().anyMatch(resultSet -> !resultSet.isEmpty())) {
final long now = time.milliseconds();
log.info(
"Internal topics {} could not be {}. Will retry in {} milliseconds. Remaining time in milliseconds: {}",
resultSetsStillToValidate.stream().flatMap(Collection::stream).collect(Collectors.toSet()),
action,
retryBackOffMs,
deadline - now
);
Utils.sleep(retryBackOffMs);
}
}
}
Loading