You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by da...@apache.org on 2023/07/07 20:21:37 UTC
[kafka] branch trunk updated: KAFKA-14462; [21/N] Add CoordinatorTimer implementation in CoordinatorRuntime (#13961)
This is an automated email from the ASF dual-hosted git repository.
dajac pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/kafka.git
The following commit(s) were added to refs/heads/trunk by this push:
new 9cde3a79107 KAFKA-14462; [21/N] Add CoordinatorTimer implementation in CoordinatorRuntime (#13961)
9cde3a79107 is described below
commit 9cde3a79107130a13a215bf65d6b2b8df93757aa
Author: David Jacot <dj...@confluent.io>
AuthorDate: Fri Jul 7 22:21:30 2023 +0200
KAFKA-14462; [21/N] Add CoordinatorTimer implementation in CoordinatorRuntime (#13961)
This patch adds EventBasedCoordinatorTimer and the CoordinatorTimer interface.
Reviewers: Jeff Kim <je...@confluent.io>, Justine Olshan <jo...@confluent.io>
---
.../coordinator/group/GroupCoordinatorService.java | 18 +
.../coordinator/group/GroupMetadataManager.java | 22 +-
.../group/ReplicatedGroupCoordinator.java | 26 ++
.../group/runtime/CoordinatorBuilder.java | 23 +
.../group/runtime/CoordinatorResult.java | 4 +-
.../group/runtime/CoordinatorRuntime.java | 187 +++++++-
.../runtime/{Timer.java => CoordinatorTimer.java} | 23 +-
.../group/GroupMetadataManagerTest.java | 12 +
.../group/runtime/CoordinatorResultTest.java | 3 +-
.../group/runtime/CoordinatorRuntimeTest.java | 479 ++++++++++++++++++++-
10 files changed, 761 insertions(+), 36 deletions(-)
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index 0c926bbf658..fd3969b3957 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -53,6 +53,7 @@ import org.apache.kafka.common.requests.RequestContext;
import org.apache.kafka.common.requests.TransactionResult;
import org.apache.kafka.common.utils.BufferSupplier;
import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.coordinator.group.runtime.CoordinatorBuilderSupplier;
import org.apache.kafka.coordinator.group.runtime.CoordinatorEventProcessor;
@@ -64,6 +65,7 @@ import org.apache.kafka.image.MetadataDelta;
import org.apache.kafka.image.MetadataImage;
import org.apache.kafka.server.record.BrokerCompressionType;
import org.apache.kafka.server.util.FutureUtils;
+import org.apache.kafka.server.util.timer.Timer;
import org.slf4j.Logger;
import java.util.List;
@@ -83,6 +85,8 @@ public class GroupCoordinatorService implements GroupCoordinator {
private final GroupCoordinatorConfig config;
private PartitionWriter<Record> writer;
private CoordinatorLoader<Record> loader;
+ private Time time;
+ private Timer timer;
public Builder(
int nodeId,
@@ -102,6 +106,16 @@ public class GroupCoordinatorService implements GroupCoordinator {
return this;
}
+ public Builder withTime(Time time) {
+ this.time = time;
+ return this;
+ }
+
+ public Builder withTimer(Timer timer) {
+ this.timer = timer;
+ return this;
+ }
+
public GroupCoordinatorService build() {
if (config == null)
throw new IllegalArgumentException("Config must be set.");
@@ -109,6 +123,10 @@ public class GroupCoordinatorService implements GroupCoordinator {
throw new IllegalArgumentException("Writer must be set.");
if (loader == null)
throw new IllegalArgumentException("Loader must be set.");
+ if (timer == null)
+ throw new IllegalArgumentException("Timer must be set.");
+ if (time == null)
+ throw new IllegalArgumentException("Time must be set.");
String logPrefix = String.format("GroupCoordinator id=%d ", nodeId);
LogContext logContext = new LogContext(String.format("[%s ]", logPrefix));
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 3f57faa19f7..e8a424c825e 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -51,6 +51,7 @@ import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmen
import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
import org.apache.kafka.coordinator.group.runtime.CoordinatorResult;
+import org.apache.kafka.coordinator.group.runtime.CoordinatorTimer;
import org.apache.kafka.image.MetadataDelta;
import org.apache.kafka.image.MetadataImage;
import org.apache.kafka.image.TopicImage;
@@ -94,6 +95,7 @@ public class GroupMetadataManager {
private LogContext logContext = null;
private SnapshotRegistry snapshotRegistry = null;
private Time time = null;
+ private CoordinatorTimer<Record> timer = null;
private List<PartitionAssignor> assignors = null;
private int consumerGroupMaxSize = Integer.MAX_VALUE;
private int consumerGroupHeartbeatIntervalMs = 5000;
@@ -115,6 +117,11 @@ public class GroupMetadataManager {
return this;
}
+ Builder withTimer(CoordinatorTimer<Record> timer) {
+ this.timer = timer;
+ return this;
+ }
+
Builder withAssignors(List<PartitionAssignor> assignors) {
this.assignors = assignors;
return this;
@@ -146,14 +153,16 @@ public class GroupMetadataManager {
if (metadataImage == null) metadataImage = MetadataImage.EMPTY;
if (time == null) time = Time.SYSTEM;
- if (assignors == null || assignors.isEmpty()) {
- throw new IllegalStateException("Assignors must be set before building.");
- }
+ if (timer == null)
+ throw new IllegalArgumentException("Timer must be set.");
+ if (assignors == null || assignors.isEmpty())
+ throw new IllegalArgumentException("Assignors must be set before building.");
return new GroupMetadataManager(
snapshotRegistry,
logContext,
time,
+ timer,
assignors,
metadataImage,
consumerGroupMaxSize,
@@ -178,6 +187,11 @@ public class GroupMetadataManager {
*/
private final Time time;
+ /**
+ * The system timer.
+ */
+ private final CoordinatorTimer<Record> timer;
+
/**
* The supported partition assignors keyed by their name.
*/
@@ -222,6 +236,7 @@ public class GroupMetadataManager {
SnapshotRegistry snapshotRegistry,
LogContext logContext,
Time time,
+ CoordinatorTimer<Record> timer,
List<PartitionAssignor> assignors,
MetadataImage metadataImage,
int consumerGroupMaxSize,
@@ -231,6 +246,7 @@ public class GroupMetadataManager {
this.log = logContext.logger(GroupMetadataManager.class);
this.snapshotRegistry = snapshotRegistry;
this.time = time;
+ this.timer = timer;
this.metadataImage = metadataImage;
this.assignors = assignors.stream().collect(Collectors.toMap(PartitionAssignor::name, Function.identity()));
this.defaultAssignor = assignors.get(0);
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/ReplicatedGroupCoordinator.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/ReplicatedGroupCoordinator.java
index 201da405e6d..0b5ae843952 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/ReplicatedGroupCoordinator.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/ReplicatedGroupCoordinator.java
@@ -21,6 +21,7 @@ import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
import org.apache.kafka.common.protocol.ApiMessage;
import org.apache.kafka.common.requests.RequestContext;
import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentKey;
import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataKey;
@@ -36,6 +37,7 @@ import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmen
import org.apache.kafka.coordinator.group.runtime.Coordinator;
import org.apache.kafka.coordinator.group.runtime.CoordinatorBuilder;
import org.apache.kafka.coordinator.group.runtime.CoordinatorResult;
+import org.apache.kafka.coordinator.group.runtime.CoordinatorTimer;
import org.apache.kafka.image.MetadataDelta;
import org.apache.kafka.image.MetadataImage;
import org.apache.kafka.server.common.ApiMessageAndVersion;
@@ -57,6 +59,8 @@ public class ReplicatedGroupCoordinator implements Coordinator<Record> {
private final GroupCoordinatorConfig config;
private LogContext logContext;
private SnapshotRegistry snapshotRegistry;
+ private Time time;
+ private CoordinatorTimer<Record> timer;
public Builder(
GroupCoordinatorConfig config
@@ -72,6 +76,22 @@ public class ReplicatedGroupCoordinator implements Coordinator<Record> {
return this;
}
+ @Override
+ public CoordinatorBuilder<ReplicatedGroupCoordinator, Record> withTime(
+ Time time
+ ) {
+ this.time = time;
+ return this;
+ }
+
+ @Override
+ public CoordinatorBuilder<ReplicatedGroupCoordinator, Record> withTimer(
+ CoordinatorTimer<Record> timer
+ ) {
+ this.timer = timer;
+ return this;
+ }
+
@Override
public CoordinatorBuilder<ReplicatedGroupCoordinator, Record> withSnapshotRegistry(
SnapshotRegistry snapshotRegistry
@@ -87,11 +107,17 @@ public class ReplicatedGroupCoordinator implements Coordinator<Record> {
throw new IllegalArgumentException("Config must be set.");
if (snapshotRegistry == null)
throw new IllegalArgumentException("SnapshotRegistry must be set.");
+ if (time == null)
+ throw new IllegalArgumentException("Time must be set.");
+ if (timer == null)
+ throw new IllegalArgumentException("Timer must be set.");
return new ReplicatedGroupCoordinator(
new GroupMetadataManager.Builder()
.withLogContext(logContext)
.withSnapshotRegistry(snapshotRegistry)
+ .withTime(time)
+ .withTimer(timer)
.withAssignors(config.consumerGroupAssignors)
.withConsumerGroupMaxSize(config.consumerGroupMaxSize)
.withConsumerGroupHeartbeatInterval(config.consumerGroupHeartbeatIntervalMs)
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorBuilder.java
index 6dd2288928a..8c9cf431544 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorBuilder.java
@@ -17,6 +17,7 @@
package org.apache.kafka.coordinator.group.runtime;
import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
import org.apache.kafka.timeline.SnapshotRegistry;
/**
@@ -50,6 +51,28 @@ public interface CoordinatorBuilder<S extends Coordinator<U>, U> {
LogContext logContext
);
+ /**
+ * Sets the time.
+ *
+ * @param time The system time.
+ *
+ * @return The builder.
+ */
+ CoordinatorBuilder<S, U> withTime(
+ Time time
+ );
+
+ /**
+ * Sets the coordinator timer.
+ *
+ * @param timer The coordinator timer.
+ *
+ * @return The builder.
+ */
+ CoordinatorBuilder<S, U> withTimer(
+ CoordinatorTimer<U> timer
+ );
+
/**
* @return The built coordinator.
*/
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorResult.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorResult.java
index 40d1e566c6f..cc24296d7a4 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorResult.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorResult.java
@@ -41,14 +41,14 @@ public class CoordinatorResult<T, U> {
* Constructs a Result with records and a response.
*
* @param records A non-null list of records.
- * @param response A non-null response.
+ * @param response A response or null.
*/
public CoordinatorResult(
List<U> records,
T response
) {
this.records = Objects.requireNonNull(records);
- this.response = Objects.requireNonNull(response);
+ this.response = response;
}
/**
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorRuntime.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorRuntime.java
index 00c8937f436..5c2a4c130fa 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorRuntime.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorRuntime.java
@@ -22,19 +22,27 @@ import org.apache.kafka.common.errors.CoordinatorLoadInProgressException;
import org.apache.kafka.common.errors.NotCoordinatorException;
import org.apache.kafka.common.protocol.Errors;
import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.deferred.DeferredEvent;
import org.apache.kafka.deferred.DeferredEventQueue;
import org.apache.kafka.image.MetadataDelta;
import org.apache.kafka.image.MetadataImage;
+import org.apache.kafka.server.util.timer.Timer;
+import org.apache.kafka.server.util.timer.TimerTask;
import org.apache.kafka.timeline.SnapshotRegistry;
import org.slf4j.Logger;
+import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
@@ -77,6 +85,8 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
private PartitionWriter<U> partitionWriter;
private CoordinatorLoader<U> loader;
private CoordinatorBuilderSupplier<S, U> coordinatorBuilderSupplier;
+ private Time time;
+ private Timer timer;
public Builder<S, U> withLogPrefix(String logPrefix) {
this.logPrefix = logPrefix;
@@ -108,6 +118,16 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
return this;
}
+ public Builder<S, U> withTime(Time time) {
+ this.time = time;
+ return this;
+ }
+
+ public Builder<S, U> withTimer(Timer timer) {
+ this.timer = timer;
+ return this;
+ }
+
public CoordinatorRuntime<S, U> build() {
if (logPrefix == null)
logPrefix = "";
@@ -121,6 +141,10 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
throw new IllegalArgumentException("Loader must be set.");
if (coordinatorBuilderSupplier == null)
throw new IllegalArgumentException("State machine supplier must be set.");
+ if (time == null)
+ throw new IllegalArgumentException("Time must be set.");
+ if (timer == null)
+ throw new IllegalArgumentException("Timer must be set.");
return new CoordinatorRuntime<>(
logPrefix,
@@ -128,7 +152,9 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
eventProcessor,
partitionWriter,
loader,
- coordinatorBuilderSupplier
+ coordinatorBuilderSupplier,
+ time,
+ timer
);
}
}
@@ -190,6 +216,133 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
abstract boolean canTransitionFrom(CoordinatorState state);
}
+ /**
+ * The EventBasedCoordinatorTimer implements the CoordinatorTimer interface and provides an event based
+ * timer which turns timeouts of a regular {@link Timer} into {@link CoordinatorWriteEvent} events which
+ * are executed by the {@link CoordinatorEventProcessor} used by this coordinator runtime. This is done
+ * to ensure that the timer respects the threading model of the coordinator runtime.
+ *
+ * The {@link CoordinatorWriteEvent} events pushed by the coordinator timer wraps the
+ * {@link TimeoutOperation} operations scheduled by the coordinators.
+ *
+ * It also keeps track of all the scheduled {@link TimerTask}. This allows timeout operations to be
+ * cancelled or rescheduled. When a timer is cancelled or overridden, the previous timer is guaranteed to
+ * not be executed even if it already expired and got pushed to the event processor.
+ *
+ * When a timer fails with an unexpected exception, the timer is rescheduled with a backoff.
+ */
+ class EventBasedCoordinatorTimer implements CoordinatorTimer<U> {
+ /**
+ * The logger.
+ */
+ final Logger log;
+
+ /**
+ * The topic partition.
+ */
+ final TopicPartition tp;
+
+ /**
+ * The scheduled timers keyed by their key.
+ */
+ final Map<String, TimerTask> tasks = new HashMap<>();
+
+ EventBasedCoordinatorTimer(TopicPartition tp, LogContext logContext) {
+ this.tp = tp;
+ this.log = logContext.logger(EventBasedCoordinatorTimer.class);
+ }
+
+ @Override
+ public void schedule(
+ String key,
+ long delay,
+ TimeUnit unit,
+ boolean retry,
+ TimeoutOperation<U> operation
+ ) {
+ // The TimerTask wraps the TimeoutOperation into a CoordinatorWriteEvent. When the TimerTask
+ // expires, the event is pushed to the queue of the coordinator runtime to be executed. This
+ // ensures that the threading model of the runtime is respected.
+ TimerTask task = new TimerTask(unit.toMillis(delay)) {
+ @Override
+ public void run() {
+ String eventName = "Timeout(tp=" + tp + ", key=" + key + ")";
+ CoordinatorWriteEvent<Void> event = new CoordinatorWriteEvent<>(eventName, tp, coordinator -> {
+ log.debug("Executing write event {} for timer {}.", eventName, key);
+
+ // If the task is different, it means that the timer has been
+ // cancelled while the event was waiting to be processed.
+ if (!tasks.remove(key, this)) {
+ throw new RejectedExecutionException("Timer " + key + " was overridden or cancelled");
+ }
+
+ // Execute the timeout operation.
+ return new CoordinatorResult<>(operation.generateRecords(), null);
+ });
+
+ // If the write event fails, it is rescheduled with a small backoff except if the
+ // error is fatal.
+ event.future.exceptionally(ex -> {
+ if (ex instanceof RejectedExecutionException) {
+ log.debug("The write event {} for the timer {} was not executed because it was " +
+ "cancelled or overridden.", event.name, key);
+ return null;
+ }
+
+ if (ex instanceof NotCoordinatorException || ex instanceof CoordinatorLoadInProgressException) {
+ log.debug("The write event {} for the timer {} failed due to {}. Ignoring it because " +
+ "the coordinator is not active.", event.name, key, ex.getMessage());
+ return null;
+ }
+
+ if (retry) {
+ log.info("The write event {} for the timer {} failed due to {}. Rescheduling it. ",
+ event.name, key, ex.getMessage());
+ schedule(key, 500, TimeUnit.MILLISECONDS, retry, operation);
+ } else {
+ log.error("The write event {} for the timer {} failed due to {}. Ignoring it. ",
+ event.name, key, ex.getMessage());
+ }
+
+ return null;
+ });
+
+ log.debug("Scheduling write event {} for timer {}.", event.name, key);
+ try {
+ enqueue(event);
+ } catch (NotCoordinatorException ex) {
+ log.info("Failed to enqueue write event {} for timer {} because the runtime is closed. Ignoring it.",
+ event.name, key);
+ }
+ }
+ };
+
+ log.debug("Registering timer {} with delay of {}ms.", key, unit.toMillis(delay));
+ TimerTask prevTask = tasks.put(key, task);
+ if (prevTask != null) prevTask.cancel();
+
+ timer.add(task);
+ }
+
+ @Override
+ public void cancel(String key) {
+ TimerTask prevTask = tasks.remove(key);
+ if (prevTask != null) prevTask.cancel();
+ }
+
+ public void cancelAll() {
+ Iterator<Map.Entry<String, TimerTask>> iterator = tasks.entrySet().iterator();
+ while (iterator.hasNext()) {
+ iterator.next().getValue().cancel();
+ iterator.remove();
+ }
+ }
+
+ public int size() {
+ return tasks.size();
+ }
+ }
+
/**
* CoordinatorContext holds all the metadata around a coordinator state machine.
*/
@@ -215,6 +368,11 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
*/
final DeferredEventQueue deferredEventQueue;
+ /**
+ * The coordinator timer.
+ */
+ final EventBasedCoordinatorTimer timer;
+
/**
* The current state.
*/
@@ -258,6 +416,7 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
));
this.snapshotRegistry = new SnapshotRegistry(logContext);
this.deferredEventQueue = new DeferredEventQueue(logContext);
+ this.timer = new EventBasedCoordinatorTimer(tp, logContext);
this.state = CoordinatorState.INITIAL;
this.epoch = -1;
this.lastWrittenOffset = 0L;
@@ -344,6 +503,8 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
.get()
.withLogContext(logContext)
.withSnapshotRegistry(snapshotRegistry)
+ .withTime(time)
+ .withTimer(timer)
.build();
break;
@@ -374,6 +535,7 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
*/
private void unload() {
partitionWriter.deregisterListener(tp, highWatermarklistener);
+ timer.cancelAll();
deferredEventQueue.failAll(Errors.NOT_COORDINATOR.exception());
if (coordinator != null) {
coordinator.onUnloaded();
@@ -772,6 +934,16 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
*/
private final Logger log;
+ /**
+ * The system time.
+ */
+ private final Time time;
+
+ /**
+ * The system timer.
+ */
+ private final Timer timer;
+
/**
* The coordinators keyed by topic partition.
*/
@@ -823,6 +995,8 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
* @param partitionWriter The partition writer.
* @param loader The coordinator loader.
* @param coordinatorBuilderSupplier The coordinator builder.
+ * @param time The system time.
+ * @param timer The system timer.
*/
private CoordinatorRuntime(
String logPrefix,
@@ -830,11 +1004,15 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
CoordinatorEventProcessor processor,
PartitionWriter<U> partitionWriter,
CoordinatorLoader<U> loader,
- CoordinatorBuilderSupplier<S, U> coordinatorBuilderSupplier
+ CoordinatorBuilderSupplier<S, U> coordinatorBuilderSupplier,
+ Time time,
+ Timer timer
) {
this.logPrefix = logPrefix;
this.logContext = logContext;
this.log = logContext.logger(CoordinatorRuntime.class);
+ this.time = time;
+ this.timer = timer;
this.coordinators = new ConcurrentHashMap<>();
this.processor = processor;
this.partitionWriter = partitionWriter;
@@ -1134,10 +1312,11 @@ public class CoordinatorRuntime<S extends Coordinator<U>, U> implements AutoClos
}
log.info("Closing coordinator runtime.");
- loader.close();
+ Utils.closeQuietly(loader, "loader");
+ Utils.closeQuietly(timer, "timer");
// This close the processor, drain all the pending events and
// reject any new events.
- processor.close();
+ Utils.closeQuietly(processor, "event processor");
// Unload all the coordinators.
coordinators.forEach((tp, context) -> {
context.transitionTo(CoordinatorState.CLOSED);
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/Timer.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorTimer.java
similarity index 61%
rename from group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/Timer.java
rename to group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorTimer.java
index f6aac982d11..ff718259b2f 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/Timer.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/runtime/CoordinatorTimer.java
@@ -16,12 +16,29 @@
*/
package org.apache.kafka.coordinator.group.runtime;
+import org.apache.kafka.common.KafkaException;
+
+import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* An interface to schedule and cancel operations.
*/
-public interface Timer {
+public interface CoordinatorTimer<U> {
+ /**
+ * Generates the records needed to implement this timeout write operation. In general,
+ * this operation should not modify the hard state of the coordinator. That modifications
+ * will happen later on, when the records generated by this function are applied to the
+ * coordinator.
+ *
+ * A typical example of timeout operation is the session timeout used by the consumer
+ * group rebalance protocol.
+ *
+ * @param <T> The record type.
+ */
+ interface TimeoutOperation<T> {
+ List<T> generateRecords() throws KafkaException;
+ }
/**
* Add an operation to the timer. If an operation with the same key
@@ -30,9 +47,11 @@ public interface Timer {
* @param key The key to identify this operation.
* @param delay The delay to wait before expiring.
* @param unit The delay unit.
+ * @param retry A boolean indicating whether the operation should
+ * be retried on failure.
* @param operation The operation to perform upon expiration.
*/
- void schedule(String key, long delay, TimeUnit unit, Runnable operation);
+ void schedule(String key, long delay, TimeUnit unit, boolean retry, TimeoutOperation<U> operation);
/**
* Remove an operation corresponding to a given key.
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index 41c2b1cb8be..7241d9741ab 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -62,6 +62,7 @@ import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmen
import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
import org.apache.kafka.coordinator.group.runtime.CoordinatorResult;
+import org.apache.kafka.coordinator.group.runtime.CoordinatorTimer;
import org.apache.kafka.image.MetadataDelta;
import org.apache.kafka.image.MetadataImage;
import org.apache.kafka.image.MetadataProvenance;
@@ -82,6 +83,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import java.util.concurrent.TimeUnit;
import static org.apache.kafka.common.utils.Utils.mkSet;
import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkAssignment;
@@ -98,6 +100,15 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class GroupMetadataManagerTest {
+ // Timer is not used yet so an empty mock is fine for now.
+ static class MockCoordinatorTimer implements CoordinatorTimer<Record> {
+ @Override
+ public void schedule(String key, long delay, TimeUnit unit, boolean retry, TimeoutOperation<Record> operation) {}
+
+ @Override
+ public void cancel(String key) {}
+ }
+
static class MockPartitionAssignor implements PartitionAssignor {
private final String name;
private GroupAssignment prepareGroupAssignment = null;
@@ -273,6 +284,7 @@ public class GroupMetadataManagerTest {
.withSnapshotRegistry(snapshotRegistry)
.withLogContext(logContext)
.withTime(time)
+ .withTimer(new MockCoordinatorTimer())
.withMetadataImage(metadataImage)
.withConsumerGroupHeartbeatInterval(5000)
.withConsumerGroupMaxSize(consumerGroupMaxSize)
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/runtime/CoordinatorResultTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/runtime/CoordinatorResultTest.java
index 7d9b19b1cd8..f45a4be62d5 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/runtime/CoordinatorResultTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/runtime/CoordinatorResultTest.java
@@ -33,8 +33,7 @@ public class CoordinatorResultTest {
}
@Test
- public void testAttributesCannotBeNull() {
- assertThrows(NullPointerException.class, () -> new CoordinatorResult<>(Collections.emptyList(), null));
+ public void testRecordsCannotBeNull() {
assertThrows(NullPointerException.class, () -> new CoordinatorResult<>(null, "response"));
}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/runtime/CoordinatorRuntimeTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/runtime/CoordinatorRuntimeTest.java
index c130fa474ad..fa8529154a5 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/runtime/CoordinatorRuntimeTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/runtime/CoordinatorRuntimeTest.java
@@ -20,9 +20,11 @@ import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.NotCoordinatorException;
import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
import org.apache.kafka.image.MetadataDelta;
import org.apache.kafka.image.MetadataImage;
import org.apache.kafka.image.MetadataProvenance;
+import org.apache.kafka.server.util.timer.MockTimer;
import org.apache.kafka.timeline.SnapshotRegistry;
import org.apache.kafka.timeline.TimelineHashSet;
import org.junit.jupiter.api.Test;
@@ -30,14 +32,17 @@ import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
+import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
+import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.kafka.common.utils.Utils.mkSet;
import static org.apache.kafka.test.TestUtils.assertFutureThrows;
@@ -57,10 +62,10 @@ public class CoordinatorRuntimeTest {
private static final TopicPartition TP = new TopicPartition("__consumer_offsets", 0);
/**
- * An CoordinatorEventProcessor that directly executes the operations. This is
+ * A CoordinatorEventProcessor that directly executes the operations. This is
* useful in unit tests where execution in threads is not required.
*/
- private static class MockEventProcessor implements CoordinatorEventProcessor {
+ private static class DirectEventProcessor implements CoordinatorEventProcessor {
@Override
public void enqueue(CoordinatorEvent event) throws RejectedExecutionException {
try {
@@ -74,6 +79,41 @@ public class CoordinatorRuntimeTest {
public void close() throws Exception {}
}
+ /**
+ * A CoordinatorEventProcessor that queues event and execute the next one
+ * when poll() is called.
+ */
+ private static class ManualEventProcessor implements CoordinatorEventProcessor {
+ private Queue<CoordinatorEvent> queue = new LinkedList<>();
+
+ @Override
+ public void enqueue(CoordinatorEvent event) throws RejectedExecutionException {
+ queue.add(event);
+ }
+
+ public boolean poll() {
+ CoordinatorEvent event = queue.poll();
+ if (event == null) return false;
+
+ try {
+ event.run();
+ } catch (Throwable ex) {
+ event.complete(ex);
+ }
+
+ return true;
+ }
+
+ public int size() {
+ return queue.size();
+ }
+
+ @Override
+ public void close() throws Exception {
+
+ }
+ }
+
/**
* A CoordinatorLoader that always succeeds.
*/
@@ -128,11 +168,14 @@ public class CoordinatorRuntimeTest {
*/
private static class MockCoordinator implements Coordinator<String> {
private final TimelineHashSet<String> records;
+ private final CoordinatorTimer<String> timer;
MockCoordinator(
- SnapshotRegistry snapshotRegistry
+ SnapshotRegistry snapshotRegistry,
+ CoordinatorTimer<String> timer
) {
- records = new TimelineHashSet<>(snapshotRegistry, 0);
+ this.records = new TimelineHashSet<>(snapshotRegistry, 0);
+ this.timer = timer;
}
@Override
@@ -143,6 +186,10 @@ public class CoordinatorRuntimeTest {
Set<String> records() {
return Collections.unmodifiableSet(new HashSet<>(records));
}
+
+ CoordinatorTimer<String> timer() {
+ return timer;
+ }
}
/**
@@ -150,6 +197,7 @@ public class CoordinatorRuntimeTest {
*/
private static class MockCoordinatorBuilder implements CoordinatorBuilder<MockCoordinator, String> {
private SnapshotRegistry snapshotRegistry;
+ private CoordinatorTimer<String> timer;
@Override
public CoordinatorBuilder<MockCoordinator, String> withSnapshotRegistry(
@@ -166,9 +214,27 @@ public class CoordinatorRuntimeTest {
return this;
}
+ @Override
+ public CoordinatorBuilder<MockCoordinator, String> withTime(
+ Time time
+ ) {
+ return this;
+ }
+
+ @Override
+ public CoordinatorBuilder<MockCoordinator, String> withTimer(
+ CoordinatorTimer<String> timer
+ ) {
+ this.timer = timer;
+ return this;
+ }
+
@Override
public MockCoordinator build() {
- return new MockCoordinator(Objects.requireNonNull(this.snapshotRegistry));
+ return new MockCoordinator(
+ Objects.requireNonNull(this.snapshotRegistry),
+ Objects.requireNonNull(this.timer)
+ );
}
}
@@ -184,6 +250,7 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleLoading() {
+ MockTimer timer = new MockTimer();
MockCoordinatorLoader loader = mock(MockCoordinatorLoader.class);
MockPartitionWriter writer = mock(MockPartitionWriter.class);
MockCoordinatorBuilderSupplier supplier = mock(MockCoordinatorBuilderSupplier.class);
@@ -192,14 +259,18 @@ public class CoordinatorRuntimeTest {
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(loader)
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(writer)
.withCoordinatorBuilderSupplier(supplier)
.build();
when(builder.withSnapshotRegistry(any())).thenReturn(builder);
when(builder.withLogContext(any())).thenReturn(builder);
+ when(builder.withTime(any())).thenReturn(builder);
+ when(builder.withTimer(any())).thenReturn(builder);
when(builder.build()).thenReturn(coordinator);
when(supplier.get()).thenReturn(builder);
CompletableFuture<Void> future = new CompletableFuture<>();
@@ -232,10 +303,17 @@ public class CoordinatorRuntimeTest {
eq(TP),
any(PartitionWriter.Listener.class)
);
+
+ // Verify that the builder got all the expected objects.
+ verify(builder, times(1)).withSnapshotRegistry(eq(ctx.snapshotRegistry));
+ verify(builder, times(1)).withLogContext(eq(ctx.logContext));
+ verify(builder, times(1)).withTime(eq(timer.time()));
+ verify(builder, times(1)).withTimer(eq(ctx.timer));
}
@Test
public void testScheduleLoadingWithFailure() {
+ MockTimer timer = new MockTimer();
MockPartitionWriter writer = mock(MockPartitionWriter.class);
MockCoordinatorLoader loader = mock(MockCoordinatorLoader.class);
MockCoordinatorBuilderSupplier supplier = mock(MockCoordinatorBuilderSupplier.class);
@@ -244,14 +322,18 @@ public class CoordinatorRuntimeTest {
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(loader)
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(writer)
.withCoordinatorBuilderSupplier(supplier)
.build();
when(builder.withSnapshotRegistry(any())).thenReturn(builder);
when(builder.withLogContext(any())).thenReturn(builder);
+ when(builder.withTime(any())).thenReturn(builder);
+ when(builder.withTimer(any())).thenReturn(builder);
when(builder.build()).thenReturn(coordinator);
when(supplier.get()).thenReturn(builder);
CompletableFuture<Void> future = new CompletableFuture<>();
@@ -282,6 +364,7 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleLoadingWithStalePartitionEpoch() {
+ MockTimer timer = new MockTimer();
MockCoordinatorLoader loader = mock(MockCoordinatorLoader.class);
MockCoordinatorBuilderSupplier supplier = mock(MockCoordinatorBuilderSupplier.class);
MockCoordinatorBuilder builder = mock(MockCoordinatorBuilder.class);
@@ -289,14 +372,18 @@ public class CoordinatorRuntimeTest {
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(loader)
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(new MockPartitionWriter())
.withCoordinatorBuilderSupplier(supplier)
.build();
when(builder.withSnapshotRegistry(any())).thenReturn(builder);
when(builder.withLogContext(any())).thenReturn(builder);
+ when(builder.withTime(any())).thenReturn(builder);
+ when(builder.withTimer(any())).thenReturn(builder);
when(builder.build()).thenReturn(coordinator);
when(supplier.get()).thenReturn(builder);
CompletableFuture<Void> future = new CompletableFuture<>();
@@ -325,6 +412,7 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleLoadingAfterLoadingFailure() {
+ MockTimer timer = new MockTimer();
MockCoordinatorLoader loader = mock(MockCoordinatorLoader.class);
MockCoordinatorBuilderSupplier supplier = mock(MockCoordinatorBuilderSupplier.class);
MockCoordinatorBuilder builder = mock(MockCoordinatorBuilder.class);
@@ -332,14 +420,18 @@ public class CoordinatorRuntimeTest {
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(loader)
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(new MockPartitionWriter())
.withCoordinatorBuilderSupplier(supplier)
.build();
when(builder.withSnapshotRegistry(any())).thenReturn(builder);
when(builder.withLogContext(any())).thenReturn(builder);
+ when(builder.withTime(any())).thenReturn(builder);
+ when(builder.withTimer(any())).thenReturn(builder);
when(builder.build()).thenReturn(coordinator);
when(supplier.get()).thenReturn(builder);
CompletableFuture<Void> future = new CompletableFuture<>();
@@ -385,6 +477,7 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleUnloading() {
+ MockTimer timer = new MockTimer();
MockPartitionWriter writer = mock(MockPartitionWriter.class);
MockCoordinatorBuilderSupplier supplier = mock(MockCoordinatorBuilderSupplier.class);
MockCoordinatorBuilder builder = mock(MockCoordinatorBuilder.class);
@@ -392,14 +485,18 @@ public class CoordinatorRuntimeTest {
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(writer)
.withCoordinatorBuilderSupplier(supplier)
.build();
when(builder.withSnapshotRegistry(any())).thenReturn(builder);
when(builder.withLogContext(any())).thenReturn(builder);
+ when(builder.withTime(any())).thenReturn(builder);
+ when(builder.withTimer(any())).thenReturn(builder);
when(builder.build()).thenReturn(coordinator);
when(supplier.get()).thenReturn(builder);
@@ -428,20 +525,27 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleUnloadingWithStalePartitionEpoch() {
+ MockTimer timer = new MockTimer();
MockCoordinatorBuilderSupplier supplier = mock(MockCoordinatorBuilderSupplier.class);
MockCoordinatorBuilder builder = mock(MockCoordinatorBuilder.class);
MockCoordinator coordinator = mock(MockCoordinator.class);
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(new MockPartitionWriter())
.withCoordinatorBuilderSupplier(supplier)
.build();
when(builder.withSnapshotRegistry(any())).thenReturn(builder);
when(builder.withLogContext(any())).thenReturn(builder);
+ when(builder.withTime(any())).thenReturn(builder);
+ when(builder.withTimer(any())).thenReturn(builder);
+ when(builder.withTime(any())).thenReturn(builder);
+ when(builder.withTimer(any())).thenReturn(builder);
when(builder.build()).thenReturn(coordinator);
when(supplier.get()).thenReturn(builder);
@@ -460,12 +564,15 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleWriteOp() throws ExecutionException, InterruptedException, TimeoutException {
+ MockTimer timer = new MockTimer();
MockPartitionWriter writer = new MockPartitionWriter();
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(writer)
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -567,10 +674,13 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleWriteOpWhenInactive() {
+ MockTimer timer = new MockTimer();
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(new MockPartitionWriter())
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -584,10 +694,13 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleWriteOpWhenOpFails() {
+ MockTimer timer = new MockTimer();
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(new MockPartitionWriter())
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -605,10 +718,13 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleWriteOpWhenReplayFails() {
+ MockTimer timer = new MockTimer();
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(new MockPartitionWriter())
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -624,7 +740,7 @@ public class CoordinatorRuntimeTest {
// Override the coordinator with a coordinator that throws
// an exception when replay is called.
- ctx.coordinator = new MockCoordinator(ctx.snapshotRegistry) {
+ ctx.coordinator = new MockCoordinator(ctx.snapshotRegistry, ctx.timer) {
@Override
public void replay(String record) throws RuntimeException {
throw new IllegalArgumentException("error");
@@ -644,13 +760,16 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleWriteOpWhenWriteFails() {
+ MockTimer timer = new MockTimer();
// The partition writer only accept on write.
MockPartitionWriter writer = new MockPartitionWriter(2);
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(writer)
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -689,12 +808,15 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleReadOp() throws ExecutionException, InterruptedException, TimeoutException {
+ MockTimer timer = new MockTimer();
MockPartitionWriter writer = new MockPartitionWriter();
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(writer)
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -742,10 +864,13 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleReadOpWhenPartitionInactive() {
+ MockTimer timer = new MockTimer();
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(new MockPartitionWriter())
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -758,12 +883,15 @@ public class CoordinatorRuntimeTest {
@Test
public void testScheduleReadOpWhenOpsFails() {
+ MockTimer timer = new MockTimer();
MockPartitionWriter writer = new MockPartitionWriter();
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(new MockCoordinatorLoader())
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(writer)
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -798,11 +926,13 @@ public class CoordinatorRuntimeTest {
@Test
public void testClose() throws Exception {
MockCoordinatorLoader loader = spy(new MockCoordinatorLoader());
-
+ MockTimer timer = new MockTimer();
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(loader)
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(new MockPartitionWriter())
.withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
.build();
@@ -827,6 +957,16 @@ public class CoordinatorRuntimeTest {
assertFalse(write1.isDone());
assertFalse(write2.isDone());
+ // The coordinator timer should be empty.
+ assertEquals(0, ctx.timer.size());
+
+ // Timer #1. This is never executed.
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.SECONDS, true,
+ () -> Arrays.asList("record5", "record6"));
+
+ // The coordinator timer should have one pending task.
+ assertEquals(1, ctx.timer.size());
+
// Close the runtime.
runtime.close();
@@ -836,6 +976,9 @@ public class CoordinatorRuntimeTest {
// Verify that the loader was closed.
verify(loader).close();
+
+ // The coordinator timer should be empty.
+ assertEquals(0, ctx.timer.size());
}
@Test
@@ -843,6 +986,7 @@ public class CoordinatorRuntimeTest {
TopicPartition tp0 = new TopicPartition("__consumer_offsets", 0);
TopicPartition tp1 = new TopicPartition("__consumer_offsets", 1);
+ MockTimer timer = new MockTimer();
MockCoordinatorLoader loader = mock(MockCoordinatorLoader.class);
MockPartitionWriter writer = mock(MockPartitionWriter.class);
MockCoordinatorBuilderSupplier supplier = mock(MockCoordinatorBuilderSupplier.class);
@@ -850,8 +994,10 @@ public class CoordinatorRuntimeTest {
CoordinatorRuntime<MockCoordinator, String> runtime =
new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
.withLoader(loader)
- .withEventProcessor(new MockEventProcessor())
+ .withEventProcessor(new DirectEventProcessor())
.withPartitionWriter(writer)
.withCoordinatorBuilderSupplier(supplier)
.build();
@@ -862,6 +1008,8 @@ public class CoordinatorRuntimeTest {
when(supplier.get()).thenReturn(builder);
when(builder.withSnapshotRegistry(any())).thenReturn(builder);
when(builder.withLogContext(any())).thenReturn(builder);
+ when(builder.withTime(any())).thenReturn(builder);
+ when(builder.withTimer(any())).thenReturn(builder);
when(builder.build())
.thenReturn(coordinator0)
.thenReturn(coordinator1);
@@ -893,4 +1041,289 @@ public class CoordinatorRuntimeTest {
future1.complete(null);
verify(coordinator1).onLoaded(newImage);
}
+
+ @Test
+ public void testScheduleTimer() throws InterruptedException {
+ MockTimer timer = new MockTimer();
+ CoordinatorRuntime<MockCoordinator, String> runtime =
+ new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
+ .withLoader(new MockCoordinatorLoader())
+ .withEventProcessor(new DirectEventProcessor())
+ .withPartitionWriter(new MockPartitionWriter())
+ .withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
+ .build();
+
+ // Loads the coordinator.
+ runtime.scheduleLoadOperation(TP, 10);
+
+ // Check initial state.
+ CoordinatorRuntime<MockCoordinator, String>.CoordinatorContext ctx = runtime.contextOrThrow(TP);
+ assertEquals(0, ctx.lastWrittenOffset);
+ assertEquals(0, ctx.lastCommittedOffset);
+
+ // The coordinator timer should be empty.
+ assertEquals(0, ctx.timer.size());
+
+ // Timer #1.
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.MILLISECONDS, true,
+ () -> Arrays.asList("record1", "record2"));
+
+ // Timer #2.
+ ctx.coordinator.timer.schedule("timer-2", 20, TimeUnit.MILLISECONDS, true,
+ () -> Arrays.asList("record3", "record4"));
+
+ // The coordinator timer should have two pending tasks.
+ assertEquals(2, ctx.timer.size());
+
+ // Advance time to fire timer #1,
+ timer.advanceClock(10 + 1);
+
+ // Verify that the operation was executed.
+ assertEquals(mkSet("record1", "record2"), ctx.coordinator.records());
+ assertEquals(1, ctx.timer.size());
+
+ // Advance time to fire timer #2,
+ timer.advanceClock(10 + 1);
+
+ // Verify that the operation was executed.
+ assertEquals(mkSet("record1", "record2", "record3", "record4"), ctx.coordinator.records());
+ assertEquals(0, ctx.timer.size());
+ }
+
+ @Test
+ public void testRescheduleTimer() throws InterruptedException {
+ MockTimer timer = new MockTimer();
+ ManualEventProcessor processor = new ManualEventProcessor();
+ CoordinatorRuntime<MockCoordinator, String> runtime =
+ new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
+ .withLoader(new MockCoordinatorLoader())
+ .withEventProcessor(processor)
+ .withPartitionWriter(new MockPartitionWriter())
+ .withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
+ .build();
+
+ // Loads the coordinator.
+ runtime.scheduleLoadOperation(TP, 10);
+
+ // Poll twice to process the pending events related to the loading.
+ processor.poll();
+ processor.poll();
+
+ // Check initial state.
+ CoordinatorRuntime<MockCoordinator, String>.CoordinatorContext ctx = runtime.contextOrThrow(TP);
+ assertEquals(0, ctx.timer.size());
+
+ // The processor should be empty.
+ assertEquals(0, processor.size());
+
+ // Timer #1.
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.MILLISECONDS, true,
+ () -> Collections.singletonList("record1"));
+
+ // The coordinator timer should have one pending task.
+ assertEquals(1, ctx.timer.size());
+
+ // Advance time to fire the pending timer.
+ timer.advanceClock(10 + 1);
+
+ // An event should be waiting in the processor.
+ assertEquals(1, processor.size());
+
+ // Schedule a second timer with the same key.
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.MILLISECONDS, true,
+ () -> Collections.singletonList("record2"));
+
+ // The coordinator timer should still have one pending task.
+ assertEquals(1, ctx.timer.size());
+
+ // Schedule a third timer with the same key.
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.MILLISECONDS, true,
+ () -> Collections.singletonList("record3"));
+
+ // The coordinator timer should still have one pending task.
+ assertEquals(1, ctx.timer.size());
+
+ // Advance time to fire the pending timer.
+ timer.advanceClock(10 + 1);
+
+ // Another event should be waiting in the processor.
+ assertEquals(2, processor.size());
+
+ // Poll twice to execute the two pending events.
+ assertTrue(processor.poll());
+ assertTrue(processor.poll());
+
+ // Verify that the correct operation was executed. Only the third
+ // instance should have been executed here.
+ assertEquals(mkSet("record3"), ctx.coordinator.records());
+ assertEquals(0, ctx.timer.size());
+ }
+
+ @Test
+ public void testCancelTimer() throws InterruptedException {
+ MockTimer timer = new MockTimer();
+ ManualEventProcessor processor = new ManualEventProcessor();
+ CoordinatorRuntime<MockCoordinator, String> runtime =
+ new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
+ .withLoader(new MockCoordinatorLoader())
+ .withEventProcessor(processor)
+ .withPartitionWriter(new MockPartitionWriter())
+ .withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
+ .build();
+
+ // Loads the coordinator.
+ runtime.scheduleLoadOperation(TP, 10);
+
+ // Poll twice to process the pending events related to the loading.
+ processor.poll();
+ processor.poll();
+
+ // Check initial state.
+ CoordinatorRuntime<MockCoordinator, String>.CoordinatorContext ctx = runtime.contextOrThrow(TP);
+ assertEquals(0, ctx.timer.size());
+
+ // The processor should be empty.
+ assertEquals(0, processor.size());
+
+ // Timer #1.
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.MILLISECONDS, true,
+ () -> Collections.singletonList("record1"));
+
+ // The coordinator timer should have one pending task.
+ assertEquals(1, ctx.timer.size());
+
+ // Advance time to fire the pending timer.
+ timer.advanceClock(10 + 1);
+
+ // An event should be waiting in the processor.
+ assertEquals(1, processor.size());
+
+ // Schedule a second timer with the same key.
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.MILLISECONDS, true,
+ () -> Collections.singletonList("record2"));
+
+ // The coordinator timer should still have one pending task.
+ assertEquals(1, ctx.timer.size());
+
+ // Cancel the timer.
+ ctx.coordinator.timer.cancel("timer-1");
+
+ // The coordinator timer have no pending timers.
+ assertEquals(0, ctx.timer.size());
+
+ // Advance time to fire the cancelled timer.
+ timer.advanceClock(10 + 1);
+
+ // No new event expected because the timer was cancelled before
+ // it expired.
+ assertEquals(1, processor.size());
+
+ // Poll to execute the pending event.
+ assertTrue(processor.poll());
+
+ // Verify that no operation was executed.
+ assertEquals(Collections.emptySet(), ctx.coordinator.records());
+ assertEquals(0, ctx.timer.size());
+ }
+
+ @Test
+ public void testRetryableTimer() throws InterruptedException {
+ MockTimer timer = new MockTimer();
+ CoordinatorRuntime<MockCoordinator, String> runtime =
+ new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
+ .withLoader(new MockCoordinatorLoader())
+ .withEventProcessor(new DirectEventProcessor())
+ .withPartitionWriter(new MockPartitionWriter())
+ .withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
+ .build();
+
+ // Loads the coordinator.
+ runtime.scheduleLoadOperation(TP, 10);
+
+ // Check initial state.
+ CoordinatorRuntime<MockCoordinator, String>.CoordinatorContext ctx = runtime.contextOrThrow(TP);
+ assertEquals(0, ctx.timer.size());
+
+ // Timer #1.
+ AtomicInteger cnt = new AtomicInteger(0);
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.MILLISECONDS, true, () -> {
+ cnt.incrementAndGet();
+ throw new KafkaException("error");
+ });
+
+ // The coordinator timer should have one pending task.
+ assertEquals(1, ctx.timer.size());
+
+ // Advance time to fire the pending timer.
+ timer.advanceClock(10 + 1);
+
+ // The timer should have been called and the timer should have one pending task.
+ assertEquals(1, cnt.get());
+ assertEquals(1, ctx.timer.size());
+
+ // Advance past the retry backoff.
+ timer.advanceClock(500 + 1);
+
+ // The timer should have been called and the timer should have one pending task.
+ assertEquals(2, cnt.get());
+ assertEquals(1, ctx.timer.size());
+
+ // Advance past the retry backoff.
+ timer.advanceClock(500 + 1);
+
+ // The timer should have been called and the timer should have one pending task.
+ assertEquals(3, cnt.get());
+ assertEquals(1, ctx.timer.size());
+
+ // Cancel Timer #1.
+ ctx.coordinator.timer.cancel("timer-1");
+ assertEquals(0, ctx.timer.size());
+ }
+
+ @Test
+ public void testNonRetryableTimer() throws InterruptedException {
+ MockTimer timer = new MockTimer();
+ CoordinatorRuntime<MockCoordinator, String> runtime =
+ new CoordinatorRuntime.Builder<MockCoordinator, String>()
+ .withTime(timer.time())
+ .withTimer(timer)
+ .withLoader(new MockCoordinatorLoader())
+ .withEventProcessor(new DirectEventProcessor())
+ .withPartitionWriter(new MockPartitionWriter())
+ .withCoordinatorBuilderSupplier(new MockCoordinatorBuilderSupplier())
+ .build();
+
+ // Loads the coordinator.
+ runtime.scheduleLoadOperation(TP, 10);
+
+ // Check initial state.
+ CoordinatorRuntime<MockCoordinator, String>.CoordinatorContext ctx = runtime.contextOrThrow(TP);
+ assertEquals(0, ctx.timer.size());
+
+ // Timer #1.
+ AtomicInteger cnt = new AtomicInteger(0);
+ ctx.coordinator.timer.schedule("timer-1", 10, TimeUnit.MILLISECONDS, false, () -> {
+ cnt.incrementAndGet();
+ throw new KafkaException("error");
+ });
+
+ // The coordinator timer should have one pending task.
+ assertEquals(1, ctx.timer.size());
+
+ // Advance time to fire the pending timer.
+ timer.advanceClock(10 + 1);
+
+ // The timer should have been called and the timer should have no pending tasks
+ // because the timer is not retried.
+ assertEquals(1, cnt.get());
+ assertEquals(0, ctx.timer.size());
+ }
}